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(permissions): manage current-instance access
Maxbe0a8d98b39c
diff --git a/docs/plans/2026-07-28-organization-management-in-avibe-app.md b/docs/plans/2026-07-28-organization-management-in-avibe-app.mddeleted file mode 100644index 8e74112b8..000000000--- a/docs/plans/2026-07-28-organization-management-in-avibe-app.md+++ /dev/null@@ -1,1205 +0,0 @@-# Organization Management in Avibe App--Status: Product decisions resolved; ready for implementation planning-Date: 2026-07-28-Last updated: 2026-07-29-Primary repository: `avibe-app`-Control-plane repository: `avibe-backend`--## Summary--Avibe App will become the primary user interface for Organization permission-management. Users will manage Organization members, groups, Instance access,-Project access, and Organization Resource ACLs without leaving the current-Avibe App.--This is a frontend ownership change, not a control-plane ownership change:--- `avibe-app/ui` owns the Organization management experience;-- `avibe-backend` remains the source of truth for Organization identity, data,- roles, access policies, revisions, and authorization decisions;-- existing `avibe-backend` Organization, Instance, Project, and Resource APIs- remain the business API surface;-- the local runtime proxies authenticated management requests but does not- duplicate Organization state or make Organization authorization decisions;-- local SQLite continues to store only the applied Project and Resource policy- projections needed to enforce access on that runtime.--The business services remain reused, but five backend contract gaps must be-closed before the frontend can be complete:--- a safe user-authentication path for Avibe App to call the existing Cloud APIs;-- member-safe Organization/Instance projections, including the caller's group- summary without exposing another member's email;-- revision-based optimistic concurrency for member and group mutations;-- Organization owner/admin authorization for Project management on- Organization-bound Instances; and-- a safe per-Instance Project/Resource synchronization summary.--Existing Cloud Console APIs are cookie-authenticated on the `avibe-backend`-origin and cannot be called reliably from localhost, managed Instance hostnames,-and custom hostnames without a Bearer-capable management session.--## Background--The current Organization Console lives in `avibe-backend`. It already supports:--- Organization membership and `owner | admin | member` roles;-- Organization groups and group membership;-- Organization-bound Instances and Instance access entries;-- per-Instance Project access policies;-- Organization Resource ACLs for Agents, Vault secrets, Skills, and Show Pages;-- versioned desired-versus-applied synchronization for Project and Resource- policies.--Avibe App currently exposes only fragments of this model. For example, the-Agents page can onboard missing Agents privately and then links to the hosted-Resource Access console. Users must switch products and navigation systems to-finish the permission workflow.--Moving the frontend into Avibe App makes permission management part of the-runtime the user is already operating. It also lets Instance, Project, and-resource status appear in the context where those objects are used. The move-must not create a second control plane or let a trusted-local request impersonate-an Organization administrator.--## Goals--- Provide one Organization management area inside Avibe App.-- Let Organization owners and admins manage members and groups.-- Let Organization owners/admins and the relevant Instance owner manage- Instance access.-- Let Organization owners/admins and the relevant Instance owner manage Project- access.-- Let Organization owners/admins manage Organization Resource ACLs through the- existing control-plane management contract.-- Preserve `avibe-backend` as the authoritative writer and validator for every- Organization-level mutation.-- Reuse existing backend service logic, payloads, validation, error codes, and- optimistic-concurrency revisions.-- Keep Project and Resource contents local. Cloud receives only the existing- safe descriptors and policy metadata.-- Make pending, offline, conflict, and failed policy application visible rather- than reporting a Cloud write as already effective locally.-- Support managed Instance hostnames and active custom hostnames without relying- on third-party cookies.-- Make authorization revocation converge across HTTP, SSE, WebSocket, resumed- streams, and every active hostname for an Instance.--## Non-Goals--- Moving Organization persistence or policy evaluation from `avibe-backend` to- the local runtime.-- Copying the complete Cloud Console application into Avibe App.-- Reimplementing Organization business rules in Python or TypeScript inside- `avibe-app`.-- Organization billing, plan management, invoices, or seat accounting.-- Organization domain verification or custom-hostname lifecycle management.-- Creating, deleting, pairing, or regenerating credentials for Instances in the- first delivery. The Instances page manages access to existing Instances.-- Organization deletion or ownership transfer in the first delivery. Member- role management must still protect the current owner.-- Custom roles, per-capability role editors, explicit deny rules, nested groups,- or group inheritance.-- Individual Resource ACL grants. Resource access remains private, whole- Organization, or selected Organization groups.-- Uploading Project paths, prompts, messages, commands, secret values, execution- output, or local logs to the control plane.-- Removing the existing Cloud Console before Avibe App reaches verified feature- parity.--## Resolved Product Decisions--The following decisions remove the remaining ambiguity from the implementation-contract.--1. **Organization routes use an identity gate, not an administrator gate.**- Every `/admin/organization` route requires a valid, user-present Cloud- management session and active Organization membership. Step-up establishes- the Cloud subject; it does not establish an owner/admin role. Ordinary- members and Instance owners may enter the routes they are authorized to- read or manage. Page and object capabilities are evaluated separately.-2. **Member and group writes use optimistic concurrency.** Last-write-wins is- not acceptable because the member editor and group editor mutate the same- membership relation. Member and group responses carry integer revisions;- every update supplies the matching revision; stale writes return `409` and- are never retried automatically.-3. **Owner-only is a first-class Project editor choice and a derived wire- state.** The UI choices are `inherit`, `owner_only`, and `restricted`.- `owner_only` serializes as `mode=restricted` with no bindings. A restricted- policy with no bindings always renders as Owner-only; the UI rejects saving- the Restricted choice until at least one binding exists.-4. **Selected-group Resource access carries `group_ids`.** The request is- `{ access_level, group_ids, if_match_revision }`. `scope` requires at least- one group from the same Organization; the UI sends a unique list and permits- only active groups to be newly selected. `public` and `private` require an- empty group list.-5. **Member-safe views do not disclose Resource policy composition.** Ordinary- members do not receive the Organization Resource management inventory or- arbitrary audience-group names. Normal capability surfaces may say that a- resource is available Organization-wide or through one of the caller's own- matching groups. They never reveal non-matching groups.-6. **Instance synchronization uses the worst active child state.** The severity- order is `Error > Offline > Applying > In sync`. Deleted or tombstoned- Projects and Resources are ignored. An Instance with no active managed- descriptors shows `No managed policies`, not `In sync`.-7. **Silent reauthorization is a one-attempt convenience, not a fallback- loop.** It is attempted only for an expired or missing local management grant- while a valid Cloud browser session can preserve the already-bound subject.- An explicit logout, subject mismatch, revocation, missing Cloud session,- `login_required`, `consent_required`, invalid callback state, or token- validation failure requires explicit sign-in.-8. **Subject mismatch is a distinct terminal state.** The stable code is- `cloud_management_subject_mismatch`. The local server immediately clears the- mismatched grant; the UI explains that the Avibe session and Cloud account- differ and requires explicit re-entry with the same account. It never- silently switches subjects. On trusted loopback, the first successful Cloud- login establishes the subject because no remote subject existed beforehand.--## Product Model--Organization authorization consists of independent layers. No layer may elevate-another:--```text-effective operation- = signed Instance role- intersected with Project access- intersected with Resource ACL- intersected with resource-specific safety rules-```--The layers answer different questions:--| Layer | Question | Values |-| --- | --- | --- |-| Organization role | Who may govern the Organization? | `owner`, `admin`, `member` |-| Instance access | What may this principal do on one Avibe Instance? | implicit owner, `editor`, `viewer` |-| Project access | What may this principal do in one Project? | inherited, restricted `editor`, restricted `viewer`, owner-only |-| Resource ACL | Which Organization audience may use one resource? | private, Organization-wide, selected groups |-| Resource management | Who may change or delete the resource definition? | separate service-level management check |--Within one Instance, the implicit Instance owner has all Instance-level-capabilities, including settings, files/terminal, access management, and Project-policy management. An Instance `editor` inherits viewer access and may perform-only explicitly editor-gated collaboration actions, such as sending messages-and invoking editor-level resources when their Project and Resource policies-also allow it. An editor cannot use owner-only system/files/terminal surfaces or-change permission policies. An Instance `viewer` is read-only: it may read-authorized Instance/Project data and view viewer-level surfaces such as an-allowed Show Page, but cannot make state-changing calls.--These Instance roles are separate from Organization `owner | admin | member`:-an Organization owner/admin governs Organization policy, while an Instance owner-governs only the Instances they own unless they also hold an Organization-management role. “All Instance-level capabilities” does not bypass Project,-Resource ACL, resource ownership, Vault approval/signing, or other independent-safety checks.--Resource use never implies resource-definition management or Organization ACL-management. A user may be allowed to invoke an Agent, load a Skill, request a-Vault secret, or open a Show Page without being allowed to edit, delete, or-share that object. Local resource-definition ownership remains separate from-the Organization owner/admin authority required by the Cloud Resource API.--Vault Resource ACLs do not bypass Vault protection, approval, signing, or-plaintext-delivery rules. Show Page Organization access remains separate from a-public internet share link.--## Information Architecture--Organization management is a first-level destination in the existing Control-Panel. It is not a new landing page and does not add Organization pages to the-Workbench capability navigation.--```text-/admin/organization- /overview- /members- /groups- /groups/:groupId- /instances- /instances/:instanceId/access- /instances/:instanceId/projects- /resources-```--`/admin/organization` redirects to `/admin/organization/overview`.--The whole route tree requires a valid Cloud management identity and active-membership in the selected Organization. It does not require the caller to be-an Organization owner/admin. Route loaders then apply the following capability-gates:--| Route | Read gate | Write gate |-| --- | --- | --- |-| Overview | Any active member; member-safe projection for non-managers | None |-| Members | Owner/admin sees the directory; other members see self only | Owner/admin, subject to owner protections |-| Groups | Any active member sees group metadata and own membership | Owner/admin |-| Instances | Backend-visible Instances only | Owner/admin or owner of the target Instance |-| Projects | Backend-visible Projects under an authorized Instance | Owner/admin or owner of the target Instance |-| Resources | Owner/admin only | Owner/admin only |--An unauthorized child route returns the localized unavailable/forbidden state;-it does not redirect to login when the management identity is already valid.--Project access is nested under an Instance because a Project is a local-runtime-resource whose safe descriptor and desired policy are mirrored through that-Instance. The UI may offer an Organization-wide Project search later, but it-must retain the Instance boundary in URLs and API calls.--An Organization switcher appears in the Organization header when the signed-in-user belongs to more than one Organization. It is omitted for a single-Organization. The selected Organization ID is kept in the route or feature-state, not written into global runtime configuration.--### Overview--The overview shows:--- Organization name and the current user's Organization role;-- member-safe aggregate active-member/active-group counts, with invited,- removed, and archived breakdowns shown only to managers;-- counts for Instances and Projects visible to the caller and, for managers,- the managed Resource inventory;-- Instances with pending, offline, or error policy synchronization;-- links into Members, Groups, Instances, Projects, and Resources;-- a member-safe summary when the caller is not an Organization manager.--It must not use fixture counts. Every value comes from Cloud responses.--### Members--Owners and admins can:--- list active, invited, and removed members;-- invite a member by email with a role and initial groups;-- resend a pending invitation;-- change a member between `admin` and `member`;-- replace a member's Organization groups; and-- remove a member by setting status to `removed`.--Only the Organization owner can make ownership decisions. The first delivery-does not expose ownership transfer, so neither an admin nor the current owner-can assign the `owner` role from the generic member editor. Existing backend-owner-protection rules remain authoritative.--Members who are not Organization managers see only their own membership, role,-and group summary. They do not receive the full member directory or other member-email addresses from the local proxy.--Each member response includes `member_revision`. Role, status, and that member's-complete group set share this revision. Member PATCH/replace-membership requests-include `if_match_revision=member_revision`; a successful change increments the-member revision and the revisions of every group whose membership relation was-added or removed.--### Groups--Owners and admins can:--- create a group with name, description, color, and initial members;-- update name, description, and color;-- replace group membership;-- archive and restore a group; and-- inspect where a group is referenced before archival.--Deletion is presented as archival because the existing backend `DELETE` route-archives a group. An archived group cannot be added to a new Instance, Project,-or Resource policy. Existing references remain visible and must fail closed when-they no longer produce a valid signed group claim.--Active members may read group name, description, color, status, and whether they-belong to the group. Only owners/admins receive the full member roster or member-identities. Each group response includes `group_revision`. Group metadata and-the complete group member set share this revision. Group PATCH/archive/restore-and replace-members requests include `if_match_revision=group_revision`; a-successful membership replacement increments the group revision and the member-revision of every member added or removed.--Both editor paths apply membership changes as relation deltas in one transaction-and lock all affected member and group rows in one shared deterministic order.-A change through either path therefore invalidates a stale editor on the other-path without overwriting unrelated membership relations or creating opposite-lock ordering. Timestamps are display metadata, not concurrency tokens.--### Instances--The list shows Organization-bound Instances visible to the current caller:--- display name and stable Instance ID;-- owner identity for managers, or `You`/a non-identifying owner label for a- member-safe caller;-- effective public address;-- pairing and runtime status;-- access-entry count; and-- Project/Resource synchronization health.--The first delivery manages access to an existing Instance. It does not create,-delete, pair, regenerate pairing keys, or manage hostnames.--The Instance access editor supports these principal types:--- Organization group;-- individual email; and-- email domain.--Each access entry grants `viewer` or `editor`. The Instance owner is implicit,-owner-equivalent, and cannot be removed or represented as a normal entry.--### Projects--The Project page lists safe Project descriptors published by one Instance. It-never displays or sends the local Project path.--Each Project has one access rule:--- `inherit`: use the effective Instance role;-- `owner_only`: only the implicit Instance owner receives Project access; an- Organization owner/admin may still manage the policy but does not gain- Project use access from management authority alone; or-- `restricted`: apply one or more explicit email, email-domain, and- Organization-group bindings with `viewer` or `editor`.--`owner_only` is a first-class UI selection but remains derived on the existing-wire contract:--| UI selection | Wire representation |-| --- | --- |-| Inherit | `mode=inherit`, empty bindings |-| Owner-only | `mode=restricted`, empty bindings |-| Restricted | `mode=restricted`, one or more bindings |--The editor never displays `Restricted, 0 bindings`. Any restricted response-with an empty binding list renders as Owner-only, and Restricted cannot be saved-until at least one valid binding exists.--Project access can only narrow the Instance role. An `editor` Project binding-does not elevate an Instance `viewer`.--Current backend Project management is limited to `instance.owner_user_id`.-Organization management is incomplete unless Organization owners/admins can-also manage Projects on Organization-bound Instances. The shared backend helper-must therefore authorize:--```text-Organization owner/admin for the Instance's Organization-OR the Instance owner-```--Personal-workspace Instances retain their existing owner-only behavior.--### Resources--The Resource page manages the safe Organization resource index for:--- Agents;-- Vault secrets;-- Skills; and-- Show Pages.--Harness Tasks and Watches are added only after their Organization-aware-authorization contract is implemented. Unknown resource kinds fail closed and-must not appear automatically.--The UI labels the three access levels as:--- `Private`;-- `Organization`; and-- `Selected groups`.--The existing wire value `public` means every active member of the Organization.-The UI must not label it `Public`, because that is easily confused with an-internet-visible Show Page. The wire contract remains `public | scope | private`-until a separately versioned protocol changes it.--The Resource ACL mutation payload is:--```json-{- "access_level": "scope",- "group_ids": ["grp_engineering", "grp_design"],- "if_match_revision": 3-}-```--`scope` requires one or more canonical group IDs belonging to the selected-Organization. Unknown and cross-Organization groups are rejected; duplicate IDs-are normalized to one binding. Archived groups cannot be newly selected. An-already-bound archived group remains visible as archived, grants no access, and-may be preserved or removed without making it selectable for another policy.-`public` and `private` require `group_ids=[]`; the backend rejects inconsistent-access-level/group combinations instead of silently normalizing them.--The `/resources` route is an owner/admin management surface. Ordinary members-discover usable resources only in their normal capability surfaces. Those-surfaces may show `Organization-wide` or `Available through <matching own-group>`, but must not expose non-matching audience groups, the full binding list,-or the Organization Resource inventory.--## Management Authorization Matrix--| Operation | Org owner | Org admin | Instance owner | Org member |-| --- | --- | --- | --- | --- |-| View Organization overview | Full | Full | Member-safe unless also manager | Member-safe |-| List all members and emails | Allow | Allow | Deny unless also manager | Deny |-| Invite/remove members | Allow | Allow except owner operations | Deny | Deny |-| Change member role | Allow except generic owner assignment | Allow between admin/member | Deny | Deny |-| Create/update/archive groups | Allow | Allow | Deny | Deny |-| Read group metadata | Allow | Allow | Active-member view | Active-member view |-| Read group member roster | Allow | Allow | Deny unless also manager | Deny |-| View all Organization Instances | Allow | Allow | Own and otherwise authorized | Authorized only |-| Manage Instance access | Allow | Allow | Own Instance | Deny |-| Manage Project access | Allow | Allow | Own Instance | Deny |-| Manage Resource ACL | Allow | Allow | Deny unless also an Org manager | Deny |-| View Resource management inventory | Allow | Allow | Deny unless also manager | Deny |-| Use an Instance/Project/resource | Re-evaluate all access layers | Re-evaluate all access layers | Re-evaluate all access layers | Re-evaluate all access layers |--The frontend uses capability projections to hide or disable actions, but the-projection is never the authorization boundary. Every backend mutation invokes-the existing service-level role and ownership checks again.--## Frontend Experience--### Page shell--Organization pages reuse the existing Avibe App Control Panel shell and UI-primitives. They do not import Cloud Console Next.js components. Cloud Console-screens are behavior and contract references only.--Suggested feature ownership:--```text-ui/src/features/organization/- api/- client.ts- errors.ts- types.ts- components/- OrganizationHeader.tsx- OrganizationSwitcher.tsx- OrganizationRoleBadge.tsx- PrincipalSelector.tsx- PolicySyncBadge.tsx- pages/- OrganizationOverviewPage.tsx- OrganizationMembersPage.tsx- OrganizationGroupsPage.tsx- OrganizationGroupDetailPage.tsx- OrganizationInstancesPage.tsx- InstanceAccessPage.tsx- InstanceProjectsPage.tsx- OrganizationResourcesPage.tsx-```--The exact extraction may follow the existing repository reuse ladder. This-layout describes ownership, not a requirement to create one file per name.--All user-visible copy lives in `ui/src/i18n/en.json` and-`ui/src/i18n/zh.json`. The UI reuses `Button`, `Badge`, `Input`, `Dialog`,-`Popover`, `Tabs`, and other primitives under `ui/src/components/ui/`.--### Loading and errors--Every page has explicit states for:--- Cloud not connected;-- Organization management authorization required;-- authorization expired and reauthorization in progress;-- management subject differs from the current remote-access subject;-- loading;-- empty Organization data;-- caller has a member-safe view but no management capability;-- Cloud unreachable;-- validation error;-- authorization revoked;-- revision conflict; and-- policy accepted but not yet applied by the Instance.--A `401` caused only by an expired or missing local grant may attempt one-controlled silent reauthorization under the rules below. Other authentication-failures require explicit sign-in. A `403` is shown as current authorization-denial and must not be retried as the local owner. A `404` for a protected object-is treated as unavailable rather than disclosing cross-Organization existence.-`cloud_management_subject_mismatch` has its own terminal state and is not-collapsed into authorization revoked.--### Mutations--Member removal, role downgrade, group archival, and access narrowing use a-confirmation dialog that names the actual effect. The frontend does not claim-an impact count unless the backend returned one.--Member and group mutations send `if_match_revision`, wait for a successful Cloud-response before changing the canonical list, and adopt the revisions returned-by that response. A `409 organization_member_conflict` or `409-organization_group_conflict` refetches the affected records and preserves the-draft for comparison; it never silently retries. Project and Resource policy-editors may render an optimistic pending revision because the existing APIs-return versioned desired policy state; a conflict restores and refetches the-authoritative row.--Any successful member-group relation mutation invalidates both the member and-group query families in the frontend cache. This ensures the other editor loads-the newly bumped revisions before its next save.--## Architecture and Ownership--```text-Browser- -> Avibe App Organization UI- -> same-origin local management proxy- -> existing avibe-backend user APIs with a short-lived user Bearer token- -> existing avibe-backend service layer- -> Cloud database--Cloud Project/Resource desired policy- -> paired-device intent polling- -> local transactional applied projection- -> local enforcement- -> exact revision acknowledgement-```--### Avibe App responsibilities--- Render the Organization management frontend.-- Start and complete a user-present Cloud management authorization flow.-- Keep Cloud management tokens in process memory, isolated per browser session.-- Proxy allowlisted Organization API requests to the configured, pairing-- validated Cloud backend URL.-- Apply existing local CSRF protection to every proxy mutation.-- Preserve Cloud status codes and stable error codes while stripping unsafe- upstream headers and response content.-- Never use the Instance device secret as proof of Organization user identity.-- Never persist member lists, Cloud tokens, or Organization policy drafts to- local product state.--### Avibe Backend responsibilities--- Authenticate the Cloud user and issue a short-lived management token.-- Accept either the existing Cloud Console cookie session or a valid management- Bearer token in the shared user API authentication boundary.-- Reuse existing Organization, group, Instance, Project, and Resource services.-- Re-evaluate current Organization role and target ownership for every request.-- Maintain optimistic-concurrency revisions for member, group, Project, and- Resource policies.-- Bump Instance authorization revision for access-narrowing and membership- changes that invalidate active local sessions.-- Return only safe Project and Resource descriptors.--### Browser responsibilities--- Hold only an opaque, HttpOnly, same-origin local management-session handle.-- Never receive the Cloud management Bearer token.-- Send the existing Avibe App CSRF token on state-changing local proxy calls.--## Cloud Management Authentication--### Why existing authentication is insufficient--Existing Organization APIs call `requireUserApi()`, which reads the-`avibe-backend` origin's HttpOnly session cookie. An Avibe App may run on-localhost, a managed Instance hostname, or a customer custom hostname. Cross--origin cookie requests are not a reliable or acceptable authentication contract.--The current paired-device user-token endpoint is also insufficient for-Organization management. It lets a device-secret-authenticated runtime request-a capability token for caller-supplied `sub` and `email`, then checks Instance-access. Extending that mechanism with an Organization management scope would let-a compromised device secret attempt to impersonate a known Organization admin.--Organization management requires a user-present Cloud authorization. The Cloud-login, not the device, determines the subject.--### Required flow--1. The user opens `/admin/organization`.-2. Avibe App verifies that the runtime is paired with Avibe Cloud.-3. If no valid per-browser management grant exists, Avibe App starts a step-up- Cloud authorization with PKCE and an opaque state bound to that browser.-4. Cloud authenticates the user and validates that the requesting client is an- active paired Instance with an allowed callback hostname.-5. Cloud issues a one-time authorization code for explicit management scopes.-6. The local server exchanges the code and verifier for a short-lived, signed- management Bearer token.-7. The local server stores the Bearer token only in process memory under a- random management-session handle.-8. The browser receives only the HttpOnly handle cookie and returns to the- requested Organization route.-9. Local proxy calls resolve the handle, attach the Bearer token server-side,- and call the existing Cloud API.-10. Expiry removes the in-memory token. The app may attempt the single silent- reauthorization path below; otherwise it requires explicit sign-in.--For a remote browser session, the authorized management subject must equal the-subject in the current validated local remote-access session. A remote viewer-must not sign in as a second account and attach that account's management grant-to the first account's local session. A trusted loopback caller has no implied-Cloud identity and must complete the same user-present Cloud login; its first-successful Cloud login establishes the bound subject for that management-session.--If a returned Cloud subject differs from an already-bound remote-access subject,-the local server deletes the management grant immediately and returns-`cloud_management_subject_mismatch`. The UI does not retry, switch accounts, or-classify this as generic revocation. It tells the user to sign out and re-enter-Organization management using the same account as the current Avibe session.-The localized state uses the title `Cloud account does not match` and the body-`The Avibe session and Avibe Cloud are signed in with different accounts. Sign-in to Organization management with the same account as this Avibe session.` It-does not need to expose either account's email address.--If the Organization flow starts on an insecure loopback origin, the paired-HTTPS Instance origin is the canonical callback and Organization management-origin. The app may hand the browser to that route after authorization. The-authorization server must not accept arbitrary callback URLs or weaken the-existing active-hostname validation.--### Token contract--The management token is an RS256 JWT using the existing published JWKS but a-distinct audience from ID tokens and low-risk capability tokens.--Required claims:--```json-{- "iss": "https://avibe.bot",- "aud": "avibe-organization-api",- "sub": "user-id",- "email": "[email protected]",- "vibe_instance_id": "inst_...",- "scope": "organization:read organization:manage instance:read instance:manage project:read project:manage resource:read resource:manage",- "jti": "token-id",- "iat": 0,- "exp": 0-}-```--The token lifetime is at most ten minutes. No refresh token is written to disk-or returned to frontend JavaScript. Reauthorization may be silent only while-Cloud still has a valid user session and the current user explicitly entered-the Organization management surface.--Silent reauthorization is attempted at most once per entry or recovery attempt-and only when all of the following are true:--- the local management handle is missing or expired;-- the user is entering or already using an Organization management route;-- Cloud still has a valid browser session that can complete authorization- without interaction; and-- the returned subject is identical to the subject already bound to the local- browser session, when one exists.--The app transitions to the explicit `Sign in to manage Organization` state,-without another silent retry, after explicit logout, subject mismatch,-authorization revocation, missing Cloud session, Cloud `login_required` or-`consent_required`, invalid callback state, authorization-code failure, or-management-token validation failure. A failed silent attempt also transitions-to explicit sign-in. This state machine must not loop or repeatedly navigate-the browser between Avibe App and Cloud.--| Trigger | Silent attempt | Result |-| --- | --- | --- |-| Local grant missing/expired; Cloud session valid; same subject | Once | Restore the local grant and requested route |-| Cloud session missing, `login_required`, or `consent_required` | Never again | Explicit sign-in state |-| Explicit logout | Never | Explicit sign-in state |-| Subject mismatch | Never | Dedicated mismatch state; grant cleared |-| Authorization revoked or token validation fails | Never | Explicit sign-in/error state; grant cleared |-| Callback state/code validation fails | Never | Explicit sign-in/error state; no grant attached |-| The one silent attempt fails for any reason | Never again | Explicit sign-in state |--To distinguish an explicitly signed-out browser from a browser whose in-memory-grant merely expired, logout sets a same-origin, HttpOnly manual-reauthorization-marker containing no identity or token. A failed silent attempt, subject-mismatch, authorization revocation, and token validation failure set the same-marker and clear any grant. The explicit sign-in action clears the marker when-starting a new interactive authorization; silent authorization never clears or-bypasses it.--Scopes are coarse transport capabilities. They do not encode the caller's-Organization role. Backend services load current membership and ownership on-every request so a demoted or removed user cannot keep managing until token-expiry.--### Local proxy contract--Suggested local endpoints:--```text-GET /api/cloud-management/session-POST /api/cloud-management/session/start-GET /auth/organization/callback-DELETE /api/cloud-management/session--ANY /api/cloud-management/organizations/*-ANY /api/cloud-management/instances/*-```--The proxy uses an explicit method/path allowlist. It does not accept an arbitrary-upstream URL. It forwards only required headers, JSON request bodies, and query-parameters. It rejects redirects, non-JSON management responses, oversized-responses, and a backend origin that did not pass pairing validation. Tokens,-cookies, and pairing secrets are redacted from logs and diagnostics.--## Existing API Reuse--The following business APIs remain authoritative. Bearer authentication is an-additional authentication mode for the same routes, not a second-implementation.--| Capability | Existing `avibe-backend` route | Required gap |-| --- | --- | --- |-| Organization switcher | `GET /api/organizations` | Bearer user auth |-| Organization detail | `GET /api/organizations/:orgId` | Bearer user auth; add caller-only group summary and manager-only detailed counts |-| Invite/list members | `GET/POST /api/organizations/:orgId/members` | Bearer user auth; return `member_revision` |-| Update/remove member | `PATCH /api/organizations/:orgId/members/:memberId` | Bearer user auth; accept `if_match_revision`; UI uses `status=removed` |-| Resend invitation | `POST /api/organizations/:orgId/members/:memberId/resend-invite` | Bearer user auth |-| List/create groups | `GET/POST /api/organizations/:orgId/groups` | Bearer user auth; return `group_revision` |-| Edit/archive group | `PATCH/DELETE /api/organizations/:orgId/groups/:groupId` | Bearer user auth; accept `if_match_revision` |-| Replace group members | `PUT /api/organizations/:orgId/groups/:groupId/members` | Bearer user auth; accept `if_match_revision`; atomically bump affected member revisions |-| List Instances | `GET /api/organizations/:orgId/instances` | Bearer user auth; member-safe owner projection; add Project/Resource sync summary |-| Manage Instance access | `GET/PUT /api/instances/:instanceId/authorized-users` | Bearer user auth |-| List Projects | `GET /api/instances/:instanceId/projects` | Bearer user auth; authorize Org owner/admin |-| Manage Project access | `GET/PUT /api/instances/:instanceId/projects/:projectId/access` | Bearer user auth; authorize Org owner/admin |-| List resources | `GET /api/organizations/:orgId/resources` | Bearer user auth |-| Manage Resource ACL | `PATCH /api/organizations/:orgId/resources/:instanceId/:kind/:resourceId/access` | Bearer user auth |--No frontend call depends on Cloud Console HTML, Next.js server actions, or a-Cloud-origin cookie.--## API Client and Contracts--Avibe App defines explicit TypeScript request and response types for the reused-Cloud APIs. Types are based on the Cloud JSON contract, not imported from the-sibling checkout at build time. A contract fixture suite prevents drift between-the repositories.--Member and group revisions are monotonically increasing, non-negative integers.-Creation returns the initial revision. A mutation of an existing entity includes-the revision observed by the editor, for example:--```json-{- "role": "member",- "group_ids": ["grp_engineering"],- "if_match_revision": 7-}-```--```json-{- "member_ids": ["mem_alice", "mem_bob"],- "if_match_revision": 12-}-```--Member responses expose `member_revision`; group responses expose-`group_revision`. A change increments only the revisions whose covered state-actually changed; a no-op returns the current revision. A stale mutation makes-no changes and returns the current safe revision hint:--```json-{- "error": "organization_member_conflict",- "current_revision": 8-}-```--The corresponding group error is `organization_group_conflict`. The revision-hint is not authorization to retry: the client must refetch the authoritative-entity and ask the user to reconcile the preserved draft.--The local proxy returns a stable envelope for transport failures while-preserving successful Cloud payloads and Cloud business error codes:--```json-{- "error": "cloud_management_unavailable",- "retryable": true-}-```--Expected stable business and management errors include:--- `unauthorized`;-- `forbidden`;-- `organization_not_found`;-- `organization_member_not_found`;-- `organization_group_not_found`;-- `organization_group_archived`;-- `organization_member_conflict`;-- `organization_group_conflict`;-- `instance_not_found`;-- `project_not_found`;-- `resource_not_found`;-- `member_email_taken`;-- `group_name_taken`;-- `too_many_entries`;-- `invalid_project_access_intent`;-- `invalid_resource_acl_intent`;-- `cloud_management_subject_mismatch`; and-- `resource_sync_conflict`.--The frontend maps codes to localized copy. It never renders raw backend error-details.--## Synchronization Semantics--Member and group changes are authoritative once the Cloud API transaction-commits, but authorization narrowing is not complete until affected runtime-sessions reject stale authorization revisions.--Project and Resource changes have two states:--1. Cloud desired policy was accepted at revision `N`.-2. The paired runtime applied and acknowledged revision `N`.--The UI derives these statuses:--| UI state | Meaning |-| --- | --- |-| Applying | Desired revision is newer than applied revision |-| In sync | Desired and applied revisions match and sync is healthy |-| Offline | Instance has not synchronized within the configured freshness window |-| Error | Runtime rejected or failed to apply the desired policy |-| Deleted | Descriptor is tombstoned and omitted from normal lists |--Project and Resource writes include `if_match_revision`. A `409-resource_sync_conflict` causes a row/dialog refetch and preserves the user's-draft only for comparison. The client never retries the stale write-automatically.--The Instance overview aggregates all active Project and Resource descriptor-states by the deterministic severity order:--```text-Error > Offline > Applying > In sync-```--The Organization Instance-list response carries the safe aggregate so the-frontend does not fetch a manager-only Resource inventory or independently-reimplement the offline freshness window:--```json-{- "policy_sync": {- "status": "error",- "projects": { "active": 3, "error": 1, "offline": 0, "applying": 1, "in_sync": 1 },- "resources": { "active": 2, "error": 0, "offline": 0, "applying": 0, "in_sync": 2 }- }-}-```--`status` is `error | offline | applying | in_sync | none`. The counts disclose-no Project/Resource names, owners, ACLs, or audience groups and are safe for a-caller already authorized to see that Instance.--The aggregate badge is the worst child state. Deleted and tombstoned descriptors-are ignored. When no active Project or Resource descriptors exist, the badge is-`No managed policies`, not `In sync`. The detail view also shows Project and-Resource counts by state so the aggregate is explainable rather than a lossy-single signal.--Access narrowing must trigger authorization refresh or revocation for:--- Organization member removal;-- Organization role downgrade where effective management changes;-- removal from an authorized group;-- group archival;-- Instance role downgrade or access-entry removal;-- Project role downgrade or binding removal; and-- Resource ACL narrowing.--## Privacy and Security Requirements--- Organization data never becomes a local source of truth.-- Member directories and email addresses are returned only to Organization- managers. Member-safe pages show only the current user's membership.-- Non-manager Resource surfaces return only resources usable by the caller and- may identify Organization-wide access or one of the caller's own matching- groups. They do not return non-matching audience names or full ACL composition.-- Project descriptors contain a safe display name and stable ID, never a path.-- Resource descriptors contain safe names and IDs, never prompts, secret values,- source paths, configuration, or execution output.-- The browser never receives the management Bearer token, Instance device- secret, or pairing secret.-- One runtime may serve multiple browsers and users. Management tokens are keyed- per browser session and subject, never stored in one global current-user slot.-- Logout deletes the in-memory token and handle mapping immediately. Its- no-token manual-reauthorization marker only suppresses silent login and is- cleared when the user explicitly starts sign-in.-- Service restart drops all management grants and requires reauthorization.-- Management responses use `Cache-Control: no-store, private` and vary on the- local management-session cookie where applicable.-- Local proxy mutations require the existing CSRF token.-- The proxy rejects cross-Origin browser requests and uses a strict upstream- allowlist derived from the paired backend URL.-- Cloud APIs continue returning `404` for protected cross-Organization objects- where existence must not be disclosed.-- Logs and Sentry data redact Authorization headers, cookies, OAuth codes,- verifiers, tokens, member invitation links, and pairing credentials.--## Delivery Plan--### Phase 1: Authentication and contracts--- Add Cloud management step-up authorization and signed short-lived tokens.-- Extend the shared Cloud user authentication boundary to accept cookie or- management Bearer authentication.-- Add the member-safe self-membership/group-summary projection without exposing- another member's identity or email.-- Add the member-safe Instance owner projection and safe per-Instance policy- synchronization aggregate.-- Add member/group revision columns, mutation preconditions, atomic cross-entity- revision bumps, and stable `409` conflict responses.-- Add the Avibe App in-memory management grant store and allowlisted local proxy.-- Add contract fixtures for Organization, member, group, Instance, Project, and- Resource payloads and errors.-- Do not expose write controls until subject binding, expiry, logout, and- revocation tests pass.--### Phase 2: Read-only Organization UI--- Add Control Panel navigation and Organization routes.-- Add Organization switcher and overview.-- Add member-safe Members and Groups pages, authorized Instance and Project- pages, and an owner/admin-gated Resources page.-- Verify owner, admin, member, Instance-owner, local-loopback, managed-hostname,- and custom-hostname views.--### Phase 3: Members and groups--- Add invite, resend, role, group-membership, removal, group create/edit/archive,- and group-member replacement flows.-- Add destructive-action confirmation, member/group optimistic-concurrency- recovery, and authorization-revision verification.--### Phase 4: Instance and Project access--- Add Instance access editor.-- Generalize Project management authorization to Organization owner/admin or- Instance owner for Organization-bound Instances.-- Add revision conflicts, pending application, offline, and error states.--### Phase 5: Resource access--- Replace the Agent-page external Resource Access dependency with native deep- links into the Organization Resources page.-- Add Agent, Vault secret, Skill, and Show Page ACL management.-- Retain separate use-versus-management enforcement and resource-specific safety- rules.--### Phase 6: Parity and Cloud Console transition--- Run cross-repository contract and E2E coverage.-- Verify mobile and desktop UI, accessibility, localization, deep links, and- browser refresh behavior.-- Keep the Cloud Console available as a fallback until the current-head Avibe- App passes the parity checklist.-- Only then decide whether Cloud Console Organization pages redirect to an- Instance or remain as a recovery surface.--## Verification Strategy--### Avibe App unit and component coverage--- Role and capability projection controls visible actions correctly.-- A valid management identity admits ordinary members and Instance owners to the- Organization shell without exposing manager-only routes or data.-- Member-safe responses cannot render a directory or management action.-- Member-safe Resource surfaces reveal only usable resources and matching own- audience reasons, never non-matching group names or full ACL composition.-- Principal editors normalize and deduplicate email, domain, and group entries.-- Archived groups remain visible on existing policies but cannot be newly- selected.-- Project `inherit`, `restricted`, and `owner_only` rules serialize correctly;- empty restricted bindings always render as Owner-only.-- Resource UI maps wire `public` to `Organization` and validates the `group_ids`- invariants for `scope`, `public`, and `private`.-- Member, group, Project, and Resource conflict recovery refetches without- auto-overwriting.-- Instance sync aggregation follows `Error > Offline > Applying > In sync` and- emits `No managed policies` for an empty active descriptor set.-- Token expiry and logout clear Organization state; silent reauthorization is- attempted at most once and never after a terminal authentication result.-- Subject mismatch clears the grant and renders its dedicated state without- silently changing accounts.-- Route changes and Organization switching cancel stale requests.--### Avibe Backend contract coverage--- Every reused route accepts the existing Cloud cookie and the new management- Bearer token through one authenticated-user abstraction.-- Scopes, issuer, audience, expiry, signature, Instance binding, and subject are- validated.-- Device-secret-only requests cannot mint an Organization management token for- caller-supplied identity.-- Current Organization role is re-read for every management request.-- The self-membership projection returns only the caller's role and groups to a- non-manager and never expands into another member's directory record.-- A member-safe Instance response hides another owner's email while returning- only descriptor counts and the canonical worst synchronization state.-- Member and group mutations reject stale revisions, bump all affected entity- revisions atomically, and cannot lose a relation change made through the- other editor path.-- Organization admins can manage Projects on Organization-bound Instances;- unrelated members and cross-Organization callers cannot.-- Project and Resource optimistic-concurrency behavior remains compatible.-- Instance synchronization aggregation ignores tombstones, uses the shared- offline freshness resolver, follows the severity order, and returns `none`- for no active descriptors.-- Resource `scope` rejects empty, unknown, and cross-Organization group IDs,- canonicalizes duplicates, and prevents new archived-group selection;- `public` and `private` reject non-empty IDs.--### Closed-loop scenarios--- Owner signs into Organization management and views the same data as the Cloud- Console.-- Admin invites a member, adds the member to a group, grants that group Instance- editor access, restricts a Project to viewer, and grants one Agent to the- group.-- The new member sees only the authorized Instance, Project, and Agent and cannot- access management actions.-- Removing the member invalidates an already-open editor session across managed- and custom hostnames.-- Archiving a referenced group prevents new use and does not expose stale policy- data.-- An offline Instance shows pending policy state, then converges to In sync after- reconnect.-- Two admins editing the same Project or resource produce a revision conflict;- neither silently overwrites the other.-- A member editor and group editor concurrently changing the same membership- relation produce a revision conflict; neither silently overwrites the other.-- An Instance with mixed Project/Resource states displays the worst state and- exposes the per-type counts that explain it.-- A local trusted owner without Cloud login cannot access Organization data.-- A stolen/invalid device secret or a mismatched remote-session subject cannot- obtain or attach an Organization management grant.-- An expired local grant with a valid same-subject Cloud session silently- reauthorizes once; logout, mismatch, revocation, and `login_required` require- explicit sign-in and never create a redirect loop.--Implementation must add the new multi-step management authorization cases to-the canonical scenario catalog and a closed-loop harness under-`tests/scenarios/auth_setup/`, following the repository scenario-testing-standard.--### Manual regression--After implementation, update the existing local Incus `master` regression-environment through the supported runner, preserve accumulated state, and verify-service health. Exercise the Organization UI from desktop and mobile viewports-and verify at least one managed hostname and one active custom hostname. Do not-reset Organization, pairing, or regression state to make the flow pass.--## Acceptance Criteria--- Organization management is available under the Avibe App Control Panel.-- All Organization routes require user-present Cloud identity, while ordinary- active members and Instance owners can enter their member-safe/owned scopes- without being treated as Organization managers.-- Owners/admins can manage members and groups without opening the Cloud Console.-- Authorized managers can manage existing Instance and Project access without- opening the Cloud Console.-- Authorized managers can manage Agent, Vault secret, Skill, and Show Page- Organization ACLs without opening the Cloud Console.-- All business mutations are processed by existing `avibe-backend` services and- stored only in the Cloud control plane.-- Avibe App does not persist a duplicate Organization directory or desired- policy database.-- Cloud-origin cookies are not required by Avibe App API calls.-- Management identity is user-present, short-lived, subject-bound, and cannot be- minted from the device secret plus caller-supplied identity.-- Trusted-local access alone does not grant Organization management authority.-- Project management works for Organization owners/admins and the relevant- Instance owner, while personal Instances remain owner-only.-- Owner-only is an unambiguous Project UI choice that serializes to restricted- with empty bindings; Restricted always has at least one binding.-- Resource `scope` carries validated `group_ids`, and non-managers never receive- arbitrary Resource audience names or management inventory.-- Member, group, Project, and Resource policy writes reject stale revisions- without silent overwrite.-- Instance sync badges use the worst active child state and distinguish an empty- managed-policy set from `In sync`.-- Silent reauthorization has a single-attempt boundary, and subject mismatch is- a dedicated terminal state that clears the grant.-- Access downgrade and removal invalidate stale HTTP, SSE, and WebSocket- authorization across all active Instance hostnames.-- Cloud Console remains available until read/write, error-state, localization,- accessibility, and regression parity are verified.--## Open Follow-Ups--These items are deliberately deferred and require separate product decisions:--- whether Organization creation and ownership transfer should later move into- Avibe App;-- whether domain and custom-hostname management belongs beside Instance access;-- whether the Cloud Console remains a permanent recovery surface;-- whether individual-user Resource ACL grants are needed beyond private,- Organization, and group audiences;-- whether Organization changes require a durable audit-log UI; and-- when Harness Task and Watch resources join the Organization Resource ACL.--## Design Appendix--High-fidelity mockups for this plan live in `avibe-docs/design.pen` (Pencil), in-the dark **"Org · … (Dark)"** cluster laid out below the light-**"avibe.bot — Console · Organization"** frames. The light frames are the Cloud-Console **reference only** (they also cover deferred first-delivery items such as-instance creation, ownership transfer, and domain management). The dark cluster-is the Avibe App Control Panel implementation described here.--All screens reuse the vibe-remote dark shell: sidebar + `padding:[32,48]` main,-breadcrumb → title → toolbar → content; tokens `$--background`, `$--card`,-`$--mint` primary, `$--muted`, with Inter body / JetBrains Mono for labels and-identifiers. A reusable **`OrgSidebar`** component provides the Overview /-Members / Groups / Instances / Resources sub-navigation with the Organization-switcher on top and a Cloud-connection status box at the bottom.--### Screen inventory--Pages (8):--| Screen | Route |-| --- | --- |-| Overview | `/overview` |-| Members | `/members` |-| Groups | `/groups` |-| Group detail | `/groups/:groupId` |-| Instances | `/instances` |-| Instance access | `/instances/:instanceId/access` |-| Instance projects | `/instances/:instanceId/projects` |-| Resources | `/resources` |--Modals & confirmations (10): Invite member; Edit member; Remove member-(confirm); New group; Edit group; Archive group (confirm); Instance access-entry; Project access editor; Resource ACL editor; Resource ACL · Selected-groups variant.--States & reference (12): Cloud not connected; Sign-in required (PKCE step-up);-Reauthorizing; Cloud unreachable; Access revoked; Cloud account does not match-(subject mismatch); Loading (skeleton); Empty; Member-safe overview; Validation-error; Revision conflict; Policy sync states reference.--### Resolved-decision traceability--| # | Resolved decision | Where it shows in the mockups |-| --- | --- | --- |-| 1 | Identity gate, not administrator gate | Sign-in required is an identity step-up; Member-safe overview shows a non-manager view without a directory |-| 2 | Member/group optimistic concurrency | Revision conflict state (`if_match` / `409`, draft kept for comparison; same pattern applies to member/group) |-| 3 | Owner-only first-class Project choice | Project access editor exposes Inherit / Restricted / Owner-only; Restricted always shows ≥1 binding |-| 4 | Selected-group Resource `group_ids` | Resource ACL · Selected groups variant with a group multi-select and `group_ids` payload note |-| 5 | Member-safe hides Resource composition | Resources page is owner/admin-only; Member-safe overview lists only the caller's own usable resources |-| 6 | Worst-active-child sync + empty set | Policy sync states reference includes In sync / Applying / Offline / Error / Deleted / **No policies** |-| 7 | Silent reauthorization single attempt | Reauthorizing state framed as an automatic one-shot |-| 8 | Subject mismatch terminal state | Dedicated "Cloud account does not match" state using the specified title/body copy |--### Known non-blocking mockup gaps--- No standalone member/group revision-conflict dialog; the project/resource- conflict screen demonstrates the identical pattern.-- The Member-safe overview sidebar shows the manager-only Resources item in a- normal inactive style rather than an explicitly gated/hidden treatment.diff --git a/docs/plans/2026-08-18-current-instance-permissions.md b/docs/plans/2026-08-18-current-instance-permissions.mdnew file mode 100644index 000000000..0f4123a2a--- /dev/null+++ b/docs/plans/2026-08-18-current-instance-permissions.md@@ -0,0 +1,78 @@+# Current-instance Permissions++## Background++Issue #1507 replaces the embedded Organization administration surface with a+Permissions page for exactly the paired Avibe instance. Backend PR #239 is the+wire authority; this implementation targets its merged head+`8bf0024d87d1cb6a64be31b8a8068e89162a9153`.++## Contract++The browser calls only same-origin routes:++- `GET /api/permissions`+- `PUT /api/permissions/authorized-users`+- `PUT /api/permissions/projects/{project_id}/access`++The local service obtains `backend_url`, `instance_id`, and `instance_secret`+from `V2Config.remote_access.vibe_cloud.runtime_credentials()`. It never accepts+an instance or Organization identifier from the browser. Server-to-server calls+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`++Reads require the existing authenticated instance session. Mutations require+`AuthorizationContext.can_manage_instance` both in the central HTTP policy and+again in the handler. Backend `local_mutation_allowed` remains an independent+write gate for Cloud-owned policy.++## State Model++- Live instance-managed: owner-capable sessions can edit users/groups and+ Project policy with explicit revisions.+- Live Cloud-managed: readable but locally immutable; the only handoff is an+ ordinary Avibe Cloud link, never Management OAuth.+- Offline: a sanitized last-known projection, bound to the exact paired+ instance ID, may be served only after connectivity or Backend availability+ failures. Credentials are never cached.+- 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.+- Denied: session authorization and paired-credential failures are not treated+ as offline or empty data.+- Empty: a successful live projection with no access entries or Projects is a+ real empty state.++## Implementation++- Add a cohesive paired-instance Permissions client/cache and narrow UI routes.+- Add neutral frontend authorization types, API client, and a two-tab+ Permissions page.+- Show Permissions immediately above Advanced Settings on desktop and mobile+ for Personal and Organization instances.+- Preserve #1498 local Show Page Private/Limited/Public policy while removing+ the independent Cloud Management OAuth/resource-proxy control.+- 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.++## Verification++- Focused Python API/client/cache tests and authorization policy tests.+- Focused Vitest coverage for navigation, authority, offline, applying, denied,+ empty, and draft-preserving conflict behavior.+- 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+ Incus regression without resetting pairing or product state.++## Non-goals++- Organization switching or member/group administration.+- Managing another instance or accepting a caller-selected target.+- 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.diff --git a/tests/scenario_harness/organization_management.py b/tests/scenario_harness/organization_management.pydeleted file mode 100644index e0ae388e4..000000000--- a/tests/scenario_harness/organization_management.py+++ /dev/null@@ -1,91 +0,0 @@-from __future__ import annotations--import os-import tempfile-from pathlib import Path-from unittest.mock import patch--from config.v2_config import (- AgentsConfig,- PlatformsConfig,- RemoteAccessConfig,- RuntimeConfig,- SlackConfig,- UiConfig,- V2Config,-)-from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie-from vibe import cloud_management, remote_access-from vibe.ui_server import app---REMOTE_ORIGIN = "https://alex.avibe.bot"---class OrganizationManagementScenarioHarness:- """Hermetic browser harness for the Cloud management authorization flow."""-- def __init__(self) -> None:- self._tempdir = tempfile.TemporaryDirectory()- self._environment = patch.dict(- os.environ,- {"AVIBE_HOME": str(Path(self._tempdir.name) / "avibe-home")},- )- self._environment.start()- cloud_management.reset_for_tests()- self.config = self._save_config()-- def _save_config(self) -> V2Config:- config = V2Config(- mode="self_host",- version="v2",- platform="slack",- platforms=PlatformsConfig(enabled=["slack"], primary="slack"),- slack=SlackConfig(bot_token=""),- runtime=RuntimeConfig(default_cwd="."),- agents=AgentsConfig(),- ui=UiConfig(),- remote_access=RemoteAccessConfig(),- )- cloud = config.remote_access.vibe_cloud- cloud.enabled = True- cloud.backend_url = "https://avibe.bot"- cloud.public_url = REMOTE_ORIGIN- cloud.client_id = "vr_client_123"- cloud.instance_id = "inst_123"- cloud.session_secret = "scenario-session-secret"- cloud.issuer = "https://avibe.bot"- cloud.jwks_uri = "https://avibe.bot/.well-known/jwks.json"- cloud.authorization_endpoint = "https://avibe.bot/oauth/authorize"- cloud.token_endpoint = "https://avibe.bot/oauth/token"- cloud.redirect_uri = f"{REMOTE_ORIGIN}/auth/callback"- config.save()- return config-- def remote_client(self, *, subject: str = "user-1", role: str = "viewer"):- client = app.test_client()- cookie = remote_session_cookie(- self.config,- "[email protected]",- subject,- role=role,- access_source="email",- )- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- cookie,- domain="alex.avibe.bot",- )- return client-- def unbound_remote_client(self):- return app.test_client()-- @staticmethod- def csrf(client, origin: str = REMOTE_ORIGIN) -> dict[str, str]:- return csrf_headers(client, origin)-- def close(self) -> None:- cloud_management.reset_for_tests()- self._environment.stop()- self._tempdir.cleanup()diff --git a/tests/scenario_harness/permissions.py b/tests/scenario_harness/permissions.pynew file mode 100644index 000000000..9d56b1335--- /dev/null+++ b/tests/scenario_harness/permissions.py@@ -0,0 +1,256 @@+from __future__ import annotations++from copy import deepcopy+import os+from pathlib import Path+import tempfile+from unittest.mock import patch+from urllib.parse import urlsplit++import requests++from config.v2_config import (+ AgentsConfig,+ PlatformsConfig,+ RemoteAccessConfig,+ RuntimeConfig,+ SlackConfig,+ UiConfig,+ V2Config,+)+from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie+from vibe import permissions, remote_access+from vibe.ui_server import app+++REMOTE_ORIGIN = "https://permissions.avibe.bot"+++class _BackendResponse:+ def __init__(self, status: int, payload: dict):+ self.status_code = status+ self._payload = deepcopy(payload)+ self.ok = 200 <= status < 300++ def json(self) -> dict:+ return deepcopy(self._payload)+++class PermissionsScenarioHarness:+ """Closed-loop browser/local-service harness for current-instance Permissions."""++ def __init__(self) -> None:+ self._tempdir = tempfile.TemporaryDirectory()+ self._environment = patch.dict(+ os.environ,+ {"AVIBE_HOME": str(Path(self._tempdir.name) / "avibe-home")},+ )+ self._environment.start()+ self.config = self._save_config()+ self.backend_available = True+ self.backend_requests: list[dict] = []+ self.projection = self._projection()+ self._backend_patch = patch.object(+ permissions.requests,+ "request",+ side_effect=self._backend_request,+ )+ self._backend_patch.start()++ def _save_config(self) -> V2Config:+ config = V2Config(+ mode="self_host",+ version="v2",+ platform="slack",+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ui=UiConfig(),+ remote_access=RemoteAccessConfig(),+ )+ cloud = config.remote_access.vibe_cloud+ cloud.enabled = True+ cloud.backend_url = "https://backend.example"+ cloud.public_url = REMOTE_ORIGIN+ cloud.client_id = "permissions-client"+ cloud.instance_id = "inst-current"+ cloud.instance_secret = "paired-device-secret"+ cloud.session_secret = "permissions-session-secret"+ cloud.issuer = "https://backend.example"+ cloud.jwks_uri = "https://backend.example/.well-known/jwks.json"+ cloud.authorization_endpoint = "https://backend.example/oauth/authorize"+ cloud.token_endpoint = "https://backend.example/oauth/token"+ cloud.redirect_uri = f"{REMOTE_ORIGIN}/auth/callback"+ config.save()+ return config++ @staticmethod+ def _projection() -> dict:+ return {+ "schema_version": 1,+ "instance": {+ "id": "inst-current",+ "access_mode": "allowlist",+ "permission_authority": "instance",+ "local_mutation_allowed": True,+ "authorization_revision": 0,+ },+ "capabilities": [+ "instance.permissions.read",+ "instance.permissions.mutate",+ ],+ "access": {+ "owner": {"email": "[email protected]", "role": "owner"},+ "entries": [],+ },+ "directory": {+ "members": [+ {+ "id": "member-1",+ "email": "[email protected]",+ "organization_role": "member",+ "group_ids": ["group-1"],+ }+ ],+ "groups": [{"id": "group-1", "name": "Design", "archived_at": None}],+ },+ "projects": [+ {+ "project_id": "project-1",+ "organization_id": "org-1",+ "display_name": "Launch Plan",+ "access": {"mode": "inherit", "revision": 0, "bindings": []},+ "sync": {+ "status": "in_sync",+ "desired_access_revision": 0,+ "applied_access_revision": 0,+ "last_synced_at": None,+ },+ }+ ],+ "policy_sync": {+ "status": "in_sync",+ "projects": {+ "active": 1,+ "error": 0,+ "offline": 0,+ "applying": 0,+ "in_sync": 1,+ },+ "resources": {+ "active": 0,+ "error": 0,+ "offline": 0,+ "applying": 0,+ "in_sync": 0,+ },+ },+ }++ def _backend_request(self, method: str, url: str, **kwargs):+ request_record = {+ "method": method,+ "url": url,+ "json": deepcopy(kwargs.get("json")),+ "headers": dict(kwargs.get("headers") or {}),+ }+ self.backend_requests.append(request_record)+ if not self.backend_available:+ raise requests.ConnectionError("scenario backend offline")+ expected_prefix = "https://backend.example/api/v1/instances/inst-current/permissions"+ if not url.startswith(expected_prefix):+ return _BackendResponse(403, {"error": "instance_credential_mismatch"})+ if request_record["headers"].get("X-Vibe-Device-Secret") != "paired-device-secret":+ return _BackendResponse(401, {"error": "invalid_device_secret"})+ path = urlsplit(url).path+ if method == "GET" and path.endswith("/permissions"):+ return _BackendResponse(200, self.projection)+ if self.projection["instance"]["permission_authority"] == "cloud":+ return _BackendResponse(403, {"error": "permission_authority_cloud"})+ payload = request_record["json"] or {}+ if method == "PUT" and path.endswith("/permissions/authorized-users"):+ current = self.projection["instance"]["authorization_revision"]+ if payload.get("if_match_revision") != current:+ return _BackendResponse(+ 409,+ {"error": "permission_revision_conflict", "current_revision": current},+ )+ self.projection["access"]["entries"] = deepcopy(payload.get("entries", []))+ self.projection["instance"]["authorization_revision"] = current + 1+ return _BackendResponse(+ 200,+ {+ "ok": True,+ "entries": self.projection["access"]["entries"],+ "authorization_revision": current + 1,+ },+ )+ if method == "PUT" and "/permissions/projects/" in path and path.endswith("/access"):+ project = self.projection["projects"][0]+ current = project["access"]["revision"]+ if payload.get("if_match_revision") != current:+ return _BackendResponse(+ 409,+ {"error": "permission_revision_conflict", "current_revision": current},+ )+ next_revision = current + 1+ project["access"] = {+ "mode": payload.get("mode"),+ "revision": next_revision,+ "bindings": deepcopy(payload.get("bindings", [])),+ }+ project["sync"].update(+ {+ "status": "pending",+ "desired_access_revision": next_revision,+ }+ )+ self.projection["policy_sync"]["status"] = "applying"+ self.projection["instance"]["authorization_revision"] += 1+ return _BackendResponse(+ 200,+ {+ "ok": True,+ "project": project,+ "authorization_revision": self.projection["instance"]["authorization_revision"],+ },+ )+ return _BackendResponse(404, {"error": "project_not_found"})++ def acknowledge_project(self) -> None:+ project = self.projection["projects"][0]+ project["sync"]["status"] = "in_sync"+ project["sync"]["applied_access_revision"] = project["sync"]["desired_access_revision"]+ self.projection["policy_sync"]["status"] = "in_sync"++ @staticmethod+ def local_client():+ return app.test_client()++ def remote_client(self, role: str = "owner"):+ client = app.test_client()+ cookie = remote_session_cookie(+ self.config,+ f"{role}@example.com",+ f"subject-{role}",+ session_claims={+ "vibe_instance_id": "inst-current",+ "vibe_instance_role": role,+ "vibe_instance_access_source": "owner" if role == "owner" else "email",+ "vibe_instance_authorization_revision": self.projection["instance"][+ "authorization_revision"+ ],+ },+ )+ client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="permissions.avibe.bot")+ return client++ @staticmethod+ def csrf(client, origin: str = "http://127.0.0.1") -> dict[str, str]:+ return csrf_headers(client, origin)++ def close(self) -> None:+ self._backend_patch.stop()+ self._environment.stop()+ self._tempdir.cleanup()diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 603540a77..9d59312e2 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -158,7 +158,19 @@ capabilities:- tests/test_claude_agent_sessions.pyunit_or_contract_tests:- tests/test_agent_auth_service.py- - tests/test_cloud_management.py+ - id: current_instance_permissions+ name: Current-instance Permissions policy and authority+ status: active+ catalog: tests/scenarios/permissions/catalog.yaml+ observations: tests/scenarios/permissions/observations.yaml+ scenario_tests:+ - tests/scenarios/permissions/test_permissions_scenarios.py+ harness:+ - tests/scenario_harness/permissions.py+ unit_or_contract_tests:+ - tests/test_permissions.py+ - ui/src/features/permissions/PermissionsPage.test.tsx+ - ui/src/components/workbench/ShowPageSharingSettings.test.tsx- id: message_deliveryname: scheduled result deliverystatus: activediff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 9589ad1dc..7c671576c 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -169,76 +169,6 @@ scenarios:layer: scenariobackend: webtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_remote_web_oauth_cold_launch_retry_is_single_owner- - id: AUTH-SETUP-301- name: Explicit Organization management sign-in starts an interactive handoff- status: covered- kind: happy_path- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_explicit_management_sign_in_starts_interactive_handoff- - id: AUTH-SETUP-302- name: Silent Organization reauthorization is attempted only once- status: covered- kind: retry- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_silent_reauthorization_stops_after_login_required- - id: AUTH-SETUP-303- name: Explicit Organization logout suppresses silent reauthorization- status: covered- kind: teardown- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_logout_suppresses_silent_reauthorization- - id: AUTH-SETUP-304- name: Organization management subject mismatch is terminal- status: covered- kind: negative_path- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_subject_mismatch_is_terminal- - id: AUTH-SETUP-305- name: Invalid Organization callback state code or token requires manual sign-in- status: covered- kind: negative_path- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_invalid_callback_token_requires_manual_sign_in- - id: AUTH-SETUP-306- name: Missing Cloud session or login_required requires explicit sign-in- status: covered- kind: negative_path- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_silent_reauthorization_stops_after_login_required- - id: AUTH-SETUP-307- name: Remote Organization callback remains subject-bound and returns failures to its workflow- status: covered- kind: authorization- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_remote_callback_keeps_the_bound_subject- - id: AUTH-SETUP-308- name: Trusted loopback Organization login establishes the first subject- status: covered- kind: happy_path- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_trusted_loopback_flow_can_establish_the_first_subject- - id: AUTH-SETUP-309- name: Unbound trusted loopback cannot start silent Organization authorization- status: covered- kind: authorization- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_unbound_loopback_requires_interactive_sign_in- - id: AUTH-SETUP-310- name: Organization subject mismatch can re-enter explicit authorization and return to the initiating workbench route- status: covered- kind: retry- layer: scenario- backend: cloud_management- test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_subject_mismatch_can_reenter_with_workbench_return_path- id: AUTH-SETUP-401name: Exact-email Show Page login stays confined to its signed pagestatus: covereddiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex afb2029d8..77614e636 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -39,15 +39,9 @@ from core.show_pages import ShowPageStorefrom modules.agents.codex.agent import CodexAgentfrom tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcessfrom tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep-from tests.scenario_harness.model_hub_native_oauth import NativeOAuthScenarioHarness-from tests.scenario_harness.organization_management import (- REMOTE_ORIGIN,- OrganizationManagementScenarioHarness,-)from tests.scenario_harness.show_page_email_access import ShowPageEmailAccessScenarioHarnessfrom tests.ui_server_test_helpers import _save_configfrom storage import remote_access_authorization_service-from vibe import cloud_managementfrom tests.scenario_harness.model_hub_native_oauth import (HubOAuthScenarioHarness,NativeOAuthScenarioHarness,@@ -250,286 +244,6 @@ class _CodexProviderBindingSessions:def bind_agent_session(self, *_args, **_kwargs):return "ses-provider"-class OrganizationManagementAuthScenarioTests(unittest.TestCase):- def setUp(self):- self.harness = OrganizationManagementScenarioHarness()- self.addCleanup(self.harness.close)-- @staticmethod- def _authorize_state(authorize_url: str) -> str:- """The `state` the browser was actually handed, read back off its own URL."""- query = urllib.parse.urlparse(authorize_url).query- return urllib.parse.parse_qs(query)["state"][0]-- def test_explicit_management_sign_in_starts_interactive_handoff(self):- """Scenario: AUTH-SETUP-301"""- client = self.harness.remote_client()- with patch.object(- cloud_management,- "begin_authorization",- return_value=("https://avibe.bot/oauth/management/authorize?state=state-1", "state-1"),- ) as begin:- response = client.post(- "/api/cloud-management/session/start",- json={"mode": "interactive", "next": "/admin/organization/members"},- headers=self.harness.csrf(client),- base_url=REMOTE_ORIGIN,- )-- self.assertEqual(response.status_code, 202)- self.assertEqual(response.get_json()["mode"], "interactive")- begin.assert_called_once()- self.assertFalse(begin.call_args.kwargs["silent"])- self.assertEqual(begin.call_args.kwargs["remote_subject"], "user-1")-- def test_silent_reauthorization_stops_after_login_required(self):- """Scenarios: AUTH-SETUP-302, AUTH-SETUP-306"""- client = self.harness.remote_client()- # The real handshake store, not a stub: the callback only tears a browser's- # session down when it proves it belongs to that browser's own live- # handshake, so a stubbed `begin_authorization` that registers nothing would- # exercise a forged callback rather than this browser's failed silent retry.- with patch.object(- cloud_management,- "begin_authorization",- wraps=cloud_management.begin_authorization,- ) as begin:- first = client.post(- "/api/cloud-management/session/start",- json={"mode": "silent", "next": "/admin/organization/overview"},- headers=self.harness.csrf(client),- base_url=REMOTE_ORIGIN,- )- self.assertEqual(first.status_code, 202)- self.assertTrue(begin.call_args.kwargs["silent"])- state = self._authorize_state(first.get_json()["authorize_url"])-- callback = client.get(- f"/auth/organization/callback?error=login_required&state={state}",- base_url=REMOTE_ORIGIN,- )- self.assertEqual(callback.status_code, 302)- self.assertIn("cloud_management_error=login_required", callback.headers["location"])-- second = client.post(- "/api/cloud-management/session/start",- json={"mode": "silent", "next": "/admin/organization/overview"},- headers=self.harness.csrf(client),- base_url=REMOTE_ORIGIN,- )- self.assertEqual(second.status_code, 401)-- def test_logout_suppresses_silent_reauthorization(self):- """Scenario: AUTH-SETUP-303"""- client = self.harness.remote_client()- client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- logout = client.delete(- "/api/cloud-management/session",- headers=self.harness.csrf(client),- base_url=REMOTE_ORIGIN,- )- self.assertEqual(logout.status_code, 200)- session = client.get("/api/cloud-management/session", base_url=REMOTE_ORIGIN)- self.assertEqual(session.status_code, 200)- self.assertFalse(session.get_json()["can_silent_reauthorize"])-- def test_subject_mismatch_is_terminal(self):- """Scenario: AUTH-SETUP-304"""- client = self.harness.remote_client()- client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- with patch.object(- cloud_management,- "resolve_grant",- return_value=(None, "cloud_management_subject_mismatch"),- ):- response = client.get("/api/cloud-management/session", base_url=REMOTE_ORIGIN)- self.assertEqual(response.status_code, 409)- self.assertEqual(response.get_json()["state"], "subject_mismatch")-- def test_invalid_callback_token_requires_manual_sign_in(self):- """Scenario: AUTH-SETUP-305"""- client = self.harness.remote_client()- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- # A real handshake for this browser: the token exchange has to fail on a- # flow the browser actually started, otherwise this asserts what a forged- # cross-site callback does rather than what a broken sign-in does.- _, 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,- )- with patch.object(- cloud_management,- "complete_authorization",- side_effect=cloud_management.CloudManagementError(- "invalid_cloud_management_token",- status=400,- ),- ):- response = client.get(- f"/auth/organization/callback?code=bad-code&state={state}",- base_url=REMOTE_ORIGIN,- )- self.assertEqual(response.status_code, 302)- self.assertIn("cloud_management_error=invalid_cloud_management_token", response.headers["location"])- session = client.get("/api/cloud-management/session", base_url=REMOTE_ORIGIN)- self.assertFalse(session.get_json()["can_silent_reauthorize"])-- def test_remote_callback_keeps_the_bound_subject(self):- """Scenario: AUTH-SETUP-307"""- backend = SimpleNamespace(base_url="https://avibe.bot")- next_path = "/chat/session-1?tab=show-page"- 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=next_path,- silent=False,- )- client = self.harness.remote_client(subject="user-2")- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- 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(- f"/auth/organization/callback?code=code-1&state={state}",- base_url=REMOTE_ORIGIN,- )- self.assertEqual(response.status_code, 302)- self.assertEqual(- response.headers["location"],- f"{next_path}&cloud_management_error=cloud_management_subject_mismatch",- )- self.assertNotIn("not-exposed", response.text)-- def test_trusted_loopback_flow_can_establish_the_first_subject(self):- """Scenario: AUTH-SETUP-308"""- client = self.harness.unbound_remote_client()- 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="first-user",- 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:- response = client.get(- "/auth/organization/callback?code=code-1&state=state-1",- base_url=REMOTE_ORIGIN,- )- self.assertEqual(response.status_code, 302)- self.assertIsNone(complete.call_args.kwargs["remote_subject"])-- def test_unbound_loopback_requires_interactive_sign_in(self):- """Scenario: AUTH-SETUP-309"""- client = self.harness.unbound_remote_client()- loopback_origin = "http://127.0.0.1:15131"-- session = client.get("/api/cloud-management/session", base_url=loopback_origin)- silent = client.post(- "/api/cloud-management/session/start",- json={"mode": "silent", "next": "/admin/organization/overview"},- headers=self.harness.csrf(client, loopback_origin),- base_url=loopback_origin,- )-- self.assertEqual(session.status_code, 200)- self.assertFalse(session.get_json()["can_silent_reauthorize"])- self.assertEqual(silent.status_code, 401)- self.assertEqual(- silent.get_json(),- {- "error": "cloud_management_authorization_required",- "retryable": False,- },- )-- def test_subject_mismatch_can_reenter_with_workbench_return_path(self):- """Scenario: AUTH-SETUP-310"""- client = self.harness.remote_client()- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- with patch.object(- cloud_management,- "complete_authorization",- side_effect=cloud_management.CloudManagementError(- "cloud_management_subject_mismatch",- status=409,- ),- ):- mismatch = client.get(- "/auth/organization/callback?code=wrong-user&state=state-1",- base_url=REMOTE_ORIGIN,- )-- self.assertEqual(mismatch.status_code, 302)- self.assertIn(- "cloud_management_error=cloud_management_subject_mismatch",- mismatch.headers["location"],- )-- clean_next = "/chat/session-1?tab=show-page"- with patch.object(- cloud_management,- "begin_authorization",- return_value=("https://avibe.bot/oauth/management/authorize?state=state-2", "state-2"),- ) as begin:- reentry = client.post(- "/api/cloud-management/session/start",- json={"mode": "interactive", "next": clean_next},- headers=self.harness.csrf(client),- base_url=REMOTE_ORIGIN,- )-- self.assertEqual(reentry.status_code, 202)- self.assertEqual(begin.call_args.kwargs["next_path"], clean_next)-- grant = cloud_management.ManagementGrant(- handle="grant-2",- 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, clean_next),- ):- success = client.get(- "/auth/organization/callback?code=right-user&state=state-2",- base_url=REMOTE_ORIGIN,- )-- self.assertEqual(success.status_code, 302)- self.assertEqual(success.headers["location"], clean_next)- self.assertNotIn("cloud_management_error", success.headers["location"])class _ReloadingV2ConfigController:diff --git a/tests/scenarios/permissions/catalog.yaml b/tests/scenarios/permissions/catalog.yamlnew file mode 100644index 000000000..5bc1d3f13--- /dev/null+++ b/tests/scenarios/permissions/catalog.yaml@@ -0,0 +1,103 @@+version: 1+capability:+ id: current_instance_permissions+ name: Current-instance Permissions policy and authority+ canonical_tests:+ - tests/scenarios/permissions/test_permissions_scenarios.py+ - tests/test_permissions.py+status_legend:+ covered: scenario coverage exists+ partial: unit or contract coverage exists but the closed loop is incomplete+ manual: currently validated only by human regression+ gap: not covered yet+scenarios:+ - id: PERMISSIONS-001+ name: Trusted-local owner enters Permissions without Cloud OAuth+ status: covered+ kind: happy_path+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_001_002_existing_sessions_enter_without_management_oauth+ given: The local owner session and paired instance credential are current+ when: The owner opens the same-origin Permissions API+ then: The current-instance projection is returned without any management OAuth route+ - id: PERMISSIONS-002+ name: Remote OIDC owner enters Permissions without Cloud OAuth+ status: covered+ kind: happy_path+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_001_002_existing_sessions_enter_without_management_oauth+ given: A current remote OIDC owner session is established+ when: The owner opens Permissions+ then: The same current-instance projection is returned without a second login+ - id: PERMISSIONS-003+ name: Viewer reads policy but mutation fails before Backend contact+ status: covered+ kind: authorization+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_003_viewer_mutation_fails_before_backend_contact+ given: A remote Viewer has a current instance session+ when: The Viewer reads and then attempts to mutate authorized users+ then: Read succeeds and mutation is denied before the paired Backend client runs+ - id: PERMISSIONS-004+ name: Instance-managed policy writes advance authorization revision+ status: covered+ kind: mutation+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_004_instance_managed_write_advances_revision+ given: The current instance owns policy at revision zero+ when: The owner replaces current-instance authorized users+ then: The exact projection changes and authorization revision advances atomically+ - id: PERMISSIONS-005+ name: Cloud-managed policy remains readable and locally read-only+ status: covered+ kind: authorization+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_005_cloud_authority_is_readable_and_read_only+ given: Avibe Cloud owns the current-instance policy+ when: The owner reads and then attempts a paired write+ then: Read succeeds and Backend returns permission_authority_cloud for the write+ - id: PERMISSIONS-006+ name: Offline state serves exact-instance last-known policy+ status: covered+ kind: recovery+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_006_offline_uses_bound_cached_projection+ given: A live projection has been cached for the paired instance+ when: Backend connectivity is lost+ then: The same projection is returned as cached and offline with writes disabled by the UI contract+ - id: PERMISSIONS-007+ name: Project applying state converges after acknowledgement+ status: covered+ kind: convergence+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_007_project_write_applies_then_acknowledges+ given: A published Project is in sync+ when: The owner writes a newer restricted access revision and the instance acknowledges it+ then: The committed response is pending and the next projection converges to in_sync+ - id: PERMISSIONS-008+ name: Revision conflict returns current revision without changing policy+ status: covered+ kind: concurrency+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_008_conflict_is_stable_and_non_mutating+ given: The authoritative instance revision is newer than the browser draft+ when: The owner submits the stale revision+ then: The API returns permission_revision_conflict and current_revision without mutation+ - id: PERMISSIONS-009+ name: Browser cannot inject another target instance+ status: covered+ kind: authorization+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_009_target_injection_is_rejected_before_backend_contact+ given: The browser is authorized for the paired current instance+ when: A mutation body includes another instance identifier+ then: The local API rejects it before Backend contact and all live requests remain exact-instance bound+ - id: PERMISSIONS-010+ name: Old Organization and Show Page Cloud-management paths are absent+ status: covered+ kind: retirement+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_010_legacy_management_surfaces_are_absent+ given: Current-instance Permissions and local Show Page sharing are installed+ when: Registered routes and frontend sources are inventoried+ then: No Management OAuth proxy or embedded Organization route remainsdiff --git a/tests/scenarios/permissions/observations.yaml b/tests/scenarios/permissions/observations.yamlnew file mode 100644index 000000000..a31f9c751--- /dev/null+++ b/tests/scenarios/permissions/observations.yaml@@ -0,0 +1,31 @@+version: 1+capability: current_instance_permissions+observations:+ - id: OBS-PERMISSIONS-001+ source: issue_contract+ related_scenarios:+ - PERMISSIONS-001+ - PERMISSIONS-002+ - PERMISSIONS-003+ - PERMISSIONS-009+ summary: Permissions authority is the existing Avibe session plus the paired exact-instance credential, not a second Cloud user session.+ previous_assumption: Embedded Organization management needed a browser-held Management OAuth grant.+ observed_behavior: Backend now accepts a device-secret capability bound to exactly one instance and independently enforces policy authority.+ required_updates:+ - never accept target instance or Organization identifiers from the browser+ - require owner or can_manage_instance before paired mutations+ - remove Management OAuth cookies callbacks and proxy routes+ - id: OBS-PERMISSIONS-002+ source: issue_contract+ related_scenarios:+ - PERMISSIONS-005+ - PERMISSIONS-006+ - PERMISSIONS-007+ - PERMISSIONS-008+ summary: Authority connectivity convergence and conflict are separate user-visible states.+ previous_assumption: A failed Cloud request could collapse to one generic empty or login-required state.+ observed_behavior: Cloud-owned policy is readable, offline uses last-known exact-instance data, applying waits for acknowledgement, and conflict retains the draft for explicit retry.+ required_updates:+ - cache only sanitized successful projections bound to the paired instance+ - never mask credential or authorization failures with cached policy+ - keep revisions explicit on every mutationdiff --git a/tests/scenarios/permissions/test_permissions_scenarios.py b/tests/scenarios/permissions/test_permissions_scenarios.pynew file mode 100644index 000000000..299a340c9--- /dev/null+++ b/tests/scenarios/permissions/test_permissions_scenarios.py@@ -0,0 +1,191 @@+from __future__ import annotations++from pathlib import Path++import pytest++from tests.scenario_harness.permissions import PermissionsScenarioHarness, REMOTE_ORIGIN+from vibe.ui_server import app+++def harness():+ value = PermissionsScenarioHarness()+ try:+ yield value+ finally:+ value.close()+++def test_permissions_001_002_existing_sessions_enter_without_management_oauth(harness) -> None:+ """Scenarios: PERMISSIONS-001, PERMISSIONS-002."""+ local = harness.local_client().get("/api/permissions")+ remote = harness.remote_client("owner").get(+ "/api/permissions",+ base_url=REMOTE_ORIGIN,+ )++ assert local.status_code == 200+ assert remote.status_code == 200+ assert local.get_json()["projection"]["instance"]["id"] == "inst-current"+ assert remote.get_json()["projection"]["instance"]["id"] == "inst-current"+ assert all("oauth" not in request["url"] for request in harness.backend_requests)+++def test_permissions_003_viewer_mutation_fails_before_backend_contact(harness) -> None:+ """Scenario: PERMISSIONS-003."""+ viewer = harness.remote_client("viewer")+ read = viewer.get("/api/permissions", base_url=REMOTE_ORIGIN)+ before = len(harness.backend_requests)+ write = viewer.put(+ "/api/permissions/authorized-users",+ json={"entries": [], "if_match_revision": 0},+ headers=harness.csrf(viewer, REMOTE_ORIGIN),+ base_url=REMOTE_ORIGIN,+ )++ assert read.status_code == 200+ assert write.status_code == 403+ assert write.get_json()["error"] == "instance_access_forbidden"+ assert len(harness.backend_requests) == before+++def test_permissions_004_instance_managed_write_advances_revision(harness) -> None:+ """Scenario: PERMISSIONS-004."""+ client = harness.local_client()+ response = client.put(+ "/api/permissions/authorized-users",+ json={+ "entries": [{"kind": "email", "value": "[email protected]", "role": "editor"}],+ "if_match_revision": 0,+ },+ headers=harness.csrf(client),+ )++ assert response.status_code == 200+ assert response.get_json()["authorization_revision"] == 1+ assert harness.projection["access"]["entries"][0]["role"] == "editor"+ assert harness.projection["instance"]["authorization_revision"] == 1+++def test_permissions_005_cloud_authority_is_readable_and_read_only(harness) -> None:+ """Scenario: PERMISSIONS-005."""+ harness.projection["instance"].update(+ {"permission_authority": "cloud", "local_mutation_allowed": False}+ )+ harness.projection["capabilities"] = ["instance.permissions.read"]+ client = harness.local_client()+ read = client.get("/api/permissions")+ write = client.put(+ "/api/permissions/authorized-users",+ json={"entries": [], "if_match_revision": 0},+ headers=harness.csrf(client),+ )++ assert read.status_code == 200+ assert read.get_json()["projection"]["instance"]["permission_authority"] == "cloud"+ assert write.status_code == 403+ assert write.get_json()["error"] == "permission_authority_cloud"+++def test_permissions_006_offline_uses_bound_cached_projection(harness) -> None:+ """Scenario: PERMISSIONS-006."""+ client = harness.local_client()+ live = client.get("/api/permissions")+ harness.backend_available = False+ cached = client.get("/api/permissions")++ assert live.get_json()["source"] == "live"+ assert cached.status_code == 200+ assert cached.get_json()["source"] == "cache"+ assert cached.get_json()["offline"] is True+ assert cached.get_json()["projection"] == live.get_json()["projection"]+++def test_permissions_007_project_write_applies_then_acknowledges(harness) -> None:+ """Scenario: PERMISSIONS-007."""+ client = harness.local_client()+ write = client.put(+ "/api/permissions/projects/project-1/access",+ json={+ "mode": "restricted",+ "bindings": [+ {+ "principal_kind": "organization_group",+ "principal_value": "group-1",+ "access_role": "viewer",+ }+ ],+ "if_match_revision": 0,+ },+ headers=harness.csrf(client),+ )+ assert write.status_code == 200+ assert write.get_json()["project"]["sync"]["status"] == "pending"+ assert write.get_json()["authorization_revision"] == 1++ harness.acknowledge_project()+ current = client.get("/api/permissions")+ assert current.get_json()["projection"]["projects"][0]["sync"]["status"] == "in_sync"+ assert current.get_json()["projection"]["projects"][0]["sync"]["applied_access_revision"] == 1+++def test_permissions_008_conflict_is_stable_and_non_mutating(harness) -> None:+ """Scenario: PERMISSIONS-008."""+ harness.projection["instance"]["authorization_revision"] = 4+ client = harness.local_client()+ response = client.put(+ "/api/permissions/authorized-users",+ json={+ "entries": [{"kind": "email", "value": "[email protected]", "role": "viewer"}],+ "if_match_revision": 3,+ },+ headers=harness.csrf(client),+ )++ assert response.status_code == 409+ assert response.get_json()["error"] == "permission_revision_conflict"+ assert response.get_json()["current_revision"] == 4+ assert harness.projection["access"]["entries"] == []+++def test_permissions_009_target_injection_is_rejected_before_backend_contact(harness) -> None:+ """Scenario: PERMISSIONS-009."""+ client = harness.local_client()+ before = len(harness.backend_requests)+ response = client.put(+ "/api/permissions/authorized-users",+ json={+ "entries": [+ {+ "kind": "email",+ "value": "[email protected]",+ "role": "viewer",+ "instance_id": "inst-other",+ }+ ],+ "if_match_revision": 0,+ },+ headers=harness.csrf(client),+ )++ assert response.status_code == 422+ assert response.get_json()["error"] == "invalid_request"+ assert len(harness.backend_requests) == before+++def test_permissions_010_legacy_management_surfaces_are_absent() -> None:+ """Scenario: PERMISSIONS-010."""+ route_paths = {route.path for route in app.routes}+ assert not any(path.startswith("/api/cloud-management") for path in route_paths)+ assert "/auth/organization/start" not in route_paths+ assert "/auth/organization/callback" not in route_paths++ root = Path(__file__).resolve().parents[3]+ assert not (root / "vibe" / "cloud_management.py").exists()+ assert not (root / "ui" / "src" / "features" / "organization").exists()+ 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 "ShowPageSharingSettings" in sourcediff --git a/tests/test_cloud_management.py b/tests/test_cloud_management.pydeleted file mode 100644index 123d903b4..000000000--- a/tests/test_cloud_management.py+++ /dev/null@@ -1,799 +0,0 @@-from __future__ import annotations--import http.client-import time-from types import SimpleNamespace--import jwt-import pytest-from cryptography.hazmat.primitives.asymmetric import rsa--from config.v2_config import (- AgentsConfig,- PlatformsConfig,- RemoteAccessConfig,- RuntimeConfig,- SlackConfig,- UiConfig,- V2Config,-)-from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie-from vibe import cloud_management, remote_access, ui_server-from vibe.ui_server import app---REMOTE_ORIGIN = "https://alex.avibe.bot"--[email protected](autouse=True)-def _isolated_management_state() -> None:- cloud_management.reset_for_tests()- yield- cloud_management.reset_for_tests()---def _save_config(monkeypatch: pytest.MonkeyPatch, tmp_path) -> V2Config:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = V2Config(- mode="self_host",- version="v2",- platform="slack",- platforms=PlatformsConfig(enabled=["slack"], primary="slack"),- slack=SlackConfig(bot_token=""),- runtime=RuntimeConfig(default_cwd="."),- agents=AgentsConfig(),- ui=UiConfig(),- remote_access=RemoteAccessConfig(),- )- cloud = config.remote_access.vibe_cloud- cloud.enabled = True- cloud.backend_url = "https://avibe.bot"- cloud.public_url = REMOTE_ORIGIN- cloud.client_id = "vr_client_123"- cloud.instance_id = "inst_123"- cloud.session_secret = "session-secret"- cloud.issuer = "https://avibe.bot"- cloud.jwks_uri = "https://avibe.bot/.well-known/jwks.json"- cloud.authorization_endpoint = "https://avibe.bot/oauth/authorize"- cloud.token_endpoint = "https://avibe.bot/oauth/token"- cloud.redirect_uri = f"{REMOTE_ORIGIN}/auth/callback"- config.save()- return config---def _remote_client(config: V2Config, *, role: str = "viewer"):- client = app.test_client()- cookie = remote_session_cookie(- config,- "[email protected]",- "user-1",- role=role,- access_source="email",- )- client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")- return client---def _grant(browser_id: str = "browser-1", *, subject: str = "user-1") -> cloud_management.ManagementGrant:- return cloud_management.ManagementGrant(- handle="grant-1",- browser_id=browser_id,- subject=subject,- email="[email protected]",- token="secret-bearer-token",- expires_at=time.time() + 300,- )--- ("candidate", "expected"),- [- ("/chat/session-1?tab=show-page", "/chat/session-1?tab=show-page"),- ("/admin/organization/members?tab=access", "/admin/organization/members?tab=access"),- ("https://example.com/chat/session-1", "/admin/organization/overview"),- ("//example.com/chat/session-1", "/admin/organization/overview"),- ("/admin/organization-impersonation", "/admin/organization/overview"),- ("/chat/session-1/extra", "/admin/organization/overview"),- ("/api/show-pages/session-1/access", "/admin/organization/overview"),- ],-)-def test_management_return_path_allows_only_supported_same_origin_workflows(- candidate: str,- expected: str,-) -> None:- assert cloud_management.validate_next_path(candidate) == expected---def test_management_return_path_is_visible_only_to_the_bound_browser(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- backend = SimpleNamespace(base_url="https://avibe.bot")- monkeypatch.setattr(cloud_management, "_validated_backend", lambda _config: backend)- _, state = cloud_management.begin_authorization(- config,- browser_id="browser-1",- remote_subject="user-1",- callback_origin=REMOTE_ORIGIN,- next_path="/chat/session-1?tab=show-page",- silent=False,- )-- assert cloud_management.handshake_next_path(state, "browser-1") == (- "/chat/session-1?tab=show-page"- )- assert cloud_management.handshake_next_path(state, "browser-2") is None- assert cloud_management.handshake_next_path("missing-state", "browser-1") is None---def test_local_start_uses_https_handoff_and_never_exposes_token(monkeypatch, tmp_path) -> None:- _save_config(monkeypatch, tmp_path)- captured: dict[str, object] = {}-- def fake_begin(config, **kwargs):- captured.update(kwargs)- return "https://avibe.bot/oauth/management/authorize?state=state-1", "state-1"-- monkeypatch.setattr(cloud_management, "begin_authorization", fake_begin)- client = app.test_client()- response = client.post(- "/api/cloud-management/session/start",- json={"mode": "interactive", "next": "/admin/organization/members"},- headers=csrf_headers(client, "http://127.0.0.1:15131"),- base_url="http://127.0.0.1:15131",- )-- assert response.status_code == 202- assert response.get_json() == {- "ok": True,- "authorize_url": f"{REMOTE_ORIGIN}/auth/organization/start?state=state-1",- "mode": "interactive",- }- assert captured["remote_subject"] is None- assert captured["callback_origin"] == REMOTE_ORIGIN- assert captured["next_path"] == "/admin/organization/members"- assert "secret-bearer-token" not in response.text- browser_cookie = next(- value- for value in response.headers.getlist("set-cookie")- if value.startswith(f"{cloud_management.BROWSER_COOKIE_NAME}=")- )- assert "HttpOnly" in browser_cookie- assert "Secure" not in browser_cookie---def test_management_cookies_use_trusted_external_https_origin_behind_http_proxy(- monkeypatch, tmp_path-) -> None:- config = _save_config(monkeypatch, tmp_path)- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- forwarded_headers = {- "X-Forwarded-Proto": "https",- "X-Forwarded-Host": "alex.avibe.bot",- "X-Forwarded-For": "203.0.113.10",- }- proxy_base_url = "http://127.0.0.1:5123"- proxy_peer = {"REMOTE_ADDR": "127.0.0.1"}- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(- config,- "[email protected]",- "user-1",- role="viewer",- access_source="email",- ),- domain="127.0.0.1",- )- headers = csrf_headers(client, proxy_base_url)- headers.update(forwarded_headers)- headers["Origin"] = REMOTE_ORIGIN- monkeypatch.setattr(- cloud_management,- "begin_authorization",- lambda *args, **kwargs: (- "https://avibe.bot/oauth/management/authorize?state=state-1",- "state-1",- ),- )-- start = client.post(- "/api/cloud-management/session/start",- json={"mode": "interactive"},- headers=headers,- base_url=proxy_base_url,- environ_base=proxy_peer,- )-- assert start.status_code == 202- start_cookies = start.headers.getlist("set-cookie")- assert any(- value.startswith(f"{cloud_management.BROWSER_COOKIE_NAME}=") and "Secure" in value- for value in start_cookies- )- assert any(- value.startswith(f"{cloud_management.MANUAL_COOKIE_NAME}=") and "Secure" in value- for value in start_cookies- )-- client.set_cookie(- cloud_management.BROWSER_COOKIE_NAME,- "browser-1",- domain="127.0.0.1",- )- monkeypatch.setattr(- cloud_management,- "complete_authorization",- lambda *args, **kwargs: (_grant(), "/admin/organization/overview"),- )- callback = client.get(- "/auth/organization/callback?code=code-1&state=state-1",- headers=forwarded_headers,- base_url=proxy_base_url,- environ_base=proxy_peer,- )-- assert callback.status_code == 302- callback_cookies = callback.headers.getlist("set-cookie")- for name in (- cloud_management.HANDLE_COOKIE_NAME,- cloud_management.BROWSER_COOKIE_NAME,- cloud_management.MANUAL_COOKIE_NAME,- ):- assert any(- value.startswith(f"{name}=") and "Secure" in value- for value in callback_cookies- )---def test_remote_callback_binds_same_remote_subject(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- client = _remote_client(config)- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- captured: dict[str, object] = {}-- def fake_complete(config, **kwargs):- captured.update(kwargs)- return _grant(), "/admin/organization/overview"-- monkeypatch.setattr(cloud_management, "complete_authorization", fake_complete)- response = client.get(- "/auth/organization/callback?code=code-1&state=state-1",- base_url=REMOTE_ORIGIN,- )-- assert response.status_code == 302- assert response.headers["location"].endswith("/admin/organization/overview")- assert captured["remote_subject"] == "user-1"- assert captured["browser_id"] == "browser-1"- handle_cookie = next(- value- for value in response.headers.getlist("set-cookie")- if value.startswith(f"{cloud_management.HANDLE_COOKIE_NAME}=")- )- assert "HttpOnly" in handle_cookie- assert "Secure" in handle_cookie---def test_subject_mismatch_is_terminal_and_clears_grant(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- client = _remote_client(config)- client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- monkeypatch.setattr(- cloud_management,- "resolve_grant",- lambda *args, **kwargs: (None, "cloud_management_subject_mismatch"),- )-- response = client.get("/api/cloud-management/session", base_url=REMOTE_ORIGIN)-- assert response.status_code == 409- assert response.get_json() == {- "connected": False,- "state": "subject_mismatch",- "error": "cloud_management_subject_mismatch",- }- cookies = response.headers.getlist("set-cookie")- assert any(- value.startswith(f"{cloud_management.HANDLE_COOKIE_NAME}=") and "Max-Age=0" in value- for value in cookies- )- assert any(value.startswith(f"{cloud_management.MANUAL_COOKIE_NAME}=") for value in cookies)---def test_explicit_logout_suppresses_silent_reauthorization(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- client = _remote_client(config)- client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- cloud_management._browser_subjects["browser-1"] = "user-1" # noqa: SLF001-- logout = client.delete(- "/api/cloud-management/session",- base_url=REMOTE_ORIGIN,- headers=csrf_headers(client, REMOTE_ORIGIN),- )- assert logout.status_code == 200-- session = client.get("/api/cloud-management/session", base_url=REMOTE_ORIGIN)- assert session.status_code == 200- assert session.get_json() == {- "connected": False,- "state": "authorization_required",- "can_silent_reauthorize": False,- }- assert cloud_management._bound_subject("browser-1") is None # noqa: SLF001---def test_unbound_browser_cannot_start_silent_authorization(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- backend = SimpleNamespace(base_url="https://avibe.bot")- monkeypatch.setattr(cloud_management, "_validated_backend", lambda _config: backend)-- with pytest.raises(cloud_management.CloudManagementError) as error:- cloud_management.begin_authorization(- config,- browser_id="browser-1",- remote_subject=None,- callback_origin=REMOTE_ORIGIN,- next_path="/admin/organization/overview",- silent=True,- )-- assert error.value.code == "cloud_management_authorization_required"- assert error.value.status == 401- assert not cloud_management._handshakes # noqa: SLF001---def test_bound_subject_allows_silent_reauthorization(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- backend = SimpleNamespace(base_url="https://avibe.bot")- monkeypatch.setattr(cloud_management, "_validated_backend", lambda _config: backend)- cloud_management._browser_subjects["browser-1"] = "user-1" # noqa: SLF001-- authorize_url, state = cloud_management.begin_authorization(- config,- browser_id="browser-1",- remote_subject=None,- callback_origin=REMOTE_ORIGIN,- next_path="/admin/organization/overview",- silent=True,- )-- assert "prompt=none" in authorize_url- assert cloud_management.handshake_for_handoff(state).expected_subject == "user-1"---def test_remote_viewer_can_use_identity_gate_but_only_allowlisted_proxy_paths(- monkeypatch, tmp_path-) -> None:- config = _save_config(monkeypatch, tmp_path)- client = _remote_client(config, role="viewer")- client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- monkeypatch.setattr(cloud_management, "resolve_grant", lambda *args, **kwargs: (_grant(), None))- captured: dict[str, object] = {}-- def fake_proxy(config, **kwargs):- captured.update(kwargs)- return 200, {"ok": True}-- monkeypatch.setattr(cloud_management, "proxy_request", fake_proxy)- response = client.put(- "/api/cloud-management/instances/inst_123/projects/proj_1/access?view=full",- base_url=REMOTE_ORIGIN,- headers=csrf_headers(client, REMOTE_ORIGIN),- json={"mode": "inherit", "bindings": [], "if_match_revision": 2},- )-- assert response.status_code == 200- assert captured["upstream_path"] == "/api/instances/inst_123/projects/proj_1/access"- assert captured["query"] == [("view", "full")]- assert captured["json_body"] == {- "mode": "inherit",- "bindings": [],- "if_match_revision": 2,- }- assert "secret-bearer-token" not in response.text- assert not cloud_management.proxy_path_allowed(- "GET", "/api/organizations/org_1/domains"- )--[email protected]("method", ["GET", "PATCH"])-def test_resource_access_proxy_allows_read_and_patch(method: str) -> None:- assert cloud_management.proxy_path_allowed(- method,- "/api/organizations/org_1/resources/inst_123/show_page/session_1/access",- )--[email protected]("method", ["POST", "PUT", "DELETE"])-def test_resource_access_proxy_rejects_other_methods(method: str) -> None:- assert not cloud_management.proxy_path_allowed(- method,- "/api/organizations/org_1/resources/inst_123/show_page/session_1/access",- )---def test_chunked_proxy_request_is_bounded_before_json_parsing(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- client = _remote_client(config, role="viewer")- client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- monkeypatch.setattr(cloud_management, "resolve_grant", lambda *args, **kwargs: (_grant(), None))- proxy_called = False-- def fake_proxy(*args, **kwargs):- nonlocal proxy_called- proxy_called = True- return 200, {"ok": True}-- monkeypatch.setattr(cloud_management, "proxy_request", fake_proxy)- oversized_body = b'{"value":"' + (b"x" * cloud_management.MAX_REQUEST_BYTES) + b'"}'- headers = csrf_headers(client, REMOTE_ORIGIN)- headers["Content-Type"] = "application/json"- headers["Transfer-Encoding"] = "chunked"-- response = client.patch(- "/api/cloud-management/organizations/org_1/resources/inst_123/agent/agent_1/access",- base_url=REMOTE_ORIGIN,- headers=headers,- content=iter((oversized_body[:1024], oversized_body[1024:])),- )-- assert response.status_code == 413- assert response.get_json() == {- "error": "cloud_management_request_too_large",- "retryable": False,- }- assert proxy_called is False--- ("status", "content_type", "body", "expected_code"),- [- (302, "application/json", b"{}", "cloud_management_redirect_blocked"),- (200, "text/html", b"{}", "cloud_management_invalid_response"),- (200, "application/json", b"{", "cloud_management_invalid_response"),- (- 200,- "application/json",- b"x" * (cloud_management.MAX_RESPONSE_BYTES + 1),- "cloud_management_response_too_large",- ),- ],-)-def test_backend_transport_rejects_unsafe_responses(- monkeypatch,- tmp_path,- status: int,- content_type: str,- body: bytes,- expected_code: str,-) -> None:- config = _save_config(monkeypatch, tmp_path)-- class FakeResponse:- def read(self, _limit: int) -> bytes:- return body-- def getheader(self, name: str) -> str | None:- return content_type if name.lower() == "content-type" else None-- class FakeConnection:- def connect(self) -> None:- return None-- def request(self, *args, **kwargs) -> None:- return None-- def getresponse(self):- response = FakeResponse()- response.status = status- return response-- def close(self) -> None:- return None-- backend = SimpleNamespace(- base_url="https://avibe.bot",- host_header="avibe.bot",- requires_proxy=False,- connect_hosts=("203.0.113.1",),- )- monkeypatch.setattr(cloud_management, "_validated_backend", lambda _config: backend)- monkeypatch.setattr(remote_access, "_validated_backend_proxy_url", lambda _url: None)- monkeypatch.setattr(- remote_access,- "_validated_backend_connection",- lambda *args, **kwargs: FakeConnection(),- )-- with pytest.raises(cloud_management.CloudManagementError) as captured:- cloud_management._backend_request(config, "GET", "/api/organizations") # noqa: SLF001- assert captured.value.code == expected_code---def test_backend_transport_retries_only_during_connection_setup(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- connections: list[str] = []- requests: list[str] = []-- class FakeResponse:- status = 200-- def read(self, _limit: int) -> bytes:- return b'{"ok":true}'-- def getheader(self, name: str) -> str | None:- return "application/json" if name.lower() == "content-type" else None-- class FakeConnection:- def __init__(self, host: str) -> None:- self.host = host-- def connect(self) -> None:- connections.append(self.host)- if self.host == "203.0.113.1":- raise OSError("first address unavailable")-- def request(self, *args, **kwargs) -> None:- requests.append(self.host)-- def getresponse(self) -> FakeResponse:- return FakeResponse()-- def close(self) -> None:- return None-- backend = SimpleNamespace(- base_url="https://avibe.bot",- host_header="avibe.bot",- requires_proxy=False,- connect_hosts=("203.0.113.1", "203.0.113.2"),- )- monkeypatch.setattr(cloud_management, "_validated_backend", lambda _config: backend)- monkeypatch.setattr(remote_access, "_validated_backend_proxy_url", lambda _url: None)- monkeypatch.setattr(- remote_access,- "_validated_backend_connection",- lambda host, *args, **kwargs: FakeConnection(host),- )-- assert cloud_management._backend_request( # noqa: SLF001- config,- "POST",- "/api/organizations/org_1/groups",- json_body={"name": "Engineering"},- ) == (200, {"ok": True})- assert connections == ["203.0.113.1", "203.0.113.2"]- assert requests == ["203.0.113.2"]---def test_backend_transport_never_replays_after_request_transmission(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- connections: list[str] = []- requests: list[str] = []-- class FakeConnection:- def __init__(self, host: str) -> None:- self.host = host-- def connect(self) -> None:- connections.append(self.host)-- def request(self, *args, **kwargs) -> None:- requests.append(self.host)-- def getresponse(self):- raise http.client.RemoteDisconnected("response lost")-- def close(self) -> None:- return None-- backend = SimpleNamespace(- base_url="https://avibe.bot",- host_header="avibe.bot",- requires_proxy=False,- connect_hosts=("203.0.113.1", "203.0.113.2"),- )- monkeypatch.setattr(cloud_management, "_validated_backend", lambda _config: backend)- monkeypatch.setattr(remote_access, "_validated_backend_proxy_url", lambda _url: None)- monkeypatch.setattr(- remote_access,- "_validated_backend_connection",- lambda host, *args, **kwargs: FakeConnection(host),- )-- with pytest.raises(cloud_management.CloudManagementError) as captured:- cloud_management._backend_request( # noqa: SLF001- config,- "POST",- "/api/organizations/org_1/groups",- json_body={"name": "Engineering"},- )- assert captured.value.code == "cloud_management_unavailable"- assert captured.value.retryable is True- assert connections == ["203.0.113.1"]- assert requests == ["203.0.113.1"]---def test_proxy_upstream_401_clears_grant_and_requires_manual_sign_in(- monkeypatch, tmp_path-) -> None:- config = _save_config(monkeypatch, tmp_path)- client = _remote_client(config)- client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- monkeypatch.setattr(cloud_management, "resolve_grant", lambda *args, **kwargs: (_grant(), None))- monkeypatch.setattr(- cloud_management,- "proxy_request",- lambda *args, **kwargs: (401, {"error": "unauthorized"}),- )-- response = client.get(- "/api/cloud-management/organizations",- base_url=REMOTE_ORIGIN,- )-- assert response.status_code == 401- assert response.get_json() == {"error": "unauthorized"}- cookies = response.headers.getlist("set-cookie")- assert any(- value.startswith(f"{cloud_management.HANDLE_COOKIE_NAME}=") and "Max-Age=0" in value- for value in cookies- )- assert any(value.startswith(f"{cloud_management.MANUAL_COOKIE_NAME}=") for value in cookies)---def test_callback_state_and_code_fail_with_distinct_errors(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- with pytest.raises(cloud_management.CloudManagementError) as invalid_state:- cloud_management.complete_authorization(- config,- state="missing-state",- code="code-1",- browser_id="browser-1",- remote_subject=None,- )- assert invalid_state.value.code == "invalid_cloud_management_state"-- backend = SimpleNamespace(base_url="https://avibe.bot")- monkeypatch.setattr(cloud_management, "_validated_backend", lambda _config: backend)- _, state = cloud_management.begin_authorization(- config,- browser_id="browser-1",- remote_subject=None,- callback_origin=REMOTE_ORIGIN,- next_path="/admin/organization/overview",- silent=False,- )- with pytest.raises(cloud_management.CloudManagementError) as invalid_code:- cloud_management.complete_authorization(- config,- state=state,- code="",- browser_id="browser-1",- remote_subject=None,- )- assert invalid_code.value.code == "invalid_cloud_management_code"---def _connected_callback_client(config: V2Config):- """A browser that already holds a live management grant."""-- client = _remote_client(config)- client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")- client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- cloud_management._grants["grant-1"] = _grant()- return client---def _handle_cookie_cleared(response) -> bool:- return any(- value.startswith(f"{cloud_management.HANDLE_COOKIE_NAME}=") and "Max-Age=0" in value- for value in response.headers.getlist("set-cookie")- )---def _manual_sign_in_required(response) -> bool:- """Whether this response tells the browser to stop reauthorizing silently."""-- return any(- value.startswith(f"{cloud_management.MANUAL_COOKIE_NAME}=") and "Max-Age=0" not in value- for value in response.headers.getlist("set-cookie")- )--- "query",- [- # Forged authorization response: no handshake matches this state.- "?code=code-1&state=forged-state",- # Forged upstream failure on the same unrelated state.- "?error=access_denied&state=forged-state",- # No state at all, as a bare cross-site link would send.- "",- ],-)-def test_unrelated_callback_never_revokes_an_active_grant(monkeypatch, tmp_path, query: str) -> None:- """The callback is unauthenticated and CSRF-exempt, so a cross-site link- reaches it with the `SameSite=Lax` management cookies attached. A failure- that cannot be tied to this browser's own handshake must leave the existing- grant intact instead of letting any site force a logout."""-- config = _save_config(monkeypatch, tmp_path)- client = _connected_callback_client(config)-- response = client.get(f"/auth/organization/callback{query}", base_url=REMOTE_ORIGIN)-- assert response.status_code == 302- assert not _handle_cookie_cleared(response)- # Nor may it downgrade the browser to manual sign-in: that is the same- # cross-site nuisance in a milder form.- assert not _manual_sign_in_required(response)- assert cloud_management.resolve_grant("grant-1", "browser-1", None)[0] is not None---def test_own_flow_callback_failure_still_revokes_the_grant(monkeypatch, tmp_path) -> None:- """A failure on a handshake this browser actually started is a real- reauthorization signal, so the stale grant is still torn down."""-- config = _save_config(monkeypatch, tmp_path)- client = _connected_callback_client(config)- monkeypatch.setattr(- cloud_management,- "_validated_backend",- lambda _config: SimpleNamespace(base_url="https://avibe.bot"),- )- _, state = cloud_management.begin_authorization(- config,- browser_id="browser-1",- remote_subject=None,- callback_origin=REMOTE_ORIGIN,- next_path="/admin/organization/overview",- silent=False,- )-- response = client.get(f"/auth/organization/callback?state={state}", base_url=REMOTE_ORIGIN)-- assert response.status_code == 302- assert _handle_cookie_cleared(response)- # AUTH-SETUP-305/306: a failure on the browser's own flow must also stop the- # silent-reauthorization retries, or the UI loops on the same failure.- assert _manual_sign_in_required(response)- assert cloud_management.resolve_grant("grant-1", "browser-1", None)[0] is None---def test_management_token_is_verified_with_real_rsa_jwks(monkeypatch, tmp_path) -> None:- config = _save_config(monkeypatch, tmp_path)- private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)- public_jwk = jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key(), as_dict=True)- public_jwk.update({"kid": "management-key", "alg": "RS256", "use": "sig"})- now = int(time.time())- claims = {- "iss": "https://avibe.bot",- "aud": cloud_management.MANAGEMENT_AUDIENCE,- "sub": "user-1",- "email": "[email protected]",- "vibe_instance_id": "inst_123",- "scope": cloud_management.MANAGEMENT_SCOPE,- "jti": "management-jti",- "iat": now,- "exp": now + 600,- }- token = jwt.encode(- claims,- private_key,- algorithm="RS256",- headers={"kid": "management-key"},- )- monkeypatch.setattr(- cloud_management,- "_backend_request",- lambda *args, **kwargs: (200, {"keys": [public_jwk]}),- )-- assert cloud_management._validate_management_token(config, token) == claims # noqa: SLF001diff --git a/tests/test_permissions.py b/tests/test_permissions.pynew file mode 100644index 000000000..e51304d57--- /dev/null+++ b/tests/test_permissions.py@@ -0,0 +1,281 @@+from __future__ import annotations++import json++import pytest+import requests++from config.v2_config import (+ AgentsConfig,+ RemoteAccessConfig,+ RuntimeConfig,+ SlackConfig,+ V2Config,+)+from tests.ui_server_test_helpers import csrf_headers+from vibe import permissions+from vibe.authorization import http_authorization_policy+from vibe.ui_server import app+++def _config(instance_id: str = "inst-123") -> V2Config:+ config = V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ remote_access=RemoteAccessConfig(),+ )+ cloud = config.remote_access.vibe_cloud+ cloud.enabled = True+ cloud.backend_url = "https://backend.example"+ cloud.instance_id = instance_id+ cloud.instance_secret = "device-secret"+ return config+++def _projection(instance_id: str = "inst-123") -> dict:+ return {+ "schema_version": 1,+ "instance": {+ "id": instance_id,+ "access_mode": "allowlist",+ "permission_authority": "instance",+ "local_mutation_allowed": True,+ "authorization_revision": 3,+ },+ "capabilities": [+ "instance.permissions.read",+ "instance.permissions.mutate",+ ],+ "access": {+ "owner": {"email": "[email protected]", "role": "owner"},+ "entries": [],+ },+ "directory": {"members": [], "groups": []},+ "projects": [],+ "policy_sync": {+ "status": "none",+ "projects": {"active": 0, "error": 0, "offline": 0, "applying": 0, "in_sync": 0},+ "resources": {"active": 0, "error": 0, "offline": 0, "applying": 0, "in_sync": 0},+ },+ }+++class _Response:+ def __init__(self, status: int, payload: object):+ self.status_code = status+ self._payload = payload+ self.ok = 200 <= status < 300++ def json(self):+ return self._payload+++class _InvalidJsonResponse(_Response):+ def json(self):+ raise ValueError("not JSON")+++def test_permissions_client_binds_requests_to_paired_instance(monkeypatch) -> None:+ captured = []++ def request(method, url, **kwargs):+ captured.append((method, url, kwargs))+ return _Response(200, _projection())++ monkeypatch.setattr(permissions.requests, "request", request)++ result = permissions.get_current_permissions(_config())++ assert result.source == "live"+ assert result.projection["instance"]["id"] == "inst-123"+ assert captured == [+ (+ "GET",+ "https://backend.example/api/v1/instances/inst-123/permissions",+ {+ "json": None,+ "headers": {+ "Accept": "application/json",+ "Content-Type": "application/json",+ "User-Agent": "avibe/dev",+ "X-Vibe-Device-Secret": "device-secret",+ },+ "timeout": permissions.DEFAULT_TIMEOUT_SECONDS,+ "allow_redirects": False,+ },+ )+ ]+++def test_permissions_offline_cache_is_sanitized_and_exact_instance_bound(monkeypatch) -> None:+ live = _projection()+ live["debug"] = {"instance_secret": "must-not-persist", "note": "kept"}+ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: _Response(200, live),+ )+ permissions.get_current_permissions(_config())++ cache = json.loads(permissions._cache_path().read_text(encoding="utf-8")) # noqa: SLF001+ assert "must-not-persist" not in json.dumps(cache)+ assert cache["projection"]["debug"] == {"note": "kept"}+ assert permissions._cache_path().stat().st_mode & 0o777 == 0o600 # noqa: SLF001++ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(requests.ConnectionError()),+ )+ cached = permissions.get_current_permissions(_config())+ assert cached.source == "cache"+ assert cached.offline is True++ with pytest.raises(permissions.PermissionsUnavailableError):+ permissions.get_current_permissions(_config("inst-other"))+++def test_permissions_offline_cache_covers_non_json_backend_failure(monkeypatch) -> None:+ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: _Response(200, _projection()),+ )+ permissions.get_current_permissions(_config())+ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: _InvalidJsonResponse(503, None),+ )++ cached = permissions.get_current_permissions(_config())++ assert cached.source == "cache"+ assert cached.offline is True+++def test_permissions_live_read_survives_cache_write_failure(monkeypatch) -> None:+ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: _Response(200, _projection()),+ )+ monkeypatch.setattr(+ permissions,+ "_write_cache",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),+ )++ result = permissions.get_current_permissions(_config())++ assert result.source == "live"+ assert result.projection["instance"]["id"] == "inst-123"+++def test_permissions_does_not_mask_credential_failures_with_cache(monkeypatch) -> None:+ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: _Response(200, _projection()),+ )+ permissions.get_current_permissions(_config())+ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: _Response(401, {"error": "invalid_device_secret"}),+ )++ with pytest.raises(permissions.PermissionsBackendError) as caught:+ permissions.get_current_permissions(_config())++ assert caught.value.status == 401+ assert caught.value.payload == {"error": "invalid_device_secret"}+++def test_permissions_rejects_backend_projection_for_another_instance(monkeypatch) -> None:+ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: _Response(200, _projection("inst-other")),+ )++ with pytest.raises(permissions.PermissionsInvalidResponseError, match="permissions_instance_mismatch"):+ permissions.get_current_permissions(_config())+++def test_permissions_http_policy_allows_viewer_reads_but_owner_only_mutations() -> None:+ assert http_authorization_policy("GET", "/api/permissions").minimum_role == "viewer"+ assert (+ http_authorization_policy("PUT", "/api/permissions/authorized-users").minimum_role+ == "owner"+ )+ assert (+ http_authorization_policy("PUT", "/api/permissions/projects/project-1/access").minimum_role+ == "owner"+ )+++def test_permissions_same_origin_routes_reject_non_contract_entry_fields(monkeypatch) -> None:+ client = app.test_client()+ headers = csrf_headers(client)+ called = False++ def replace(_payload):+ nonlocal called+ called = True+ return {"ok": True}++ monkeypatch.setattr(permissions, "replace_authorized_users", replace)+ response = client.put(+ "/api/permissions/authorized-users",+ json={+ "entries": [+ {+ "kind": "email",+ "value": "[email protected]",+ "role": "viewer",+ "instance_id": "inst-other",+ }+ ],+ "if_match_revision": 3,+ },+ headers=headers,+ )++ assert response.status_code == 422+ assert response.get_json() == {"ok": False, "error": "invalid_request"}+ assert called is False+++def test_permissions_same_origin_routes_forward_revision_and_conflict(monkeypatch) -> None:+ client = app.test_client()+ headers = csrf_headers(client)+ captured = {}++ def update(project_id, payload):+ captured.update(project_id=project_id, payload=payload)+ raise permissions.PermissionsBackendError(+ 409,+ {"error": "permission_revision_conflict", "current_revision": 7},+ )++ monkeypatch.setattr(permissions, "update_project_access", update)+ response = client.put(+ "/api/permissions/projects/project-1/access",+ json={"mode": "inherit", "bindings": [], "if_match_revision": 6},+ headers=headers,+ )++ assert response.status_code == 409+ assert response.get_json() == {+ "ok": False,+ "error": "permission_revision_conflict",+ "current_revision": 7,+ }+ assert captured == {+ "project_id": "project-1",+ "payload": {"mode": "inherit", "bindings": [], "if_match_revision": 6},+ }diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 759c64afc..b99aaeda3 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -105,19 +105,7 @@ import { applyAppTitle } from './lib/documentTitle';import { useTranslation } from 'react-i18next';import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './components/ui/card';import { Button } from './components/ui/button';-import { OrganizationOverviewPage } from './features/organization/pages/OrganizationOverviewPage';-import { OrganizationMembersPage } from './features/organization/pages/OrganizationMembersPage';-import {- OrganizationGroupDetailPage,- OrganizationGroupsPage,-} from './features/organization/pages/OrganizationGroupsPages';-import { OrganizationInstancesPage } from './features/organization/pages/OrganizationInstancesPage';-import {- InstanceAccessPage,- InstanceProjectsPage,-} from './features/organization/pages/OrganizationInstancePages';-import { OrganizationResourcesPage } from './features/organization/pages/OrganizationResourcesPage';-import { OrganizationShell } from './features/organization/OrganizationShell';+import { PermissionsPage } from './features/permissions/PermissionsPage';const RemoteLoginGate = ({ target }: { target: string }) => {const { t } = useTranslation();@@ -758,17 +746,7 @@ const router = createBrowserRouter({/* Control Panel mode — existing pages moved under /admin/* */}<Route path="/admin" element={<Navigate to="/admin/dashboard" replace />} /><Route path="/admin/dashboard" element={<Dashboard />} />- <Route path="/admin/organization" element={<OrganizationShell />}>- <Route index element={<Navigate to="/admin/organization/overview" replace />} />- <Route path="overview" element={<OrganizationOverviewPage />} />- <Route path="members" element={<OrganizationMembersPage />} />- <Route path="groups" element={<OrganizationGroupsPage />} />- <Route path="groups/:groupId" element={<OrganizationGroupDetailPage />} />- <Route path="instances" element={<OrganizationInstancesPage />} />- <Route path="instances/:instanceId/access" element={<InstanceAccessPage />} />- <Route path="instances/:instanceId/projects" element={<InstanceProjectsPage />} />- <Route path="resources" element={<OrganizationResourcesPage />} />- </Route>+ <Route path="/admin/permissions" element={<PermissionsPage />} /><Route path="/admin/remote-access" element={<RemoteAccessPage />} /><Route path="/admin/groups" element={<ChannelList isPage />} /><Route path="/admin/users" element={<UserList />} />diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsxindex 6f9aa4942..ec995d7ab 100644--- a/ui/src/components/AppShell.test.tsx+++ b/ui/src/components/AppShell.test.tsx@@ -129,12 +129,12 @@ describe('AppShell setup recovery', () => {});});-describe('AppShell Organization navigation', () => {+describe('AppShell Permissions navigation', () => {it.each([- ['personal', 0],- [null, 0],+ ['personal', 2],+ [null, 2],['organization', 2],- ] as const)('shows Organization only for %s instances', async (instanceKind, expectedCount) => {+ ] as const)('shows current-instance Permissions for %s instances', async (instanceKind, expectedCount) => {instanceAuth.instanceKind = instanceKind;render(@@ -148,8 +148,16 @@ describe('AppShell Organization navigation', () => {);expect(await screen.findByTestId('dashboard')).toBeTruthy();- const organizationEntries = screen.queryAllByText('nav.organization');- expect(organizationEntries).toHaveLength(expectedCount);+ const permissionEntries = screen.queryAllByText('nav.permissions');+ expect(permissionEntries).toHaveLength(expectedCount);+ const advancedEntries = screen.queryAllByText('nav.advancedSettings');+ expect(advancedEntries).toHaveLength(expectedCount);+ permissionEntries.forEach((permission, index) => {+ expect(+ permission.compareDocumentPosition(advancedEntries[index]!)+ & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ });});});diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex b2decbce6..44d566368 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -1,6 +1,6 @@import React, { useEffect, useState } from 'react';import { Link, Navigate, NavLink, Outlet, useLocation } from 'react-router-dom';-import { AlertTriangle, ArrowLeft, Bot, Brain, Building2, ChevronDown, Cpu, FolderTree, Globe, Grid2x2, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, PlugZap, Plus, Settings, Sparkles, X } from 'lucide-react';+import { AlertTriangle, ArrowLeft, Bot, Brain, ChevronDown, Cpu, FolderTree, Globe, Grid2x2, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, PlugZap, Plus, Settings, ShieldCheck, Sparkles, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';@@ -260,7 +260,6 @@ export const AppShell: React.FC = () => {const { totalUnread } = useWorkbenchInbox();const {capabilities,- instanceKind,remote,} = useInstanceAuthorization();const api = useApi();@@ -391,7 +390,6 @@ export const AppShell: React.FC = () => {const modelHubEnabled = modelHubEnabledFromConfig(config);const isRunning = status.state === 'running';const canUseApps = capabilities.can_chat;- const showOrganizationNavigation = instanceKind === 'organization';const canUseShowPageApp =location.pathname.startsWith('/apps/show/') && capabilities.can_use_show_pages;const localSystemPath = isOwnerOnlyPath(location.pathname);@@ -423,14 +421,6 @@ export const AppShell: React.FC = () => {const adminItems: ShellNavItem[] = [{ to: '/admin/dashboard', label: t('nav.dashboard'), icon: LayoutDashboard },- ...(showOrganizationNavigation- ? [{- to: '/admin/organization/overview',- label: t('nav.organization'),- icon: Building2,- match: (p: string) => p.startsWith('/admin/organization'),- }]- : []),// Permanent escape hatch to the App Library (a workbench app) for principals// covered by the current Apps policy. It stays reachable even when undocked....(canUseApps@@ -472,6 +462,12 @@ export const AppShell: React.FC = () => {...(memoryNavVisible? [{ to: '/admin/settings/memory', label: t('memory.betaTitle'), icon: Brain, match: isMemorySettingsPath }]: []),+ {+ to: '/admin/permissions',+ label: t('nav.permissions'),+ icon: ShieldCheck,+ match: (p: string) => p.startsWith('/admin/permissions'),+ },{// 高级设置: the remaining Settings tabs (messaging leads). Platforms,// backends, models, and Memory have their own sidebar destinations, so@@ -492,15 +488,12 @@ export const AppShell: React.FC = () => {// A bottom tab bar can't hold the nested admin nav, so mobile keeps a trimmed// bar with Workbench, Control Panel, and More (which opens the full nested nav- // sheet). The Organization tab follows the same capability visibility as- // every other shell entry point. See ``adminMenuOpen``.+ // sheet). See ``adminMenuOpen``.const adminMobileTabsAll: ShellNavItem[] = [{ to: '/', label: t('nav.workbench'), icon: Sparkles, variant: 'workbench' },{ to: '/admin/dashboard', label: t('nav.dashboard'), icon: LayoutDashboard },- ...(showOrganizationNavigation- ? [{ to: '/admin/organization/overview', label: t('nav.organization'), icon: Building2 }]- : []),{ label: t('nav.more'), icon: Menu, onClick: () => setAdminMenuOpen(true), match: () => adminMenuOpen },+ { to: '/admin/permissions', label: t('nav.permissions'), icon: ShieldCheck },{to: '/admin/settings/messaging',label: t('nav.advancedSettings'),@@ -742,9 +735,7 @@ export const AppShell: React.FC = () => {'w-full',chromeless? 'h-full'- : location.pathname.startsWith('/admin/organization')- ? 'mx-auto'- : 'mx-auto px-4 py-5 md:px-10 md:py-8',+ : 'mx-auto px-4 py-5 md:px-10 md:py-8',)}>{/* A crashing page only replaces the content area — the sidebar + chrome stay usable, andnavigating elsewhere clears the error without a manual retry. Key on location.key (notdiff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsxindex 3561c2aee..d37152ee5 100644--- a/ui/src/components/workbench/ShowPageShareControl.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.tsx@@ -15,7 +15,6 @@ 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;@@ -295,21 +294,6 @@ export const ShowPageShareControl: React.FC<{</div>) : null}- <div className="border-t border-border pt-3">- <ShowPageWorkspaceAccessControl- access={access}- active={open}- sessionId={sessionId}- onConfirmationOpenChange={setConfirmationOpen}- ownerWindowId={ownerWindowId}- />- {accessError ? (- <p className="mt-2 text-[11px] leading-snug text-destructive-ink">- {t('chat.showPage.accessLoadError')}- </p>- ) : null}- </div>-{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.tsxdeleted file mode 100644index 3121c684e..000000000--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx+++ /dev/null@@ -1,106 +0,0 @@-import { renderToStaticMarkup } from 'react-dom/server';-import { describe, expect, it, vi } from 'vitest';--import type { ShowPageAccess } from '@/lib/showPageAccess';-import {- ShowPageOrganizationAuthorizationPrompt,- ShowPageWorkspaceAccessControl,-} from './ShowPageWorkspaceAccessControl';--vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}));--vi.mock('@/components/ui/confirm-dialog', () => ({- ConfirmDialog: ({ open, title }: { open: boolean; title: string }) => (- <div data-confirm-open={String(open)}>{title}</div>- ),-}));--const access = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({- ok: true,- mode: 'organization',- instance_id: 'inst-1',- organization_id: 'org-1',- access_level: 'private',- group_ids: [],- policy_revision: 4,- last_applied_control_plane_revision: 4,- can_use: true,- can_manage: true,- can_publish_public: true,- ...overrides,-});--const renderControl = (value: ShowPageAccess) => renderToStaticMarkup(- <ShowPageWorkspaceAccessControl access={value} active={false} sessionId="session-1" />,-);--describe('ShowPageWorkspaceAccessControl', () => {- it('offers explicit reauthorization after an Organization subject mismatch', () => {- const html = renderToStaticMarkup(- <ShowPageOrganizationAuthorizationPrompt gate="subject_mismatch" onAuthorize={() => undefined} />,- );-- expect(html).toContain('chat.showPage.organizationSubjectMismatch');- expect(html).toContain('chat.showPage.organizationSignInAgain');- expect(html).toContain('<button');- });-- it('keeps the normal Organization sign-in action on the same recovery component', () => {- const html = renderToStaticMarkup(- <ShowPageOrganizationAuthorizationPrompt gate="authorization_required" onAuthorize={() => undefined} />,- );-- expect(html).toContain('chat.showPage.organizationSignInDesc');- expect(html).toContain('chat.showPage.organizationSignIn');- expect(html).toContain('<button');- });-- it('keeps Personal workspace access private without link-sharing controls', () => {- const html = renderControl(access({- mode: 'personal',- instance_id: null,- organization_id: null,- policy_revision: null,- last_applied_control_plane_revision: null,- }));-- expect(html).toContain('chat.showPage.workspaceLevels.private');- expect(html).not.toContain('chat.showPage.workspaceLevels.public');- expect(html).not.toContain('chat.showPage.workspaceLevels.scope');- expect(html).not.toContain('<select');- expect(html).not.toContain('chat.showPage.limitedEmails');- });-- it('renders all Organization audiences and keeps the public wire value labeled as Organization', () => {- const html = renderControl(access({ access_level: 'public' }));-- expect(html).toContain('value="private"');- expect(html).toContain('value="public" selected=""');- expect(html).toContain('value="scope"');- expect(html).toContain('chat.showPage.workspaceLevels.public');- expect(html).not.toContain('chat.showPage.limitedEmails');- });-- it('keeps the Organization audience read-only for a non-owner viewer', () => {- const html = renderControl(access({ can_manage: false, can_publish_public: false }));-- expect(html).toContain('<select disabled=""');- expect(html).toContain('chat.showPage.workspaceReadOnly');- expect(html).not.toContain('chat.showPage.limitedEmails');- });-- it('never nests local link sharing inside Workspace access', () => {- const html = renderControl(access({ can_manage: true, can_publish_public: false }));-- expect(html).not.toContain('chat.showPage.limitedEmails');- });-- it('mounts the established Organization audience-narrowing confirmation', () => {- const html = renderControl(access({ access_level: 'public' }));-- expect(html).toContain('data-confirm-open="false"');- expect(html).toContain('organization.resources.narrowTitle');- });-});diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsxdeleted file mode 100644index d3df03b1f..000000000--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx+++ /dev/null@@ -1,449 +0,0 @@-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import clsx from 'clsx';-import {- Building2,- CloudOff,- Loader2,- LockKeyhole,- LogIn,- RefreshCw,- TriangleAlert,- Users,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Button } from '@/components/ui/button';-import { Checkbox } from '@/components/ui/checkbox';-import { ConfirmDialog } from '@/components/ui/confirm-dialog';-import { Select } from '@/components/ui/select';-import {- isRevisionConflict,- jsonBody,- OrganizationApiError,- organizationRequest,-} from '@/features/organization/api/client';-import type {- CloudManagementSession,- OrganizationGroup,- OrganizationResource,- ResourceAccessLevel,-} from '@/features/organization/api/types';-import {- organizationAuthorizationReturnPath,- requiresResourceAccessNarrowingConfirmation,-} from '@/features/organization/policy';-import {- buildShowPageAccessPatch,- showPageAudienceLabelKey,- showPageAudienceLevels,- showPageSyncPresentation,- type ShowPageAccess,-} from '@/lib/showPageAccess';--type ManagementGate =- | 'idle'- | 'loading'- | 'authorization_required'- | 'cloud_not_connected'- | 'subject_mismatch'- | 'ready'- | 'conflict'- | 'unreachable'- | 'error';--type ResourceResponse = { resource: OrganizationResource };-type OrganizationAuthorizationGate = 'authorization_required' | 'subject_mismatch';--const LEVEL_ICONS = {- private: LockKeyhole,- public: Building2,- scope: Users,-} satisfies Record<ResourceAccessLevel, typeof LockKeyhole>;--function gateForError(error: unknown): ManagementGate {- if (!(error instanceof OrganizationApiError)) return 'unreachable';- if (error.code === 'cloud_management_subject_mismatch') return 'subject_mismatch';- if (error.status === 401) return 'authorization_required';- if (error.status === 409 && error.code === 'cloud_management_not_connected') {- return 'cloud_not_connected';- }- if (error.retryable || error.status >= 500) return 'unreachable';- return 'error';-}--function sessionGate(session: CloudManagementSession): ManagementGate {- if (session.connected) return 'ready';- return session.state;-}--export function ShowPageOrganizationAuthorizationPrompt({- gate,- onAuthorize,-}: {- gate: OrganizationAuthorizationGate;- onAuthorize: () => void;-}) {- const { t } = useTranslation();- const subjectMismatch = gate === 'subject_mismatch';- return (- <div className="flex items-center justify-between gap-2 border-t border-border pt-2">- <span className={clsx(- 'flex min-w-0 items-start gap-1.5 text-[11px] leading-snug',- subjectMismatch ? 'text-destructive-ink' : 'text-muted',- )}>- {subjectMismatch ? <TriangleAlert className="mt-0.5 size-3.5 shrink-0" /> : null}- <span>- {t(subjectMismatch- ? 'chat.showPage.organizationSubjectMismatch'- : 'chat.showPage.organizationSignInDesc')}- </span>- </span>- <Button- type="button"- size="sm"- variant="outline"- className="h-7 shrink-0"- onClick={onAuthorize}- >- <LogIn className="size-3.5" />- {t(subjectMismatch- ? 'chat.showPage.organizationSignInAgain'- : 'chat.showPage.organizationSignIn')}- </Button>- </div>- );-}--export function ShowPageWorkspaceAccessControl({- access,- active,- sessionId,- onConfirmationOpenChange,- ownerWindowId,-}: {- access: ShowPageAccess | null;- active: boolean;- sessionId: string;- onConfirmationOpenChange?: (open: boolean) => void;- /** Attribute this control's body-portalled ConfirmDialog to its owning app window. */- ownerWindowId?: string;-}) {- const { t } = useTranslation();- const [gate, setGate] = useState<ManagementGate>('idle');- const [resource, setResource] = useState<OrganizationResource | null>(null);- const [groups, setGroups] = useState<OrganizationGroup[]>([]);- const [level, setLevel] = useState<ResourceAccessLevel>(access?.access_level ?? 'private');- const [groupIds, setGroupIds] = useState<string[]>(access?.group_ids ?? []);- const [saving, setSaving] = useState(false);- const [confirmNarrowing, setConfirmNarrowing] = useState(false);- const generationRef = useRef(0);-- const organizationId = access?.organization_id ?? null;- const instanceId = access?.instance_id ?? null;- const canManage = access?.can_manage === true;- const setNarrowingConfirmationOpen = useCallback((next: boolean) => {- setConfirmNarrowing(next);- onConfirmationOpenChange?.(next);- }, [onConfirmationOpenChange]);-- const accessPath = useMemo(() => {- if (!organizationId || !instanceId) return null;- return `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/resources/${encodeURIComponent(instanceId)}/show_page/${encodeURIComponent(sessionId)}/access`;- }, [instanceId, organizationId, sessionId]);-- const loadManagement = useCallback(async () => {- if (!access || access.mode !== 'organization' || !canManage || !organizationId || !accessPath) {- return;- }- const generation = ++generationRef.current;- setGate('loading');- try {- const session = await organizationRequest<CloudManagementSession>('/api/cloud-management/session');- if (generation !== generationRef.current) return;- const nextGate = sessionGate(session);- if (!session.connected) {- setGate(nextGate);- setResource(null);- setGroups([]);- return;- }- const [resourceResult, groupResult] = await Promise.all([- organizationRequest<ResourceResponse>(accessPath),- organizationRequest<{ groups: OrganizationGroup[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/groups`,- ),- ]);- if (generation !== generationRef.current) return;- const nextResource = resourceResult.resource;- setResource(nextResource);- setGroups(groupResult.groups);- setLevel(nextResource.access?.access_level ?? access.access_level);- setGroupIds(nextResource.access?.group_ids ?? access.group_ids);- setGate('ready');- } catch (error) {- if (generation !== generationRef.current) return;- setGate(gateForError(error));- }- }, [access, accessPath, canManage, organizationId]);-- useEffect(() => {- generationRef.current += 1;- setResource(null);- setGroups([]);- setLevel(access?.access_level ?? 'private');- setGroupIds(access?.group_ids ?? []);- setNarrowingConfirmationOpen(false);- setGate('idle');- if (active && access?.mode === 'organization' && access.can_manage) {- void loadManagement();- }- return () => {- generationRef.current += 1;- };- }, [access, active, loadManagement, setNarrowingConfirmationOpen]);-- const visibleGroups = groups.filter((group) => !group.archived_at || groupIds.includes(group.id));- const toggleGroup = (group: OrganizationGroup) => {- const selected = groupIds.includes(group.id);- if (group.archived_at && !selected) return;- setGroupIds((current) => selected- ? current.filter((id) => id !== group.id)- : [...current, group.id]);- };-- const currentLevel = resource?.access?.access_level ?? access?.access_level ?? 'private';- const currentGroupIds = resource?.access?.group_ids ?? access?.group_ids ?? [];- const revision = resource?.access?.revision ?? access?.policy_revision ?? null;- const patch = revision === null ? null : buildShowPageAccessPatch(level, groupIds, revision);- const normalizedCurrentGroups = currentLevel === 'scope' ? [...currentGroupIds].sort() : [];- const normalizedDraftGroups = patch?.group_ids ? [...patch.group_ids].sort() : [];- const dirty = Boolean(- patch- && (level !== currentLevel- || normalizedCurrentGroups.join('\u0000') !== normalizedDraftGroups.join('\u0000')),- );- const editable = access?.mode === 'organization' && canManage && gate === 'ready' && !saving;-- const commit = async () => {- if (!accessPath || !patch || !dirty || !editable) return;- setSaving(true);- try {- const result = await organizationRequest<ResourceResponse>(accessPath, {- method: 'PATCH',- body: jsonBody(patch),- });- setResource(result.resource);- setLevel(result.resource.access?.access_level ?? level);- setGroupIds(result.resource.access?.group_ids ?? []);- setGate('ready');- } catch (error) {- setGate(isRevisionConflict(error) ? 'conflict' : gateForError(error));- } finally {- setSaving(false);- setNarrowingConfirmationOpen(false);- }- };-- const save = () => {- if (!patch || !dirty || !editable) return;- if (requiresResourceAccessNarrowingConfirmation(- currentLevel,- currentGroupIds,- patch.access_level,- patch.group_ids,- )) {- setNarrowingConfirmationOpen(true);- return;- }- void commit();- };-- const startAuthorization = async () => {- setGate('loading');- try {- const result = await organizationRequest<{ authorize_url: string }>(- '/api/cloud-management/session/start',- {- method: 'POST',- body: jsonBody({- mode: 'interactive',- next: organizationAuthorizationReturnPath(- window.location.pathname,- window.location.search,- ),- }),- },- );- window.location.assign(result.authorize_url);- } catch (error) {- setGate(gateForError(error));- }- };-- const LevelIcon = LEVEL_ICONS[level];- const syncPresentation = resource ? showPageSyncPresentation(resource.sync.status) : null;-- return (- <>- <section className="space-y-2.5" aria-label={t('chat.showPage.workspaceAccess')}>- <div className="flex items-center justify-between gap-3">- <div className="min-w-0">- <div className="text-sm font-medium">{t('chat.showPage.workspaceAccess')}</div>- <div className="mt-0.5 text-[11px] leading-snug text-muted">- {t('chat.showPage.workspaceAccessDesc')}- </div>- </div>- {!access ? (- <Loader2 className="size-4 shrink-0 animate-spin text-muted" />- ) : access.mode === 'personal' ? (- <span className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs">- <LockKeyhole className="size-3.5 text-muted" />- {t(showPageAudienceLabelKey('private'))}- </span>- ) : (- <Select- value={level}- disabled={!editable}- onChange={(event) => setLevel(event.target.value as ResourceAccessLevel)}- wrapperClassName="w-[148px] shrink-0"- className="h-8 text-xs"- aria-label={t('chat.showPage.workspaceAccess')}- >- {showPageAudienceLevels('organization').map((candidate) => (- <option key={candidate} value={candidate}>- {t(showPageAudienceLabelKey(candidate))}- </option>- ))}- </Select>- )}- </div>-- {access?.mode === 'organization' ? (- <div className="flex items-start gap-2 text-[11px] leading-snug text-muted">- <LevelIcon className="mt-0.5 size-3.5 shrink-0" />- <span>{t(`chat.showPage.workspaceHelp.${level}`)}</span>- </div>- ) : null}-- {access?.mode === 'organization' && level === 'scope' && gate === 'ready' ? (- <fieldset>- <legend className="mb-1.5 text-[11px] font-medium">- {t('chat.showPage.selectedGroups')}- </legend>- <div className="max-h-36 space-y-0.5 overflow-y-auto rounded-md border border-border p-1">- {visibleGroups.map((group) => {- const selected = groupIds.includes(group.id);- const disabled = !editable || Boolean(group.archived_at && !selected);- return (- <button- key={group.id}- type="button"- role="checkbox"- aria-checked={selected}- disabled={disabled}- className={clsx(- 'flex w-full items-center gap-2 rounded px-1.5 py-1.5 text-left text-xs',- disabled ? 'cursor-not-allowed opacity-60' : 'hover:bg-foreground/[0.04]',- )}- onClick={() => toggleGroup(group)}- >- <Checkbox checked={selected} presentational />- <span className="min-w-0 flex-1 truncate">{group.name}</span>- {group.archived_at ? (- <span className="text-[10px] text-muted">{t('chat.showPage.archivedGroup')}</span>- ) : null}- </button>- );- })}- </div>- {!patch ? (- <p className="mt-1.5 text-[11px] text-gold-ink">{t('chat.showPage.groupRequired')}</p>- ) : null}- </fieldset>- ) : null}-- {access?.mode === 'organization' && canManage && gate === 'loading' ? (- <div className="flex items-center gap-1.5 text-[11px] text-muted">- <Loader2 className="size-3.5 animate-spin" />- {t('chat.showPage.loadingWorkspaceAccess')}- </div>- ) : null}-- {access?.mode === 'organization'- && canManage- && (gate === 'authorization_required' || gate === 'subject_mismatch') ? (- <ShowPageOrganizationAuthorizationPrompt- gate={gate}- onAuthorize={() => void startAuthorization()}- />- ) : null}-- {access?.mode === 'organization' && canManage && gate === 'cloud_not_connected' ? (- <div className="flex items-start gap-1.5 text-[11px] leading-snug text-muted">- <CloudOff className="mt-0.5 size-3.5 shrink-0" />- {t('chat.showPage.organizationUnavailable')}- </div>- ) : null}-- {access?.mode === 'organization' && canManage && ['conflict', 'unreachable', 'error'].includes(gate) ? (- <div className="flex items-center justify-between gap-2 border-t border-border pt-2">- <span className="text-[11px] leading-snug text-destructive-ink">- {t(`chat.showPage.workspaceErrors.${gate}`)}- </span>- <Button type="button" size="icon" variant="ghost" className="size-7 shrink-0" onClick={() => void loadManagement()} aria-label={t('common.retry')} title={t('common.retry')}>- <RefreshCw className="size-3.5" />- </Button>- </div>- ) : null}-- {access?.mode === 'organization' && !canManage ? (- <p className="text-[11px] leading-snug text-muted">- {t('chat.showPage.workspaceReadOnly')}- </p>- ) : null}-- {syncPresentation ? (- <div- className={clsx(- 'flex items-center gap-1.5 text-[11px] leading-snug',- syncPresentation.tone === 'error' ? 'text-destructive-ink' : 'text-gold-ink',- )}- >- {syncPresentation.tone === 'error' ? (- <TriangleAlert className="size-3.5 shrink-0" />- ) : (- <Loader2 className="size-3.5 shrink-0 animate-spin" />- )}- {t(syncPresentation.key)}- </div>- ) : null}-- {access?.mode === 'organization' && canManage && gate === 'ready' ? (- <div className="flex justify-end">- <Button- type="button"- size="sm"- variant="outline"- className="h-7"- disabled={!dirty || !patch || saving}- onClick={save}- >- {saving ? <Loader2 className="size-3.5 animate-spin" /> : null}- {t('chat.showPage.applyWorkspaceAccess')}- </Button>- </div>- ) : null}-- </section>- <ConfirmDialog- open={confirmNarrowing}- onOpenChange={setNarrowingConfirmationOpen}- title={t('organization.resources.narrowTitle')}- description={t('organization.resources.narrowBody')}- confirmLabel={t('organization.actions.saveChanges')}- onConfirm={commit}- windowOwnerId={ownerWindowId}- />- </>- );-}diff --git a/ui/src/features/organization/OrganizationProvider.tsx b/ui/src/features/organization/OrganizationProvider.tsxdeleted file mode 100644index a4ba61994..000000000--- a/ui/src/features/organization/OrganizationProvider.tsx+++ /dev/null@@ -1,263 +0,0 @@-import React, {- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from 'react';--import { OrganizationApiError, organizationRequest } from './api/client';-import type {- CloudManagementSession,- Organization,- OrganizationDetail,-} from './api/types';-import {- OrganizationContext,- type GateState,- type OrganizationContextValue,-} from './context';-import { organizationAuthorizationReturnPath } from './policy';-const SELECTED_ORG_KEY = 'avibe.organization.selected';--function callbackError(): string | null {- const params = new URLSearchParams(window.location.search);- const error = params.get('cloud_management_error');- if (error) {- const next = organizationAuthorizationReturnPath(- window.location.pathname,- window.location.search,- );- window.history.replaceState(null, '', `${next}${window.location.hash}`);- }- return error;-}--function gateForOrganizationError(- error: unknown,- unauthorizedGate: Extract<GateState, 'authorization_required' | 'revoked'>,-): GateState {- if (!(error instanceof OrganizationApiError)) return 'unreachable';- if (error.code === 'cloud_management_subject_mismatch') return 'subject_mismatch';- if (error.status === 401) return unauthorizedGate;- if (error.status === 409) return 'cloud_not_connected';- if (error.retryable || error.status >= 500) return 'unreachable';- return 'error';-}--export function OrganizationProvider({ children }: { children: React.ReactNode }) {- const [gate, setGate] = useState<GateState>('loading');- const [session, setSession] = useState<Extract<CloudManagementSession, { connected: true }> | null>(null);- const [organizations, setOrganizations] = useState<Organization[]>([]);- const [selectedOrganizationId, setSelectedOrganizationId] = useState<string | null>(null);- const [detail, setDetail] = useState<OrganizationDetail | null>(null);- const [dataVersion, setDataVersion] = useState(0);- const silentAttempted = useRef(false);- const operationGeneration = useRef(0);-- const startAuthorization = useCallback(async (mode: 'interactive' | 'silent') => {- operationGeneration.current += 1;- setGate('reauthorizing');- try {- const result = await organizationRequest<{ authorize_url: string }>(- '/api/cloud-management/session/start',- {- method: 'POST',- body: JSON.stringify({- mode,- next: organizationAuthorizationReturnPath(- window.location.pathname,- window.location.search,- ),- }),- },- );- window.location.assign(result.authorize_url);- } catch (error) {- setGate(gateForOrganizationError(error, 'authorization_required'));- }- }, []);-- const loadOrganizationAtGeneration = useCallback(async (- organizationId: string,- generation: number,- ): Promise<boolean> => {- let result: OrganizationDetail;- try {- result = await organizationRequest<OrganizationDetail>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}`,- );- } catch (error) {- if (generation !== operationGeneration.current) return false;- throw error;- }- if (generation !== operationGeneration.current) return false;- setSelectedOrganizationId(organizationId);- setDetail(result);- sessionStorage.setItem(SELECTED_ORG_KEY, organizationId);- return true;- }, []);-- const selectOrganization = useCallback(async (organizationId: string) => {- const generation = ++operationGeneration.current;- setSelectedOrganizationId(organizationId);- setDetail(null);- sessionStorage.setItem(SELECTED_ORG_KEY, organizationId);- try {- await loadOrganizationAtGeneration(organizationId, generation);- } catch (error) {- if (generation !== operationGeneration.current) return;- setGate(gateForOrganizationError(error, 'revoked'));- }- }, [loadOrganizationAtGeneration]);-- const loadOrganizations = useCallback(async (generation: number) => {- const result = await organizationRequest<{ organizations: Organization[] }>(- '/api/cloud-management/organizations',- );- if (generation !== operationGeneration.current) return;- setOrganizations(result.organizations);- if (result.organizations.length === 0) {- setSelectedOrganizationId(null);- setDetail(null);- setGate('connected');- return;- }- const remembered = sessionStorage.getItem(SELECTED_ORG_KEY);- const selected = result.organizations.some((item) => item.id === remembered)- ? remembered!- : result.organizations[0].id;- if (await loadOrganizationAtGeneration(selected, generation)) {- setGate('connected');- }- }, [loadOrganizationAtGeneration]);-- const probe = useCallback(async () => {- const generation = ++operationGeneration.current;- const returnedError = callbackError();- if (returnedError === 'cloud_management_subject_mismatch') {- setGate('subject_mismatch');- return;- }- setGate('loading');- try {- const result = await organizationRequest<CloudManagementSession>(- '/api/cloud-management/session',- );- if (generation !== operationGeneration.current) return;- if (!result.connected) {- setSession(null);- setOrganizations([]);- setDetail(null);- if (result.state === 'cloud_not_connected') {- setGate('cloud_not_connected');- } else if (result.state === 'subject_mismatch') {- setGate('subject_mismatch');- } else if (- result.can_silent_reauthorize- && !silentAttempted.current- && returnedError === null- ) {- silentAttempted.current = true;- await startAuthorization('silent');- } else {- setGate('authorization_required');- }- return;- }- setSession(result);- silentAttempted.current = false;- await loadOrganizations(generation);- } catch (error) {- if (generation !== operationGeneration.current) return;- setGate(gateForOrganizationError(- error,- returnedError ? 'authorization_required' : 'revoked',- ));- }- }, [loadOrganizations, startAuthorization]);-- useEffect(() => {- void probe();- }, [probe]);-- const request = useCallback(async <T,>(path: string, init: RequestInit = {}): Promise<T> => {- try {- return await organizationRequest<T>(path, init);- } catch (error) {- if (error instanceof OrganizationApiError) {- if (error.code === 'cloud_management_subject_mismatch') {- operationGeneration.current += 1;- setGate('subject_mismatch');- } else if (error.status === 401) {- if (error.canSilentReauthorize && !silentAttempted.current) {- silentAttempted.current = true;- await startAuthorization('silent');- } else {- operationGeneration.current += 1;- setGate('revoked');- }- } else if (error.status >= 500 && error.retryable) {- setGate('unreachable');- }- }- throw error;- }- }, [startAuthorization]);-- const signOut = useCallback(async () => {- operationGeneration.current += 1;- try {- await organizationRequest('/api/cloud-management/session', { method: 'DELETE' });- } finally {- operationGeneration.current += 1;- setSession(null);- setOrganizations([]);- setDetail(null);- setGate('authorization_required');- silentAttempted.current = true;- }- }, []);-- const refreshOrganization = useCallback(async () => {- if (!selectedOrganizationId) return;- const generation = ++operationGeneration.current;- try {- await loadOrganizationAtGeneration(selectedOrganizationId, generation);- } catch (error) {- if (generation !== operationGeneration.current) return;- setGate(gateForOrganizationError(error, 'revoked'));- }- }, [loadOrganizationAtGeneration, selectedOrganizationId]);-- const value = useMemo<OrganizationContextValue>(() => ({- gate,- session,- organizations,- selectedOrganizationId,- detail,- dataVersion,- signIn: () => startAuthorization('interactive'),- signOut,- retry: probe,- selectOrganization,- refreshOrganization,- invalidate: () => setDataVersion((version) => version + 1),- request,- }), [- dataVersion,- detail,- gate,- organizations,- probe,- refreshOrganization,- request,- selectedOrganizationId,- session,- selectOrganization,- signOut,- startAuthorization,- ]);-- return <OrganizationContext.Provider value={value}>{children}</OrganizationContext.Provider>;-}diff --git a/ui/src/features/organization/OrganizationShell.test.tsx b/ui/src/features/organization/OrganizationShell.test.tsxdeleted file mode 100644index 291d838cd..000000000--- a/ui/src/features/organization/OrganizationShell.test.tsx+++ /dev/null@@ -1,81 +0,0 @@-/* @vitest-environment jsdom */--import { afterEach, describe, expect, it, vi } from 'vitest';-import { cleanup, render, screen } from '@testing-library/react';-import { MemoryRouter } from 'react-router-dom';--import { InstanceAuthorizationContext, type InstanceAuthorizationValue } from '@/context/InstanceAuthorizationContext';-import { OWNER_INSTANCE_CAPABILITIES } from '@/lib/sessionInfo';--import { OrganizationShell } from './OrganizationShell';--const organizationState = vi.hoisted(() => ({- gate: 'cloud_not_connected' as const,- signIn: vi.fn(),- retry: vi.fn(),- selectOrganization: vi.fn(),- signOut: vi.fn(),- organizations: [],- selectedOrganizationId: null,- detail: {- organization: { name: 'Acme' },- membership: { role: 'owner' },- },- session: {- user: { email: '[email protected]' },- expires_in: 3600,- },-}));--vi.mock('./context', () => ({- useOrganization: () => organizationState,-}));--vi.mock('./OrganizationProvider', () => ({- OrganizationProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,-}));--vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}));--function renderShell(capabilities: InstanceAuthorizationValue['capabilities']) {- render(- <InstanceAuthorizationContext.Provider- value={{- remote: true,- instanceKind: 'organization',- instanceRole: 'owner',- capabilities,- }}- >- <MemoryRouter>- <OrganizationShell />- </MemoryRouter>- </InstanceAuthorizationContext.Provider>,- );-}--describe('OrganizationShell cloud_not_connected action', () => {- afterEach(() => {- cleanup();- vi.clearAllMocks();- });-- it('keeps the remote access CTA reachable for owners', () => {- renderShell(OWNER_INSTANCE_CAPABILITIES);-- const action = screen.getByRole('link', { name: 'organization.actions.openRemoteAccess' });- expect(action.getAttribute('href')).toBe('/admin/remote-access');- });-- it('sends remote owners to a reachable control-panel destination', () => {- renderShell({- ...OWNER_INSTANCE_CAPABILITIES,- can_use_system: false,- });-- const actions = screen.getAllByRole('link', { name: 'organization.actions.backToControlPanel' });- expect(actions.every((action) => action.getAttribute('href') === '/admin/settings/messaging')).toBe(true);- });-});diff --git a/ui/src/features/organization/OrganizationShell.tsx b/ui/src/features/organization/OrganizationShell.tsxdeleted file mode 100644index 023bfbfe9..000000000--- a/ui/src/features/organization/OrganizationShell.tsx+++ /dev/null@@ -1,245 +0,0 @@-import {- ArrowLeft,- Boxes,- Building2,- Cloud,- CloudOff,- Grid2x2,- LoaderCircle,- LogOut,- Server,- ShieldAlert,- Users,- WifiOff,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';-import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';-import clsx from 'clsx';--import { Button } from '@/components/ui/button';-import { Select } from '@/components/ui/select';-import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';-import { adminLandingPath } from '@/lib/adminNavigation';--import { useOrganization } from './context';-import { OrganizationProvider } from './OrganizationProvider';-import { EmptyState, InitialsAvatar } from './components';-import { organizationSwitchDestination } from './policy';--const NAV = [- { path: '/admin/organization/overview', key: 'overview', icon: Grid2x2 },- { path: '/admin/organization/instances', key: 'instances', icon: Server },- { path: '/admin/organization/members', key: 'members', icon: Users },- { path: '/admin/organization/groups', key: 'groups', icon: Boxes },- { path: '/admin/organization/resources', key: 'resources', icon: Building2 },-] as const;--// Resolve "back to control panel" against the current Instance capability.-function useBackToControlPanelPath(): string {- const { capabilities } = useInstanceAuthorization();- return adminLandingPath(capabilities.can_use_system);-}--function GateState() {- const { t } = useTranslation();- const { gate, signIn, retry } = useOrganization();- const { capabilities } = useInstanceAuthorization();- const backToControlPanelPath = useBackToControlPanelPath();- const cloudNotConnectedPath = capabilities.can_use_system ? '/admin/remote-access' : backToControlPanelPath;- const cloudNotConnectedLabel = capabilities.can_use_system- ? t('organization.actions.openRemoteAccess')- : t('organization.actions.backToControlPanel');- if (gate === 'loading' || gate === 'reauthorizing') {- return (- <div className="grid min-h-[100dvh] place-items-center bg-background p-6 text-center">- <div>- <LoaderCircle className="mx-auto size-8 animate-spin text-mint-ink" />- <h1 className="mt-4 text-lg font-semibold">- {t(gate === 'reauthorizing' ? 'organization.states.reauthorizingTitle' : 'organization.states.loadingTitle')}- </h1>- <p className="mt-1 text-[13px] text-muted">- {t(gate === 'reauthorizing' ? 'organization.states.reauthorizingBody' : 'organization.states.loadingBody')}- </p>- </div>- </div>- );- }- const config = {- cloud_not_connected: {- icon: CloudOff,- title: t('organization.states.notConnectedTitle'),- body: t('organization.states.notConnectedBody'),- action: <Button asChild variant="brand"><Link to={cloudNotConnectedPath}>{cloudNotConnectedLabel}</Link></Button>,- },- authorization_required: {- icon: Cloud,- title: t('organization.states.signInTitle'),- body: t('organization.states.signInBody'),- action: <Button variant="brand" onClick={() => void signIn()}>{t('organization.actions.signIn')}</Button>,- },- subject_mismatch: {- icon: ShieldAlert,- title: t('organization.states.mismatchTitle'),- body: t('organization.states.mismatchBody'),- action: <Button variant="brand" onClick={() => void signIn()}>{t('organization.actions.signInAgain')}</Button>,- },- unreachable: {- icon: WifiOff,- title: t('organization.states.unreachableTitle'),- body: t('organization.states.unreachableBody'),- action: <Button variant="outline" onClick={() => void retry()}>{t('common.retry')}</Button>,- },- revoked: {- icon: ShieldAlert,- title: t('organization.states.revokedTitle'),- body: t('organization.states.revokedBody'),- action: <Button variant="brand" onClick={() => void signIn()}>{t('organization.actions.signIn')}</Button>,- },- error: {- icon: ShieldAlert,- title: t('organization.states.errorTitle'),- body: t('organization.errors.generic'),- action: <Button variant="outline" onClick={() => void retry()}>{t('common.retry')}</Button>,- },- } as const;- const state = config[gate as keyof typeof config] ?? config.error;- const Icon = state.icon;- return (- <div className="min-h-[100dvh] bg-background p-4 md:p-8">- <Link to={backToControlPanelPath} className="inline-flex items-center gap-2 text-[13px] text-muted hover:text-foreground">- <ArrowLeft className="size-4" />- {t('organization.actions.backToControlPanel')}- </Link>- <div className="mx-auto mt-20 max-w-xl">- <EmptyState- title={state.title}- body={state.body}- action={state.action}- />- <Icon className="sr-only" />- </div>- </div>- );-}--function OrganizationNavbar() {- const { t } = useTranslation();- const location = useLocation();- const navigate = useNavigate();- const {- organizations,- selectedOrganizationId,- selectOrganization,- detail,- session,- signOut,- } = useOrganization();- const switchOrganization = async (organizationId: string) => {- const destination = organizationSwitchDestination(location.pathname);- if (destination) navigate(destination, { replace: true });- await selectOrganization(organizationId);- };- return (- <header className="border-b border-border bg-background/95 px-4 pt-5 backdrop-blur md:px-10 md:pt-8">- <div className="flex flex-wrap items-start justify-between gap-4">- <div className="flex min-w-0 items-start gap-3">- <InitialsAvatar value={detail?.organization.name ?? ''} tone="violet" />- <div className="min-w-0">- <h1 className="truncate text-[28px] font-bold leading-tight tracking-[-0.4px] text-foreground">- {detail?.organization.name}- </h1>- <p className="mt-1 text-[14px] leading-[1.55] text-muted">- {t(`organization.roles.${detail?.membership.role ?? 'member'}`)}- {organizations.length > 1 ? ` · ${t('organization.sidebar.organizationCount', { count: organizations.length })}` : ''}- </p>- </div>- </div>- <div className="flex shrink-0 items-center gap-2">- {organizations.length > 1 ? (- <Select- className="w-auto min-w-[150px]"- value={selectedOrganizationId ?? ''}- aria-label={t('organization.sidebar.switchOrganization')}- onChange={(event) => void switchOrganization(event.target.value)}- >- {organizations.map((organization) => (- <option key={organization.id} value={organization.id}>{organization.name}</option>- ))}- </Select>- ) : null}- <div className="hidden items-center gap-2 sm:flex">- <div className="rounded-lg border border-mint/30 bg-mint/10 px-3 py-2">- <div className="flex items-center gap-2 text-[12px] font-semibold">- <span className="size-2 rounded-full bg-mint shadow-glow-dot-mint" />- {t('organization.sidebar.cloudConnected')}- <span className="font-mono text-[10px] font-normal text-muted">- · {t('organization.sidebar.sessionRemaining', { minutes: Math.max(1, Math.ceil((session?.expires_in ?? 0) / 60)) })}- </span>- </div>- </div>- <InitialsAvatar value={session?.user.email ?? ''} className="size-8 rounded-full" />- </div>- <Button- variant="ghost"- size="sm"- aria-label={t('organization.actions.signOut')}- onClick={() => void signOut()}- >- <LogOut className="size-4" />- <span>{t('organization.actions.signOut')}</span>- </Button>- </div>- </div>- <nav className="mt-6 -mb-px overflow-x-auto" aria-label={t('organization.sidebar.section')}>- <div className="flex min-w-max gap-1">- {NAV.map((item) => {- const Icon = item.icon;- return (- <NavLink key={item.path} to={item.path} className={({ isActive }) => clsx(- 'inline-flex h-11 shrink-0 items-center gap-2 border-b-2 px-4 text-[13px] transition-colors',- isActive ? 'border-mint font-semibold text-foreground' : 'border-transparent font-medium text-muted hover:border-border-strong hover:text-foreground',- )}>- <Icon className="size-4" />- {t(`organization.nav.${item.key}`)}- </NavLink>- );- })}- </div>- </nav>- </header>- );-}--function ConnectedShell() {- const { t } = useTranslation();- const location = useLocation();- const { organizations, detail } = useOrganization();- if (organizations.length === 0 || !detail) {- return (- <div className="min-h-[100dvh] bg-background p-6">- <EmptyState title={t('organization.states.emptyTitle')} body={t('organization.states.emptyBody')} />- </div>- );- }- return (- <div className="min-h-[100dvh] bg-background text-foreground">- <OrganizationNavbar />- <main key={location.pathname} className="mx-auto w-full max-w-[1560px] px-4 py-5 md:px-8 md:py-7">- <Outlet />- </main>- </div>- );-}--function OrganizationShellInner() {- const { gate } = useOrganization();- return gate === 'connected' ? <ConnectedShell /> : <GateState />;-}--export function OrganizationShell() {- return (- <OrganizationProvider>- <OrganizationShellInner />- </OrganizationProvider>- );-}diff --git a/ui/src/features/organization/api/client.ts b/ui/src/features/organization/api/client.tsdeleted file mode 100644index 3e7aa1cf7..000000000--- a/ui/src/features/organization/api/client.ts+++ /dev/null@@ -1,59 +0,0 @@-import { apiFetch } from '@/lib/apiFetch';--import type { CloudErrorPayload } from './types';--export class OrganizationApiError extends Error {- status: number;- code: string;- retryable: boolean;- currentRevision?: number;- canSilentReauthorize: boolean;-- constructor(status: number, payload: CloudErrorPayload = {}) {- const code = payload.error || 'cloud_management_unavailable';- super(code);- this.name = 'OrganizationApiError';- this.status = status;- this.code = code;- this.retryable = payload.retryable === true;- this.currentRevision = payload.current_revision;- this.canSilentReauthorize = payload.can_silent_reauthorize === true;- }-}--export async function organizationRequest<T>(path: string, init: RequestInit = {}): Promise<T> {- if (!path.startsWith('/api/cloud-management/')) {- throw new Error('Organization API path must use the local management proxy');- }- const headers = new Headers(init.headers);- if (init.body !== undefined && !headers.has('Content-Type')) {- headers.set('Content-Type', 'application/json');- }- const response = await apiFetch(path, {- ...init,- headers,- credentials: 'same-origin',- });- let payload: unknown = {};- try {- payload = await response.json();- } catch {- throw new OrganizationApiError(response.ok ? 502 : response.status);- }- if (!response.ok) {- throw new OrganizationApiError(response.status, payload as CloudErrorPayload);- }- return payload as T;-}--export function jsonBody(value: unknown): string {- return JSON.stringify(value);-}--export function isRevisionConflict(error: unknown): error is OrganizationApiError {- return error instanceof OrganizationApiError- && error.status === 409- && (error.code === 'organization_member_conflict'- || error.code === 'organization_group_conflict'- || error.code === 'resource_sync_conflict');-}diff --git a/ui/src/features/organization/api/types.ts b/ui/src/features/organization/api/types.tsdeleted file mode 100644index 55415678b..000000000--- a/ui/src/features/organization/api/types.ts+++ /dev/null@@ -1,204 +0,0 @@-export type OrganizationRole = 'owner' | 'admin' | 'member';-export type MemberStatus = 'active' | 'invited' | 'removed';-export type AccessRole = 'viewer' | 'editor';-export type SyncStatus = 'none' | 'in_sync' | 'applying' | 'pending' | 'offline' | 'error' | 'deleted';-export type GroupColor = 'mint' | 'cyan' | 'blue' | 'violet' | 'rose' | 'gold';--export type Organization = {- id: string;- name: string;- slug: string;- plan: string;- created_at: string;- updated_at: string;- role: OrganizationRole;- member_id: string;-};--export type GroupSummary = {- id: string;- name: string;- archived_at: string | null;-};--export type OrganizationDetail = {- organization: Omit<Organization, 'role' | 'member_id'>;- membership: {- id: string;- role: OrganizationRole;- status: MemberStatus;- member_revision: number;- groups: GroupSummary[];- };- capabilities: { can_manage_organization: boolean };- counts: {- members: number;- groups: number;- instances: number;- domains?: number;- invitedMembers?: number;- removedMembers?: number;- archivedGroups?: number;- };-};--export type OrganizationMember = {- id: string;- user_id: string | null;- email: string;- role: OrganizationRole;- status: MemberStatus;- member_revision: number;- invited_by_user_id: string | null;- created_at: string;- updated_at: string;- groups: GroupSummary[];-};--export type GroupUsage = { instances: number; projects: number; resources: number };-export type GroupReferences = {- instances: Array<{ id: string; slug: string }>;- projects: Array<{ instanceId: string; projectId: string; displayName: string }>;- resources: Array<{- instanceId: string;- resourceKind: string;- resourceId: string;- displayName: string;- }>;-};--export type OrganizationGroup = {- id: string;- name: string;- normalized_name: string;- description: string | null;- color: GroupColor | null;- group_revision: number;- member_count?: number;- archived_at: string | null;- created_at: string;- updated_at: string;- is_member: boolean;- can_manage: boolean;- usage?: GroupUsage;- members?: OrganizationMember[];- references?: GroupReferences;-};--export type SyncCounts = {- active: number;- error: number;- offline: number;- applying: number;- in_sync: number;-};--export type OrganizationInstance = {- id: string;- slug: string;- organization_id: string;- owner_user_id: string | null;- owner_email: string | null;- owner_is_current_user: boolean;- can_manage_access: boolean;- public_hostname: string;- primary_url: string;- managed_url: string;- status: 'pending' | 'active' | 'disabled' | 'deleted';- paired: boolean;- access_entries_count: number;- policy_sync: {- status: Exclude<SyncStatus, 'pending' | 'deleted'>;- projects: SyncCounts;- resources: SyncCounts;- };- hostnames: Array<{- id: string;- hostname: string;- kind?: string;- status?: string;- primary?: boolean;- }>;-};--export type InstanceAccessEntry = {- id?: string;- instanceId?: string;- kind: 'email' | 'email_domain' | 'organization_group';- value: string;- role: AccessRole;- createdAt?: string;-};--export type ProjectBinding = {- principal_kind: 'email' | 'email_domain' | 'organization_group';- principal_value: string;- access_role: AccessRole;-};--export type OrganizationProject = {- project_id: string;- organization_id: string | null;- display_name: string;- access: {- mode: 'inherit' | 'restricted';- revision: number;- bindings: ProjectBinding[];- };- sync: {- status: SyncStatus;- desired_access_revision: number;- applied_access_revision: number;- last_synced_at: string | null;- last_sync_error?: string;- };-};--export type ResourceKind = 'agent' | 'vault_secret' | 'skill' | 'show_page';-export type ResourceAccessLevel = 'public' | 'scope' | 'private';--export type OrganizationResource = {- instance_id: string;- resource_kind: ResourceKind;- resource_id: string;- display_name: string;- owner_user_id: string | null;- access: {- access_level: ResourceAccessLevel;- group_ids: string[];- revision: number;- } | null;- sync: {- status: SyncStatus;- desired_acl_revision: number;- applied_acl_revision: number;- last_synced_at: string | null;- last_sync_error?: string;- };-};--export type CloudManagementSession =- | { connected: false; state: 'cloud_not_connected' }- | {- connected: false;- state: 'authorization_required';- can_silent_reauthorize: boolean;- }- | {- connected: false;- state: 'subject_mismatch';- error: 'cloud_management_subject_mismatch';- }- | {- connected: true;- state: 'connected';- user: { subject: string; email: string };- expires_in: number;- };--export type CloudErrorPayload = {- error?: string;- retryable?: boolean;- current_revision?: number;- can_silent_reauthorize?: boolean;-};diff --git a/ui/src/features/organization/components.tsx b/ui/src/features/organization/components.tsxdeleted file mode 100644index f5d7803f1..000000000--- a/ui/src/features/organization/components.tsx+++ /dev/null@@ -1,260 +0,0 @@-import React from 'react';-import {- AlertTriangle,- CheckCircle2,- CloudOff,- LoaderCircle,- Search,- ShieldAlert,- WifiOff,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';-import clsx from 'clsx';--import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';-import { Card } from '@/components/ui/card';-import { Input } from '@/components/ui/input';--import type {- GroupColor,- OrganizationRole,- SyncStatus,-} from './api/types';--export function PageHeader({- title,- titleAccessory,- description,- eyebrow,- actions,-}: {- title: string;- titleAccessory?: React.ReactNode;- description?: string;- eyebrow?: string;- actions?: React.ReactNode;-}) {- return (- <header className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">- <div className="min-w-0">- {eyebrow ? <div className="mb-2 text-[13px] text-muted">{eyebrow}</div> : null}- <div className="flex min-w-0 flex-wrap items-center gap-2">- <h1 className="min-w-0 text-2xl font-semibold md:text-[30px]">{title}</h1>- {titleAccessory}- </div>- {description ? <p className="mt-1.5 max-w-4xl text-[13px] leading-5 text-muted md:text-sm">{description}</p> : null}- </div>- {actions ? <div className="flex shrink-0 flex-wrap items-center gap-2">{actions}</div> : null}- </header>- );-}--export function SearchField({ value, onChange, placeholder }: {- value: string;- onChange: (value: string) => void;- placeholder: string;-}) {- return (- <label className="flex h-9 min-w-0 items-center gap-2 rounded-lg border border-border bg-card px-3 md:w-64">- <Search className="size-4 shrink-0 text-muted" />- <Input- variant="bare"- value={value}- onChange={(event) => onChange(event.target.value)}- placeholder={placeholder}- className="min-w-0 flex-1 text-[13px]"- />- </label>- );-}--export function TableFrame({ children, className }: { children: React.ReactNode; className?: string }) {- return <div className={clsx('overflow-hidden rounded-lg border border-border bg-card', className)}>{children}</div>;-}--export function StatCard({ label, value, detail, icon }: {- label: string;- value: React.ReactNode;- detail?: string;- icon: React.ReactNode;-}) {- return (- <Card className="flex min-h-28 items-start justify-between p-4">- <div>- <div className="font-mono text-[10px] font-bold uppercase text-muted">{label}</div>- <div className="mt-3 text-3xl font-semibold tabular-nums">{value}</div>- {detail ? <div className="mt-1 text-[12px] text-muted">{detail}</div> : null}- </div>- <div className="grid size-9 place-items-center rounded-lg bg-mint/10 text-mint-ink">{icon}</div>- </Card>- );-}--export function InitialsAvatar({ value, tone = 'mint', className }: {- value: string;- tone?: 'mint' | 'cyan' | 'violet' | 'gold' | 'pink';- className?: string;-}) {- const initial = value.trim().charAt(0).toUpperCase() || '?';- const tones = {- mint: 'border-mint/30 bg-mint/15 text-mint-ink',- cyan: 'border-cyan/30 bg-cyan/15 text-cyan-ink',- violet: 'border-violet/30 bg-violet/15 text-violet-ink',- gold: 'border-gold/30 bg-gold/15 text-gold-ink',- pink: 'border-pink/30 bg-pink/15 text-pink-ink',- };- return (- <span className={clsx('grid size-9 shrink-0 place-items-center rounded-lg border text-[13px] font-bold', tones[tone], className)}>- {initial}- </span>- );-}--export function RoleBadge({ role }: { role: OrganizationRole }) {- const { t } = useTranslation();- return (- <Badge variant={role === 'owner' ? 'success' : role === 'admin' ? 'info' : 'secondary'}>- {t(`organization.roles.${role}`)}- </Badge>- );-}--const GROUP_TONES: Record<GroupColor, string> = {- mint: 'border-mint/25 bg-mint/10 text-mint-ink',- cyan: 'border-cyan/25 bg-cyan/10 text-cyan-ink',- blue: 'border-cyan/25 bg-cyan/10 text-cyan-ink',- violet: 'border-violet/25 bg-violet/10 text-violet-ink',- rose: 'border-pink/25 bg-pink/10 text-pink-ink',- gold: 'border-gold/25 bg-gold/10 text-gold-ink',-};--export function GroupPill({ name, color = 'violet' }: { name: string; color?: GroupColor | null }) {- return (- <span className={clsx('inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] font-medium', GROUP_TONES[color ?? 'violet'])}>- <span className="size-1.5 rounded-full bg-current" />- {name}- </span>- );-}--export function SyncBadge({ status }: { status: SyncStatus }) {- const { t } = useTranslation();- const normalized = status === 'pending' ? 'applying' : status;- const variant = normalized === 'in_sync'- ? 'success'- : normalized === 'applying'- ? 'warning'- : normalized === 'error'- ? 'destructive'- : 'secondary';- const Icon = normalized === 'in_sync'- ? CheckCircle2- : normalized === 'applying'- ? LoaderCircle- : normalized === 'offline'- ? WifiOff- : normalized === 'error'- ? AlertTriangle- : CloudOff;- return (- <Badge variant={variant}>- <Icon className={clsx('size-3', normalized === 'applying' && 'animate-spin')} />- {t(`organization.sync.${normalized}`)}- </Badge>- );-}--export function LoadingState({ rows = 5 }: { rows?: number }) {- const { t } = useTranslation();- return (- <div className="space-y-3" aria-label={t('organization.states.loadingTitle')}>- {Array.from({ length: rows }, (_, index) => (- <div key={index} className="h-16 animate-pulse rounded-lg border border-border bg-card/70" />- ))}- </div>- );-}--export function EmptyState({ title, body, action }: { title: string; body: string; action?: React.ReactNode }) {- return (- <div className="flex min-h-64 flex-col items-center justify-center rounded-lg border border-dashed border-border px-6 text-center">- <CloudOff className="mb-4 size-8 text-muted" />- <h2 className="text-[15px] font-semibold">{title}</h2>- <p className="mt-1 max-w-md text-[13px] leading-5 text-muted">{body}</p>- {action ? <div className="mt-5">{action}</div> : null}- </div>- );-}--export function ForbiddenState() {- const { t } = useTranslation();- return (- <EmptyState- title={t('organization.states.unavailableTitle')}- body={t('organization.states.unavailableBody')}- />- );-}--export function ErrorBanner({ code, onRetry }: { code?: string; onRetry?: () => void }) {- const { t } = useTranslation();- const known = [- 'forbidden',- 'organization_not_found',- 'organization_member_not_found',- 'organization_group_not_found',- 'organization_group_archived',- 'instance_not_found',- 'project_not_found',- 'resource_not_found',- 'member_email_taken',- 'group_name_taken',- 'organization_member_not_active_in_organization',- 'invalid_organization_group_name',- 'invalid_organization_group_color',- 'invalid_request',- 'too_many_entries',- 'invalid_project_access_intent',- 'invalid_project_access_principal',- 'invalid_project_access_role',- 'invalid_resource_acl_intent',- 'invalid_email',- 'invalid_domain',- 'duplicate_instance_access_principal',- 'duplicate_project_access_principal',- 'owner_entry_locked',- 'resource_sync_conflict',- 'organization_member_conflict',- 'organization_group_conflict',- ];- const messageKey = code && known.includes(code) ? `organization.errors.${code}` : 'organization.errors.generic';- return (- <div className="flex flex-col gap-3 rounded-lg border border-destructive/35 bg-destructive/10 p-4 sm:flex-row sm:items-center sm:justify-between">- <div className="flex items-start gap-3">- <ShieldAlert className="mt-0.5 size-4 shrink-0 text-destructive-ink" />- <div>- <div className="text-[13px] font-semibold">{t('organization.states.errorTitle')}</div>- <div className="mt-0.5 text-[12px] text-muted">{t(messageKey)}</div>- </div>- </div>- {onRetry ? <Button variant="outline" size="sm" onClick={onRetry}>{t('common.retry')}</Button> : null}- </div>- );-}--export function ConflictBanner({ onReload }: { onReload: () => void }) {- const { t } = useTranslation();- return (- <div className="flex flex-col gap-3 rounded-lg border border-gold/35 bg-gold/10 p-4 sm:flex-row sm:items-center sm:justify-between">- <div className="flex items-start gap-3">- <AlertTriangle className="mt-0.5 size-4 shrink-0 text-gold-ink" />- <div>- <div className="text-[13px] font-semibold">{t('organization.states.conflictTitle')}</div>- <div className="mt-0.5 text-[12px] text-muted">{t('organization.states.conflictBody')}</div>- </div>- </div>- <Button variant="outline" size="sm" onClick={onReload}>{t('organization.actions.reload')}</Button>- </div>- );-}diff --git a/ui/src/features/organization/context.ts b/ui/src/features/organization/context.tsdeleted file mode 100644index 0294a0e66..000000000--- a/ui/src/features/organization/context.ts+++ /dev/null@@ -1,42 +0,0 @@-import { createContext, useContext } from 'react';--import type {- CloudManagementSession,- Organization,- OrganizationDetail,-} from './api/types';--export type GateState =- | 'loading'- | 'cloud_not_connected'- | 'authorization_required'- | 'reauthorizing'- | 'subject_mismatch'- | 'unreachable'- | 'revoked'- | 'connected'- | 'error';--export type OrganizationContextValue = {- gate: GateState;- session: Extract<CloudManagementSession, { connected: true }> | null;- organizations: Organization[];- selectedOrganizationId: string | null;- detail: OrganizationDetail | null;- dataVersion: number;- signIn: () => Promise<void>;- signOut: () => Promise<void>;- retry: () => Promise<void>;- selectOrganization: (organizationId: string) => Promise<void>;- refreshOrganization: () => Promise<void>;- invalidate: () => void;- request: <T>(path: string, init?: RequestInit) => Promise<T>;-};--export const OrganizationContext = createContext<OrganizationContextValue | null>(null);--export function useOrganization(): OrganizationContextValue {- const value = useContext(OrganizationContext);- if (!value) throw new Error('useOrganization must be used within OrganizationProvider');- return value;-}diff --git a/ui/src/features/organization/pages/OrganizationGroupsPages.tsx b/ui/src/features/organization/pages/OrganizationGroupsPages.tsxdeleted file mode 100644index 9fa3e4c78..000000000--- a/ui/src/features/organization/pages/OrganizationGroupsPages.tsx+++ /dev/null@@ -1,673 +0,0 @@-import React, {- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from 'react';-import {- Archive,- Boxes,- Pencil,- Plus,- RotateCcw,- Server,- Workflow,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';-import { Link, useParams } from 'react-router-dom';--import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';-import { Checkbox } from '@/components/ui/checkbox';-import { ConfirmDialog } from '@/components/ui/confirm-dialog';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { SegmentedRadio } from '@/components/ui/segmented';-import { Textarea } from '@/components/ui/textarea';--import { isRevisionConflict, jsonBody, OrganizationApiError } from '../api/client';-import type {- GroupColor,- OrganizationGroup,- OrganizationMember,-} from '../api/types';-import {- ConflictBanner,- EmptyState,- ErrorBanner,- GroupPill,- InitialsAvatar,- LoadingState,- PageHeader,- RoleBadge,- SearchField,- TableFrame,-} from '../components';-import { useOrganization } from '../context';-import { isCurrentOrganizationLoad } from '../policy';--type GroupFilter = 'active' | 'archived' | 'all';--const COLORS: GroupColor[] = ['mint', 'cyan', 'blue', 'violet', 'rose', 'gold'];--function GroupDialog({- open,- group,- members,- onOpenChange,- onSaved,-}: {- open: boolean;- group: OrganizationGroup | null;- members: OrganizationMember[];- onOpenChange: (open: boolean) => void;- onSaved: () => Promise<OrganizationGroup | null>;-}) {- const { t } = useTranslation();- const { selectedOrganizationId, request, invalidate } = useOrganization();- const [name, setName] = useState('');- const [description, setDescription] = useState('');- const [color, setColor] = useState<GroupColor>('violet');- const [memberIds, setMemberIds] = useState<string[]>([]);- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string>();- const [conflict, setConflict] = useState(false);- const [authoritativeGroup, setAuthoritativeGroup] = useState<OrganizationGroup | null>(null);- const [revision, setRevision] = useState(0);- const draftKey = useRef<string | null>(null);-- useEffect(() => {- if (!open) {- draftKey.current = null;- return;- }- const key = group?.id ?? 'new';- if (draftKey.current === key) return;- draftKey.current = key;- setName(group?.name ?? '');- setDescription(group?.description ?? '');- setColor(group?.color ?? 'violet');- setMemberIds(group?.members?.map((member) => member.id) ?? []);- setRevision(group?.group_revision ?? 0);- setError(undefined);- setConflict(false);- setAuthoritativeGroup(null);- }, [group, open]);-- const save = async () => {- if (!selectedOrganizationId || !name.trim()) return;- setSaving(true);- setError(undefined);- try {- const base = `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/groups`;- if (group) {- await request(`${base}/${encodeURIComponent(group.id)}`, {- method: 'PATCH',- body: jsonBody({- name: name.trim(),- description: description.trim() || null,- color,- if_match_revision: revision,- }),- });- } else {- await request(base, {- method: 'POST',- body: jsonBody({- name: name.trim(),- description: description.trim() || null,- color,- member_ids: memberIds,- }),- });- }- invalidate();- await onSaved();- onOpenChange(false);- } catch (caught) {- if (isRevisionConflict(caught)) {- setAuthoritativeGroup(await onSaved());- setConflict(true);- } else {- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');- }- } finally {- setSaving(false);- }- };-- const reloadAuthoritativeGroup = () => {- if (!authoritativeGroup) {- onOpenChange(false);- return;- }- setName(authoritativeGroup.name);- setDescription(authoritativeGroup.description ?? '');- setColor(authoritativeGroup.color ?? 'violet');- setRevision(authoritativeGroup.group_revision);- setError(undefined);- setConflict(false);- setAuthoritativeGroup(null);- };-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>{t(group ? 'organization.groups.editTitle' : 'organization.groups.createTitle')}</DialogTitle>- <DialogDescription>{t(group ? 'organization.groups.editBody' : 'organization.groups.createBody')}</DialogDescription>- </DialogHeader>- {conflict ? <ConflictBanner onReload={reloadAuthoritativeGroup} /> : null}- {error ? <ErrorBanner code={error} /> : null}- <div className="space-y-4">- <div className="space-y-1.5">- <Label htmlFor="organization-group-name">{t('organization.fields.name')}</Label>- <Input id="organization-group-name" value={name} onChange={(event) => setName(event.target.value)} />- </div>- <div className="space-y-1.5">- <Label htmlFor="organization-group-description">{t('organization.fields.description')}</Label>- <Textarea id="organization-group-description" value={description} onChange={(event) => setDescription(event.target.value)} />- </div>- <fieldset>- <legend className="mb-2 text-[12px] font-medium">{t('organization.fields.color')}</legend>- <div className="flex flex-wrap gap-2">- {COLORS.map((option) => (- <button- key={option}- type="button"- className={`rounded-lg border p-1.5 ${color === option ? 'border-mint bg-mint/10' : 'border-border'}`}- onClick={() => setColor(option)}- aria-label={t(`organization.colors.${option}`)}- >- <GroupPill name={t(`organization.colors.${option}`)} color={option} />- </button>- ))}- </div>- </fieldset>- {!group && members.length ? (- <fieldset>- <legend className="mb-2 text-[12px] font-medium">{t('organization.groups.initialMembers')}</legend>- <div className="max-h-48 space-y-1 overflow-y-auto rounded-lg border border-border p-2">- {members.filter((member) => member.status === 'active').map((member) => (- <button- key={member.id}- type="button"- role="checkbox"- aria-checked={memberIds.includes(member.id)}- className="flex w-full items-center gap-3 rounded-md px-2 py-2 text-left hover:bg-foreground/[0.04]"- onClick={() => setMemberIds((current) => current.includes(member.id)- ? current.filter((id) => id !== member.id)- : [...current, member.id])}- >- <Checkbox checked={memberIds.includes(member.id)} presentational />- <span className="truncate text-[12px]">{member.email}</span>- </button>- ))}- </div>- </fieldset>- ) : null}- </div>- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>- <Button variant="brand" disabled={saving || conflict || !name.trim()} onClick={() => void save()}>- {saving ? t('organization.actions.saving') : t('organization.actions.saveChanges')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- );-}--function MemberPickerDialog({- open,- group,- allMembers,- onOpenChange,- onSaved,-}: {- open: boolean;- group: OrganizationGroup;- allMembers: OrganizationMember[];- onOpenChange: (open: boolean) => void;- onSaved: () => Promise<OrganizationGroup | null>;-}) {- const { t } = useTranslation();- const { selectedOrganizationId, request, invalidate } = useOrganization();- const [memberIds, setMemberIds] = useState<string[]>([]);- const [conflict, setConflict] = useState(false);- const [authoritativeGroup, setAuthoritativeGroup] = useState<OrganizationGroup | null>(null);- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string>();- const [revision, setRevision] = useState(group.group_revision);- const draftGroupId = useRef<string | null>(null);-- useEffect(() => {- if (!open) {- draftGroupId.current = null;- return;- }- if (draftGroupId.current === group.id) return;- draftGroupId.current = group.id;- setMemberIds(group.members?.map((member) => member.id) ?? []);- setRevision(group.group_revision);- setConflict(false);- setError(undefined);- setAuthoritativeGroup(null);- }, [group, open]);-- const save = async () => {- if (!selectedOrganizationId) return;- setSaving(true);- setError(undefined);- try {- await request(- `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/groups/${encodeURIComponent(group.id)}/members`,- {- method: 'PUT',- body: jsonBody({ member_ids: memberIds, if_match_revision: revision }),- },- );- invalidate();- await onSaved();- onOpenChange(false);- } catch (caught) {- if (isRevisionConflict(caught)) {- setAuthoritativeGroup(await onSaved());- setConflict(true);- setError(undefined);- } else {- setConflict(false);- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');- }- } finally {- setSaving(false);- }- };-- const reloadAuthoritativeGroup = () => {- if (!authoritativeGroup) {- onOpenChange(false);- return;- }- setMemberIds(authoritativeGroup.members?.map((member) => member.id) ?? []);- setRevision(authoritativeGroup.group_revision);- setConflict(false);- setError(undefined);- setAuthoritativeGroup(null);- };-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>{t('organization.groups.manageMembersTitle')}</DialogTitle>- <DialogDescription>{t('organization.groups.manageMembersBody', { name: group.name })}</DialogDescription>- </DialogHeader>- {conflict ? <ConflictBanner onReload={reloadAuthoritativeGroup} /> : null}- {error ? <ErrorBanner code={error} /> : null}- <div className="max-h-[45vh] space-y-1 overflow-y-auto rounded-lg border border-border p-2">- {allMembers.filter((member) => member.status === 'active').map((member) => (- <button- key={member.id}- type="button"- role="checkbox"- aria-checked={memberIds.includes(member.id)}- className="flex w-full items-center gap-3 rounded-md px-2 py-2 text-left hover:bg-foreground/[0.04]"- onClick={() => setMemberIds((current) => current.includes(member.id)- ? current.filter((id) => id !== member.id)- : [...current, member.id])}- >- <Checkbox checked={memberIds.includes(member.id)} presentational />- <InitialsAvatar value={member.email} className="size-8 rounded-full" />- <span className="min-w-0 flex-1 truncate text-[12px]">{member.email}</span>- <RoleBadge role={member.role} />- </button>- ))}- </div>- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>- <Button variant="brand" disabled={saving || conflict} onClick={() => void save()}>{t('organization.actions.saveMembers')}</Button>- </DialogFooter>- </DialogContent>- </Dialog>- );-}--export function OrganizationGroupsPage() {- const { t } = useTranslation();- const { detail, selectedOrganizationId, request, dataVersion } = useOrganization();- const [directory, setDirectory] = useState<{- organizationId: string;- groups: OrganizationGroup[];- members: OrganizationMember[];- } | null>(null);- const [filter, setFilter] = useState<GroupFilter>('active');- const [search, setSearch] = useState('');- const [errorState, setErrorState] = useState<{ organizationId: string; code: string } | null>(null);- const [dialogOpen, setDialogOpen] = useState(false);- const loadGeneration = useRef(0);- const selectedOrganizationIdRef = useRef(selectedOrganizationId);- const currentDirectory = directory?.organizationId === selectedOrganizationId ? directory : null;- const groups = currentDirectory?.groups ?? null;- const members = currentDirectory?.members ?? [];- 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 () => {- if (!selectedOrganizationId) return;- const organizationId = selectedOrganizationId;- const generation = ++loadGeneration.current;- const isCurrent = () => isCurrentOrganizationLoad(- organizationId,- selectedOrganizationIdRef.current,- generation,- loadGeneration.current,- );- setErrorState(null);- try {- const [groupResult, memberResult] = await Promise.all([- request<{ groups: OrganizationGroup[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/groups`,- ),- canManage- ? request<{ members: OrganizationMember[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/members`,- )- : Promise.resolve({ members: [] }),- ]);- if (!isCurrent()) return;- setDirectory({- organizationId,- groups: groupResult.groups,- members: memberResult.members,- });- } catch (caught) {- if (!isCurrent()) return;- setErrorState({- organizationId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- }, [canManage, request, selectedOrganizationId]);-- useEffect(() => {- const timer = window.setTimeout(() => void load(), 0);- return () => window.clearTimeout(timer);- }, [dataVersion, load]);-- const filtered = useMemo(() => (groups ?? []).filter((group) => (- (filter === 'all' || (filter === 'active' ? !group.archived_at : Boolean(group.archived_at)))- && `${group.name} ${group.description ?? ''}`.toLowerCase().includes(search.trim().toLowerCase())- )), [filter, groups, search]);-- if (!groups && !error) return <LoadingState />;- return (- <div className="space-y-6">- <PageHeader- eyebrow={t('organization.breadcrumb.groups')}- title={t('organization.nav.groups')}- description={canManage ? t('organization.groups.description') : t('organization.groups.memberDescription')}- actions={canManage ? <Button variant="brand" onClick={() => setDialogOpen(true)}><Plus className="size-4" />{t('organization.actions.newGroup')}</Button> : undefined}- />- {error ? <ErrorBanner code={error} onRetry={() => void load()} /> : null}- <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">- <SegmentedRadio- value={filter}- onChange={setFilter}- ariaLabel={t('organization.groups.filterLabel')}- options={([- ['active', t('organization.groups.active')],- ['archived', t('organization.groups.archived')],- ['all', t('organization.members.filterAll')],- ] as Array<[GroupFilter, string]>).map(([id, label]) => ({ id, label }))}- />- <SearchField value={search} onChange={setSearch} placeholder={t('organization.groups.searchPlaceholder')} />- </div>- {filtered.length === 0 ? (- <EmptyState title={t('organization.groups.emptyTitle')} body={t('organization.groups.emptyBody')} />- ) : (- <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">- {filtered.map((group) => (- <Link key={group.id} to={`/admin/organization/groups/${encodeURIComponent(group.id)}`} className="rounded-lg border border-border bg-card p-4 transition hover:border-border-strong">- <div className="flex items-start justify-between gap-3">- <GroupPill name={group.name} color={group.color} />- <div className="flex flex-wrap justify-end gap-1.5">- {!canManage && group.is_member ? <Badge variant="info">{t('organization.groups.yourGroup')}</Badge> : null}- <Badge variant={group.archived_at ? 'secondary' : 'success'}>{t(group.archived_at ? 'organization.groups.archived' : 'organization.groups.active')}</Badge>- </div>- </div>- <p className="mt-3 min-h-10 text-[12px] leading-5 text-muted">{group.description || t('organization.groups.noDescription')}</p>- {canManage ? (- <div className="mt-4 grid grid-cols-4 gap-2 border-t border-border pt-3 text-center">- <div><div className="text-sm font-semibold">{group.member_count ?? 0}</div><div className="text-[9px] uppercase text-muted">{t('organization.nav.members')}</div></div>- <div><div className="text-sm font-semibold">{group.usage?.instances ?? 0}</div><div className="text-[9px] uppercase text-muted">{t('organization.nav.instances')}</div></div>- <div><div className="text-sm font-semibold">{group.usage?.projects ?? 0}</div><div className="text-[9px] uppercase text-muted">{t('organization.overview.projects')}</div></div>- <div><div className="text-sm font-semibold">{group.usage?.resources ?? 0}</div><div className="text-[9px] uppercase text-muted">{t('organization.nav.resources')}</div></div>- </div>- ) : null}- </Link>- ))}- </div>- )}- <GroupDialog- open={dialogOpen}- group={null}- members={members}- onOpenChange={setDialogOpen}- onSaved={async () => { await load(); return null; }}- />- </div>- );-}--export function OrganizationGroupDetailPage() {- const { t } = useTranslation();- const { groupId = '' } = useParams();- const { selectedOrganizationId, request, dataVersion, invalidate } = useOrganization();- const [directory, setDirectory] = useState<{- organizationId: string;- groupId: string;- group: OrganizationGroup;- members: OrganizationMember[];- } | null>(null);- const [errorState, setErrorState] = useState<{- organizationId: string;- groupId: string;- code: string;- } | null>(null);- const [editOpen, setEditOpen] = useState(false);- const [membersOpen, setMembersOpen] = useState(false);- const [archiveOpen, setArchiveOpen] = useState(false);- const loadGeneration = useRef(0);- const selectionRef = useRef({ organizationId: selectedOrganizationId, groupId });- const currentDirectory = (- directory?.organizationId === selectedOrganizationId- && directory.groupId === groupId- ) ? directory : null;- const group = currentDirectory?.group ?? null;- const allMembers = currentDirectory?.members ?? [];- const error = (- errorState?.organizationId === selectedOrganizationId- && errorState.groupId === groupId- ) ? errorState.code : undefined;-- useLayoutEffect(() => {- selectionRef.current = { organizationId: selectedOrganizationId, groupId };- loadGeneration.current += 1;- }, [groupId, selectedOrganizationId]);-- const load = useCallback(async (): Promise<OrganizationGroup | null> => {- if (!selectedOrganizationId || !groupId) return null;- const organizationId = selectedOrganizationId;- const requestedGroupId = groupId;- const generation = ++loadGeneration.current;- const isCurrent = () => (- isCurrentOrganizationLoad(- organizationId,- selectionRef.current.organizationId,- generation,- loadGeneration.current,- )- && requestedGroupId === selectionRef.current.groupId- );- setErrorState(null);- try {- const result = await request<{ group: OrganizationGroup }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/groups/${encodeURIComponent(requestedGroupId)}`,- );- if (!isCurrent()) return null;- let members: OrganizationMember[] = [];- if (result.group.can_manage) {- const memberResult = await request<{ members: OrganizationMember[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/members`,- );- if (!isCurrent()) return null;- members = memberResult.members;- }- setDirectory({- organizationId,- groupId: requestedGroupId,- group: result.group,- members,- });- return result.group;- } catch (caught) {- if (!isCurrent()) return null;- setErrorState({- organizationId,- groupId: requestedGroupId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- return null;- }- }, [groupId, request, selectedOrganizationId]);-- useEffect(() => {- const timer = window.setTimeout(() => void load(), 0);- return () => window.clearTimeout(timer);- }, [dataVersion, load]);-- const setArchived = async (archived: boolean) => {- if (!selectedOrganizationId || !group) return;- const path = `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/groups/${encodeURIComponent(group.id)}`;- try {- await request(path, archived ? {- method: 'DELETE',- body: jsonBody({ if_match_revision: group.group_revision }),- } : {- method: 'PATCH',- body: jsonBody({ archived: false, if_match_revision: group.group_revision }),- });- invalidate();- await load();- setArchiveOpen(false);- } catch (caught) {- if (isRevisionConflict(caught)) await load();- setErrorState({- organizationId: selectedOrganizationId,- groupId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- };-- if (!group && !error) return <LoadingState />;- if (!group) return <ErrorBanner code={error} onRetry={() => void load()} />;- const references = group.references;- const referenceCount = (references?.instances.length ?? 0) + (references?.projects.length ?? 0) + (references?.resources.length ?? 0);- return (- <div className="space-y-6">- <PageHeader- eyebrow={t('organization.breadcrumb.groupDetail', { name: group.name })}- title={group.name}- titleAccessory={!group.can_manage && group.is_member ? <Badge variant="info">{t('organization.groups.yourGroup')}</Badge> : undefined}- description={group.description || t('organization.groups.noDescription')}- actions={group.can_manage ? (- <>- <Button variant="outline" onClick={() => setEditOpen(true)}><Pencil className="size-4" />{t('organization.actions.editGroup')}</Button>- {group.archived_at ? (- <Button variant="outline" onClick={() => void setArchived(false)}><RotateCcw className="size-4" />{t('organization.actions.restoreGroup')}</Button>- ) : (- <Button variant="destructive-soft" onClick={() => setArchiveOpen(true)}><Archive className="size-4" />{t('organization.actions.archiveGroup')}</Button>- )}- </>- ) : undefined}- />- {error ? <ErrorBanner code={error} onRetry={() => void load()} /> : null}- {group.can_manage ? <div className="grid gap-4 xl:grid-cols-[minmax(0,1.35fr)_minmax(320px,0.65fr)]">- <TableFrame>- <div className="flex items-center justify-between border-b border-border px-5 py-4">- <div className="text-[14px] font-semibold">{t('organization.nav.members')} <span className="ml-1 text-muted">{group.members?.length ?? group.member_count ?? 0}</span></div>- {!group.archived_at ? <Button size="sm" variant="brand" onClick={() => setMembersOpen(true)}><Plus className="size-4" />{t('organization.actions.manageMembers')}</Button> : null}- </div>- {(group.members ?? []).length === 0 ? (- <div className="p-5"><EmptyState title={t('organization.members.emptyTitle')} body={t('organization.members.emptyBody')} /></div>- ) : group.members?.map((member) => (- <div key={member.id} className="flex items-center gap-3 border-b border-border px-5 py-3 last:border-0">- <InitialsAvatar value={member.email} className="rounded-full" />- <div className="min-w-0 flex-1 truncate text-[12px]">{member.email}</div>- <RoleBadge role={member.role} />- </div>- ))}- </TableFrame>- <div className="space-y-4">- <TableFrame>- <div className="border-b border-border px-5 py-4 text-[14px] font-semibold">- {t('organization.groups.referencedBy')} <span className="ml-1 text-muted">{referenceCount}</span>- </div>- <div className="space-y-4 p-5 text-[12px]">- <ReferenceSection icon={<Server className="size-4 text-cyan-ink" />} title={t('organization.nav.instances')} items={references?.instances.map((item) => item.slug) ?? []} />- <ReferenceSection icon={<Workflow className="size-4 text-gold-ink" />} title={t('organization.overview.projects')} items={references?.projects.map((item) => item.displayName) ?? []} />- <ReferenceSection icon={<Boxes className="size-4 text-pink-ink" />} title={t('organization.nav.resources')} items={references?.resources.map((item) => item.displayName) ?? []} />- </div>- </TableFrame>- <div className="rounded-lg border border-gold/35 bg-gold/10 p-4">- <div className="flex items-center gap-2 text-[13px] font-semibold"><Archive className="size-4 text-gold-ink" />{t('organization.groups.archiveImpactTitle')}</div>- <p className="mt-1 text-[12px] leading-5 text-muted">{t('organization.groups.archiveImpactBody')}</p>- </div>- </div>- </div> : null}- <GroupDialog open={editOpen} group={group} members={allMembers} onOpenChange={setEditOpen} onSaved={load} />- <MemberPickerDialog open={membersOpen} group={group} allMembers={allMembers} onOpenChange={setMembersOpen} onSaved={load} />- <ConfirmDialog- open={archiveOpen}- onOpenChange={setArchiveOpen}- title={t('organization.groups.archiveTitle')}- description={t('organization.groups.archiveBody', { name: group.name, count: referenceCount })}- destructive- confirmLabel={t('organization.actions.archiveGroup')}- onConfirm={() => setArchived(true)}- >- <div className="rounded-lg border border-gold/30 bg-gold/10 p-3 text-[12px] text-muted">- {t('organization.groups.archiveImpactBody')}- </div>- </ConfirmDialog>- </div>- );-}--function ReferenceSection({ icon, title, items }: { icon: React.ReactNode; title: string; items: string[] }) {- const { t } = useTranslation();- return (- <div>- <div className="mb-2 flex items-center gap-2 font-mono text-[10px] font-bold uppercase text-muted">{icon}{title}</div>- {items.length ? items.slice(0, 5).map((item) => <div key={item} className="mb-1 truncate">{item}</div>) : <div className="text-muted">{t('common.none')}</div>}- {items.length > 5 ? <div className="text-muted">{t('organization.groups.moreReferences', { count: items.length - 5 })}</div> : null}- </div>- );-}diff --git a/ui/src/features/organization/pages/OrganizationInstancePages.tsx b/ui/src/features/organization/pages/OrganizationInstancePages.tsxdeleted file mode 100644index dc386f62d..000000000--- a/ui/src/features/organization/pages/OrganizationInstancePages.tsx+++ /dev/null@@ -1,1071 +0,0 @@-import {- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from 'react';-import {- Eye,- FolderKey,- Globe2,- LockKeyhole,- Mail,- Pencil,- Plus,- Shield,- Trash2,- Users,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';-import { NavLink, useParams } from 'react-router-dom';-import clsx from 'clsx';--import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';-import { ConfirmDialog } from '@/components/ui/confirm-dialog';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { SegmentedRadio } from '@/components/ui/segmented';-import { Select } from '@/components/ui/select';--import { isRevisionConflict, jsonBody, OrganizationApiError } from '../api/client';-import type {- AccessRole,- InstanceAccessEntry,- OrganizationGroup,- OrganizationInstance,- OrganizationProject,- ProjectBinding,-} from '../api/types';-import {- ConflictBanner,- EmptyState,- ErrorBanner,- ForbiddenState,- InitialsAvatar,- LoadingState,- SearchField,- SyncBadge,- TableFrame,-} from '../components';-import { useOrganization } from '../context';-import {- hasDuplicateOrganizationPrincipals,- hasDuplicateProjectPrincipals,- isCurrentOrganizationLoad,- normalizeOrganizationPrincipal,- type ProjectAccessMode,- requiresProjectAccessNarrowingConfirmation,-} from '../policy';--type PrincipalKind = InstanceAccessEntry['kind'];--function displayPrincipal(kind: PrincipalKind, value: string, groups: OrganizationGroup[]): string {- if (kind === 'organization_group') {- return groups.find((group) => group.id === value)?.name ?? value;- }- if (kind === 'email_domain') return `@${value.replace(/^@/, '')}`;- return value;-}--function principalIcon(kind: PrincipalKind) {- if (kind === 'organization_group') return Users;- if (kind === 'email_domain') return Globe2;- return Mail;-}--function projectMode(project: OrganizationProject): ProjectAccessMode {- if (project.access.mode === 'inherit') return 'inherit';- return project.access.bindings.length === 0 ? 'owner_only' : 'restricted';-}--function InstanceHeader({ instance }: { instance: OrganizationInstance }) {- const { t } = useTranslation();- return (- <div className="space-y-5">- <div className="flex min-w-0 items-center gap-3">- <InitialsAvatar value={instance.slug} tone="mint" className="size-12" />- <div className="min-w-0">- <div className="flex flex-wrap items-center gap-2">- <h1 className="truncate text-2xl font-semibold">{instance.slug}</h1>- <Badge variant={instance.paired && instance.status === 'active' ? 'success' : 'secondary'}>- {t(instance.paired ? 'organization.instances.paired' : 'organization.instances.notPaired')}- {' · '}- {t(`organization.instances.status.${instance.status}`)}- </Badge>- </div>- <div className="mt-1 flex flex-wrap gap-x-2 font-mono text-[11px] text-muted">- <span>{instance.public_hostname}</span>- <span>·</span>- <span>{instance.id}</span>- <span>·</span>- <span>{instance.owner_is_current_user ? t('organization.instances.youAreOwner') : (instance.owner_email || t('organization.instances.ownerProtected'))}</span>- </div>- </div>- </div>- <div className="flex items-center gap-2" role="tablist" aria-label={t('organization.instances.tabsLabel')}>- {instance.can_manage_access ? (- <NavLink- to={`/admin/organization/instances/${encodeURIComponent(instance.id)}/access`}- role="tab"- className={({ isActive }) => clsx(- 'inline-flex h-9 items-center gap-2 rounded-lg border px-3 text-[12px] font-medium',- isActive ? 'border-border-strong bg-card text-foreground' : 'border-transparent text-muted hover:text-foreground',- )}- >- <Users className="size-4" />- {t('organization.instances.accessTab')}- </NavLink>- ) : null}- <NavLink- to={`/admin/organization/instances/${encodeURIComponent(instance.id)}/projects`}- role="tab"- className={({ isActive }) => clsx(- 'inline-flex h-9 items-center gap-2 rounded-lg border px-3 text-[12px] font-medium',- isActive ? 'border-border-strong bg-card text-foreground' : 'border-transparent text-muted hover:text-foreground',- )}- >- <FolderKey className="size-4" />- {t('organization.instances.projectsTab')}- </NavLink>- </div>- </div>- );-}--function useOrganizationInstance() {- const { instanceId } = useParams();- const { selectedOrganizationId, request, dataVersion } = useOrganization();- const [loadedInstance, setLoadedInstance] = useState<{- organizationId: string;- instanceId: string;- instance: OrganizationInstance | null;- } | null>(null);- const [errorState, setErrorState] = useState<{- organizationId: string;- instanceId: string;- code: string;- } | null>(null);- const loadGeneration = useRef(0);- const selectedOrganizationIdRef = useRef(selectedOrganizationId);- const instanceIdRef = useRef(instanceId);- const currentInstance = loadedInstance?.organizationId === selectedOrganizationId- && loadedInstance.instanceId === instanceId- ? loadedInstance- : null;- const instance = currentInstance ? currentInstance.instance : undefined;- const error = errorState?.organizationId === selectedOrganizationId- && errorState.instanceId === instanceId- ? errorState.code- : undefined;-- useLayoutEffect(() => {- selectedOrganizationIdRef.current = selectedOrganizationId;- instanceIdRef.current = instanceId;- loadGeneration.current += 1;- }, [instanceId, selectedOrganizationId]);-- const load = useCallback(async () => {- if (!selectedOrganizationId || !instanceId) return;- const organizationId = selectedOrganizationId;- const requestedInstanceId = instanceId;- if (- selectedOrganizationIdRef.current !== organizationId- || instanceIdRef.current !== requestedInstanceId- ) return;- const generation = ++loadGeneration.current;- const isCurrent = () => isCurrentOrganizationLoad(- organizationId,- selectedOrganizationIdRef.current,- generation,- loadGeneration.current,- );- setErrorState(null);- try {- const result = await request<{ instances: OrganizationInstance[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/instances`,- );- if (!isCurrent()) return;- setLoadedInstance({- organizationId,- instanceId: requestedInstanceId,- instance: result.instances.find((item) => item.id === requestedInstanceId) ?? null,- });- } catch (caught) {- if (!isCurrent()) return;- setErrorState({- organizationId,- instanceId: requestedInstanceId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- }, [instanceId, request, selectedOrganizationId]);-- useEffect(() => {- const timer = window.setTimeout(() => void load(), 0);- return () => window.clearTimeout(timer);- }, [dataVersion, load]);- return { instance, instanceId, error, reload: load };-}--function AccessEntryDialog({- open,- entries,- editingIndex,- groups,- instanceId,- onOpenChange,- onSaved,-}: {- open: boolean;- entries: InstanceAccessEntry[];- editingIndex: number | null;- groups: OrganizationGroup[];- instanceId: string;- onOpenChange: (open: boolean) => void;- onSaved: (entries: InstanceAccessEntry[]) => void;-}) {- const { t } = useTranslation();- const { request } = useOrganization();- const editing = editingIndex === null ? null : entries[editingIndex];- const [kind, setKind] = useState<PrincipalKind>('email');- const [value, setValue] = useState('');- const [role, setRole] = useState<AccessRole>('viewer');- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string>();- const [confirmNarrowing, setConfirmNarrowing] = useState(false);-- useEffect(() => {- if (!open) return;- setKind(editing?.kind ?? 'email');- setValue(editing?.value ?? '');- setRole(editing?.role ?? 'viewer');- setError(undefined);- setConfirmNarrowing(false);- }, [editing, open]);-- const activeGroups = groups.filter((group) => !group.archived_at);- const resolvedValue = kind === 'organization_group'- ? (value || activeGroups[0]?.id || '')- : value;- const candidate: InstanceAccessEntry = {- kind,- value: normalizeOrganizationPrincipal(kind, resolvedValue),- role,- };- const archivedGroup = kind === 'organization_group'- ? groups.find((group) => group.id === value && group.archived_at)- : undefined;- const nextEntries = () => (- editingIndex === null- ? [...entries, candidate]- : entries.map((entry, index) => (index === editingIndex ? candidate : entry))- );- const hasDuplicatePrincipal = (next: InstanceAccessEntry[]) => (- hasDuplicateOrganizationPrincipals(next.map((entry) => ({- kind: entry.kind,- value: entry.value,- })))- );-- const commit = async () => {- if (!candidate.value) return;- setError(undefined);- const next = nextEntries();- if (hasDuplicatePrincipal(next)) {- setError('duplicate_instance_access_principal');- setConfirmNarrowing(false);- return;- }- setSaving(true);- try {- const result = await request<{ entries: InstanceAccessEntry[] }>(- `/api/cloud-management/instances/${encodeURIComponent(instanceId)}/authorized-users`,- { method: 'PUT', body: jsonBody({ entries: next }) },- );- onSaved(result.entries);- onOpenChange(false);- } catch (caught) {- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');- } finally {- setSaving(false);- setConfirmNarrowing(false);- }- };-- const save = () => {- setError(undefined);- if (hasDuplicatePrincipal(nextEntries())) {- setError('duplicate_instance_access_principal');- return;- }- const narrows = Boolean(editing) && (- editing?.role === 'editor' && candidate.role === 'viewer'- || editing?.kind !== candidate.kind- || normalizeOrganizationPrincipal(editing?.kind ?? 'email', editing?.value ?? '') !== candidate.value- );- if (narrows) setConfirmNarrowing(true);- else void commit();- };-- return (- <>- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>{t(editing ? 'organization.access.editTitle' : 'organization.access.addTitle')}</DialogTitle>- <DialogDescription>{t('organization.access.dialogBody')}</DialogDescription>- </DialogHeader>- {error ? <ErrorBanner code={error} /> : null}- <div className="space-y-4">- <div className="space-y-1.5">- <Label htmlFor="organization-access-kind">{t('organization.fields.principalType')}</Label>- <Select- id="organization-access-kind"- value={kind}- onChange={(event) => { setKind(event.target.value as PrincipalKind); setValue(''); }}- >- <option value="organization_group">{t('organization.principals.organization_group')}</option>- <option value="email">{t('organization.principals.email')}</option>- <option value="email_domain">{t('organization.principals.email_domain')}</option>- </Select>- </div>- <div className="space-y-1.5">- <Label htmlFor="organization-access-value">{t('organization.fields.principal')}</Label>- {kind === 'organization_group' ? (- <Select- id="organization-access-value"- value={resolvedValue}- onChange={(event) => setValue(event.target.value)}- >- {archivedGroup ? (- <option value={archivedGroup.id}>- {archivedGroup.name} ({t('organization.groups.archived')})- </option>- ) : null}- {activeGroups.map((group) => <option key={group.id} value={group.id}>{group.name}</option>)}- </Select>- ) : (- <Input- id="organization-access-value"- type={kind === 'email' ? 'email' : 'text'}- value={value}- onChange={(event) => setValue(event.target.value)}- placeholder={t(kind === 'email' ? 'organization.access.emailPlaceholder' : 'organization.access.domainPlaceholder')}- />- )}- </div>- <div className="space-y-1.5">- <Label>{t('organization.fields.role')}</Label>- <SegmentedRadio- value={role}- onChange={setRole}- ariaLabel={t('organization.fields.role')}- options={[- { id: 'viewer', label: t('organization.access.viewer') },- { id: 'editor', label: t('organization.access.editor') },- ]}- />- </div>- </div>- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>- <Button variant="brand" disabled={saving || !candidate.value} onClick={save}>- {saving ? t('organization.actions.saving') : t('organization.actions.saveChanges')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- <ConfirmDialog- open={confirmNarrowing}- onOpenChange={setConfirmNarrowing}- title={t('organization.access.narrowTitle')}- description={t('organization.access.narrowBody')}- confirmLabel={t('organization.actions.saveChanges')}- onConfirm={commit}- />- </>- );-}--export function InstanceAccessPage() {- const { t } = useTranslation();- const { selectedOrganizationId, request } = useOrganization();- const { instance, instanceId, error: instanceError, reload } = useOrganizationInstance();- const [directory, setDirectory] = useState<{- organizationId: string;- instanceId: string;- entries: InstanceAccessEntry[];- groups: OrganizationGroup[];- } | null>(null);- const [errorState, setErrorState] = useState<{- organizationId: string;- instanceId: string;- code: string;- } | null>(null);- const [editing, setEditing] = useState<{- organizationId: string;- instanceId: string;- index: number | null;- } | null>(null);- const [removing, setRemoving] = useState<{- organizationId: string;- instanceId: string;- index: number;- } | null>(null);- const loadGeneration = useRef(0);- const selectedOrganizationIdRef = useRef(selectedOrganizationId);- const instanceIdRef = useRef(instanceId);- const currentDirectory = directory?.organizationId === selectedOrganizationId- && directory.instanceId === instanceId- ? directory- : null;- const entries = currentDirectory?.entries ?? null;- const groups = currentDirectory?.groups ?? [];- const error = errorState?.organizationId === selectedOrganizationId- && errorState.instanceId === instanceId- ? errorState.code- : undefined;- const currentEditing = editing?.organizationId === selectedOrganizationId- && editing.instanceId === instanceId- ? editing- : null;- const currentRemoving = removing?.organizationId === selectedOrganizationId- && removing.instanceId === instanceId- ? removing- : null;-- useLayoutEffect(() => {- selectedOrganizationIdRef.current = selectedOrganizationId;- instanceIdRef.current = instanceId;- loadGeneration.current += 1;- }, [instanceId, selectedOrganizationId]);-- const load = useCallback(async () => {- if (!instanceId || !selectedOrganizationId || instance?.can_manage_access !== true) return;- const organizationId = selectedOrganizationId;- const requestedInstanceId = instanceId;- if (- selectedOrganizationIdRef.current !== organizationId- || instanceIdRef.current !== requestedInstanceId- ) return;- const generation = ++loadGeneration.current;- const isCurrent = () => isCurrentOrganizationLoad(- organizationId,- selectedOrganizationIdRef.current,- generation,- loadGeneration.current,- );- setErrorState(null);- try {- const [accessResult, groupResult] = await Promise.all([- request<{ entries: InstanceAccessEntry[] }>(- `/api/cloud-management/instances/${encodeURIComponent(requestedInstanceId)}/authorized-users`,- ),- request<{ groups: OrganizationGroup[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/groups`,- ),- ]);- if (!isCurrent()) return;- setDirectory({- organizationId,- instanceId: requestedInstanceId,- entries: accessResult.entries,- groups: groupResult.groups,- });- } catch (caught) {- if (!isCurrent()) return;- setErrorState({- organizationId,- instanceId: requestedInstanceId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- }, [instance?.can_manage_access, instanceId, request, selectedOrganizationId]);-- useEffect(() => {- const timer = window.setTimeout(() => void load(), 0);- return () => window.clearTimeout(timer);- }, [load]);-- const remove = async () => {- if (!currentRemoving || !entries) return;- const { organizationId, instanceId: requestedInstanceId, index: removingIndex } = currentRemoving;- const next = entries.filter((_, index) => index !== removingIndex);- try {- const result = await request<{ entries: InstanceAccessEntry[] }>(- `/api/cloud-management/instances/${encodeURIComponent(requestedInstanceId)}/authorized-users`,- { method: 'PUT', body: jsonBody({ entries: next }) },- );- setDirectory((current) => (- current?.organizationId === organizationId && current.instanceId === requestedInstanceId- ? { ...current, entries: result.entries }- : current- ));- setRemoving(null);- } catch (caught) {- setErrorState({- organizationId,- instanceId: requestedInstanceId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- };-- if (instance === undefined) return <LoadingState />;- if (instanceError) return <ErrorBanner code={instanceError} onRetry={() => void reload()} />;- if (!instance) return <ForbiddenState />;- if (!instance.can_manage_access) return <ForbiddenState />;- if (!entries && !error) return <LoadingState />;-- return (- <div className="space-y-6">- <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">- <InstanceHeader instance={instance} />- <Button- variant="brand"- onClick={() => {- if (selectedOrganizationId && instanceId) {- setEditing({ organizationId: selectedOrganizationId, instanceId, index: null });- }- }}- >- <Plus className="size-4" />- {t('organization.actions.addAccess')}- </Button>- </div>- <div className="flex items-center gap-3 rounded-lg border border-violet/35 bg-violet/10 p-4">- <Shield className="size-5 shrink-0 text-violet-ink" />- <div className="min-w-0 flex-1">- <div className="text-[13px] font-semibold">{t('organization.access.ownerTitle', { owner: instance.owner_is_current_user ? t('organization.instances.you') : (instance.owner_email || t('organization.instances.ownerProtected')) })}</div>- <div className="mt-0.5 text-[12px] text-muted">{t('organization.access.ownerBody')}</div>- </div>- <Badge variant="secondary">{t('organization.roles.owner')}</Badge>- </div>- {error ? <ErrorBanner code={error} onRetry={() => void load()} /> : null}- {(entries ?? []).length === 0 ? (- <EmptyState title={t('organization.access.emptyTitle')} body={t('organization.access.emptyBody')} />- ) : (- <TableFrame>- <div className="hidden grid-cols-[minmax(220px,1.5fr)_150px_140px_80px] gap-4 border-b border-border px-5 py-3 font-mono text-[10px] font-bold uppercase text-muted md:grid">- <div>{t('organization.access.columns.principal')}</div>- <div>{t('organization.access.columns.type')}</div>- <div>{t('organization.access.columns.role')}</div>- <div />- </div>- {(entries ?? []).map((entry, index) => {- const Icon = principalIcon(entry.kind);- return (- <div key={`${entry.kind}:${entry.value}`} className="grid gap-3 border-b border-border px-4 py-4 last:border-0 md:grid-cols-[minmax(220px,1.5fr)_150px_140px_80px] md:items-center md:px-5">- <div className="flex min-w-0 items-center gap-3">- <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-mint/10 text-mint-ink"><Icon className="size-4" /></span>- <div className="min-w-0">- <div className="truncate text-[12px] font-semibold">{displayPrincipal(entry.kind, entry.value, groups)}</div>- <div className="text-[10px] text-muted">{t(`organization.principals.${entry.kind}`)}</div>- </div>- </div>- <Badge variant="secondary">{t(`organization.principals.${entry.kind}`)}</Badge>- <Badge variant={entry.role === 'editor' ? 'success' : 'secondary'}>- {entry.role === 'editor' ? <Pencil className="size-3" /> : <Eye className="size-3" />}- {t(`organization.access.${entry.role}`)}- </Badge>- <div className="flex justify-end gap-1">- <Button- size="icon"- variant="ghost"- aria-label={t('organization.actions.editAccess')}- onClick={() => {- if (selectedOrganizationId && instanceId) {- setEditing({ organizationId: selectedOrganizationId, instanceId, index });- }- }}- >- <Pencil className="size-4" />- </Button>- <Button- size="icon"- variant="ghost"- aria-label={t('organization.actions.removeAccess')}- onClick={() => {- if (selectedOrganizationId && instanceId) {- setRemoving({ organizationId: selectedOrganizationId, instanceId, index });- }- }}- >- <Trash2 className="size-4 text-destructive-ink" />- </Button>- </div>- </div>- );- })}- </TableFrame>- )}- <AccessEntryDialog- open={Boolean(currentEditing)}- entries={entries ?? []}- editingIndex={currentEditing?.index ?? null}- groups={groups}- instanceId={instance.id}- onOpenChange={(open) => { if (!open) setEditing(null); }}- onSaved={(nextEntries) => {- if (!selectedOrganizationId || !instanceId) return;- setDirectory((current) => (- current?.organizationId === selectedOrganizationId && current.instanceId === instanceId- ? { ...current, entries: nextEntries }- : current- ));- }}- />- <ConfirmDialog- open={Boolean(currentRemoving)}- onOpenChange={(open) => { if (!open) setRemoving(null); }}- title={t('organization.access.removeTitle')}- description={t('organization.access.removeBody', {- principal: currentRemoving === null ? '' : displayPrincipal(entries?.[currentRemoving.index]?.kind ?? 'email', entries?.[currentRemoving.index]?.value ?? '', groups),- })}- destructive- confirmLabel={t('organization.actions.removeAccess')}- onConfirm={remove}- />- </div>- );-}--function ProjectAccessDialog({- project,- groups,- instanceId,- onOpenChange,- onSaved,-}: {- project: OrganizationProject | null;- groups: OrganizationGroup[];- instanceId: string;- onOpenChange: (open: boolean) => void;- onSaved: () => Promise<OrganizationProject | null>;-}) {- const { t } = useTranslation();- const { request } = useOrganization();- const [mode, setMode] = useState<ProjectAccessMode>('inherit');- const [bindings, setBindings] = useState<ProjectBinding[]>([]);- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string>();- const [conflict, setConflict] = useState(false);- const [authoritativeProject, setAuthoritativeProject] = useState<OrganizationProject | null>(null);- const [revision, setRevision] = useState(0);- const [confirmNarrowing, setConfirmNarrowing] = useState(false);- const comparisonProjectRef = useRef<OrganizationProject | null>(null);-- useEffect(() => {- if (!project) return;- comparisonProjectRef.current = project;- setMode(projectMode(project));- setBindings(project.access.bindings);- setRevision(project.access.revision);- setError(undefined);- setConflict(false);- setAuthoritativeProject(null);- setConfirmNarrowing(false);- }, [project]);-- const activeGroups = groups.filter((group) => !group.archived_at);- const addBinding = () => {- const firstGroup = activeGroups.find((group) => !bindings.some((binding) => (- binding.principal_kind === 'organization_group' && binding.principal_value === group.id- )));- setBindings((current) => [...current, {- principal_kind: firstGroup ? 'organization_group' : 'email',- principal_value: firstGroup?.id ?? '',- access_role: 'viewer',- }]);- };- const updateBinding = (index: number, patch: Partial<ProjectBinding>) => {- setBindings((current) => current.map((binding, itemIndex) => (- itemIndex === index ? { ...binding, ...patch } : binding- )));- };-- const wireBindings = mode === 'restricted'- ? bindings.map((binding) => ({- ...binding,- principal_value: normalizeOrganizationPrincipal(binding.principal_kind, binding.principal_value),- }))- : [];-- const commit = async () => {- if (!project || (mode === 'restricted' && bindings.length === 0)) return;- setSaving(true);- setError(undefined);- try {- await request(- `/api/cloud-management/instances/${encodeURIComponent(instanceId)}/projects/${encodeURIComponent(project.project_id)}/access`,- {- method: 'PUT',- body: jsonBody({- mode: mode === 'inherit' ? 'inherit' : 'restricted',- bindings: wireBindings,- if_match_revision: revision,- }),- },- );- await onSaved();- onOpenChange(false);- } catch (caught) {- if (isRevisionConflict(caught)) {- const latest = await onSaved();- setAuthoritativeProject(latest);- setConflict(true);- } else {- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');- }- } finally {- setSaving(false);- setConfirmNarrowing(false);- }- };-- const save = () => {- if (!project || (mode === 'restricted' && bindings.length === 0)) return;- setError(undefined);- if (hasDuplicateProjectPrincipals(wireBindings)) {- setError('duplicate_project_access_principal');- return;- }- const comparisonProject = comparisonProjectRef.current ?? project;- if (requiresProjectAccessNarrowingConfirmation(- projectMode(comparisonProject),- comparisonProject.access.bindings,- mode,- wireBindings,- )) {- setConfirmNarrowing(true);- return;- }- void commit();- };-- const reloadAuthoritativeProject = () => {- if (!authoritativeProject) {- onOpenChange(false);- return;- }- comparisonProjectRef.current = authoritativeProject;- setMode(projectMode(authoritativeProject));- setBindings(authoritativeProject.access.bindings);- setRevision(authoritativeProject.access.revision);- setError(undefined);- setConflict(false);- setAuthoritativeProject(null);- };-- return (- <>- <Dialog open={Boolean(project)} onOpenChange={onOpenChange}>- <DialogContent className="max-w-2xl">- <DialogHeader>- <DialogTitle>{t('organization.projects.dialogTitle', { name: project?.display_name })}</DialogTitle>- <DialogDescription>{t('organization.projects.dialogBody')}</DialogDescription>- </DialogHeader>- {conflict ? <ConflictBanner onReload={reloadAuthoritativeProject} /> : null}- {error ? <ErrorBanner code={error} /> : null}- <div className="space-y-5">- <div className="space-y-1.5">- <Label>{t('organization.projects.accessRule')}</Label>- <SegmentedRadio- value={mode}- onChange={setMode}- ariaLabel={t('organization.projects.accessRule')}- options={[- { id: 'inherit', label: t('organization.projects.modes.inherit') },- { id: 'restricted', label: t('organization.projects.modes.restricted') },- { id: 'owner_only', label: t('organization.projects.modes.owner_only') },- ]}- />- </div>- <div className="rounded-lg border border-border bg-foreground/[0.025] p-3 text-[12px] leading-5 text-muted">- {t(`organization.projects.modeHelp.${mode}`)}- </div>- {mode === 'restricted' ? (- <div className="space-y-3">- <div className="flex items-center justify-between">- <Label>{t('organization.projects.bindings')}</Label>- <Button size="sm" variant="outline" onClick={addBinding}><Plus className="size-4" />{t('organization.actions.addBinding')}</Button>- </div>- {bindings.length === 0 ? (- <div className="rounded-lg border border-gold/35 bg-gold/10 p-3 text-[12px] text-muted">{t('organization.projects.bindingRequired')}</div>- ) : bindings.map((binding, index) => {- const archivedGroup = binding.principal_kind === 'organization_group'- ? groups.find((group) => group.id === binding.principal_value && group.archived_at)- : undefined;- return (- <div key={`${index}:${binding.principal_kind}`} className="grid gap-2 rounded-lg border border-border p-3 sm:grid-cols-[150px_minmax(0,1fr)_110px_36px]">- <Select- aria-label={t('organization.fields.principalType')}- value={binding.principal_kind}- onChange={(event) => updateBinding(index, {- principal_kind: event.target.value as PrincipalKind,- principal_value: event.target.value === 'organization_group' ? (activeGroups[0]?.id ?? '') : '',- })}- >- <option value="organization_group">{t('organization.principals.organization_group')}</option>- <option value="email">{t('organization.principals.email')}</option>- <option value="email_domain">{t('organization.principals.email_domain')}</option>- </Select>- {binding.principal_kind === 'organization_group' ? (- <Select- aria-label={t('organization.fields.principal')}- value={binding.principal_value}- onChange={(event) => updateBinding(index, { principal_value: event.target.value })}- >- {archivedGroup ? <option value={archivedGroup.id}>{archivedGroup.name} ({t('organization.groups.archived')})</option> : null}- {activeGroups.map((group) => <option key={group.id} value={group.id}>{group.name}</option>)}- </Select>- ) : (- <Input- aria-label={t('organization.fields.principal')}- value={binding.principal_value}- onChange={(event) => updateBinding(index, { principal_value: event.target.value })}- />- )}- <Select- aria-label={t('organization.fields.role')}- value={binding.access_role}- onChange={(event) => updateBinding(index, { access_role: event.target.value as AccessRole })}- >- <option value="viewer">{t('organization.access.viewer')}</option>- <option value="editor">{t('organization.access.editor')}</option>- </Select>- <Button size="icon" variant="ghost" aria-label={t('organization.actions.removeBinding')} onClick={() => setBindings((current) => current.filter((_, itemIndex) => itemIndex !== index))}><Trash2 className="size-4" /></Button>- </div>- );- })}- </div>- ) : null}- </div>- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>- <Button- variant="brand"- disabled={saving || conflict || (mode === 'restricted' && (bindings.length === 0 || bindings.some((binding) => !binding.principal_value.trim())))}- onClick={save}- >- {saving ? t('organization.actions.saving') : t('organization.actions.saveChanges')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- <ConfirmDialog- open={confirmNarrowing}- onOpenChange={setConfirmNarrowing}- title={t('organization.projects.narrowTitle')}- description={t('organization.projects.narrowBody')}- confirmLabel={t('organization.actions.saveChanges')}- onConfirm={commit}- />- </>- );-}--export function InstanceProjectsPage() {- const { t } = useTranslation();- const { selectedOrganizationId, request } = useOrganization();- const { instance, instanceId, error: instanceError, reload } = useOrganizationInstance();- const [directory, setDirectory] = useState<{- organizationId: string;- instanceId: string;- projects: OrganizationProject[];- groups: OrganizationGroup[];- canManageProjects: boolean;- } | null>(null);- const [search, setSearch] = useState('');- const [errorState, setErrorState] = useState<{- organizationId: string;- instanceId: string;- code: string;- } | null>(null);- const [forbiddenState, setForbiddenState] = useState<{- organizationId: string;- instanceId: string;- } | null>(null);- const [editing, setEditing] = useState<{- organizationId: string;- instanceId: string;- project: OrganizationProject;- } | null>(null);- const loadGeneration = useRef(0);- const selectedOrganizationIdRef = useRef(selectedOrganizationId);- const instanceIdRef = useRef(instanceId);- const currentDirectory = directory?.organizationId === selectedOrganizationId- && directory.instanceId === instanceId- ? directory- : null;- const projects = currentDirectory?.projects ?? null;- const groups = currentDirectory?.groups ?? [];- const canManageProjects = currentDirectory?.canManageProjects === true;- const error = errorState?.organizationId === selectedOrganizationId- && errorState.instanceId === instanceId- ? errorState.code- : undefined;- const forbidden = forbiddenState?.organizationId === selectedOrganizationId- && forbiddenState.instanceId === instanceId;- const currentEditing = editing?.organizationId === selectedOrganizationId- && editing.instanceId === instanceId- ? editing.project- : null;-- useLayoutEffect(() => {- selectedOrganizationIdRef.current = selectedOrganizationId;- instanceIdRef.current = instanceId;- loadGeneration.current += 1;- }, [instanceId, selectedOrganizationId]);-- const load = useCallback(async (): Promise<OrganizationProject[]> => {- if (!instanceId || !selectedOrganizationId || instance?.id !== instanceId) return [];- const organizationId = selectedOrganizationId;- const requestedInstanceId = instanceId;- if (- selectedOrganizationIdRef.current !== organizationId- || instanceIdRef.current !== requestedInstanceId- ) return [];- const generation = ++loadGeneration.current;- const isCurrent = () => isCurrentOrganizationLoad(- organizationId,- selectedOrganizationIdRef.current,- generation,- loadGeneration.current,- );- setErrorState(null);- setForbiddenState(null);- try {- const result = await request<{- projects: OrganizationProject[];- groups: OrganizationGroup[];- capabilities: { can_manage_projects: boolean };- }>(- `/api/cloud-management/instances/${encodeURIComponent(requestedInstanceId)}/projects`,- );- const activeProjects = result.projects.filter((project) => project.sync.status !== 'deleted');- if (!isCurrent()) return [];- setDirectory({- organizationId,- instanceId: requestedInstanceId,- projects: activeProjects,- groups: result.groups,- canManageProjects: result.capabilities.can_manage_projects,- });- return activeProjects;- } catch (caught) {- if (!isCurrent()) return [];- if (caught instanceof OrganizationApiError && (caught.status === 403 || caught.status === 404)) {- setForbiddenState({ organizationId, instanceId: requestedInstanceId });- } else {- setErrorState({- organizationId,- instanceId: requestedInstanceId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- return [];- }- }, [instance?.id, instanceId, request, selectedOrganizationId]);-- useEffect(() => {- const timer = window.setTimeout(() => void load(), 0);- return () => window.clearTimeout(timer);- }, [load]);- const filtered = useMemo(() => (projects ?? []).filter((project) => (- `${project.display_name} ${project.project_id}`.toLowerCase().includes(search.trim().toLowerCase())- )), [projects, search]);-- if (instance === undefined) return <LoadingState />;- if (instanceError) return <ErrorBanner code={instanceError} onRetry={() => void reload()} />;- if (!instance) return <ForbiddenState />;- if (!projects && !error && !forbidden) return <LoadingState />;-- return (- <div className="space-y-6">- <div className="flex flex-col gap-5 sm:flex-row sm:items-start sm:justify-between">- <InstanceHeader instance={instance} />- <SearchField value={search} onChange={setSearch} placeholder={t('organization.projects.searchPlaceholder')} />- </div>- <div className="flex items-center gap-2 rounded-lg border border-border px-4 py-3 text-[12px] text-muted">- <Shield className="size-4 shrink-0" />- {t('organization.projects.safeDescriptorNotice')}- </div>- {forbidden ? <ForbiddenState /> : null}- {error ? <ErrorBanner code={error} onRetry={() => void load()} /> : null}- {!forbidden && filtered.length === 0 ? (- <EmptyState title={t('organization.projects.emptyTitle')} body={t('organization.projects.emptyBody')} />- ) : !forbidden ? (- <TableFrame>- <div className="hidden grid-cols-[minmax(220px,1.25fr)_160px_minmax(180px,1fr)_130px_90px] gap-4 border-b border-border px-5 py-3 font-mono text-[10px] font-bold uppercase text-muted md:grid">- <div>{t('organization.projects.columns.project')}</div>- <div>{t('organization.projects.columns.rule')}</div>- <div>{t('organization.projects.columns.bindings')}</div>- <div>{t('organization.projects.columns.sync')}</div>- <div />- </div>- {filtered.map((project) => {- const mode = projectMode(project);- return (- <div key={project.project_id} className="grid gap-3 border-b border-border px-4 py-4 last:border-0 md:grid-cols-[minmax(220px,1.25fr)_160px_minmax(180px,1fr)_130px_90px] md:items-center md:px-5">- <div className="flex min-w-0 items-center gap-3">- <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-mint/10 text-mint-ink"><FolderKey className="size-4" /></span>- <div className="min-w-0">- <div className="truncate text-[12px] font-semibold">{project.display_name}</div>- <div className="truncate font-mono text-[10px] text-muted">{project.project_id}</div>- </div>- </div>- <Badge variant={mode === 'owner_only' ? 'warning' : mode === 'restricted' ? 'info' : 'secondary'}>- {mode === 'owner_only' ? <Shield className="size-3" /> : mode === 'restricted' ? <LockKeyhole className="size-3" /> : <Users className="size-3" />}- {t(`organization.projects.modes.${mode}`)}- </Badge>- <div className="truncate text-[12px] text-muted">- {mode === 'inherit'- ? t('organization.projects.usesAvibeRole')- : mode === 'owner_only'- ? t('organization.projects.ownerOnlyAudience')- : t('organization.projects.bindingCount', { count: project.access.bindings.length })}- </div>- <SyncBadge status={project.sync.status} />- {canManageProjects ? (- <Button- size="sm"- variant="outline"- onClick={() => {- if (selectedOrganizationId && instanceId) {- setEditing({ organizationId: selectedOrganizationId, instanceId, project });- }- }}- >- {t('organization.actions.manage')}- </Button>- ) : <span />}- </div>- );- })}- </TableFrame>- ) : null}- <ProjectAccessDialog- project={currentEditing}- groups={groups}- instanceId={instance.id}- onOpenChange={(open) => { if (!open) setEditing(null); }}- onSaved={async () => {- const latestProjects = await load();- return latestProjects.find((project) => project.project_id === currentEditing?.project_id) ?? null;- }}- />- </div>- );-}diff --git a/ui/src/features/organization/pages/OrganizationInstancesPage.tsx b/ui/src/features/organization/pages/OrganizationInstancesPage.tsxdeleted file mode 100644index 0975bf66b..000000000--- a/ui/src/features/organization/pages/OrganizationInstancesPage.tsx+++ /dev/null@@ -1,184 +0,0 @@-import {- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from 'react';-import {- ChevronRight,- CircleDot,- Link2,- Server,- ShieldCheck,- Users,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';-import { Link } from 'react-router-dom';--import { Badge } from '@/components/ui/badge';--import { OrganizationApiError } from '../api/client';-import type { OrganizationInstance } from '../api/types';-import {- EmptyState,- ErrorBanner,- InitialsAvatar,- LoadingState,- PageHeader,- SearchField,- SyncBadge,- TableFrame,-} from '../components';-import { useOrganization } from '../context';-import { isCurrentOrganizationLoad } from '../policy';--function safeHostname(value: string): string {- try {- return new URL(value).hostname;- } catch {- return value;- }-}--function ownerLabel(instance: OrganizationInstance, t: (key: string) => string): string {- if (instance.owner_is_current_user) return t('organization.instances.you');- return instance.owner_email || t('organization.instances.organizationOwner');-}--export function OrganizationInstancesPage() {- const { t } = useTranslation();- const { selectedOrganizationId, request, dataVersion } = useOrganization();- const [directory, setDirectory] = useState<{- organizationId: string;- instances: OrganizationInstance[];- } | null>(null);- const [search, setSearch] = useState('');- const [errorState, setErrorState] = useState<{ organizationId: string; code: string } | null>(null);- const loadGeneration = useRef(0);- const selectedOrganizationIdRef = useRef(selectedOrganizationId);- const instances = directory?.organizationId === selectedOrganizationId ? directory.instances : null;- const error = errorState?.organizationId === selectedOrganizationId ? errorState.code : undefined;-- useLayoutEffect(() => {- selectedOrganizationIdRef.current = selectedOrganizationId;- loadGeneration.current += 1;- }, [selectedOrganizationId]);-- const load = useCallback(async () => {- if (!selectedOrganizationId) return;- const organizationId = selectedOrganizationId;- if (selectedOrganizationIdRef.current !== organizationId) return;- const generation = ++loadGeneration.current;- const isCurrent = () => isCurrentOrganizationLoad(- organizationId,- selectedOrganizationIdRef.current,- generation,- loadGeneration.current,- );- setErrorState(null);- try {- const result = await request<{ instances: OrganizationInstance[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/instances`,- );- if (!isCurrent()) return;- setDirectory({ organizationId, instances: result.instances });- } catch (caught) {- if (!isCurrent()) return;- setErrorState({- organizationId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- }, [request, selectedOrganizationId]);-- useEffect(() => {- const timer = window.setTimeout(() => void load(), 0);- return () => window.clearTimeout(timer);- }, [dataVersion, load]);-- const filtered = useMemo(() => (instances ?? []).filter((instance) => (- `${instance.slug} ${instance.id} ${instance.public_hostname}`- .toLowerCase()- .includes(search.trim().toLowerCase())- )), [instances, search]);-- if (!instances && !error) return <LoadingState />;-- return (- <div className="space-y-6">- <PageHeader- eyebrow={t('organization.breadcrumb.instances')}- title={t('organization.nav.instances')}- description={t('organization.instances.description')}- actions={(- <SearchField- value={search}- onChange={setSearch}- placeholder={t('organization.instances.searchPlaceholder')}- />- )}- />- {error ? <ErrorBanner code={error} onRetry={() => void load()} /> : null}- {filtered.length === 0 ? (- <EmptyState title={t('organization.instances.emptyTitle')} body={t('organization.instances.emptyBody')} />- ) : (- <TableFrame>- <div className="hidden grid-cols-[minmax(220px,1.3fr)_minmax(150px,0.85fr)_minmax(190px,1.15fr)_140px_80px_130px_32px] gap-4 border-b border-border px-5 py-3 font-mono text-[10px] font-bold uppercase text-muted lg:grid">- <div>{t('organization.instances.columns.instance')}</div>- <div>{t('organization.instances.columns.owner')}</div>- <div>{t('organization.instances.columns.address')}</div>- <div>{t('organization.instances.columns.status')}</div>- <div>{t('organization.instances.columns.access')}</div>- <div>{t('organization.instances.columns.sync')}</div>- <div />- </div>- {filtered.map((instance, index) => (- <Link- key={instance.id}- to={`/admin/organization/instances/${encodeURIComponent(instance.id)}/${instance.can_manage_access ? 'access' : 'projects'}`}- className="grid gap-4 border-b border-border px-4 py-4 transition-colors last:border-0 hover:bg-foreground/[0.025] lg:grid-cols-[minmax(220px,1.3fr)_minmax(150px,0.85fr)_minmax(190px,1.15fr)_140px_80px_130px_32px] lg:items-center lg:px-5"- >- <div className="flex min-w-0 items-center gap-3">- <span className={index % 2- ? 'grid size-9 shrink-0 place-items-center rounded-lg border border-violet/30 bg-violet/15 text-violet-ink'- : 'grid size-9 shrink-0 place-items-center rounded-lg border border-mint/30 bg-mint/15 text-mint-ink'}>- <Server className="size-4" />- </span>- <div className="min-w-0">- <div className="truncate text-[13px] font-semibold">{instance.slug}</div>- <div className="truncate font-mono text-[10px] text-muted">{instance.id}</div>- </div>- </div>- <div className="flex min-w-0 items-center gap-2 text-[12px] text-muted">- <InitialsAvatar value={ownerLabel(instance, t)} className="size-7 rounded-full" />- <span className="truncate">{ownerLabel(instance, t)}</span>- </div>- <div className="flex min-w-0 items-center gap-2 font-mono text-[11px] text-muted">- <Link2 className="size-3.5 shrink-0" />- <span className="truncate">{safeHostname(instance.primary_url)}</span>- </div>- <div className="flex flex-wrap items-center gap-1.5">- <Badge variant={instance.paired ? 'success' : 'secondary'}>- <ShieldCheck className="size-3" />- {t(instance.paired ? 'organization.instances.paired' : 'organization.instances.notPaired')}- </Badge>- <span className="inline-flex items-center gap-1 text-[11px] text-muted">- <CircleDot className={instance.status === 'active' ? 'size-3 text-mint-ink' : 'size-3'} />- {t(`organization.instances.status.${instance.status}`)}- </span>- </div>- <div className="flex items-center gap-1.5 text-[12px]">- <Users className="size-3.5 text-muted" />- {instance.access_entries_count}- </div>- <SyncBadge status={instance.policy_sync.status} />- <ChevronRight className="size-4 text-muted" />- </Link>- ))}- </TableFrame>- )}- </div>- );-}diff --git a/ui/src/features/organization/pages/OrganizationMembersPage.tsx b/ui/src/features/organization/pages/OrganizationMembersPage.tsxdeleted file mode 100644index 4a76ab398..000000000--- a/ui/src/features/organization/pages/OrganizationMembersPage.tsx+++ /dev/null@@ -1,523 +0,0 @@-import {- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from 'react';-import {- Download,- Mail,- Pencil,- Plus,- RefreshCw,- ShieldCheck,- Trash2,- UserCheck,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';-import { Checkbox } from '@/components/ui/checkbox';-import { ConfirmDialog } from '@/components/ui/confirm-dialog';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { SegmentedRadio } from '@/components/ui/segmented';-import { Select } from '@/components/ui/select';--import { isRevisionConflict, jsonBody, OrganizationApiError } from '../api/client';-import type {- MemberStatus,- OrganizationGroup,- OrganizationMember,- OrganizationRole,-} from '../api/types';-import {- ConflictBanner,- EmptyState,- ErrorBanner,- GroupPill,- InitialsAvatar,- LoadingState,- PageHeader,- RoleBadge,- SearchField,- StatCard,- TableFrame,-} from '../components';-import { useOrganization } from '../context';-import {- isCurrentOrganizationLoad,- requiresMemberRoleDowngradeConfirmation,-} from '../policy';--type MemberFilter = 'all' | MemberStatus;--function memberName(email: string): string {- return email.split('@')[0].split(/[._+-]/).filter(Boolean).map((part) => (- `${part.charAt(0).toUpperCase()}${part.slice(1)}`- )).join(' ');-}--function MemberDialog({- open,- member,- groups,- onOpenChange,- onSaved,-}: {- open: boolean;- member: OrganizationMember | null;- groups: OrganizationGroup[];- onOpenChange: (open: boolean) => void;- onSaved: () => Promise<OrganizationMember[]>;-}) {- const { t } = useTranslation();- const { selectedOrganizationId, request, invalidate } = useOrganization();- const [email, setEmail] = useState('');- const [role, setRole] = useState<Exclude<OrganizationRole, 'owner'>>('member');- const [groupIds, setGroupIds] = useState<string[]>([]);- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string>();- const [conflict, setConflict] = useState(false);- const [authoritativeMember, setAuthoritativeMember] = useState<OrganizationMember | null>(null);- const [revision, setRevision] = useState(0);- const [downgradeConfirmOpen, setDowngradeConfirmOpen] = useState(false);- const comparisonMemberRef = useRef<OrganizationMember | null>(null);-- useEffect(() => {- if (!open) return;- comparisonMemberRef.current = member;- setEmail(member?.email ?? '');- setRole(member?.role === 'admin' ? 'admin' : 'member');- setGroupIds(member?.groups.map((group) => group.id) ?? []);- setRevision(member?.member_revision ?? 0);- setError(undefined);- setConflict(false);- setAuthoritativeMember(null);- setDowngradeConfirmOpen(false);- }, [member, open]);-- const save = async () => {- if (!selectedOrganizationId || !email.trim()) return;- setSaving(true);- setError(undefined);- try {- const base = `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/members`;- if (member) {- await request(`${base}/${encodeURIComponent(member.id)}`, {- method: 'PATCH',- body: jsonBody({- role,- group_ids: groupIds,- if_match_revision: revision,- }),- });- } else {- await request(base, {- method: 'POST',- body: jsonBody({ email: email.trim(), role, group_ids: groupIds }),- });- }- invalidate();- await onSaved();- onOpenChange(false);- } catch (caught) {- if (isRevisionConflict(caught)) {- const latestMembers = await onSaved();- setAuthoritativeMember(- latestMembers.find((candidate) => candidate.id === member?.id) ?? null,- );- setConflict(true);- } else {- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');- }- } finally {- setSaving(false);- }- };-- const reloadAuthoritativeMember = () => {- if (!authoritativeMember) {- onOpenChange(false);- return;- }- comparisonMemberRef.current = authoritativeMember;- setEmail(authoritativeMember.email);- setRole(authoritativeMember.role === 'admin' ? 'admin' : 'member');- setGroupIds(authoritativeMember.groups.map((group) => group.id));- setRevision(authoritativeMember.member_revision);- setError(undefined);- setConflict(false);- setAuthoritativeMember(null);- };-- const requestSave = () => {- const comparisonMember = comparisonMemberRef.current ?? member;- if (comparisonMember && requiresMemberRoleDowngradeConfirmation(comparisonMember.role, role)) {- setDowngradeConfirmOpen(true);- return;- }- void save();- };-- return (- <>- <Dialog- open={open}- onOpenChange={(nextOpen) => {- if (!nextOpen) setDowngradeConfirmOpen(false);- onOpenChange(nextOpen);- }}- >- <DialogContent>- <DialogHeader>- <DialogTitle>{t(member ? 'organization.members.editTitle' : 'organization.members.inviteTitle')}</DialogTitle>- <DialogDescription>{t(member ? 'organization.members.editBody' : 'organization.members.inviteBody')}</DialogDescription>- </DialogHeader>- {conflict ? <ConflictBanner onReload={reloadAuthoritativeMember} /> : null}- {error ? <ErrorBanner code={error} /> : null}- <div className="space-y-4">- <div className="space-y-1.5">- <Label htmlFor="organization-member-email">{t('organization.fields.email')}</Label>- <Input- id="organization-member-email"- type="email"- value={email}- disabled={Boolean(member)}- onChange={(event) => setEmail(event.target.value)}- placeholder={t('organization.members.emailPlaceholder')}- />- </div>- <div className="space-y-1.5">- <Label htmlFor="organization-member-role">{t('organization.fields.role')}</Label>- <Select id="organization-member-role" value={role} onChange={(event) => setRole(event.target.value as typeof role)}>- <option value="member">{t('organization.roles.member')}</option>- <option value="admin">{t('organization.roles.admin')}</option>- </Select>- </div>- <fieldset>- <legend className="mb-2 text-[12px] font-medium">{t('organization.fields.groups')}</legend>- <div className="max-h-48 space-y-1 overflow-y-auto rounded-lg border border-border p-2">- {groups.filter((group) => !group.archived_at).map((group) => (- <button- key={group.id}- type="button"- role="checkbox"- aria-checked={groupIds.includes(group.id)}- className="flex w-full items-center gap-3 rounded-md px-2 py-2 text-left hover:bg-foreground/[0.04]"- onClick={() => setGroupIds((current) => current.includes(group.id)- ? current.filter((id) => id !== group.id)- : [...current, group.id])}- >- <Checkbox checked={groupIds.includes(group.id)} presentational />- <GroupPill name={group.name} color={group.color} />- </button>- ))}- {groups.filter((group) => !group.archived_at).length === 0 ? (- <div className="px-2 py-4 text-center text-[12px] text-muted">{t('organization.groups.emptyTitle')}</div>- ) : null}- </div>- </fieldset>- </div>- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>- <Button variant="brand" disabled={saving || conflict || !email.trim()} onClick={requestSave}>- {saving ? t('organization.actions.saving') : t(member ? 'organization.actions.saveChanges' : 'organization.actions.sendInvite')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- <ConfirmDialog- open={downgradeConfirmOpen}- onOpenChange={setDowngradeConfirmOpen}- title={t('organization.members.downgradeTitle')}- description={t('organization.members.downgradeBody', { email: member?.email })}- confirmLabel={t('organization.members.downgradeConfirm')}- destructive- onConfirm={async () => {- await save();- setDowngradeConfirmOpen(false);- }}- />- </>- );-}--export function OrganizationMembersPage() {- const { t } = useTranslation();- const {- detail,- session,- selectedOrganizationId,- request,- dataVersion,- invalidate,- } = useOrganization();- const [directory, setDirectory] = useState<{- organizationId: string;- members: OrganizationMember[];- groups: OrganizationGroup[];- } | null>(null);- const [filter, setFilter] = useState<MemberFilter>('all');- const [search, setSearch] = useState('');- 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- || selectedOrganizationIdRef.current !== selectedOrganizationId- || detail?.organization.id !== selectedOrganizationId- || !session- ) return [];- const organizationId = selectedOrganizationId;- const generation = ++loadGeneration.current;- const isCurrent = () => isCurrentOrganizationLoad(- organizationId,- selectedOrganizationIdRef.current,- generation,- loadGeneration.current,- );- setErrorState(null);- try {- const memberRequest = canManage- ? request<{ members: OrganizationMember[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/members`,- )- : Promise.resolve({- members: [{- id: detail.membership.id,- user_id: session.user.subject,- email: session.user.email,- role: detail.membership.role,- status: detail.membership.status,- member_revision: detail.membership.member_revision,- invited_by_user_id: null,- created_at: detail.organization.created_at,- updated_at: detail.organization.updated_at,- groups: detail.membership.groups,- }],- });- const [memberResult, groupResult] = await Promise.all([- memberRequest,- request<{ groups: OrganizationGroup[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/groups`,- ),- ]);- if (!isCurrent()) return [];- setDirectory({- organizationId,- members: memberResult.members,- groups: groupResult.groups,- });- return memberResult.members;- } catch (caught) {- if (!isCurrent()) return [];- setErrorState({- organizationId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- return [];- }- }, [canManage, detail, request, selectedOrganizationId, session]);-- useEffect(() => {- const timer = window.setTimeout(() => void load(), 0);- return () => window.clearTimeout(timer);- }, [dataVersion, load]);-- const filtered = useMemo(() => (members ?? []).filter((member) => (- (filter === 'all' || member.status === filter)- && member.email.toLowerCase().includes(search.trim().toLowerCase())- )), [filter, members, search]);- const counts = useMemo(() => ({- active: (members ?? []).filter((member) => member.status === 'active').length,- invited: (members ?? []).filter((member) => member.status === 'invited').length,- admin: (members ?? []).filter((member) => member.status === 'active' && ['owner', 'admin'].includes(member.role)).length,- }), [members]);-- const exportCsv = async () => {- if (!selectedOrganizationId) return;- try {- const result = await request<{ filename: string; csv: string }>(- `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/members/export`,- );- const url = URL.createObjectURL(new Blob([result.csv], { type: 'text/csv;charset=utf-8' }));- const anchor = document.createElement('a');- anchor.href = url;- anchor.download = result.filename;- anchor.click();- URL.revokeObjectURL(url);- } catch (caught) {- setErrorState({- organizationId: selectedOrganizationId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- };-- const removeMember = async () => {- if (!selectedOrganizationId || !removing) return;- try {- await request(- `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/members/${encodeURIComponent(removing.id)}`,- {- method: 'PATCH',- body: jsonBody({ status: 'removed', if_match_revision: removing.member_revision }),- },- );- setRemoving(null);- invalidate();- await load();- } catch (caught) {- if (isRevisionConflict(caught)) {- const latestMembers = await load();- setRemoving((current) => (- current- ? latestMembers.find((member) => member.id === current.id && member.status !== 'removed') ?? null- : null- ));- }- setErrorState({- organizationId: selectedOrganizationId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- };-- const resend = async (member: OrganizationMember) => {- if (!selectedOrganizationId) return;- try {- await request(- `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/members/${encodeURIComponent(member.id)}/resend-invite`,- { method: 'POST', body: jsonBody({}) },- );- } catch (caught) {- setErrorState({- organizationId: selectedOrganizationId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- };-- if (!detail) return null;- if (!members && !error) return <LoadingState />;- return (- <div className="space-y-6">- <PageHeader- eyebrow={t('organization.breadcrumb.members')}- title={t('organization.nav.members')}- description={canManage ? t('organization.members.description') : t('organization.members.memberDescription')}- actions={canManage ? (- <>- <Button variant="outline" onClick={() => void exportCsv()}><Download className="size-4" />{t('organization.actions.exportCsv')}</Button>- <Button variant="brand" onClick={() => { setEditing(null); setDialogOpen(true); }}><Plus className="size-4" />{t('organization.actions.inviteMember')}</Button>- </>- ) : undefined}- />- {error ? <ErrorBanner code={error} onRetry={() => void load()} /> : null}- {canManage ? (- <div className="grid gap-3 sm:grid-cols-3">- <StatCard label={t('organization.members.active')} value={counts.active} icon={<UserCheck className="size-5" />} />- <StatCard label={t('organization.members.invited')} value={counts.invited} icon={<Mail className="size-5" />} />- <StatCard label={t('organization.members.admins')} value={counts.admin} icon={<ShieldCheck className="size-5" />} />- </div>- ) : null}- <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">- <SegmentedRadio- value={filter}- onChange={setFilter}- ariaLabel={t('organization.members.filterLabel')}- options={([- ['all', t('organization.members.filterAll')],- ['active', t('organization.members.active')],- ['invited', t('organization.members.invited')],- ['removed', t('organization.members.removed')],- ] as Array<[MemberFilter, string]>).map(([id, label]) => ({ id, label }))}- />- <SearchField value={search} onChange={setSearch} placeholder={t('organization.members.searchPlaceholder')} />- </div>- {filtered.length === 0 ? (- <EmptyState title={t('organization.members.emptyTitle')} body={t('organization.members.emptyBody')} />- ) : (- <TableFrame>- <div className="hidden grid-cols-[minmax(240px,2fr)_140px_minmax(220px,1.4fr)_120px_132px] gap-4 border-b border-border px-5 py-3 font-mono text-[10px] font-bold uppercase text-muted md:grid">- <span>{t('organization.fields.member')}</span><span>{t('organization.fields.role')}</span><span>{t('organization.fields.groups')}</span><span>{t('organization.fields.status')}</span><span />- </div>- {filtered.map((member) => (- <div key={member.id} className="grid gap-3 border-b border-border p-4 last:border-0 md:grid-cols-[minmax(240px,2fr)_140px_minmax(220px,1.4fr)_120px_132px] md:items-center md:gap-4 md:px-5">- <div className="flex min-w-0 items-center gap-3">- <InitialsAvatar value={member.email} className="rounded-full" />- <div className="min-w-0">- <div className="truncate text-[13px] font-semibold">{memberName(member.email)}</div>- <div className="truncate font-mono text-[10px] text-muted">{member.email}</div>- </div>- </div>- <div><RoleBadge role={member.role} /></div>- <div className="flex flex-wrap gap-1.5">- {member.groups.length ? member.groups.map((group) => <GroupPill key={group.id} name={group.name} />) : <span className="text-[12px] text-muted">{t('common.none')}</span>}- </div>- <div>- <Badge variant={member.status === 'active' ? 'success' : member.status === 'invited' ? 'warning' : 'secondary'}>- {t(`organization.status.${member.status}`)}- </Badge>- </div>- <div className="flex justify-end gap-1">- {canManage && member.status === 'invited' ? (- <Button size="icon" variant="ghost" aria-label={t('organization.actions.resendInvite')} onClick={() => void resend(member)}><RefreshCw className="size-4" /></Button>- ) : null}- {canManage && member.role !== 'owner' && member.status !== 'removed' ? (- <Button size="icon" variant="ghost" aria-label={t('organization.actions.editMember')} onClick={() => { setEditing(member); setDialogOpen(true); }}><Pencil className="size-4" /></Button>- ) : null}- {canManage && member.role !== 'owner' && member.status !== 'removed' ? (- <Button size="icon" variant="ghost" aria-label={t('organization.actions.removeMember')} onClick={() => setRemoving(member)}><Trash2 className="size-4 text-destructive-ink" /></Button>- ) : null}- </div>- </div>- ))}- </TableFrame>- )}- <MemberDialog- open={dialogOpen && currentDirectory !== null}- member={currentDirectory ? editing : null}- groups={groups}- onOpenChange={setDialogOpen}- onSaved={load}- />- <ConfirmDialog- open={Boolean(removing && currentDirectory)}- onOpenChange={(open) => { if (!open) setRemoving(null); }}- title={t('organization.members.removeTitle')}- description={t('organization.members.removeBody', { email: removing?.email })}- confirmLabel={t('organization.actions.removeMember')}- destructive- onConfirm={removeMember}- />- </div>- );-}diff --git a/ui/src/features/organization/pages/OrganizationOverviewPage.tsx b/ui/src/features/organization/pages/OrganizationOverviewPage.tsxdeleted file mode 100644index 5f4021f95..000000000--- a/ui/src/features/organization/pages/OrganizationOverviewPage.tsx+++ /dev/null@@ -1,278 +0,0 @@-import {- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from 'react';-import {- AlertTriangle,- Boxes,- FolderTree,- Server,- Users,- Workflow,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';-import { Link } from 'react-router-dom';--import { Button } from '@/components/ui/button';-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';--import type {- OrganizationInstance,- OrganizationMember,- OrganizationProject,- OrganizationResource,-} from '../api/types';-import {- EmptyState,- ErrorBanner,- LoadingState,- PageHeader,- RoleBadge,- StatCard,- SyncBadge,-} from '../components';-import { useOrganization } from '../context';-import { aggregateSyncStatus, isCurrentOrganizationLoad } from '../policy';--type OverviewData = {- instances: OrganizationInstance[];- members: OrganizationMember[];- resources: OrganizationResource[];- projects: OrganizationProject[] | null;-};--function isUnhealthy(status: ReturnType<typeof aggregateSyncStatus>): boolean {- return status !== 'in_sync' && status !== 'none';-}--function instanceDiagnosticsPath(instance: OrganizationInstance, canManage: boolean): string {- if (isUnhealthy(aggregateSyncStatus(instance.policy_sync.projects))) {- return `/admin/organization/instances/${encodeURIComponent(instance.id)}/projects`;- }- if (canManage && isUnhealthy(aggregateSyncStatus(instance.policy_sync.resources))) {- return '/admin/organization/resources';- }- return '/admin/organization/instances';-}--export function OrganizationOverviewPage() {- const { t } = useTranslation();- const { detail, selectedOrganizationId, request, dataVersion } = useOrganization();- const [loadedData, setLoadedData] = useState<{- organizationId: string;- data: OverviewData;- } | null>(null);- const [errorState, setErrorState] = useState<{ organizationId: string; code: string } | null>(null);- const loadGeneration = useRef(0);- const selectedOrganizationIdRef = useRef(selectedOrganizationId);- const data = loadedData?.organizationId === selectedOrganizationId ? loadedData.data : null;- 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 () => {- if (!selectedOrganizationId) return;- const organizationId = selectedOrganizationId;- if (selectedOrganizationIdRef.current !== organizationId) return;- const generation = ++loadGeneration.current;- const isCurrent = () => isCurrentOrganizationLoad(- organizationId,- selectedOrganizationIdRef.current,- generation,- loadGeneration.current,- );- setErrorState(null);- try {- const [instanceResult, memberResult, resourceResult] = await Promise.all([- request<{ instances: OrganizationInstance[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/instances`,- ),- canManage- ? request<{ members: OrganizationMember[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/members`,- )- : Promise.resolve({ members: [] }),- canManage- ? request<{ resources: OrganizationResource[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/resources`,- )- : Promise.resolve({ resources: [] }),- ]);- const projectResults = await Promise.allSettled(- instanceResult.instances.map((instance) => request<{ projects: OrganizationProject[] }>(- `/api/cloud-management/instances/${encodeURIComponent(instance.id)}/projects`,- )),- );- if (!isCurrent()) return;- setLoadedData({- organizationId,- data: {- instances: instanceResult.instances,- members: memberResult.members,- resources: resourceResult.resources,- projects: projectResults.every((result) => result.status === 'fulfilled')- ? projectResults.flatMap((result) => (- result.status === 'fulfilled' ? result.value.projects : []- ))- : null,- },- });- } catch (caught) {- if (!isCurrent()) return;- setErrorState({- organizationId,- code: caught instanceof Error ? caught.message : 'cloud_management_unavailable',- });- }- }, [canManage, request, selectedOrganizationId]);-- useEffect(() => {- const timer = window.setTimeout(() => void load(), 0);- return () => window.clearTimeout(timer);- }, [dataVersion, load]);-- const attention = useMemo(() => {- if (!data) return [];- return [- ...(canManage && (detail?.counts.invitedMembers ?? 0) > 0- ? [{- key: 'invites',- title: t('organization.overview.pendingInvites', { count: detail?.counts.invitedMembers }),- body: t('organization.overview.pendingInvitesBody', { count: detail?.counts.invitedMembers }),- to: '/admin/organization/members',- }]- : []),- ...data.instances.flatMap((instance) => {- const projectStatus = aggregateSyncStatus(instance.policy_sync.projects);- const resourceStatus = aggregateSyncStatus(instance.policy_sync.resources);- return [- ...(isUnhealthy(projectStatus) ? [{- key: `${instance.id}:projects`,- title: t('organization.overview.projectSyncNeedsAttention', { name: instance.slug }),- body: t(`organization.sync.${projectStatus}`),- to: `/admin/organization/instances/${encodeURIComponent(instance.id)}/projects`,- }] : []),- ...(isUnhealthy(resourceStatus) ? [{- key: `${instance.id}:resources`,- title: t('organization.overview.resourceSyncNeedsAttention', { name: instance.slug }),- body: t(`organization.sync.${resourceStatus}`),- to: canManage ? '/admin/organization/resources' : '/admin/organization/instances',- }] : []),- ];- }),- ];- }, [canManage, data, detail?.counts, t]);-- if (!detail) return null;- if (!data && !error) return <LoadingState rows={6} />;- return (- <div className="space-y-6">- <PageHeader- eyebrow={t('organization.breadcrumb.overview')}- title={detail.organization.name}- titleAccessory={<RoleBadge role={detail.membership.role} />}- description={canManage ? t('organization.overview.description') : t('organization.overview.memberDescription')}- />- {error ? <ErrorBanner code={error} onRetry={() => void load()} /> : null}- {data ? (- <>- <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">- <StatCard- label={t('organization.nav.members')}- value={detail.counts.members}- detail={canManage ? t('organization.overview.memberBreakdown', {- invited: detail.counts.invitedMembers ?? 0,- removed: detail.counts.removedMembers ?? 0,- }) : undefined}- icon={<Users className="size-5" />}- />- <StatCard- label={t('organization.nav.groups')}- value={detail.counts.groups}- detail={canManage ? t('organization.overview.groupBreakdown', { archived: detail.counts.archivedGroups ?? 0 }) : undefined}- icon={<Boxes className="size-5" />}- />- <StatCard label={t('organization.nav.instances')} value={data.instances.length} icon={<Server className="size-5" />} />- <StatCard- label={t('organization.overview.projects')}- value={data.projects === null ? '-' : data.projects.length}- detail={data.projects === null ? t('organization.overview.projectCountUnavailable') : undefined}- icon={<FolderTree className="size-5" />}- />- {canManage ? (- <StatCard label={t('organization.nav.resources')} value={data.resources.length} icon={<Workflow className="size-5" />} />- ) : null}- </div>-- {!canManage ? (- <div className="rounded-lg border border-cyan/30 bg-cyan/10 p-4 text-[13px] text-muted">- <div className="font-semibold text-foreground">{t('organization.overview.memberSafeTitle')}</div>- <div className="mt-1">{t('organization.overview.memberSafeBody')}</div>- </div>- ) : null}-- <div className="grid gap-4 xl:grid-cols-[minmax(0,1.35fr)_minmax(340px,0.75fr)]">- <Card>- <CardHeader className="flex-row items-center justify-between">- <CardTitle>{t('organization.overview.policySync')}</CardTitle>- <Button asChild variant="ghost" size="sm">- <Link to="/admin/organization/instances">{t('organization.overview.viewAllInstances')}</Link>- </Button>- </CardHeader>- <CardContent className="p-0">- {data.instances.length === 0 ? (- <div className="p-5"><EmptyState title={t('organization.instances.emptyTitle')} body={t('organization.instances.emptyBody')} /></div>- ) : data.instances.map((instance) => (- <Link- key={instance.id}- to={instanceDiagnosticsPath(instance, canManage)}- className="flex items-center gap-3 border-b border-border px-5 py-4 last:border-b-0 hover:bg-foreground/[0.025]"- >- <div className="grid size-9 shrink-0 place-items-center rounded-lg bg-mint/10 font-bold text-mint-ink">- {instance.slug.charAt(0).toUpperCase()}- </div>- <div className="min-w-0 flex-1">- <div className="truncate text-[13px] font-semibold">{instance.slug}</div>- <div className="mt-0.5 truncate font-mono text-[10px] text-muted">- {instance.primary_url} · {t('organization.instances.accessCount', { count: instance.access_entries_count })}- </div>- </div>- <SyncBadge status={instance.policy_sync.status} />- </Link>- ))}- </CardContent>- </Card>-- <Card>- <CardHeader className="flex-row items-center justify-between">- <CardTitle className="flex items-center gap-2">- <AlertTriangle className="size-4 text-gold-ink" />- {t('organization.overview.needsAttention')}- </CardTitle>- <span className="rounded-full bg-gold/15 px-2 py-0.5 text-[11px] font-semibold text-gold-ink">{attention.length}</span>- </CardHeader>- <CardContent className="p-0">- {attention.length === 0 ? (- <div className="p-6 text-center text-[13px] text-muted">{t('organization.overview.noAttention')}</div>- ) : attention.map((item) => (- <Link key={item.key} to={item.to} className="block border-b border-border px-5 py-4 last:border-0 hover:bg-foreground/[0.025]">- <div className="text-[13px] font-semibold">{item.title}</div>- <div className="mt-0.5 text-[11px] text-muted">{item.body}</div>- </Link>- ))}- </CardContent>- </Card>- </div>- </>- ) : null}- </div>- );-}diff --git a/ui/src/features/organization/pages/OrganizationResourcesPage.tsx b/ui/src/features/organization/pages/OrganizationResourcesPage.tsxdeleted file mode 100644index 991fd1ab9..000000000--- a/ui/src/features/organization/pages/OrganizationResourcesPage.tsx+++ /dev/null@@ -1,447 +0,0 @@-import {- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from 'react';-import {- Bot,- Building2,- KeyRound,- LayoutPanelTop,- LockKeyhole,- Sparkles,- Users,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';-import clsx from 'clsx';--import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';-import { Checkbox } from '@/components/ui/checkbox';-import { ConfirmDialog } from '@/components/ui/confirm-dialog';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';-import { Label } from '@/components/ui/label';-import { SegmentedRadio } from '@/components/ui/segmented';--import { isRevisionConflict, jsonBody, OrganizationApiError } from '../api/client';-import type {- OrganizationGroup,- OrganizationInstance,- OrganizationResource,- ResourceAccessLevel,- ResourceKind,-} from '../api/types';-import {- ConflictBanner,- EmptyState,- ErrorBanner,- ForbiddenState,- LoadingState,- PageHeader,- SyncBadge,- TableFrame,-} from '../components';-import { useOrganization } from '../context';-import {- isCurrentOrganizationLoad,- requiresResourceAccessNarrowingConfirmation,-} from '../policy';--const RESOURCE_KINDS: Array<{ kind: ResourceKind; icon: typeof Bot }> = [- { kind: 'agent', icon: Bot },- { kind: 'vault_secret', icon: KeyRound },- { kind: 'skill', icon: Sparkles },- { kind: 'show_page', icon: LayoutPanelTop },-];-const EMPTY_GROUPS: OrganizationGroup[] = [];-const EMPTY_INSTANCES: OrganizationInstance[] = [];--function resourceIcon(kind: ResourceKind) {- return RESOURCE_KINDS.find((item) => item.kind === kind)?.icon ?? Bot;-}--function ResourceAccessDialog({- resource,- groups,- onOpenChange,- onSaved,-}: {- resource: OrganizationResource | null;- groups: OrganizationGroup[];- onOpenChange: (open: boolean) => void;- onSaved: () => Promise<OrganizationResource | null>;-}) {- const { t } = useTranslation();- const { selectedOrganizationId, request } = useOrganization();- const [level, setLevel] = useState<ResourceAccessLevel>('private');- const [groupIds, setGroupIds] = useState<string[]>([]);- const [revision, setRevision] = useState(0);- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string>();- const [conflict, setConflict] = useState(false);- const [authoritativeResource, setAuthoritativeResource] = useState<OrganizationResource | null>(null);- const [confirmNarrowing, setConfirmNarrowing] = useState(false);- const comparisonResourceRef = useRef<OrganizationResource | null>(null);-- useEffect(() => {- if (!resource) return;- comparisonResourceRef.current = resource;- setLevel(resource.access?.access_level ?? 'private');- setGroupIds(resource.access?.group_ids ?? []);- setRevision(resource.access?.revision ?? 0);- setError(undefined);- setConflict(false);- setAuthoritativeResource(null);- setConfirmNarrowing(false);- }, [resource]);-- const visibleGroups = groups.filter((group) => !group.archived_at || groupIds.includes(group.id));- const toggleGroup = (group: OrganizationGroup) => {- const selected = groupIds.includes(group.id);- if (group.archived_at && !selected) return;- setGroupIds((current) => selected- ? current.filter((id) => id !== group.id)- : [...current, group.id]);- };-- const wireGroupIds = level === 'scope' ? [...new Set(groupIds)] : [];-- const commit = async () => {- if (!resource || !selectedOrganizationId || (level === 'scope' && groupIds.length === 0)) return;- setSaving(true);- setError(undefined);- try {- await request(- `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/resources/${encodeURIComponent(resource.instance_id)}/${encodeURIComponent(resource.resource_kind)}/${encodeURIComponent(resource.resource_id)}/access`,- {- method: 'PATCH',- body: jsonBody({- access_level: level,- group_ids: wireGroupIds,- if_match_revision: revision,- }),- },- );- await onSaved();- onOpenChange(false);- } catch (caught) {- if (isRevisionConflict(caught)) {- setAuthoritativeResource(await onSaved());- setConflict(true);- } else {- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');- }- } finally {- setSaving(false);- setConfirmNarrowing(false);- }- };-- const save = () => {- if (!resource || !selectedOrganizationId || (level === 'scope' && groupIds.length === 0)) return;- const comparisonResource = comparisonResourceRef.current ?? resource;- const currentLevel = comparisonResource.access?.access_level ?? 'private';- const currentGroupIds = comparisonResource.access?.group_ids ?? [];- if (requiresResourceAccessNarrowingConfirmation(- currentLevel,- currentGroupIds,- level,- wireGroupIds,- )) {- setConfirmNarrowing(true);- return;- }- void commit();- };-- const reloadAuthoritativeResource = () => {- if (!authoritativeResource) {- onOpenChange(false);- return;- }- comparisonResourceRef.current = authoritativeResource;- setLevel(authoritativeResource.access?.access_level ?? 'private');- setGroupIds(authoritativeResource.access?.group_ids ?? []);- setRevision(authoritativeResource.access?.revision ?? 0);- setError(undefined);- setConflict(false);- setAuthoritativeResource(null);- };-- return (- <>- <Dialog open={Boolean(resource)} onOpenChange={onOpenChange}>- <DialogContent className="max-w-xl">- <DialogHeader>- <DialogTitle>{t('organization.resources.dialogTitle', { name: resource?.display_name })}</DialogTitle>- <DialogDescription>{t('organization.resources.dialogBody')}</DialogDescription>- </DialogHeader>- {conflict ? <ConflictBanner onReload={reloadAuthoritativeResource} /> : null}- {error ? <ErrorBanner code={error} /> : null}- <div className="space-y-5">- <div className="space-y-1.5">- <Label>{t('organization.resources.accessLevel')}</Label>- <SegmentedRadio- value={level}- onChange={setLevel}- ariaLabel={t('organization.resources.accessLevel')}- options={[- { id: 'private', label: t('organization.resources.levels.private') },- { id: 'public', label: t('organization.resources.levels.public') },- { id: 'scope', label: t('organization.resources.levels.scope') },- ]}- />- </div>- <div className="rounded-lg border border-border bg-foreground/[0.025] p-3 text-[12px] leading-5 text-muted">- {t(`organization.resources.levelHelp.${level}`)}- </div>- {level === 'scope' ? (- <fieldset>- <legend className="mb-2 text-[12px] font-medium">{t('organization.resources.selectGroups')}</legend>- <div className="max-h-64 space-y-1 overflow-y-auto rounded-lg border border-border p-2">- {visibleGroups.map((group) => {- const selected = groupIds.includes(group.id);- return (- <button- key={group.id}- type="button"- role="checkbox"- aria-checked={selected}- className={clsx(- 'flex w-full items-center gap-3 rounded-md px-2 py-2 text-left',- group.archived_at && !selected ? 'cursor-not-allowed opacity-50' : 'hover:bg-foreground/[0.04]',- )}- disabled={Boolean(group.archived_at && !selected)}- onClick={() => toggleGroup(group)}- >- <Checkbox checked={selected} presentational />- <span className="min-w-0 flex-1 truncate text-[12px]">{group.name}</span>- {group.archived_at ? <Badge variant="secondary">{t('organization.groups.archived')}</Badge> : null}- </button>- );- })}- </div>- {groupIds.length === 0 ? <div className="mt-2 text-[11px] text-gold-ink">{t('organization.resources.groupRequired')}</div> : null}- </fieldset>- ) : null}- </div>- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>- <Button variant="brand" disabled={saving || conflict || (level === 'scope' && groupIds.length === 0)} onClick={save}>- {saving ? t('organization.actions.saving') : t('organization.actions.saveChanges')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- <ConfirmDialog- open={confirmNarrowing}- onOpenChange={setConfirmNarrowing}- title={t('organization.resources.narrowTitle')}- description={t('organization.resources.narrowBody')}- confirmLabel={t('organization.actions.saveChanges')}- onConfirm={commit}- />- </>- );-}--export function OrganizationResourcesPage() {- const { t } = useTranslation();- const { detail, selectedOrganizationId, request, dataVersion } = useOrganization();- const [directory, setDirectory] = useState<{- organizationId: string;- resources: OrganizationResource[];- groups: OrganizationGroup[];- instances: OrganizationInstance[];- } | null>(null);- const [kind, setKind] = useState<ResourceKind>('agent');- const [editing, setEditing] = useState<{- organizationId: string;- resource: OrganizationResource;- } | null>(null);- const [errorState, setErrorState] = useState<{ organizationId: string; code: string } | null>(null);- const [forbiddenOrganizationId, setForbiddenOrganizationId] = useState<string | null>(null);- const loadGeneration = useRef(0);- const selectedOrganizationIdRef = useRef(selectedOrganizationId);- const currentDirectory = directory?.organizationId === selectedOrganizationId ? directory : null;- const resources = currentDirectory?.resources ?? null;- const groups = currentDirectory?.groups ?? EMPTY_GROUPS;- const instances = currentDirectory?.instances ?? EMPTY_INSTANCES;- const currentEditing = editing?.organizationId === selectedOrganizationId ? editing.resource : null;- const error = errorState?.organizationId === selectedOrganizationId ? errorState.code : undefined;- const forbidden = forbiddenOrganizationId === selectedOrganizationId;- const canManage = detail?.capabilities.can_manage_organization === true;-- useLayoutEffect(() => {- selectedOrganizationIdRef.current = selectedOrganizationId;- loadGeneration.current += 1;- }, [selectedOrganizationId]);-- const load = useCallback(async (): Promise<OrganizationResource[]> => {- if (!selectedOrganizationId || !canManage) return [];- const organizationId = selectedOrganizationId;- if (selectedOrganizationIdRef.current !== organizationId) return [];- const generation = ++loadGeneration.current;- const isCurrent = () => isCurrentOrganizationLoad(- organizationId,- selectedOrganizationIdRef.current,- generation,- loadGeneration.current,- );- setErrorState(null);- setForbiddenOrganizationId(null);- try {- const [resourceResult, groupResult, instanceResult] = await Promise.all([- request<{ resources: OrganizationResource[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/resources`,- ),- request<{ groups: OrganizationGroup[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/groups`,- ),- request<{ instances: OrganizationInstance[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/instances`,- ),- ]);- const activeResources = resourceResult.resources.filter((resource) => resource.sync.status !== 'deleted');- if (!isCurrent()) return [];- setDirectory({- organizationId,- resources: activeResources,- groups: groupResult.groups,- instances: instanceResult.instances,- });- return activeResources;- } catch (caught) {- if (!isCurrent()) return [];- if (caught instanceof OrganizationApiError && (caught.status === 403 || caught.status === 404)) {- setForbiddenOrganizationId(organizationId);- } else {- setErrorState({- organizationId,- code: caught instanceof OrganizationApiError ? caught.code : 'generic',- });- }- return [];- }- }, [canManage, request, selectedOrganizationId]);-- useEffect(() => {- const timer = window.setTimeout(() => void load(), 0);- return () => window.clearTimeout(timer);- }, [dataVersion, load]);-- const visible = useMemo(() => (resources ?? []).filter((resource) => resource.resource_kind === kind), [kind, resources]);- const groupNames = useMemo(() => new Map(groups.map((group) => [group.id, group.name])), [groups]);- const instanceNames = useMemo(() => new Map(instances.map((instance) => [instance.id, instance.slug])), [instances]);-- if (!canManage) return <ForbiddenState />;- if (!resources && !error && !forbidden) return <LoadingState />;-- return (- <div className="space-y-6">- <PageHeader- eyebrow={t('organization.breadcrumb.resources')}- title={t('organization.nav.resources')}- description={t('organization.resources.description')}- />- <div className="flex flex-wrap items-center gap-1 border-b border-border" role="tablist" aria-label={t('organization.resources.tabsLabel')}>- {RESOURCE_KINDS.map((item) => {- const Icon = item.icon;- const count = (resources ?? []).filter((resource) => resource.resource_kind === item.kind).length;- return (- <button- key={item.kind}- type="button"- role="tab"- aria-selected={kind === item.kind}- className={clsx(- 'inline-flex h-10 items-center gap-2 border-b-2 px-3 text-[12px] font-medium',- kind === item.kind ? 'border-mint text-foreground' : 'border-transparent text-muted hover:text-foreground',- )}- onClick={() => setKind(item.kind)}- >- <Icon className="size-4" />- {t(`organization.resources.kinds.${item.kind}`)}- <span className="text-[10px] text-muted">{count}</span>- </button>- );- })}- </div>- {forbidden ? <ForbiddenState /> : null}- {error ? <ErrorBanner code={error} onRetry={() => void load()} /> : null}- {!forbidden && visible.length === 0 ? (- <EmptyState title={t('organization.resources.emptyTitle')} body={t('organization.resources.emptyBody', { kind: t(`organization.resources.kinds.${kind}`) })} />- ) : !forbidden ? (- <TableFrame>- <div className="hidden grid-cols-[minmax(220px,1.35fr)_170px_minmax(190px,1fr)_130px_90px] gap-4 border-b border-border px-5 py-3 font-mono text-[10px] font-bold uppercase text-muted md:grid">- <div>{t(`organization.resources.kinds.${kind}`)}</div>- <div>{t('organization.resources.columns.access')}</div>- <div>{t('organization.resources.columns.audience')}</div>- <div>{t('organization.resources.columns.sync')}</div>- <div />- </div>- {visible.map((resource) => {- const Icon = resourceIcon(resource.resource_kind);- const level = resource.access?.access_level ?? 'private';- const selectedNames = (resource.access?.group_ids ?? []).map((id) => groupNames.get(id) ?? id);- return (- <div key={`${resource.instance_id}:${resource.resource_kind}:${resource.resource_id}`} className="grid gap-3 border-b border-border px-4 py-4 last:border-0 md:grid-cols-[minmax(220px,1.35fr)_170px_minmax(190px,1fr)_130px_90px] md:items-center md:px-5">- <div className="flex min-w-0 items-center gap-3">- <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-mint/10 text-mint-ink"><Icon className="size-4" /></span>- <div className="min-w-0">- <div className="truncate text-[12px] font-semibold">{resource.display_name}</div>- <div className="truncate font-mono text-[10px] text-muted">{resource.resource_id} · {instanceNames.get(resource.instance_id) ?? resource.instance_id}</div>- </div>- </div>- <Badge variant={level === 'public' ? 'success' : level === 'scope' ? 'info' : 'secondary'}>- {level === 'public' ? <Building2 className="size-3" /> : level === 'scope' ? <Users className="size-3" /> : <LockKeyhole className="size-3" />}- {t(`organization.resources.levels.${level}`)}- </Badge>- <div className="truncate text-[12px] text-muted">- {level === 'public'- ? t('organization.resources.everyActiveMember')- : level === 'private'- ? t('organization.resources.ownerOnly')- : selectedNames.join(', ')}- </div>- <SyncBadge status={resource.sync.status} />- <Button- size="sm"- variant="outline"- onClick={() => {- if (selectedOrganizationId) setEditing({ organizationId: selectedOrganizationId, resource });- }}- >- {t('organization.actions.manage')}- </Button>- </div>- );- })}- </TableFrame>- ) : null}- <ResourceAccessDialog- resource={currentEditing}- groups={groups}- onOpenChange={(open) => { if (!open) setEditing(null); }}- onSaved={async () => {- const latestResources = await load();- return latestResources.find((resource) => (- resource.instance_id === currentEditing?.instance_id- && resource.resource_kind === currentEditing?.resource_kind- && resource.resource_id === currentEditing?.resource_id- )) ?? null;- }}- />- </div>- );-}diff --git a/ui/src/features/organization/policy.test.ts b/ui/src/features/organization/policy.test.tsdeleted file mode 100644index e760a4094..000000000--- a/ui/src/features/organization/policy.test.ts+++ /dev/null@@ -1,123 +0,0 @@-import { describe, expect, it } from 'vitest';--import {- aggregateSyncStatus,- hasDuplicateOrganizationPrincipals,- hasDuplicateProjectPrincipals,- isCurrentOrganizationLoad,- normalizeOrganizationPrincipal,- organizationAuthorizationReturnPath,- organizationSwitchDestination,- requiresMemberRoleDowngradeConfirmation,- requiresProjectAccessNarrowingConfirmation,- requiresResourceAccessNarrowingConfirmation,-} from './policy';--describe('Organization policy helpers', () => {- it('normalizes email and domain principals like the runtime validator', () => {- expect(normalizeOrganizationPrincipal('email', ' [email protected] ')).toBe('[email protected]');- expect(normalizeOrganizationPrincipal('email_domain', ' @Example.com ')).toBe('example.com');- expect(normalizeOrganizationPrincipal('organization_group', ' group-1 ')).toBe('group-1');- });-- it('rejects duplicate normalized Project principals without collapsing roles', () => {- expect(hasDuplicateProjectPrincipals([- { principal_kind: 'email', principal_value: '[email protected]', access_role: 'viewer' },- { principal_kind: 'email', principal_value: ' [email protected] ', access_role: 'editor' },- ])).toBe(true);- expect(hasDuplicateProjectPrincipals([- { principal_kind: 'email', principal_value: '[email protected]', access_role: 'viewer' },- { principal_kind: 'email_domain', principal_value: '[email protected]', access_role: 'viewer' },- ])).toBe(false);- });-- it('rejects duplicate normalized Avibe access principals', () => {- expect(hasDuplicateOrganizationPrincipals([- { kind: 'email', value: '[email protected]' },- { kind: 'email', value: ' [email protected] ' },- ])).toBe(true);- expect(hasDuplicateOrganizationPrincipals([- { kind: 'email_domain', value: '@Example.com' },- { kind: 'email_domain', value: ' example.com ' },- ])).toBe(true);- expect(hasDuplicateOrganizationPrincipals([- { kind: 'organization_group', value: 'group-1' },- { kind: 'organization_group', value: ' group-1 ' },- ])).toBe(true);- expect(hasDuplicateOrganizationPrincipals([- { kind: 'email', value: '[email protected]' },- { kind: 'email_domain', value: '[email protected]' },- ])).toBe(false);- });-- it('removes callback errors from Organization authorization return paths', () => {- expect(organizationAuthorizationReturnPath(- '/admin/organization/overview',- '?tab=access&cloud_management_error=cloud_management_subject_mismatch',- )).toBe('/admin/organization/overview?tab=access');- expect(organizationAuthorizationReturnPath(- '/admin/organization/overview',- '?cloud_management_error=cloud_management_subject_mismatch',- )).toBe('/admin/organization/overview');- });-- it('derives child sync status in the documented severity order', () => {- expect(aggregateSyncStatus({ active: 4, error: 1, offline: 1, applying: 1, in_sync: 1 })).toBe('error');- expect(aggregateSyncStatus({ active: 3, error: 0, offline: 1, applying: 1, in_sync: 1 })).toBe('offline');- expect(aggregateSyncStatus({ active: 2, error: 0, offline: 0, applying: 1, in_sync: 1 })).toBe('applying');- 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);- });-- it('requires confirmation before the member editor removes admin access', () => {- expect(requiresMemberRoleDowngradeConfirmation('admin', 'member')).toBe(true);- expect(requiresMemberRoleDowngradeConfirmation('member', 'admin')).toBe(false);- expect(requiresMemberRoleDowngradeConfirmation('member', 'member')).toBe(false);- });-- it('requires confirmation for every Project access narrowing', () => {- const editor = { principal_kind: 'email' as const, principal_value: '[email protected]', access_role: 'editor' as const };- const viewer = { ...editor, access_role: 'viewer' as const };- const secondViewer = { principal_kind: 'email' as const, principal_value: '[email protected]', access_role: 'viewer' as const };-- expect(requiresProjectAccessNarrowingConfirmation('inherit', [], 'restricted', [viewer])).toBe(true);- expect(requiresProjectAccessNarrowingConfirmation('inherit', [], 'owner_only', [])).toBe(true);- expect(requiresProjectAccessNarrowingConfirmation('restricted', [viewer], 'owner_only', [])).toBe(true);- expect(requiresProjectAccessNarrowingConfirmation('restricted', [viewer, secondViewer], 'restricted', [viewer])).toBe(true);- expect(requiresProjectAccessNarrowingConfirmation('restricted', [editor], 'restricted', [viewer])).toBe(true);- expect(requiresProjectAccessNarrowingConfirmation('restricted', [viewer], 'restricted', [secondViewer])).toBe(true);- expect(requiresProjectAccessNarrowingConfirmation('restricted', [viewer], 'restricted', [viewer, secondViewer])).toBe(false);- expect(requiresProjectAccessNarrowingConfirmation('restricted', [viewer], 'restricted', [editor])).toBe(false);- expect(requiresProjectAccessNarrowingConfirmation('restricted', [viewer], 'inherit', [])).toBe(false);- });-- it('requires confirmation for every Resource access narrowing', () => {- expect(requiresResourceAccessNarrowingConfirmation('public', [], 'scope', ['group-1'])).toBe(true);- expect(requiresResourceAccessNarrowingConfirmation('public', [], 'private', [])).toBe(true);- expect(requiresResourceAccessNarrowingConfirmation('scope', ['group-1'], 'private', [])).toBe(true);- expect(requiresResourceAccessNarrowingConfirmation('scope', ['group-1', 'group-2'], 'scope', ['group-1'])).toBe(true);- expect(requiresResourceAccessNarrowingConfirmation('private', [], 'scope', ['group-1'])).toBe(true);- expect(requiresResourceAccessNarrowingConfirmation('private', [], 'public', [])).toBe(false);- expect(requiresResourceAccessNarrowingConfirmation('scope', ['group-1'], 'public', [])).toBe(false);- expect(requiresResourceAccessNarrowingConfirmation('scope', ['group-1'], 'scope', ['group-1', 'group-2'])).toBe(false);- });-- it('leaves object detail routes when switching Organizations', () => {- expect(organizationSwitchDestination('/admin/organization/groups/group-1')).toBe(- '/admin/organization/groups',- );- expect(organizationSwitchDestination('/admin/organization/instances/instance-1/access')).toBe(- '/admin/organization/instances',- );- expect(organizationSwitchDestination('/admin/organization/instances/instance-1/projects')).toBe(- '/admin/organization/instances',- );- expect(organizationSwitchDestination('/admin/organization/members')).toBeNull();- });-});diff --git a/ui/src/features/organization/policy.ts b/ui/src/features/organization/policy.tsdeleted file mode 100644index f92c44364..000000000--- a/ui/src/features/organization/policy.ts+++ /dev/null@@ -1,131 +0,0 @@-import type {- OrganizationRole,- ProjectBinding,- ResourceAccessLevel,- SyncCounts,-} from './api/types';--export type OrganizationPrincipalKind = ProjectBinding['principal_kind'];-export type ProjectAccessMode = 'inherit' | 'owner_only' | 'restricted';-export type AggregateSyncStatus = 'none' | 'in_sync' | 'applying' | 'offline' | 'error';--type OrganizationPrincipal = {- kind: OrganizationPrincipalKind;- value: string;-};--const ORGANIZATION_GROUP_DETAIL_PATH = /^\/admin\/organization\/groups\/[^/]+\/?$/;-const ORGANIZATION_INSTANCE_DETAIL_PATH = /^\/admin\/organization\/instances\/[^/]+\/(?:access|projects)\/?$/;--export function normalizeOrganizationPrincipal(- kind: OrganizationPrincipalKind,- value: string,-): string {- const normalized = value.trim();- if (kind === 'organization_group') return normalized;- return (kind === 'email_domain' ? normalized.replace(/^@/, '') : normalized).toLowerCase();-}--export function hasDuplicateOrganizationPrincipals(principals: OrganizationPrincipal[]): boolean {- const keys = principals.map((principal) => (- `${principal.kind}:${normalizeOrganizationPrincipal(principal.kind, principal.value)}`- ));- return new Set(keys).size !== keys.length;-}--export function hasDuplicateProjectPrincipals(bindings: ProjectBinding[]): boolean {- return hasDuplicateOrganizationPrincipals(bindings.map((binding) => ({- kind: binding.principal_kind,- value: binding.principal_value,- })));-}--function projectBindingKey(binding: ProjectBinding): string {- return `${binding.principal_kind}:${normalizeOrganizationPrincipal(- binding.principal_kind,- binding.principal_value,- )}`;-}--export function requiresProjectAccessNarrowingConfirmation(- currentMode: ProjectAccessMode,- currentBindings: ProjectBinding[],- nextMode: ProjectAccessMode,- nextBindings: ProjectBinding[],-): boolean {- if (currentMode === 'inherit') return nextMode !== 'inherit';- if (currentMode === 'owner_only') return false;- if (nextMode === 'owner_only') return true;- if (nextMode === 'inherit') return false;-- const nextByPrincipal = new Map(nextBindings.map((binding) => [projectBindingKey(binding), binding]));- return currentBindings.some((binding) => {- const nextBinding = nextByPrincipal.get(projectBindingKey(binding));- return (- !nextBinding- || (binding.access_role === 'editor' && nextBinding.access_role === 'viewer')- );- });-}--export function requiresResourceAccessNarrowingConfirmation(- currentLevel: ResourceAccessLevel,- currentGroupIds: string[],- nextLevel: ResourceAccessLevel,- nextGroupIds: string[],-): boolean {- const audienceBreadth: Record<ResourceAccessLevel, number> = {- private: 0,- scope: 1,- public: 2,- };- if (currentLevel === 'private') return nextLevel === 'scope';- if (audienceBreadth[nextLevel] < audienceBreadth[currentLevel]) return true;- if (currentLevel !== 'scope' || nextLevel !== 'scope') return false;-- const nextGroups = new Set(nextGroupIds);- return currentGroupIds.some((groupId) => !nextGroups.has(groupId));-}--export function aggregateSyncStatus(counts: SyncCounts): AggregateSyncStatus {- if (counts.error > 0) return 'error';- if (counts.offline > 0) return 'offline';- 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- );-}--export function organizationSwitchDestination(pathname: string): string | null {- if (ORGANIZATION_GROUP_DETAIL_PATH.test(pathname)) {- return '/admin/organization/groups';- }- if (ORGANIZATION_INSTANCE_DETAIL_PATH.test(pathname)) {- return '/admin/organization/instances';- }- return null;-}--export function organizationAuthorizationReturnPath(pathname: string, search: string): string {- const params = new URLSearchParams(search);- params.delete('cloud_management_error');- const query = params.toString();- return `${pathname}${query ? `?${query}` : ''}`;-}--export function requiresMemberRoleDowngradeConfirmation(- currentRole: OrganizationRole,- nextRole: OrganizationRole,-): boolean {- return currentRole === 'admin' && nextRole === 'member';-}diff --git a/ui/src/features/permissions/PermissionsPage.test.tsx b/ui/src/features/permissions/PermissionsPage.test.tsxnew file mode 100644index 000000000..a7c0fe51c--- /dev/null+++ b/ui/src/features/permissions/PermissionsPage.test.tsx@@ -0,0 +1,289 @@+/* @vitest-environment jsdom */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++import { InstanceAuthorizationContext } from '@/context/InstanceAuthorizationContext';+import { OWNER_INSTANCE_CAPABILITIES } from '@/lib/sessionInfo';++import { PermissionsApiError } from './api';+import { PermissionsPage } from './PermissionsPage';+import type { PermissionsResponse } from './types';++const api = vi.hoisted(() => ({+ getPermissions: vi.fn(),+ replaceAuthorizedUsers: vi.fn(),+ updateProjectAccess: vi.fn(),+}));++vi.mock('./api', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./api')>()),+ getPermissions: api.getPermissions,+ replaceAuthorizedUsers: api.replaceAuthorizedUsers,+ updateProjectAccess: api.updateProjectAccess,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++const response = (overrides: Partial<PermissionsResponse> = {}): PermissionsResponse => ({+ ok: true,+ source: 'live',+ offline: false,+ cached_at: null,+ projection: {+ schema_version: 1,+ instance: {+ id: 'inst-123',+ access_mode: 'allowlist',+ permission_authority: 'instance',+ local_mutation_allowed: true,+ authorization_revision: 4,+ },+ capabilities: ['instance.permissions.read', 'instance.permissions.mutate'],+ access: {+ owner: { email: '[email protected]', role: 'owner' },+ entries: [],+ },+ directory: { members: [], groups: [] },+ projects: [{+ project_id: 'project-1',+ organization_id: 'org-1',+ display_name: 'Launch Plan',+ access: {+ mode: 'restricted',+ revision: 1,+ bindings: [{+ principal_kind: 'email',+ principal_value: '[email protected]',+ access_role: 'viewer',+ }],+ },+ sync: {+ status: 'in_sync',+ desired_access_revision: 1,+ applied_access_revision: 1,+ last_synced_at: null,+ },+ }],+ policy_sync: {+ status: 'in_sync',+ projects: { active: 1, error: 0, offline: 0, applying: 0, in_sync: 1 },+ resources: { active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 },+ },+ },+ ...overrides,+});++function renderPage(canManage = true) {+ render(+ <InstanceAuthorizationContext.Provider value={{+ remote: true,+ instanceKind: 'organization',+ instanceRole: canManage ? 'owner' : 'viewer',+ capabilities: canManage+ ? OWNER_INSTANCE_CAPABILITIES+ : { ...OWNER_INSTANCE_CAPABILITIES, can_manage_instance: false, is_instance_owner: false },+ }}>+ <PermissionsPage />+ </InstanceAuthorizationContext.Provider>,+ );+}++beforeEach(() => {+ api.getPermissions.mockResolvedValue(response());+ api.replaceAuthorizedUsers.mockReset();+ api.updateProjectAccess.mockReset();+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('PermissionsPage state model', () => {+ it('renders Cloud-owned policy as a visible read-only state', async () => {+ const cloud = response();+ cloud.projection.instance.permission_authority = 'cloud';+ cloud.projection.instance.local_mutation_allowed = false;+ api.getPermissions.mockResolvedValue(cloud);++ renderPage();++ expect(await screen.findByText('permissions.states.cloudTitle')).toBeTruthy();+ expect(screen.getByRole('link', { name: /permissions.actions.openCloud/ })).toBeTruthy();+ expect(screen.queryByRole('button', { name: /permissions.actions.addAccess/ })).toBeNull();+ });++ it('keeps cached offline policy distinct from a live empty policy', async () => {+ api.getPermissions.mockResolvedValue(response({ source: 'cache', offline: true, cached_at: 123 }));++ renderPage();++ expect(await screen.findByText('permissions.states.offlineTitle')).toBeTruthy();+ expect(screen.getByText('permissions.access.emptyTitle')).toBeTruthy();+ expect(screen.queryByRole('button', { name: /permissions.actions.addAccess/ })).toBeNull();+ });++ it('lets a Viewer read policy while keeping mutation controls absent', async () => {+ renderPage(false);++ expect(await screen.findByText('permissions.states.readOnlyTitle')).toBeTruthy();+ expect(screen.getByText('[email protected]')).toBeTruthy();+ expect(screen.queryByRole('button', { name: /permissions.actions.addAccess/ })).toBeNull();+ });++ it('renders an API denial instead of an empty policy', async () => {+ api.getPermissions.mockRejectedValue(new PermissionsApiError(403, { error: 'instance_access_forbidden' }));++ renderPage(false);++ expect(await screen.findByText('permissions.states.deniedTitle')).toBeTruthy();+ expect(screen.queryByText('permissions.access.emptyTitle')).toBeNull();+ });++ it('does not misclassify a paired credential failure as user denial', async () => {+ api.getPermissions.mockRejectedValue(new PermissionsApiError(401, {+ error: 'invalid_device_secret',+ }));++ renderPage();++ expect(await screen.findByText('permissions.states.unavailableTitle')).toBeTruthy();+ expect(screen.queryByText('permissions.states.deniedTitle')).toBeNull();+ });+});++describe('PermissionsPage conflict handling', () => {+ it('reconciles an access draft by principal after the authoritative list is reordered', async () => {+ const initial = response();+ initial.projection.access.entries = [+ { kind: 'email', value: '[email protected]', role: 'viewer' },+ { kind: 'email', value: '[email protected]', role: 'viewer' },+ ];+ const latest = response();+ latest.projection.instance.authorization_revision = 5;+ latest.projection.access.entries = [+ { kind: 'email', value: '[email protected]', role: 'viewer' },+ { kind: 'email', value: '[email protected]', role: 'viewer' },+ ];+ api.getPermissions+ .mockResolvedValueOnce(initial)+ .mockResolvedValueOnce(latest);+ api.replaceAuthorizedUsers+ .mockRejectedValueOnce(new PermissionsApiError(409, {+ error: 'permission_revision_conflict',+ current_revision: 5,+ }))+ .mockResolvedValueOnce({+ ok: true,+ authorization_revision: 6,+ entries: [+ { kind: 'email', value: '[email protected]', role: 'editor' },+ { kind: 'email', value: '[email protected]', role: 'viewer' },+ ],+ });+ const user = userEvent.setup();+ renderPage();++ const editButtons = await screen.findAllByRole('button', { name: 'permissions.actions.editAccess' });+ await user.click(editButtons[1]!);+ await user.click(screen.getByRole('radio', { name: 'permissions.roles.editor' }));+ await user.click(screen.getByRole('button', { name: 'permissions.actions.save' }));++ expect(await screen.findByText('permissions.states.conflictTitle')).toBeTruthy();+ await user.click(screen.getByRole('button', { name: 'permissions.actions.retrySave' }));++ await waitFor(() => expect(api.replaceAuthorizedUsers).toHaveBeenCalledTimes(2));+ expect(api.replaceAuthorizedUsers.mock.calls[1]).toEqual([+ [+ { kind: 'email', value: '[email protected]', role: 'editor' },+ { kind: 'email', value: '[email protected]', role: 'viewer' },+ ],+ 5,+ ]);+ });++ it('sends owner-only as the exact Backend access mode', async () => {+ api.updateProjectAccess.mockResolvedValue({+ ok: true,+ authorization_revision: 5,+ project: {+ ...response().projection.projects[0]!,+ access: { mode: 'owner_only', revision: 2, bindings: [] },+ },+ });+ const user = userEvent.setup();+ renderPage();++ await user.click(await screen.findByRole('tab', { name: 'permissions.tabs.projects' }));+ await user.click(screen.getByRole('button', { name: 'permissions.actions.manage' }));+ await user.click(screen.getByRole('radio', { name: 'permissions.projects.modes.owner_only' }));+ await user.click(screen.getByRole('button', { name: 'permissions.actions.save' }));+ await user.click(screen.getByRole('button', { name: 'permissions.actions.save' }));++ await waitFor(() => expect(api.updateProjectAccess).toHaveBeenCalledOnce());+ expect(api.updateProjectAccess).toHaveBeenCalledWith(+ expect.objectContaining({ project_id: 'project-1' }),+ 'owner_only',+ [],+ 1,+ );+ });++ it('keeps the Project draft, refreshes the revision, and requires explicit retry', async () => {+ const latest = response();+ latest.projection.projects[0]!.access.revision = 2;+ api.getPermissions+ .mockResolvedValueOnce(response())+ .mockResolvedValueOnce(latest);+ api.updateProjectAccess+ .mockRejectedValueOnce(new PermissionsApiError(409, {+ error: 'permission_revision_conflict',+ current_revision: 2,+ }))+ .mockResolvedValueOnce({+ ok: true,+ authorization_revision: 5,+ project: {+ ...latest.projection.projects[0]!,+ access: {+ ...latest.projection.projects[0]!.access,+ bindings: [{+ principal_kind: 'email',+ principal_value: '[email protected]',+ access_role: 'editor',+ }],+ },+ },+ });+ const user = userEvent.setup();+ renderPage();++ await user.click(await screen.findByRole('tab', { name: 'permissions.tabs.projects' }));+ await user.click(screen.getByRole('button', { name: 'permissions.actions.manage' }));+ await user.selectOptions(screen.getByLabelText('permissions.fields.role'), 'editor');+ await user.click(screen.getByRole('button', { name: 'permissions.actions.save' }));++ expect(await screen.findByText('permissions.states.conflictTitle')).toBeTruthy();+ expect((screen.getByLabelText('permissions.fields.role') as HTMLSelectElement).value).toBe('editor');+ const retry = screen.getByRole('button', { name: 'permissions.actions.retrySave' });+ await user.click(retry);++ await waitFor(() => expect(api.updateProjectAccess).toHaveBeenCalledTimes(2));+ expect(api.updateProjectAccess.mock.calls[1]).toEqual([+ expect.objectContaining({ project_id: 'project-1' }),+ 'restricted',+ [{+ principal_kind: 'email',+ principal_value: '[email protected]',+ access_role: 'editor',+ }],+ 2,+ ]);+ });+});diff --git a/ui/src/features/permissions/PermissionsPage.tsx b/ui/src/features/permissions/PermissionsPage.tsxnew file mode 100644index 000000000..1e2da6505--- /dev/null+++ b/ui/src/features/permissions/PermissionsPage.tsx@@ -0,0 +1,790 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import {+ AlertTriangle,+ CheckCircle2,+ Cloud,+ CloudOff,+ ExternalLink,+ Eye,+ FolderKey,+ Globe2,+ Loader2,+ LockKeyhole,+ Mail,+ Pencil,+ Plus,+ RefreshCw,+ ShieldCheck,+ ShieldX,+ Trash2,+ Users,+ WifiOff,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';+import clsx from 'clsx';++import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { ConfirmDialog } from '@/components/ui/confirm-dialog';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { SegmentedRadio } from '@/components/ui/segmented';+import { Select } from '@/components/ui/select';+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';++import {+ getPermissions,+ isRevisionConflict,+ PermissionsApiError,+ replaceAuthorizedUsers,+ updateProjectAccess,+} from './api';+import {+ hasDuplicateAccessEntries,+ hasDuplicateProjectBindings,+ normalizePrincipal,+ projectMode,+ requiresProjectNarrowing,+ type ProjectAccessMode,+} from './policy';+import type {+ AccessEntry,+ AccessRole,+ DirectoryGroup,+ PermissionProject,+ PermissionsResponse,+ PrincipalKind,+ ProjectBinding,+ SyncStatus,+} from './types';++type PageState =+ | { kind: 'loading' }+ | { kind: 'ready'; response: PermissionsResponse }+ | { kind: 'denied'; code: string }+ | { kind: 'unavailable'; code: string; offline: boolean };++const principalIcon = (kind: PrincipalKind) => {+ if (kind === 'organization_group') return Users;+ if (kind === 'email_domain') return Globe2;+ return Mail;+};++const displayPrincipal = (kind: PrincipalKind, value: string, groups: DirectoryGroup[]): string => {+ if (kind === 'organization_group') {+ return groups.find((group) => group.id === value)?.name ?? value;+ }+ if (kind === 'email_domain') return `@${value.replace(/^@/, '')}`;+ return value;+};++const accessEntryKey = (entry: AccessEntry): string => (+ `${entry.kind}:${normalizePrincipal(entry.kind, entry.value)}`+);++function SyncBadge({ status }: { status: SyncStatus }) {+ const { t } = useTranslation();+ const normalized = status === 'pending' ? 'applying' : status;+ const Icon = normalized === 'in_sync'+ ? CheckCircle2+ : normalized === 'applying'+ ? Loader2+ : normalized === 'offline'+ ? WifiOff+ : normalized === 'error'+ ? AlertTriangle+ : CloudOff;+ const variant = normalized === 'in_sync'+ ? 'success'+ : normalized === 'applying'+ ? 'warning'+ : normalized === 'error'+ ? 'destructive'+ : 'secondary';+ return (+ <Badge variant={variant}>+ <Icon className={clsx('size-3', normalized === 'applying' && 'animate-spin')} />+ {t(`permissions.sync.${normalized}`)}+ </Badge>+ );+}++function Notice({+ tone,+ icon: Icon,+ title,+ body,+ action,+}: {+ tone: 'neutral' | 'warning' | 'danger' | 'info';+ icon: typeof ShieldCheck;+ title: string;+ body: string;+ action?: React.ReactNode;+}) {+ return (+ <div+ className={clsx(+ 'flex flex-col gap-3 rounded-lg border px-4 py-3 sm:flex-row sm:items-center',+ tone === 'warning' && 'border-gold/40 bg-gold/10',+ tone === 'danger' && 'border-destructive/35 bg-destructive/10',+ tone === 'info' && 'border-cyan/35 bg-cyan/10',+ tone === 'neutral' && 'border-border bg-foreground/[0.025]',+ )}+ role={tone === 'danger' ? 'alert' : 'status'}+ >+ <Icon className={clsx(+ 'size-4 shrink-0',+ tone === 'warning' && 'text-gold-ink',+ tone === 'danger' && 'text-destructive-ink',+ tone === 'info' && 'text-cyan-ink',+ tone === 'neutral' && 'text-muted',+ )} />+ <div className="min-w-0 flex-1">+ <div className="text-[13px] font-semibold">{title}</div>+ <div className="mt-0.5 text-[12px] leading-5 text-muted">{body}</div>+ </div>+ {action ? <div className="shrink-0">{action}</div> : null}+ </div>+ );+}++function EmptyState({ icon: Icon, title, body }: {+ icon: typeof ShieldCheck;+ title: string;+ body: string;+}) {+ return (+ <div className="flex min-h-56 flex-col items-center justify-center rounded-lg border border-dashed border-border px-6 text-center">+ <Icon className="mb-3 size-7 text-muted" />+ <h2 className="text-[15px] font-semibold">{title}</h2>+ <p className="mt-1 max-w-md text-[13px] leading-5 text-muted">{body}</p>+ </div>+ );+}++function AccessEntryDialog({+ open,+ editingIndex,+ response,+ onOpenChange,+ onReload,+ onSaved,+}: {+ open: boolean;+ editingIndex: number | null;+ response: PermissionsResponse;+ onOpenChange: (open: boolean) => void;+ onReload: () => Promise<PermissionsResponse | null>;+ onSaved: (result: Awaited<ReturnType<typeof replaceAuthorizedUsers>>) => void;+}) {+ const { t } = useTranslation();+ const initialized = useRef(false);+ const entries = response.projection.access.entries;+ const editing = editingIndex === null ? null : entries[editingIndex];+ const groups = response.projection.directory.groups;+ const [kind, setKind] = useState<PrincipalKind>('email');+ const [value, setValue] = useState('');+ const [role, setRole] = useState<AccessRole>('viewer');+ const [revision, setRevision] = useState(0);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string>();+ const [conflict, setConflict] = useState(false);+ const originalEntry = useRef<AccessEntry | null>(null);++ useEffect(() => {+ if (open && !initialized.current) {+ originalEntry.current = editing ?? null;+ setKind(editing?.kind ?? 'email');+ setValue(editing?.value ?? '');+ setRole(editing?.role ?? 'viewer');+ setRevision(response.projection.instance.authorization_revision);+ setError(undefined);+ setConflict(false);+ }+ initialized.current = open;+ }, [editing, open, response]);++ const activeGroups = groups.filter((group) => !group.archived_at);+ const resolvedValue = kind === 'organization_group'+ ? (value || activeGroups[0]?.id || '')+ : normalizePrincipal(kind, value);+ const candidate: AccessEntry = { kind, value: resolvedValue, role };+ const originalKey = originalEntry.current ? accessEntryKey(originalEntry.current) : null;+ const authoritativeIndex = originalKey === null+ ? -1+ : entries.findIndex((entry) => accessEntryKey(entry) === originalKey);+ const nextEntries = editingIndex === null || authoritativeIndex < 0+ ? [...entries, candidate]+ : entries.map((entry, index) => (index === authoritativeIndex ? candidate : entry));++ const commit = async () => {+ if (!candidate.value || hasDuplicateAccessEntries(nextEntries)) {+ setError(candidate.value ? 'duplicate_access_principal' : 'invalid_request');+ return;+ }+ setSaving(true);+ setError(undefined);+ try {+ const result = await replaceAuthorizedUsers(nextEntries, revision);+ onSaved(result);+ onOpenChange(false);+ } catch (caught) {+ if (isRevisionConflict(caught)) {+ const latest = await onReload();+ if (latest) setRevision(latest.projection.instance.authorization_revision);+ setConflict(true);+ } else {+ setError(caught instanceof PermissionsApiError ? caught.code : 'permissions_unavailable');+ }+ } finally {+ setSaving(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t(editing ? 'permissions.access.editTitle' : 'permissions.access.addTitle')}</DialogTitle>+ <DialogDescription>{t('permissions.access.dialogBody')}</DialogDescription>+ </DialogHeader>+ {conflict ? (+ <Notice+ tone="warning"+ icon={AlertTriangle}+ title={t('permissions.states.conflictTitle')}+ body={t('permissions.states.conflictBody')}+ />+ ) : null}+ {error ? (+ <Notice tone="danger" icon={ShieldX} title={t('permissions.states.errorTitle')} body={t(`permissions.errors.${error}`, { defaultValue: t('permissions.errors.generic') })} />+ ) : null}+ <div className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="permissions-access-kind">{t('permissions.fields.principalType')}</Label>+ <Select+ id="permissions-access-kind"+ value={kind}+ onChange={(event) => { setKind(event.target.value as PrincipalKind); setValue(''); }}+ >+ {activeGroups.length > 0 ? <option value="organization_group">{t('permissions.principals.organization_group')}</option> : null}+ <option value="email">{t('permissions.principals.email')}</option>+ <option value="email_domain">{t('permissions.principals.email_domain')}</option>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="permissions-access-value">{t('permissions.fields.principal')}</Label>+ {kind === 'organization_group' ? (+ <Select id="permissions-access-value" value={resolvedValue} onChange={(event) => setValue(event.target.value)}>+ {activeGroups.map((group) => <option key={group.id} value={group.id}>{group.name}</option>)}+ </Select>+ ) : (+ <Input+ id="permissions-access-value"+ type={kind === 'email' ? 'email' : 'text'}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ placeholder={t(kind === 'email' ? 'permissions.access.emailPlaceholder' : 'permissions.access.domainPlaceholder')}+ />+ )}+ </div>+ <div className="space-y-1.5">+ <Label>{t('permissions.fields.role')}</Label>+ <SegmentedRadio+ value={role}+ onChange={setRole}+ ariaLabel={t('permissions.fields.role')}+ options={[+ { id: 'viewer', label: t('permissions.roles.viewer') },+ { id: 'editor', label: t('permissions.roles.editor') },+ ]}+ />+ </div>+ </div>+ <DialogFooter>+ <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>+ <Button variant="brand" disabled={saving || !candidate.value} onClick={() => void commit()}>+ {saving ? <Loader2 className="size-4 animate-spin" /> : null}+ {t(conflict ? 'permissions.actions.retrySave' : 'permissions.actions.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++function ProjectAccessDialog({+ project,+ groups,+ onOpenChange,+ onReload,+ onSaved,+}: {+ project: PermissionProject | null;+ groups: DirectoryGroup[];+ onOpenChange: (open: boolean) => void;+ onReload: () => Promise<PermissionsResponse | null>;+ onSaved: (result: Awaited<ReturnType<typeof updateProjectAccess>>) => void;+}) {+ const { t } = useTranslation();+ const initialized = useRef(false);+ const [mode, setMode] = useState<ProjectAccessMode>('inherit');+ const [bindings, setBindings] = useState<ProjectBinding[]>([]);+ const [revision, setRevision] = useState(0);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string>();+ const [conflict, setConflict] = useState(false);+ const [confirmNarrowing, setConfirmNarrowing] = useState(false);+ const baseline = useRef<PermissionProject | null>(null);+ const open = Boolean(project);++ useEffect(() => {+ if (project && !initialized.current) {+ baseline.current = project;+ setMode(projectMode(project));+ setBindings(project.access.bindings);+ setRevision(project.access.revision);+ setError(undefined);+ setConflict(false);+ setConfirmNarrowing(false);+ }+ initialized.current = open;+ }, [open, project]);++ const activeGroups = groups.filter((group) => !group.archived_at);+ const wireBindings = mode === 'restricted'+ ? bindings.map((binding) => ({+ ...binding,+ principal_value: normalizePrincipal(binding.principal_kind, binding.principal_value),+ }))+ : [];+ const invalid = mode === 'restricted' && (+ wireBindings.length === 0 || wireBindings.some((binding) => !binding.principal_value)+ );++ const commit = async () => {+ if (!project || invalid) return;+ if (hasDuplicateProjectBindings(wireBindings)) {+ setError('duplicate_project_access_principal');+ return;+ }+ setSaving(true);+ setError(undefined);+ try {+ const result = await updateProjectAccess(+ project,+ mode,+ wireBindings,+ revision,+ );+ onSaved(result);+ onOpenChange(false);+ } catch (caught) {+ if (isRevisionConflict(caught)) {+ const latest = await onReload();+ const authoritative = latest?.projection.projects.find((item) => item.project_id === project.project_id);+ if (authoritative) {+ baseline.current = authoritative;+ setRevision(authoritative.access.revision);+ } else if (caught.currentRevision !== undefined) {+ setRevision(caught.currentRevision);+ }+ setConflict(true);+ } else {+ setError(caught instanceof PermissionsApiError ? caught.code : 'permissions_unavailable');+ }+ } finally {+ setSaving(false);+ setConfirmNarrowing(false);+ }+ };++ const save = () => {+ if (!project || invalid) return;+ const current = baseline.current ?? project;+ if (requiresProjectNarrowing(projectMode(current), current.access.bindings, mode, wireBindings)) {+ setConfirmNarrowing(true);+ return;+ }+ void commit();+ };++ const addBinding = () => {+ const group = activeGroups.find((candidate) => !bindings.some((binding) => (+ binding.principal_kind === 'organization_group' && binding.principal_value === candidate.id+ )));+ setBindings((current) => [...current, {+ principal_kind: group ? 'organization_group' : 'email',+ principal_value: group?.id ?? '',+ access_role: 'viewer',+ }]);+ };++ return (+ <>+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>{t('permissions.projects.dialogTitle', { name: project?.display_name })}</DialogTitle>+ <DialogDescription>{t('permissions.projects.dialogBody')}</DialogDescription>+ </DialogHeader>+ {conflict ? <Notice tone="warning" icon={AlertTriangle} title={t('permissions.states.conflictTitle')} body={t('permissions.states.conflictBody')} /> : null}+ {error ? <Notice tone="danger" icon={ShieldX} title={t('permissions.states.errorTitle')} body={t(`permissions.errors.${error}`, { defaultValue: t('permissions.errors.generic') })} /> : null}+ <div className="space-y-5">+ <div className="space-y-1.5">+ <Label>{t('permissions.projects.accessRule')}</Label>+ <SegmentedRadio+ value={mode}+ onChange={setMode}+ ariaLabel={t('permissions.projects.accessRule')}+ options={[+ { id: 'inherit', label: t('permissions.projects.modes.inherit') },+ { id: 'restricted', label: t('permissions.projects.modes.restricted') },+ { id: 'owner_only', label: t('permissions.projects.modes.owner_only') },+ ]}+ />+ </div>+ <p className="rounded-lg border border-border bg-foreground/[0.025] p-3 text-[12px] leading-5 text-muted">+ {t(`permissions.projects.modeHelp.${mode}`)}+ </p>+ {mode === 'restricted' ? (+ <div className="space-y-3">+ <div className="flex items-center justify-between gap-3">+ <Label>{t('permissions.projects.bindings')}</Label>+ <Button size="sm" variant="outline" onClick={addBinding}><Plus className="size-4" />{t('permissions.actions.addBinding')}</Button>+ </div>+ {bindings.map((binding, index) => (+ <div key={`${index}:${binding.principal_kind}`} className="grid gap-2 rounded-lg border border-border p-3 sm:grid-cols-[150px_minmax(0,1fr)_110px_36px]">+ <Select+ aria-label={t('permissions.fields.principalType')}+ value={binding.principal_kind}+ onChange={(event) => setBindings((current) => current.map((item, itemIndex) => itemIndex === index ? {+ ...item,+ principal_kind: event.target.value as PrincipalKind,+ principal_value: event.target.value === 'organization_group' ? (activeGroups[0]?.id ?? '') : '',+ } : item))}+ >+ {activeGroups.length > 0 ? <option value="organization_group">{t('permissions.principals.organization_group')}</option> : null}+ <option value="email">{t('permissions.principals.email')}</option>+ <option value="email_domain">{t('permissions.principals.email_domain')}</option>+ </Select>+ {binding.principal_kind === 'organization_group' ? (+ <Select+ aria-label={t('permissions.fields.principal')}+ value={binding.principal_value}+ onChange={(event) => setBindings((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, principal_value: event.target.value } : item))}+ >+ {activeGroups.map((group) => <option key={group.id} value={group.id}>{group.name}</option>)}+ </Select>+ ) : (+ <Input+ aria-label={t('permissions.fields.principal')}+ value={binding.principal_value}+ onChange={(event) => setBindings((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, principal_value: event.target.value } : item))}+ />+ )}+ <Select+ aria-label={t('permissions.fields.role')}+ value={binding.access_role}+ onChange={(event) => setBindings((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, access_role: event.target.value as AccessRole } : item))}+ >+ <option value="viewer">{t('permissions.roles.viewer')}</option>+ <option value="editor">{t('permissions.roles.editor')}</option>+ </Select>+ <Button size="icon" variant="ghost" aria-label={t('permissions.actions.removeBinding')} onClick={() => setBindings((current) => current.filter((_, itemIndex) => itemIndex !== index))}><Trash2 className="size-4" /></Button>+ </div>+ ))}+ {bindings.length === 0 ? <p className="text-[12px] text-gold-ink">{t('permissions.projects.bindingRequired')}</p> : null}+ </div>+ ) : null}+ </div>+ <DialogFooter>+ <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>+ <Button variant="brand" disabled={saving || invalid} onClick={conflict ? () => void commit() : save}>+ {saving ? <Loader2 className="size-4 animate-spin" /> : null}+ {t(conflict ? 'permissions.actions.retrySave' : 'permissions.actions.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ <ConfirmDialog+ open={confirmNarrowing}+ onOpenChange={setConfirmNarrowing}+ title={t('permissions.projects.narrowTitle')}+ description={t('permissions.projects.narrowBody')}+ confirmLabel={t('permissions.actions.save')}+ onConfirm={commit}+ />+ </>+ );+}++export function PermissionsPage() {+ const { t } = useTranslation();+ const { capabilities, instanceRole } = useInstanceAuthorization();+ const [state, setState] = useState<PageState>({ kind: 'loading' });+ const [tab, setTab] = useState<'access' | 'projects'>('access');+ const [editingAccess, setEditingAccess] = useState<number | null | undefined>(undefined);+ const [editingProject, setEditingProject] = useState<PermissionProject | null>(null);+ const [removingAccess, setRemovingAccess] = useState<number | null>(null);+ const [search, setSearch] = useState('');++ const load = useCallback(async (): Promise<PermissionsResponse | null> => {+ try {+ const response = await getPermissions();+ setState({ kind: 'ready', response });+ return response;+ } catch (caught) {+ const error = caught instanceof PermissionsApiError ? caught : null;+ if (error?.code === 'instance_access_forbidden') {+ setState({ kind: 'denied', code: error.code });+ } else {+ setState({+ kind: 'unavailable',+ code: error?.code ?? 'permissions_unavailable',+ offline: error?.offline === true,+ });+ }+ return null;+ }+ }, []);++ useEffect(() => { void load(); }, [load]);++ if (state.kind === 'loading') {+ return (+ <div className="space-y-4" aria-label={t('permissions.states.loadingTitle')}>+ <div className="h-20 animate-pulse rounded-lg border border-border bg-card/70" />+ <div className="h-64 animate-pulse rounded-lg border border-border bg-card/70" />+ </div>+ );+ }+ if (state.kind === 'denied') {+ return <EmptyState icon={ShieldX} title={t('permissions.states.deniedTitle')} body={t('permissions.states.deniedBody')} />;+ }+ if (state.kind === 'unavailable') {+ return (+ <div className="space-y-5">+ <EmptyState icon={state.offline ? WifiOff : CloudOff} title={t('permissions.states.unavailableTitle')} body={t('permissions.states.unavailableBody')} />+ <div className="flex justify-center"><Button variant="outline" onClick={() => void load()}><RefreshCw className="size-4" />{t('common.retry')}</Button></div>+ </div>+ );+ }++ const { response } = state;+ const projection = response.projection;+ const groups = projection.directory.groups;+ const editable = capabilities.can_manage_instance+ && projection.instance.local_mutation_allowed+ && !response.offline;+ const applying = projection.policy_sync.status === 'applying'+ || projection.projects.some((project) => ['pending', 'applying'].includes(project.sync.status));+ const filteredProjects = projection.projects.filter((project) => (+ `${project.display_name} ${project.project_id}`.toLowerCase().includes(search.trim().toLowerCase())+ ));++ const updateResponse = (updater: (current: PermissionsResponse) => PermissionsResponse) => {+ setState((current) => current.kind === 'ready'+ ? { kind: 'ready', response: updater(current.response) }+ : current);+ };++ const removeAccess = async () => {+ if (removingAccess === null) return;+ const entries = projection.access.entries.filter((_, index) => index !== removingAccess);+ try {+ const result = await replaceAuthorizedUsers(entries, projection.instance.authorization_revision);+ updateResponse((current) => ({+ ...current,+ projection: {+ ...current.projection,+ instance: { ...current.projection.instance, authorization_revision: result.authorization_revision },+ access: { ...current.projection.access, entries: result.entries },+ },+ }));+ setRemovingAccess(null);+ } catch (caught) {+ if (isRevisionConflict(caught)) await load();+ }+ };++ return (+ <div className="mx-auto max-w-6xl space-y-6">+ <header className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <ShieldCheck className="size-6 text-mint-ink" />+ <h1 className="text-2xl font-semibold md:text-[30px]">{t('permissions.title')}</h1>+ </div>+ <p className="mt-1.5 max-w-3xl text-[13px] leading-5 text-muted md:text-sm">{t('permissions.description')}</p>+ </div>+ <Badge variant={projection.instance.permission_authority === 'instance' ? 'success' : 'info'}>+ {projection.instance.permission_authority === 'instance' ? <ShieldCheck className="size-3" /> : <Cloud className="size-3" />}+ {t(`permissions.authority.${projection.instance.permission_authority}`)}+ </Badge>+ </header>++ <div className="flex min-w-0 items-center gap-3 rounded-lg border border-border bg-card px-4 py-3">+ <span className="grid size-10 shrink-0 place-items-center rounded-lg bg-mint/10 text-mint-ink"><ShieldCheck className="size-5" /></span>+ <div className="min-w-0 flex-1">+ <div className="text-[13px] font-semibold">{t('permissions.currentInstance')}</div>+ <div className="truncate font-mono text-[11px] text-muted">{projection.instance.id}</div>+ </div>+ <Badge variant="secondary">{t(`permissions.roles.${instanceRole ?? 'viewer'}`)}</Badge>+ </div>++ {response.offline ? (+ <Notice tone="warning" icon={WifiOff} title={t('permissions.states.offlineTitle')} body={t('permissions.states.offlineBody')} />+ ) : projection.instance.permission_authority === 'cloud' ? (+ <Notice+ tone="info"+ icon={Cloud}+ title={t('permissions.states.cloudTitle')}+ body={t('permissions.states.cloudBody')}+ action={<Button asChild size="sm" variant="outline"><a href="https://avibe.bot" target="_blank" rel="noreferrer">{t('permissions.actions.openCloud')}<ExternalLink className="size-3.5" /></a></Button>}+ />+ ) : !capabilities.can_manage_instance ? (+ <Notice tone="neutral" icon={Eye} title={t('permissions.states.readOnlyTitle')} body={t('permissions.states.readOnlyBody')} />+ ) : applying ? (+ <Notice tone="warning" icon={Loader2} title={t('permissions.states.applyingTitle')} body={t('permissions.states.applyingBody')} />+ ) : null}++ <div className="flex h-10 items-center gap-1 border-b border-border" role="tablist" aria-label={t('permissions.tabs.label')}>+ {(['access', 'projects'] as const).map((candidate) => (+ <button+ key={candidate}+ type="button"+ role="tab"+ aria-selected={tab === candidate}+ onClick={() => setTab(candidate)}+ className={clsx(+ 'inline-flex h-10 items-center gap-2 border-b-2 px-3 text-[13px] font-medium',+ tab === candidate ? 'border-mint text-foreground' : 'border-transparent text-muted hover:text-foreground',+ )}+ >+ {candidate === 'access' ? <Users className="size-4" /> : <FolderKey className="size-4" />}+ {t(`permissions.tabs.${candidate}`)}+ </button>+ ))}+ </div>++ {tab === 'access' ? (+ <section className="space-y-4">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div>+ <h2 className="text-[15px] font-semibold">{t('permissions.access.title')}</h2>+ <p className="mt-0.5 text-[12px] text-muted">{t('permissions.access.description')}</p>+ </div>+ {editable ? <Button variant="brand" size="sm" onClick={() => setEditingAccess(null)}><Plus className="size-4" />{t('permissions.actions.addAccess')}</Button> : null}+ </div>+ <div className="flex items-center gap-3 rounded-lg border border-violet/35 bg-violet/10 px-4 py-3">+ <ShieldCheck className="size-5 shrink-0 text-violet-ink" />+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13px] font-semibold">{projection.access.owner.email ?? t('permissions.access.protectedOwner')}</div>+ <div className="text-[11px] text-muted">{t('permissions.access.ownerBody')}</div>+ </div>+ <Badge variant="secondary">{t('permissions.roles.owner')}</Badge>+ </div>+ {projection.access.entries.length === 0 ? (+ <EmptyState icon={Users} title={t('permissions.access.emptyTitle')} body={t('permissions.access.emptyBody')} />+ ) : (+ <div className="overflow-hidden rounded-lg border border-border bg-card">+ {projection.access.entries.map((entry, index) => {+ const Icon = principalIcon(entry.kind);+ return (+ <div key={`${entry.kind}:${entry.value}`} className="grid gap-3 border-b border-border px-4 py-3 last:border-0 md:grid-cols-[minmax(220px,1fr)_150px_120px_84px] md:items-center">+ <div className="flex min-w-0 items-center gap-3">+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-mint/10 text-mint-ink"><Icon className="size-4" /></span>+ <span className="truncate text-[12px] font-semibold">{displayPrincipal(entry.kind, entry.value, groups)}</span>+ </div>+ <Badge variant="secondary">{t(`permissions.principals.${entry.kind}`)}</Badge>+ <Badge variant={entry.role === 'editor' ? 'success' : 'secondary'}>{entry.role === 'editor' ? <Pencil className="size-3" /> : <Eye className="size-3" />}{t(`permissions.roles.${entry.role}`)}</Badge>+ <div className="flex justify-end gap-1">+ {editable ? <><Button size="icon" variant="ghost" aria-label={t('permissions.actions.editAccess')} onClick={() => setEditingAccess(index)}><Pencil className="size-4" /></Button><Button size="icon" variant="ghost" aria-label={t('permissions.actions.removeAccess')} onClick={() => setRemovingAccess(index)}><Trash2 className="size-4 text-destructive-ink" /></Button></> : null}+ </div>+ </div>+ );+ })}+ </div>+ )}+ </section>+ ) : (+ <section className="space-y-4">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div>+ <h2 className="text-[15px] font-semibold">{t('permissions.projects.title')}</h2>+ <p className="mt-0.5 text-[12px] text-muted">{t('permissions.projects.description')}</p>+ </div>+ <Input className="h-9 sm:w-64" value={search} onChange={(event) => setSearch(event.target.value)} placeholder={t('permissions.projects.searchPlaceholder')} />+ </div>+ {filteredProjects.length === 0 ? (+ <EmptyState icon={FolderKey} title={t('permissions.projects.emptyTitle')} body={t('permissions.projects.emptyBody')} />+ ) : (+ <div className="overflow-hidden rounded-lg border border-border bg-card">+ {filteredProjects.map((project) => {+ const mode = projectMode(project);+ return (+ <div key={project.project_id} className="grid gap-3 border-b border-border px-4 py-3 last:border-0 md:grid-cols-[minmax(220px,1fr)_150px_minmax(160px,1fr)_130px_90px] md:items-center">+ <div className="flex min-w-0 items-center gap-3"><span className="grid size-9 shrink-0 place-items-center rounded-lg bg-cyan/10 text-cyan-ink"><FolderKey className="size-4" /></span><div className="min-w-0"><div className="truncate text-[12px] font-semibold">{project.display_name}</div><div className="truncate font-mono text-[10px] text-muted">{project.project_id}</div></div></div>+ <Badge variant={mode === 'owner_only' ? 'warning' : mode === 'restricted' ? 'info' : 'secondary'}>{mode === 'owner_only' ? <LockKeyhole className="size-3" /> : mode === 'restricted' ? <ShieldCheck className="size-3" /> : <Users className="size-3" />}{t(`permissions.projects.modes.${mode}`)}</Badge>+ <span className="truncate text-[12px] text-muted">{mode === 'restricted' ? t('permissions.projects.bindingCount', { count: project.access.bindings.length }) : t(`permissions.projects.audience.${mode}`)}</span>+ <SyncBadge status={project.sync.status} />+ {editable ? <Button size="sm" variant="outline" onClick={() => setEditingProject(project)}>{t('permissions.actions.manage')}</Button> : <span />}+ </div>+ );+ })}+ </div>+ )}+ </section>+ )}++ <AccessEntryDialog+ open={editingAccess !== undefined}+ editingIndex={editingAccess ?? null}+ response={response}+ onOpenChange={(open) => { if (!open) setEditingAccess(undefined); }}+ onReload={load}+ onSaved={(result) => updateResponse((current) => ({+ ...current,+ projection: {+ ...current.projection,+ instance: { ...current.projection.instance, authorization_revision: result.authorization_revision },+ access: { ...current.projection.access, entries: result.entries },+ },+ }))}+ />+ <ProjectAccessDialog+ project={editingProject}+ groups={groups}+ onOpenChange={(open) => { if (!open) setEditingProject(null); }}+ onReload={load}+ onSaved={(result) => updateResponse((current) => ({+ ...current,+ projection: {+ ...current.projection,+ instance: { ...current.projection.instance, authorization_revision: result.authorization_revision },+ projects: current.projection.projects.map((project) => project.project_id === result.project.project_id ? result.project : project),+ },+ }))}+ />+ <ConfirmDialog+ open={removingAccess !== null}+ onOpenChange={(open) => { if (!open) setRemovingAccess(null); }}+ title={t('permissions.access.removeTitle')}+ description={t('permissions.access.removeBody')}+ destructive+ confirmLabel={t('permissions.actions.removeAccess')}+ onConfirm={removeAccess}+ />+ </div>+ );+}diff --git a/ui/src/features/permissions/api.ts b/ui/src/features/permissions/api.tsnew file mode 100644index 000000000..859382078--- /dev/null+++ b/ui/src/features/permissions/api.ts@@ -0,0 +1,83 @@+import { apiFetch } from '@/lib/apiFetch';++import type {+ AccessEntry,+ AuthorizedUsersWriteResponse,+ PermissionProject,+ PermissionsErrorPayload,+ PermissionsResponse,+ ProjectAccessWriteResponse,+ ProjectBinding,+} from './types';++export class PermissionsApiError extends Error {+ status: number;+ code: string;+ currentRevision?: number;+ offline: boolean;++ constructor(status: number, payload: PermissionsErrorPayload = {}) {+ const code = payload.error || 'permissions_unavailable';+ super(code);+ this.name = 'PermissionsApiError';+ this.status = status;+ this.code = code;+ this.currentRevision = payload.current_revision;+ this.offline = payload.offline === true;+ }+}++async function permissionsRequest<T>(path: string, init: RequestInit = {}): Promise<T> {+ if (!(path === '/api/permissions' || path.startsWith('/api/permissions/'))) {+ throw new Error('Permissions requests must use the same-origin current-instance API');+ }+ const headers = new Headers(init.headers);+ if (init.body !== undefined && !headers.has('Content-Type')) {+ headers.set('Content-Type', 'application/json');+ }+ const response = await apiFetch(path, { ...init, headers, credentials: 'same-origin' });+ let payload: unknown = {};+ try {+ payload = await response.json();+ } catch {+ throw new PermissionsApiError(response.ok ? 502 : response.status);+ }+ if (!response.ok) {+ throw new PermissionsApiError(response.status, payload as PermissionsErrorPayload);+ }+ return payload as T;+}++export const getPermissions = (): Promise<PermissionsResponse> => (+ permissionsRequest('/api/permissions')+);++export const replaceAuthorizedUsers = (+ entries: AccessEntry[],+ revision: number,+): Promise<AuthorizedUsersWriteResponse> => permissionsRequest(+ '/api/permissions/authorized-users',+ {+ method: 'PUT',+ body: JSON.stringify({ entries, if_match_revision: revision }),+ },+);++export const updateProjectAccess = (+ project: Pick<PermissionProject, 'project_id'>,+ mode: PermissionProject['access']['mode'],+ bindings: ProjectBinding[],+ revision: number,+): Promise<ProjectAccessWriteResponse> => permissionsRequest(+ `/api/permissions/projects/${encodeURIComponent(project.project_id)}/access`,+ {+ method: 'PUT',+ body: JSON.stringify({ mode, bindings, if_match_revision: revision }),+ },+);++export const isRevisionConflict = (error: unknown): error is PermissionsApiError => (+ error instanceof PermissionsApiError+ && error.status === 409+ && error.code === 'permission_revision_conflict'+);diff --git a/ui/src/features/permissions/policy.ts b/ui/src/features/permissions/policy.tsnew file mode 100644index 000000000..6e78b0132--- /dev/null+++ b/ui/src/features/permissions/policy.ts@@ -0,0 +1,51 @@+import type {+ AccessEntry,+ PermissionProject,+ PrincipalKind,+ ProjectBinding,+} from './types';++export type ProjectAccessMode = 'inherit' | 'owner_only' | 'restricted';++export function normalizePrincipal(kind: PrincipalKind, value: string): string {+ const normalized = value.trim();+ if (kind === 'organization_group') return normalized;+ return (kind === 'email_domain' ? normalized.replace(/^@/, '') : normalized).toLowerCase();+}++export function hasDuplicateAccessEntries(entries: AccessEntry[]): boolean {+ const keys = entries.map((entry) => `${entry.kind}:${normalizePrincipal(entry.kind, entry.value)}`);+ return new Set(keys).size !== keys.length;+}++export function hasDuplicateProjectBindings(bindings: ProjectBinding[]): boolean {+ const keys = bindings.map((binding) => (+ `${binding.principal_kind}:${normalizePrincipal(binding.principal_kind, binding.principal_value)}`+ ));+ return new Set(keys).size !== keys.length;+}++export function projectMode(project: PermissionProject): ProjectAccessMode {+ return project.access.mode;+}++const bindingKey = (binding: ProjectBinding): string => (+ `${binding.principal_kind}:${normalizePrincipal(binding.principal_kind, binding.principal_value)}`+);++export function requiresProjectNarrowing(+ currentMode: ProjectAccessMode,+ currentBindings: ProjectBinding[],+ nextMode: ProjectAccessMode,+ nextBindings: ProjectBinding[],+): boolean {+ if (currentMode === 'inherit') return nextMode !== 'inherit';+ if (currentMode === 'owner_only') return false;+ if (nextMode === 'owner_only') return true;+ if (nextMode === 'inherit') return false;+ const nextByPrincipal = new Map(nextBindings.map((binding) => [bindingKey(binding), binding]));+ return currentBindings.some((binding) => {+ const next = nextByPrincipal.get(bindingKey(binding));+ return !next || (binding.access_role === 'editor' && next.access_role === 'viewer');+ });+}diff --git a/ui/src/features/permissions/types.ts b/ui/src/features/permissions/types.tsnew file mode 100644index 000000000..14c504ccb--- /dev/null+++ b/ui/src/features/permissions/types.ts@@ -0,0 +1,107 @@+export type AccessRole = 'viewer' | 'editor';+export type PrincipalKind = 'email' | 'email_domain' | 'organization_group';+export type SyncStatus = 'none' | 'in_sync' | 'applying' | 'pending' | 'offline' | 'error' | 'deleted';+export type ResourceAccessLevel = 'public' | 'scope' | 'private';++export type AccessEntry = {+ kind: PrincipalKind;+ value: string;+ role: AccessRole;+};++export type DirectoryMember = {+ id: string;+ email: string;+ organization_role: 'owner' | 'admin' | 'member';+ group_ids: string[];+};++export type DirectoryGroup = {+ id: string;+ name: string;+ archived_at: string | null;+};++export type ProjectBinding = {+ principal_kind: PrincipalKind;+ principal_value: string;+ access_role: AccessRole;+};++export type PermissionProject = {+ project_id: string;+ organization_id: string | null;+ display_name: string;+ access: {+ mode: 'inherit' | 'restricted' | 'owner_only';+ revision: number;+ bindings: ProjectBinding[];+ };+ sync: {+ status: SyncStatus;+ desired_access_revision: number;+ applied_access_revision: number;+ last_synced_at: string | null;+ last_sync_error?: string;+ };+};++export type SyncCounts = {+ active: number;+ error: number;+ offline: number;+ applying: number;+ in_sync: number;+};++export type PermissionsProjection = {+ schema_version: 1;+ instance: {+ id: string;+ access_mode: 'allowlist' | 'public';+ permission_authority: 'instance' | 'cloud';+ local_mutation_allowed: boolean;+ authorization_revision: number;+ };+ capabilities: Array<'instance.permissions.read' | 'instance.permissions.mutate'>;+ access: {+ owner: { email: string | null; role: 'owner' };+ entries: AccessEntry[];+ };+ directory: {+ members: DirectoryMember[];+ groups: DirectoryGroup[];+ };+ projects: PermissionProject[];+ policy_sync: {+ status: 'none' | 'error' | 'offline' | 'applying' | 'in_sync';+ projects: SyncCounts;+ resources: SyncCounts;+ };+};++export type PermissionsResponse = {+ ok: true;+ source: 'live' | 'cache';+ offline: boolean;+ cached_at: number | null;+ projection: PermissionsProjection;+};++export type AuthorizedUsersWriteResponse = {+ ok: true;+ entries: AccessEntry[];+ authorization_revision: number;+};++export type ProjectAccessWriteResponse = {+ ok: true;+ project: PermissionProject;+ authorization_revision: number;+};++export type PermissionsErrorPayload = {+ error?: string;+ current_revision?: number;+ offline?: boolean;+};diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 91eee1e90..1122219c7 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -127,7 +127,7 @@},"nav": {"dashboard": "Dashboard",- "organization": "Organization",+ "permissions": "Permissions","appLibrary": "App Library","channels": "Groups","users": "Direct Messages",@@ -3569,39 +3569,6 @@"applySharingAccess": "Apply","narrowSharingTitle": "Restrict link access?","narrowSharingBody": "People who lose access will be denied on their next page request.",- "workspaceAccess": "Workspace access",- "workspaceAccessDesc": "Who can open this page after signing in.",- "workspaceLevels": {- "private": "Private",- "public": "Organization",- "scope": "Selected groups"- },- "workspaceHelp": {- "private": "Only the Show Page owner can open it through this access rule.",- "public": "Any active Organization member may open it, subject to their Avibe and Project access.",- "scope": "Only active members of the selected groups may open it, subject to their Avibe and Project access."- },- "selectedGroups": "Selected groups",- "archivedGroup": "Archived",- "groupRequired": "Select at least one group.",- "applyWorkspaceAccess": "Apply",- "loadingWorkspaceAccess": "Loading Organization access…",- "workspaceReadOnly": "Only the Show Page owner or an Organization manager can change this audience.",- "organizationSignIn": "Sign in",- "organizationSignInAgain": "Sign in again",- "organizationSignInDesc": "Sign in to avibe.bot to change the Organization audience.",- "organizationUnavailable": "This Avibe is not connected to avibe.bot Organization management.",- "organizationSubjectMismatch": "The signed-in avibe.bot account does not match this Avibe session.",- "workspaceErrors": {- "conflict": "This audience changed elsewhere. Reload the latest version.",- "unreachable": "Organization access is temporarily unavailable.",- "error": "Organization access could not be loaded."- },- "workspaceSync": {- "pending": "This audience change is waiting to be applied on this Avibe.",- "offline": "This Avibe is offline. The audience change will apply after it reconnects.",- "error": "This Avibe could not apply the audience change."- },"emailPlaceholder": "[email protected]","addEmail": "Add email","removeEmail": "Remove {{email}}",@@ -4623,340 +4590,134 @@"fact": "Fact"}},- "organization": {- "nav": {- "overview": "Overview",- "instances": "Avibes",- "members": "Members",- "groups": "Groups",- "resources": "Resources"+ "permissions": {+ "title": "Permissions",+ "description": "Manage access to this Avibe and the Projects available through it.",+ "currentInstance": "Current Avibe",+ "authority": {+ "instance": "Instance managed",+ "cloud": "Managed by Avibe Cloud"},"actions": {- "backToControlPanel": "Control Panel",- "openRemoteAccess": "Open Remote Access",- "signIn": "Sign in with Avibe Cloud",- "signInAgain": "Sign in with the same account",- "signOut": "Sign Out",- "reload": "Review latest",- "saving": "Saving...",- "saveChanges": "Save changes",- "sendInvite": "Send invite",- "inviteMember": "Invite member",- "editMember": "Edit member",- "removeMember": "Remove member",- "resendInvite": "Resend invite",- "exportCsv": "Export CSV",- "newGroup": "New group",- "editGroup": "Edit group",- "archiveGroup": "Archive group",- "restoreGroup": "Restore group",- "manageMembers": "Manage members",- "saveMembers": "Save members",+ "openCloud": "Open in Cloud","addAccess": "Add access","editAccess": "Edit access","removeAccess": "Remove access",+ "manage": "Manage",+ "save": "Save changes",+ "retrySave": "Retry save","addBinding": "Add binding",- "removeBinding": "Remove binding",- "manage": "Manage"+ "removeBinding": "Remove binding"},- "roles": {- "owner": "Owner",- "admin": "Admin",- "member": "Member"+ "tabs": {+ "label": "Permission views",+ "access": "Instance access",+ "projects": "Projects"},- "status": {- "active": "Active",- "invited": "Invited",- "removed": "Removed"+ "states": {+ "loadingTitle": "Loading Permissions",+ "deniedTitle": "Permissions are unavailable",+ "deniedBody": "Your current Avibe session does not allow this policy to be viewed.",+ "unavailableTitle": "Permissions could not be loaded",+ "unavailableBody": "This Avibe is not paired or its current policy is unavailable.",+ "offlineTitle": "Showing last known policy",+ "offlineBody": "Avibe Cloud is unavailable. The cached policy is read-only until the connection recovers.",+ "cloudTitle": "Managed by Avibe Cloud",+ "cloudBody": "This policy is centrally managed and remains read-only on this Avibe.",+ "readOnlyTitle": "Read-only access",+ "readOnlyBody": "Your current Avibe role can view this policy but cannot change it.",+ "applyingTitle": "Policy changes are applying",+ "applyingBody": "One or more Project policies are waiting for this Avibe to acknowledge them.",+ "conflictTitle": "This policy changed elsewhere",+ "conflictBody": "Your draft was kept. The latest revision is loaded; review the draft and retry explicitly.",+ "errorTitle": "Unable to save Permissions"},"sync": {- "none": "No managed policies",+ "none": "No policy","in_sync": "In sync","applying": "Applying","offline": "Offline","error": "Error","deleted": "Deleted"},- "sidebar": {- "section": "Organization",- "organizationCount": "{{count}} organizations",- "switchOrganization": "Switch Organization",- "cloudConnected": "Avibe Cloud connected",- "sessionRemaining": "{{minutes}}m",- "openMenu": "Open Organization menu"- },- "states": {- "loadingTitle": "Loading Organization",- "loadingBody": "Fetching the latest Organization data from Avibe Cloud.",- "notConnectedTitle": "Avibe Cloud is not connected",- "notConnectedBody": "Connect this Avibe to Avibe Cloud before opening Organization management.",- "signInTitle": "Sign in required",- "signInBody": "Sign in to Avibe Cloud to establish a short-lived Organization management session.",- "reauthorizingTitle": "Reauthorizing",- "reauthorizingBody": "Restoring your Organization management session with the same Cloud account.",- "mismatchTitle": "Cloud account does not match",- "mismatchBody": "The Avibe session and Cloud account belong to different users. Sign in again with the same account used for this Avibe session.",- "unreachableTitle": "Avibe Cloud is unreachable",- "unreachableBody": "Organization data could not be reached. Your local Avibe remains available.",- "revokedTitle": "Organization access was revoked",- "revokedBody": "This management session is no longer valid. Sign in again to confirm your current access.",- "emptyTitle": "No Organizations available",- "emptyBody": "The signed-in Cloud account is not an active member of an Organization.",- "unavailableTitle": "This Organization page is unavailable",- "unavailableBody": "Your current Organization or Avibe access does not allow this page.",- "errorTitle": "Unable to complete the request",- "conflictTitle": "This policy changed elsewhere",- "conflictBody": "Your draft was not saved. Review it, then reload the latest version before making changes again."- },- "errors": {- "generic": "Avibe could not complete this Organization request.",- "forbidden": "Your current Organization role does not allow this action.",- "organization_not_found": "This Organization is unavailable.",- "organization_member_not_found": "This member is no longer available.",- "organization_group_not_found": "This group is no longer available.",- "organization_group_archived": "Archived groups cannot be added to a new policy.",- "instance_not_found": "This Avibe is unavailable.",- "project_not_found": "This Project is unavailable.",- "resource_not_found": "This resource is unavailable.",- "member_email_taken": "That email already belongs to this Organization.",- "group_name_taken": "A group with that name already exists.",- "organization_member_not_active_in_organization": "One of the selected initial members is no longer active in this Organization. Refresh the member list and try again.",- "invalid_organization_group_name": "The group name is invalid. Use 1-120 characters.",- "invalid_organization_group_color": "The group color is invalid. Choose a color from the list.",- "invalid_request": "The request parameters are invalid. Check the form and try again.",- "too_many_entries": "This policy has too many entries.",- "invalid_project_access_intent": "Choose a valid Project access rule.",- "invalid_project_access_principal": "One Project access principal is invalid.",- "invalid_project_access_role": "One Project access role is invalid.",- "invalid_resource_acl_intent": "Choose a valid Resource audience.",- "invalid_email": "Enter a valid email address.",- "invalid_domain": "Enter a valid email domain.",- "duplicate_instance_access_principal": "Each Avibe access principal can appear only once.",- "duplicate_project_access_principal": "Each Project principal can appear only once.",- "owner_entry_locked": "The Avibe owner's implicit access cannot be changed.",- "resource_sync_conflict": "This policy changed elsewhere. Review the latest version before saving.",- "organization_member_conflict": "This member changed elsewhere. Review the latest version before trying again.",- "organization_group_conflict": "This group changed elsewhere. Review the latest version before trying again."+ "roles": {+ "owner": "Owner",+ "editor": "Editor",+ "viewer": "Viewer"},"fields": {- "name": "Name",- "description": "Description",- "color": "Color",- "email": "Email",- "role": "Role",- "groups": "Groups",- "member": "Member",- "status": "Status","principalType": "Principal type",- "principal": "Principal"- },- "colors": {- "mint": "Mint",- "cyan": "Cyan",- "blue": "Blue",- "violet": "Violet",- "rose": "Rose",- "gold": "Gold"+ "principal": "Principal",+ "role": "Role"},"principals": {- "organization_group": "Group",+ "organization_group": "Organization group","email": "Email","email_domain": "Email domain"},- "breadcrumb": {- "overview": "Organization / Overview",- "members": "Organization / Members",- "groups": "Organization / Groups",- "groupDetail": "Organization / Groups / {{name}}",- "instances": "Organization / Avibes",- "resources": "Organization / Resources"- },- "overview": {- "description": "Manage membership, access, and policy health for this Organization.",- "memberDescription": "Your Organization membership and the Avibes available to you.",- "memberBreakdown": "{{invited}} invited · {{removed}} removed",- "groupBreakdown": "{{archived}} archived",- "projects": "Projects",- "projectCountUnavailable": "Count unavailable",- "policySync": "Policy sync",- "needsAttention": "Needs attention",- "instanceNeedsAttention": "{{name}} has policy changes that need attention.",- "projectSyncNeedsAttention": "{{name}} has Project policies that need attention.",- "resourceSyncNeedsAttention": "{{name}} has Resource policies that need attention.",- "noAttention": "All visible managed policies are healthy.",- "pendingInvites": "Pending invites",- "pendingInvitesBody": "{{count}} invitation(s) are waiting to be accepted.",- "viewAllInstances": "View all Avibes",- "memberSafeTitle": "Member view",- "memberSafeBody": "You can see your own membership and the Avibes available to you. Member directories and Resource policy composition are visible only to Organization managers."- },- "members": {- "description": "Invite members, assign Organization roles, and manage group membership.",- "memberDescription": "View your Organization role and group membership.",- "filterLabel": "Filter members",- "filterAll": "All",- "active": "Active",- "invited": "Invited",- "removed": "Removed",- "admins": "Admins",- "searchPlaceholder": "Search members...",- "emptyTitle": "No members found",- "emptyBody": "No members match the current view.",- "inviteTitle": "Invite a member",- "inviteBody": "Send an Organization invitation and optionally assign initial groups.",- "editTitle": "Edit member",- "editBody": "Changes to role and complete group membership share one revision.",- "emailPlaceholder": "[email protected]",- "downgradeTitle": "Downgrade this admin?",- "downgradeBody": "{{email}} will lose Organization management access. Their membership and group assignments will remain unchanged.",- "downgradeConfirm": "Downgrade to member",- "removeTitle": "Remove this member?",- "removeBody": "{{email}} will lose Organization membership and any access derived from it."- },- "groups": {- "description": "Build reusable Organization audiences and inspect every policy that references them.",- "memberDescription": "View Organization groups and your own group membership.",- "active": "Active",- "archived": "Archived",- "filterLabel": "Filter groups",- "searchPlaceholder": "Search groups...",- "emptyTitle": "No groups found",- "emptyBody": "No groups match the current view.",- "noDescription": "No description",- "yourGroup": "Your group",- "createTitle": "Create group",- "createBody": "Create an Organization group and optionally add initial members.",- "editTitle": "Edit group",- "editBody": "Update the group's display details.",- "initialMembers": "Initial members",- "manageMembersTitle": "Manage group members",- "manageMembersBody": "Replace the complete member list for {{name}}.",- "referencedBy": "Referenced by",- "moreReferences": "+{{count}} more",- "archiveTitle": "Archive this group?",- "archiveBody": "{{name}} is referenced by {{count}} active policy item(s).",- "archiveImpactTitle": "Archive impact",- "archiveImpactBody": "Existing references remain visible but stop granting access. The archived group cannot be selected for new policies."- },- "instances": {- "description": "Organization-bound Avibes you can see. Manage access and Project policy without changing pairing or hostnames.",- "searchPlaceholder": "Search Avibes...",- "emptyTitle": "No Avibes found",- "emptyBody": "No Organization-bound Avibes are available in this view.",- "you": "You",- "organizationOwner": "Avibe owner",- "ownerProtected": "Owner identity protected",- "youAreOwner": "you are the Avibe owner",- "paired": "Paired",- "notPaired": "Not paired",- "accessCount": "{{count}} access entries",- "accessTab": "Access",- "projectsTab": "Projects",- "tabsLabel": "Avibe management views",- "columns": {- "instance": "Avibe",- "owner": "Owner",- "address": "Public address",- "status": "Status",- "access": "Access",- "sync": "Sync"- },- "status": {- "pending": "Pending",- "active": "Online",- "disabled": "Disabled",- "deleted": "Deleted"- }+ "errors": {+ "generic": "Avibe could not complete this Permissions request.",+ "permissions_unavailable": "The Permissions service is unavailable.",+ "permission_authority_cloud": "This policy is managed by Avibe Cloud and cannot be changed here.",+ "instance_access_forbidden": "Your current Avibe role cannot change Permissions.",+ "cloud_policy_unavailable": "The current Cloud policy is temporarily unavailable.",+ "invalid_request": "Check the form values and try again.",+ "invalid_email": "Enter a valid email address.",+ "invalid_domain": "Enter a valid email domain.",+ "too_many_entries": "This policy has too many entries.",+ "duplicate_access_principal": "Each access principal can appear only once.",+ "duplicate_project_access_principal": "Each Project principal can appear only once.",+ "organization_group_not_found": "This Organization group is no longer available.",+ "organization_group_archived": "Archived groups cannot be added to new policy.",+ "invalid_project_access_intent": "Choose a valid Project access rule.",+ "invalid_project_access_principal": "One Project access principal is invalid.",+ "invalid_project_access_role": "One Project access role is invalid.",+ "project_not_found": "This Project is no longer available."},"access": {- "viewer": "Viewer",- "editor": "Editor",- "ownerTitle": "{{owner}} · Avibe owner",- "ownerBody": "Implicit owner-equivalent access. It cannot be edited or removed as an entry.",- "emptyTitle": "No explicit access entries",- "emptyBody": "Only the implicit Avibe owner currently has access.",- "addTitle": "Add Avibe access",- "editTitle": "Edit Avibe access",- "dialogBody": "Grant a group, individual email, or email domain Viewer or Editor access.",- "emailPlaceholder": "[email protected]",+ "title": "Who can access this Avibe",+ "description": "Viewer and Editor assignments for the current Avibe.",+ "protectedOwner": "Protected owner identity",+ "ownerBody": "The owner always retains management access.",+ "emptyTitle": "No additional access",+ "emptyBody": "Only the owner can access this Avibe through the current policy.",+ "addTitle": "Add access",+ "editTitle": "Edit access",+ "dialogBody": "Assign Viewer or Editor access for this Avibe.",+ "emailPlaceholder": "[email protected]","domainPlaceholder": "example.com",- "narrowTitle": "Narrow this access entry?",- "narrowBody": "The previous principal or Editor capability will stop applying after this change.","removeTitle": "Remove this access entry?",- "removeBody": "{{principal}} will lose access granted by this entry.",- "columns": {- "principal": "Principal",- "type": "Type",- "role": "Role"- }+ "removeBody": "This principal will no longer receive access from the instance policy."},"projects": {+ "title": "Project access",+ "description": "Apply narrower access rules to Projects published by this Avibe.","searchPlaceholder": "Search Projects...",- "safeDescriptorNotice": "Safe descriptors only. Local Project paths are never displayed or sent. Project access can only narrow the Avibe role.",- "emptyTitle": "No Projects found",- "emptyBody": "This Avibe has not published any active managed Project descriptors.",+ "emptyTitle": "No Projects available",+ "emptyBody": "This Avibe has not published any Projects yet.",+ "dialogTitle": "Project access · {{name}}",+ "dialogBody": "Choose who can open and use this Project.","accessRule": "Access rule",- "bindings": "Restricted bindings",- "bindingRequired": "Restricted access requires at least one binding.",- "usesAvibeRole": "Uses Avibe role",- "ownerOnlyAudience": "Avibe owner only",- "bindingCount": "{{count}} binding(s)",- "dialogTitle": "Manage {{name}} access",- "dialogBody": "Organization management authority lets you change this policy; it does not grant you permission to use the Project.",- "narrowTitle": "Narrow this Project's access?",- "narrowBody": "This change removes an existing audience, downgrades Editor access, or switches to a more restrictive rule.",+ "bindings": "Access bindings",+ "bindingRequired": "Add at least one binding for restricted access.",+ "bindingCount": "{{count}} binding",+ "bindingCount_other": "{{count}} bindings","modes": {- "inherit": "Inherit",+ "inherit": "Inherit Avibe access","restricted": "Restricted",- "owner_only": "Owner-only"+ "owner_only": "Owner only"},"modeHelp": {- "inherit": "Use each principal's effective Avibe role.",- "restricted": "Allow one or more explicit groups, emails, or domains. This rule can only narrow the Avibe role.",- "owner_only": "Only the canonical owner of this Avibe can use this Project. Organization managers can manage the policy but do not gain use access."+ "inherit": "Everyone who can use this Avibe can use the Project.",+ "restricted": "Only the selected users, domains, and groups can use the Project.",+ "owner_only": "Only the Avibe owner can use the Project."},- "columns": {- "project": "Project",- "rule": "Access rule",- "bindings": "Bindings",- "sync": "Sync"- }- },- "resources": {- "description": "Manage which Organization audience may use each resource. Resource use never grants permission to edit, delete, or re-share it.",- "tabsLabel": "Resource kinds",- "accessLevel": "Audience",- "selectGroups": "Selected groups",- "groupRequired": "Select at least one group.",- "dialogTitle": "Manage {{name}} audience",- "dialogBody": "Choose Private, the whole Organization, or selected Organization groups.",- "narrowTitle": "Narrow this resource audience?",- "narrowBody": "Some people who can use this resource now will lose access after this change.",- "emptyTitle": "No resources found",- "emptyBody": "No active {{kind}} descriptors are available.",- "everyActiveMember": "Every active member",- "ownerOnly": "Resource owner only",- "kinds": {- "agent": "Agents",- "vault_secret": "Vault secrets",- "skill": "Skills",- "show_page": "Show Pages"+ "audience": {+ "inherit": "Uses Avibe roles",+ "owner_only": "Owner only"},- "levels": {- "private": "Private",- "public": "Organization",- "scope": "Selected groups"- },- "levelHelp": {- "private": "Only the resource owner can use it through this Organization ACL.",- "public": "Every active member of this Organization may use it, subject to all other access layers.",- "scope": "Only active members of the selected groups may use it, subject to all other access layers."- },- "columns": {- "access": "Access",- "audience": "Audience",- "sync": "Sync"- }+ "narrowTitle": "Narrow Project access?",+ "narrowBody": "Some people may lose access as soon as this policy is applied."}}}diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 986b75db2..9886f1017 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -127,7 +127,7 @@},"nav": {"dashboard": "控制台",- "organization": "组织",+ "permissions": "权限","appLibrary": "应用库","channels": "群组","users": "私聊",@@ -3569,39 +3569,6 @@"applySharingAccess": "应用","narrowSharingTitle": "收紧链接访问范围?","narrowSharingBody": "失去权限的用户在下一次请求页面时将被拒绝。",- "workspaceAccess": "登录访问范围",- "workspaceAccessDesc": "控制登录后哪些人可以打开此页面。",- "workspaceLevels": {- "private": "私有",- "public": "组织",- "scope": "指定群组"- },- "workspaceHelp": {- "private": "此规则下只有页面所有者可以打开。",- "public": "组织内所有活跃成员均可打开,同时仍受 Avibe 和项目权限限制。",- "scope": "只有指定群组的活跃成员可以打开,同时仍受 Avibe 和项目权限限制。"- },- "selectedGroups": "指定群组",- "archivedGroup": "已归档",- "groupRequired": "至少选择一个群组。",- "applyWorkspaceAccess": "应用",- "loadingWorkspaceAccess": "正在加载组织权限…",- "workspaceReadOnly": "只有页面所有者或组织管理者可以修改此访问范围。",- "organizationSignIn": "登录",- "organizationSignInAgain": "重新登录",- "organizationSignInDesc": "登录 avibe.bot 后才能修改组织访问范围。",- "organizationUnavailable": "当前 Avibe 尚未连接 avibe.bot 的组织管理功能。",- "organizationSubjectMismatch": "当前登录的 avibe.bot 账号与此 Avibe 会话不一致。",- "workspaceErrors": {- "conflict": "访问范围已在其他位置更新,请重新加载最新版本。",- "unreachable": "组织权限暂时不可用。",- "error": "无法加载组织权限。"- },- "workspaceSync": {- "pending": "访问范围变更正在等待应用到当前 Avibe。",- "offline": "当前 Avibe 已离线,重新连接后会应用访问范围变更。",- "error": "当前 Avibe 无法应用访问范围变更。"- },"emailPlaceholder": "[email protected]","addEmail": "添加邮箱","removeEmail": "移除 {{email}}",@@ -4623,340 +4590,134 @@"fact": "事实"}},- "organization": {- "nav": {- "overview": "概览",- "instances": "Avibe",- "members": "成员",- "groups": "群组",- "resources": "资源"+ "permissions": {+ "title": "权限",+ "description": "管理谁可以访问当前 Avibe,以及他们可使用的项目。",+ "currentInstance": "当前 Avibe",+ "authority": {+ "instance": "实例管理",+ "cloud": "由 Avibe Cloud 管理"},"actions": {- "backToControlPanel": "控制面板",- "openRemoteAccess": "打开远程访问",- "signIn": "登录 Avibe Cloud",- "signInAgain": "使用同一账号重新登录",- "signOut": "退出",- "reload": "查看最新版本",- "saving": "保存中...",- "saveChanges": "保存更改",- "sendInvite": "发送邀请",- "inviteMember": "邀请成员",- "editMember": "编辑成员",- "removeMember": "移除成员",- "resendInvite": "重新发送邀请",- "exportCsv": "导出 CSV",- "newGroup": "新建群组",- "editGroup": "编辑群组",- "archiveGroup": "归档群组",- "restoreGroup": "恢复群组",- "manageMembers": "管理成员",- "saveMembers": "保存成员",+ "openCloud": "在 Cloud 中打开","addAccess": "添加访问权限","editAccess": "编辑访问权限","removeAccess": "移除访问权限",+ "manage": "管理",+ "save": "保存更改",+ "retrySave": "重试保存","addBinding": "添加绑定",- "removeBinding": "移除绑定",- "manage": "管理"+ "removeBinding": "移除绑定"},- "roles": {- "owner": "所有者",- "admin": "管理员",- "member": "成员"+ "tabs": {+ "label": "权限视图",+ "access": "实例访问",+ "projects": "项目"},- "status": {- "active": "活跃",- "invited": "已邀请",- "removed": "已移除"+ "states": {+ "loadingTitle": "正在加载权限",+ "deniedTitle": "权限不可用",+ "deniedBody": "当前 Avibe 会话无权查看此策略。",+ "unavailableTitle": "无法加载权限",+ "unavailableBody": "此 Avibe 尚未配对,或当前策略不可用。",+ "offlineTitle": "正在显示上次已知策略",+ "offlineBody": "Avibe Cloud 当前不可用。连接恢复前,缓存策略仅供查看。",+ "cloudTitle": "由 Avibe Cloud 管理",+ "cloudBody": "此策略由中央管理,在当前 Avibe 中保持只读。",+ "readOnlyTitle": "只读访问",+ "readOnlyBody": "当前 Avibe 角色可以查看策略,但不能修改。",+ "applyingTitle": "策略更改正在应用",+ "applyingBody": "一个或多个项目策略正在等待当前 Avibe 确认。",+ "conflictTitle": "此策略已在其他位置更改",+ "conflictBody": "你的草稿已保留,并已加载最新修订。请检查草稿后明确重试。",+ "errorTitle": "无法保存权限"},"sync": {- "none": "没有受管策略",+ "none": "无策略","in_sync": "已同步",- "applying": "应用中",+ "applying": "正在应用","offline": "离线","error": "错误","deleted": "已删除"},- "sidebar": {- "section": "组织",- "organizationCount": "{{count}} 个组织",- "switchOrganization": "切换组织",- "cloudConnected": "Avibe Cloud已连接",- "sessionRemaining": "{{minutes}} 分钟",- "openMenu": "打开组织菜单"- },- "states": {- "loadingTitle": "正在加载组织",- "loadingBody": "正在从 Avibe Cloud 获取最新组织数据。",- "notConnectedTitle": "尚未连接 Avibe Cloud",- "notConnectedBody": "请先将此 Avibe 连接到 Avibe Cloud,再打开组织管理。",- "signInTitle": "需要登录",- "signInBody": "登录 Avibe Cloud,以建立短期有效的组织管理会话。",- "reauthorizingTitle": "正在重新授权",- "reauthorizingBody": "正在使用同一 Cloud 账号恢复组织管理会话。",- "mismatchTitle": "Cloud 账号不匹配",- "mismatchBody": "当前 Avibe 会话与 Cloud 账号属于不同用户。请使用建立此 Avibe 会话的同一账号重新登录。",- "unreachableTitle": "无法连接 Avibe Cloud",- "unreachableBody": "暂时无法获取组织数据,本地 Avibe 仍可正常使用。",- "revokedTitle": "组织访问权限已撤销",- "revokedBody": "此管理会话已失效。请重新登录以确认当前权限。",- "emptyTitle": "没有可用组织",- "emptyBody": "当前 Cloud 账号不是任何组织的活跃成员。",- "unavailableTitle": "无法访问此组织页面",- "unavailableBody": "当前组织权限或 Avibe 权限不允许访问此页面。",- "errorTitle": "无法完成请求",- "conflictTitle": "策略已在其他位置更改",- "conflictBody": "你的草稿尚未保存。请先检查草稿,再重新加载最新版本后继续修改。"- },- "errors": {- "generic": "Avibe 无法完成此组织请求。",- "forbidden": "当前组织角色不允许执行此操作。",- "organization_not_found": "无法访问此组织。",- "organization_member_not_found": "此成员已不可用。",- "organization_group_not_found": "此群组已不可用。",- "organization_group_archived": "不能把已归档群组添加到新策略。",- "instance_not_found": "无法访问此 Avibe。",- "project_not_found": "无法访问此 Project。",- "resource_not_found": "无法访问此资源。",- "member_email_taken": "该邮箱已属于此组织。",- "group_name_taken": "已存在同名群组。",- "organization_member_not_active_in_organization": "所选初始成员已不是该组织的活跃成员,请刷新成员列表后重试。",- "invalid_organization_group_name": "群组名称无效,请使用 1-120 个字符。",- "invalid_organization_group_color": "群组颜色无效,请选择列表中的颜色。",- "invalid_request": "请求参数无效,请检查填写内容后重试。",- "too_many_entries": "此策略包含过多条目。",- "invalid_project_access_intent": "请选择有效的 Project 访问规则。",- "invalid_project_access_principal": "某个 Project 访问主体无效。",- "invalid_project_access_role": "某个 Project 访问角色无效。",- "invalid_resource_acl_intent": "请选择有效的资源受众。",- "invalid_email": "请输入有效的邮箱地址。",- "invalid_domain": "请输入有效的邮箱域名。",- "duplicate_instance_access_principal": "同一个 Avibe 访问主体只能出现一次。",- "duplicate_project_access_principal": "同一个 Project 主体只能出现一次。",- "owner_entry_locked": "不能修改 Avibe 所有者的隐式访问权限。",- "resource_sync_conflict": "策略已在其他位置更改,请检查最新版本后再保存。",- "organization_member_conflict": "成员已在其他位置更改,请检查最新版本后重试。",- "organization_group_conflict": "群组已在其他位置更改,请检查最新版本后重试。"+ "roles": {+ "owner": "所有者",+ "editor": "编辑者",+ "viewer": "查看者"},"fields": {- "name": "名称",- "description": "描述",- "color": "颜色",- "email": "邮箱",- "role": "角色",- "groups": "群组",- "member": "成员",- "status": "状态","principalType": "主体类型",- "principal": "访问主体"- },- "colors": {- "mint": "薄荷绿",- "cyan": "青色",- "blue": "蓝色",- "violet": "紫罗兰",- "rose": "玫红",- "gold": "金色"+ "principal": "主体",+ "role": "角色"},"principals": {- "organization_group": "群组",+ "organization_group": "组织组","email": "邮箱","email_domain": "邮箱域名"},- "breadcrumb": {- "overview": "组织 / 概览",- "members": "组织 / 成员",- "groups": "组织 / 群组",- "groupDetail": "组织 / 群组 / {{name}}",- "instances": "组织 / Avibe",- "resources": "组织 / 资源"- },- "overview": {- "description": "管理此组织的成员、访问权限和策略同步状态。",- "memberDescription": "查看你的组织成员身份和可访问的 Avibe。",- "memberBreakdown": "{{invited}} 个已邀请 · {{removed}} 个已移除",- "groupBreakdown": "{{archived}} 个已归档",- "projects": "Project",- "projectCountUnavailable": "计数暂不可用",- "policySync": "策略同步",- "needsAttention": "需要处理",- "instanceNeedsAttention": "{{name}} 的策略变更需要处理。",- "projectSyncNeedsAttention": "{{name}} 的 Project 策略需要处理。",- "resourceSyncNeedsAttention": "{{name}} 的资源策略需要处理。",- "noAttention": "所有可见的受管策略状态正常。",- "pendingInvites": "待接受邀请",- "pendingInvitesBody": "有 {{count}} 个邀请等待接受。",- "viewAllInstances": "查看全部 Avibe",- "memberSafeTitle": "成员视图",- "memberSafeBody": "你可以查看自己的成员身份和可访问的 Avibe。成员目录和资源策略构成仅对组织管理者可见。"- },- "members": {- "description": "邀请成员、分配组织角色并管理群组成员关系。",- "memberDescription": "查看你的组织角色和群组成员关系。",- "filterLabel": "筛选成员",- "filterAll": "全部",- "active": "活跃",- "invited": "已邀请",- "removed": "已移除",- "admins": "管理员",- "searchPlaceholder": "搜索成员...",- "emptyTitle": "没有找到成员",- "emptyBody": "当前视图中没有匹配的成员。",- "inviteTitle": "邀请成员",- "inviteBody": "发送组织邀请,并可选择初始群组。",- "editTitle": "编辑成员",- "editBody": "角色和完整群组成员关系共用同一 revision。",- "emailPlaceholder": "[email protected]",- "downgradeTitle": "将此管理员降级?",- "downgradeBody": "{{email}} 将失去组织管理权限,其成员身份和群组分配保持不变。",- "downgradeConfirm": "降级为成员",- "removeTitle": "移除此成员?",- "removeBody": "{{email}} 将失去组织成员身份以及由此获得的全部权限。"- },- "groups": {- "description": "创建可复用的组织受众,并检查引用这些群组的全部策略。",- "memberDescription": "查看组织群组和你自己的群组成员关系。",- "active": "活跃",- "archived": "已归档",- "filterLabel": "筛选群组",- "searchPlaceholder": "搜索群组...",- "emptyTitle": "没有找到群组",- "emptyBody": "当前视图中没有匹配的群组。",- "noDescription": "没有描述",- "yourGroup": "我的群组",- "createTitle": "创建群组",- "createBody": "创建组织群组,并可选择初始成员。",- "editTitle": "编辑群组",- "editBody": "更新群组的展示信息。",- "initialMembers": "初始成员",- "manageMembersTitle": "管理群组成员",- "manageMembersBody": "替换 {{name}} 的完整成员列表。",- "referencedBy": "引用位置",- "moreReferences": "另有 {{count}} 项",- "archiveTitle": "归档此群组?",- "archiveBody": "{{name}} 被 {{count}} 个活跃策略项引用。",- "archiveImpactTitle": "归档影响",- "archiveImpactBody": "现有引用仍会显示,但不再授予访问权限;已归档群组不能加入新策略。"- },- "instances": {- "description": "你可以看到的组织 Avibe。可管理访问权限和 Project 策略,但不会改变配对或域名。",- "searchPlaceholder": "搜索 Avibe...",- "emptyTitle": "没有找到 Avibe",- "emptyBody": "当前视图中没有可用的组织 Avibe。",- "you": "你",- "organizationOwner": "Avibe 所有者",- "ownerProtected": "所有者身份受保护",- "youAreOwner": "你是此 Avibe 的所有者",- "paired": "已配对",- "notPaired": "未配对",- "accessCount": "{{count}} 条访问规则",- "accessTab": "访问权限",- "projectsTab": "Project",- "tabsLabel": "Avibe 管理视图",- "columns": {- "instance": "Avibe",- "owner": "所有者",- "address": "公开地址",- "status": "状态",- "access": "访问规则",- "sync": "同步"- },- "status": {- "pending": "等待中",- "active": "在线",- "disabled": "已停用",- "deleted": "已删除"- }+ "errors": {+ "generic": "Avibe 无法完成此次权限请求。",+ "permissions_unavailable": "权限服务当前不可用。",+ "permission_authority_cloud": "此策略由 Avibe Cloud 管理,无法在此修改。",+ "instance_access_forbidden": "当前 Avibe 角色无权修改权限。",+ "cloud_policy_unavailable": "当前 Cloud 策略暂时不可用。",+ "invalid_request": "请检查表单内容后重试。",+ "invalid_email": "请输入有效的邮箱地址。",+ "invalid_domain": "请输入有效的邮箱域名。",+ "too_many_entries": "此策略包含过多条目。",+ "duplicate_access_principal": "每个访问主体只能出现一次。",+ "duplicate_project_access_principal": "每个项目主体只能出现一次。",+ "organization_group_not_found": "此组织组已不可用。",+ "organization_group_archived": "不能把已归档的组加入新策略。",+ "invalid_project_access_intent": "请选择有效的项目访问规则。",+ "invalid_project_access_principal": "某个项目访问主体无效。",+ "invalid_project_access_role": "某个项目访问角色无效。",+ "project_not_found": "此项目已不可用。"},"access": {- "viewer": "查看者",- "editor": "编辑者",- "ownerTitle": "{{owner}} · Avibe 所有者",- "ownerBody": "这是隐式的所有者同等权限,不能作为普通条目编辑或移除。",- "emptyTitle": "没有显式访问条目",- "emptyBody": "当前只有隐式的 Avibe 所有者可以访问。",- "addTitle": "添加 Avibe 访问权限",- "editTitle": "编辑 Avibe 访问权限",- "dialogBody": "为群组、单个邮箱或邮箱域名授予查看者或编辑者权限。",- "emailPlaceholder": "[email protected]",+ "title": "谁可以访问此 Avibe",+ "description": "当前 Avibe 的查看者与编辑者分配。",+ "protectedOwner": "受保护的所有者身份",+ "ownerBody": "所有者始终保留管理权限。",+ "emptyTitle": "没有其他访问主体",+ "emptyBody": "当前策略下只有所有者可以访问此 Avibe。",+ "addTitle": "添加访问权限",+ "editTitle": "编辑访问权限",+ "dialogBody": "为此 Avibe 分配查看者或编辑者权限。",+ "emailPlaceholder": "[email protected]","domainPlaceholder": "example.com",- "narrowTitle": "收窄此访问权限?",- "narrowBody": "保存后,原访问主体或编辑能力将不再生效。","removeTitle": "移除此访问条目?",- "removeBody": "{{principal}} 将失去此条目授予的访问权限。",- "columns": {- "principal": "访问主体",- "type": "类型",- "role": "角色"- }+ "removeBody": "此主体将不再通过实例策略获得访问权限。"},"projects": {- "searchPlaceholder": "搜索 Project...",- "safeDescriptorNotice": "这里只显示安全描述信息,不会显示或发送本地 Project 路径。Project 权限只能收窄 Avibe 角色。",- "emptyTitle": "没有找到 Project",- "emptyBody": "此 Avibe 尚未发布活跃的受管 Project 描述信息。",+ "title": "项目访问",+ "description": "为当前 Avibe 发布的项目设置更严格的访问规则。",+ "searchPlaceholder": "搜索项目...",+ "emptyTitle": "没有可用项目",+ "emptyBody": "当前 Avibe 尚未发布任何项目。",+ "dialogTitle": "项目访问 · {{name}}",+ "dialogBody": "选择谁可以打开和使用此项目。","accessRule": "访问规则",- "bindings": "受限绑定",+ "bindings": "访问绑定","bindingRequired": "受限访问至少需要一个绑定。",- "usesAvibeRole": "使用 Avibe 角色",- "ownerOnlyAudience": "仅 Avibe 所有者","bindingCount": "{{count}} 个绑定",- "dialogTitle": "管理 {{name}} 的访问权限",- "dialogBody": "组织管理权限只允许你修改此策略,不会因此获得 Project 使用权限。",- "narrowTitle": "收窄此 Project 的访问权限?",- "narrowBody": "此更改会移除现有受众、将编辑者降为查看者,或切换到更严格的规则。",+ "bindingCount_other": "{{count}} 个绑定","modes": {- "inherit": "继承",+ "inherit": "继承 Avibe 权限","restricted": "受限","owner_only": "仅所有者"},"modeHelp": {- "inherit": "使用各访问主体在此 Avibe 上的有效角色。",- "restricted": "允许一个或多个明确的群组、邮箱或域名;此规则只能收窄 Avibe 角色。",- "owner_only": "只有此 Avibe 的所有者可以使用此 Project。组织管理者可以管理策略,但不会因此获得使用权限。"- },- "columns": {- "project": "Project",- "rule": "访问规则",- "bindings": "绑定",- "sync": "同步"- }- },- "resources": {- "description": "管理每项资源可由哪些组织受众使用。可以使用资源不代表可以编辑、删除或再次分享资源。",- "tabsLabel": "资源类型",- "accessLevel": "受众",- "selectGroups": "选择群组",- "groupRequired": "请至少选择一个群组。",- "dialogTitle": "管理 {{name}} 的受众",- "dialogBody": "选择私有、整个组织或指定组织群组。",- "narrowTitle": "收窄此资源的受众?",- "narrowBody": "部分当前可以使用此资源的成员将在更改后失去访问权限。",- "emptyTitle": "没有找到资源",- "emptyBody": "没有可用的活跃{{kind}}描述信息。",- "everyActiveMember": "每个活跃成员",- "ownerOnly": "仅资源所有者",- "kinds": {- "agent": "Agent",- "vault_secret": "Vault 密钥",- "skill": "Skill",- "show_page": "Show Page"- },- "levels": {- "private": "私有",- "public": "组织",- "scope": "指定群组"+ "inherit": "所有能使用此 Avibe 的用户都能使用该项目。",+ "restricted": "只有选中的用户、域名和组可以使用该项目。",+ "owner_only": "只有 Avibe 所有者可以使用该项目。"},- "levelHelp": {- "private": "通过此组织 ACL,仅资源所有者可以使用。",- "public": "此组织的每个活跃成员都可以使用,但仍需满足其他全部权限层。",- "scope": "只有指定群组的活跃成员可以使用,并且仍需满足其他全部权限层。"+ "audience": {+ "inherit": "使用 Avibe 角色",+ "owner_only": "仅所有者"},- "columns": {- "access": "访问级别",- "audience": "受众",- "sync": "同步"- }+ "narrowTitle": "收紧项目访问权限?",+ "narrowBody": "策略应用后,部分用户可能立即失去访问权限。"}}}diff --git a/ui/src/lib/adminNavigation.test.ts b/ui/src/lib/adminNavigation.test.tsindex bae71073a..e352d351c 100644--- a/ui/src/lib/adminNavigation.test.ts+++ b/ui/src/lib/adminNavigation.test.ts@@ -60,7 +60,7 @@ describe('isOwnerOnlyPath', () => {it('leaves remotely usable destinations open', () => {expect(isOwnerOnlyPath('/admin/settings/messaging')).toBe(false);- expect(isOwnerOnlyPath('/admin/organization/overview')).toBe(false);+ expect(isOwnerOnlyPath('/admin/permissions')).toBe(false);expect(isOwnerOnlyPath('/apps/files')).toBe(false);expect(isOwnerOnlyPath('/apps/editor')).toBe(false);expect(isOwnerOnlyPath('/apps/terminal')).toBe(false);diff --git a/ui/src/lib/applicationRoutes.ts b/ui/src/lib/applicationRoutes.tsindex b76fb1c53..d5ea53b11 100644--- a/ui/src/lib/applicationRoutes.ts+++ b/ui/src/lib/applicationRoutes.ts@@ -20,12 +20,7 @@ export const APPLICATION_ROUTE_PATHS = ['/apps/library','/admin','/admin/dashboard',- '/admin/organization',- '/admin/organization/overview',- '/admin/organization/members',- '/admin/organization/groups',- '/admin/organization/instances',- '/admin/organization/resources',+ '/admin/permissions','/admin/remote-access','/admin/groups','/admin/users',@@ -71,9 +66,6 @@ export const APPLICATION_ROUTE_PATHS = [export const APPLICATION_DYNAMIC_ROUTE_PATHS = ['/apps/show/:sessionId','/chat/:sessionId',- '/admin/organization/groups/:groupId',- '/admin/organization/instances/:instanceId/access',- '/admin/organization/instances/:instanceId/projects',] as const;const APPLICATION_ROUTES = new Set<string>(APPLICATION_ROUTE_PATHS);diff --git a/ui/src/lib/showPageAccess.test.ts b/ui/src/lib/showPageAccess.test.tsindex a7a8183de..8c001d1eb 100644--- a/ui/src/lib/showPageAccess.test.ts+++ b/ui/src/lib/showPageAccess.test.ts@@ -1,19 +1,14 @@import { describe, expect, it } from 'vitest';-import { isRevisionConflict, OrganizationApiError } from '@/features/organization/api/client';import {SHOW_ACCESS_EMAIL_MAX_COUNT,- buildShowPageAccessPatch,classifyShowPageAccessProbe,normalizeShowAccessEmail,normalizeShowAccessEmails,showAccessDraftChanged,showAccessTargetEmails,showPageHeaderAccess,- showPageAudienceLabelKey,- showPageAudienceLevels,showPageRestoreAccessDecision,- showPageSyncPresentation,type ShowAccess,type ShowPageAccess,} from './showPageAccess';@@ -34,18 +29,6 @@ const access = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({});describe('Show Page access policy helpers', () => {- it('keeps Personal authenticated access private', () => {- expect(showPageAudienceLevels('personal')).toEqual(['private']);- });-- it('offers all three Organization audiences', () => {- expect(showPageAudienceLevels('organization')).toEqual(['private', 'public', 'scope']);- });-- it('presents the public wire value as Organization access', () => {- expect(showPageAudienceLabelKey('public')).toBe('chat.showPage.workspaceLevels.public');- });-it('normalizes ShowAccess emails with the frozen ASCII contract', () => {expect(normalizeShowAccessEmail(' [email protected] ')).toBe(@@ -96,25 +79,6 @@ describe('Show Page access policy helpers', () => {expect(showAccessDraftChanged(saved, 'public', 'stable-link', [])).toBe(true);});- it('requires at least one group for scoped access and normalizes duplicates', () => {- expect(buildShowPageAccessPatch('scope', [], 4)).toBeNull();- expect(buildShowPageAccessPatch('scope', ['group-1', ' group-1 ', 'group-2'], 4)).toEqual({- access_level: 'scope',- group_ids: ['group-1', 'group-2'],- if_match_revision: 4,- });- });-- it('keeps local ShowAccess state out of Organization ACL mutations', () => {- const patch = buildShowPageAccessPatch('public', ['ignored-group'], 4);- expect(patch).toEqual({- access_level: 'public',- group_ids: [],- if_match_revision: 4,- });- expect(patch).not.toHaveProperty('visibility');- });-it('separates page use from page-specific access management in the chat header', () => {expect(showPageHeaderAccess(false, access({ can_use: true, can_manage: false }))).toEqual({canOpen: true,@@ -144,29 +108,4 @@ describe('Show Page access policy helpers', () => {expect(showPageRestoreAccessDecision(true, null)).toBe('allow');});- it('distinguishes pending, offline, and error sync states', () => {- expect(showPageSyncPresentation('pending')).toEqual({- key: 'chat.showPage.workspaceSync.pending',- tone: 'pending',- });- expect(showPageSyncPresentation('offline')).toEqual({- key: 'chat.showPage.workspaceSync.offline',- tone: 'pending',- });- expect(showPageSyncPresentation('error')).toEqual({- key: 'chat.showPage.workspaceSync.error',- tone: 'error',- });- });-- it('recognizes a Resource revision conflict without treating generic errors as conflicts', () => {- expect(isRevisionConflict(new OrganizationApiError(409, {- error: 'resource_sync_conflict',- current_revision: 5,- }))).toBe(true);- expect(isRevisionConflict(new OrganizationApiError(502, {- error: 'cloud_management_unavailable',- retryable: true,- }))).toBe(false);- });});diff --git a/ui/src/lib/showPageAccess.ts b/ui/src/lib/showPageAccess.tsindex 460284698..76636166e 100644--- a/ui/src/lib/showPageAccess.ts+++ b/ui/src/lib/showPageAccess.ts@@ -1,4 +1,4 @@-import type { ResourceAccessLevel, SyncStatus } from '@/features/organization/api/types';+import type { ResourceAccessLevel } from '@/features/permissions/types';export type ShowPageAccess = {ok: true;mode: 'personal' | 'organization';@@ -124,49 +124,3 @@ export function showPageHeaderAccess(canManage: canManageInstance || access?.can_manage === true,};}--export type ShowPageAccessPatch = {- access_level: ResourceAccessLevel;- group_ids: string[];- if_match_revision: number;-};--export const showPageAudienceLevels = (- mode: ShowPageAccess['mode'],-): ResourceAccessLevel[] => (- mode === 'organization' ? ['private', 'public', 'scope'] : ['private']-);--export const showPageAudienceLabelKey = (level: ResourceAccessLevel): string => (- `chat.showPage.workspaceLevels.${level}`-);--export function buildShowPageAccessPatch(- level: ResourceAccessLevel,- groupIds: string[],- revision: number,-): ShowPageAccessPatch | null {- const normalizedGroupIds = level === 'scope'- ? [...new Set(groupIds.map((id) => id.trim()).filter(Boolean))]- : [];- if (level === 'scope' && normalizedGroupIds.length === 0) return null;- return {- access_level: level,- group_ids: normalizedGroupIds,- if_match_revision: revision,- };-}--export function showPageSyncPresentation(status: SyncStatus): {- key: string;- tone: 'muted' | 'pending' | 'error';-} | null {- if (status === 'in_sync' || status === 'none' || status === 'deleted') return null;- if (status === 'error') {- return { key: 'chat.showPage.workspaceSync.error', tone: 'error' };- }- if (status === 'offline') {- return { key: 'chat.showPage.workspaceSync.offline', tone: 'pending' };- }- return { key: 'chat.showPage.workspaceSync.pending', tone: 'pending' };-}diff --git a/vibe/authorization.py b/vibe/authorization.pyindex 19d331727..17088e6ba 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -345,6 +345,7 @@ _VIEWER_HTTP_RULES = tuple(r"^/api/media/[^/]+(?:/meta)?$",r"^/api/org/(?:context|groups)$",r"^/api/resource-policies$",+ r"^/api/permissions$",r"^/api/show-pages$",r"^/api/show-pages/[^/]+/access$",r"^/api/show-pages/[^/]+/icon$",@@ -428,10 +429,6 @@ def http_authorization_policy("""Return the minimum Instance role for one HTTP request."""normalized_method = method.upper()- # Organization management is an explicit Cloud proxy namespace. Cloud user- # identity and object authorization are re-evaluated by that boundary.- if path.startswith("/api/cloud-management/"):- return HttpAuthorizationPolicy("viewer")if path.startswith("/show/"):return HttpAuthorizationPolicy("viewer")if path == "/status":diff --git a/vibe/cloud_management.py b/vibe/cloud_management.pydeleted file mode 100644index 3f3f8fd57..000000000--- a/vibe/cloud_management.py+++ /dev/null@@ -1,605 +0,0 @@-"""Browser-bound Avibe Cloud Organization management grants and proxying.--The browser never receives the Cloud Bearer token. A short-lived grant is held-in this process and addressed by two HttpOnly cookies: an opaque grant handle-and a stable browser binding. All Cloud requests are constrained to the paired,-SSRF-validated backend and an explicit management API allowlist.-"""--from __future__ import annotations--import base64-import hashlib-import http.client-import json-import re-import secrets-import threading-import time-import urllib.parse-from collections import OrderedDict-from dataclasses import dataclass-from typing import Any, Mapping, Sequence--import jwt--from config.v2_config import V2Config-from vibe import remote_access---MANAGEMENT_AUDIENCE = "avibe-organization-api"-MANAGEMENT_SCOPES = (- "organization:read",- "organization:manage",- "instance:read",- "instance:manage",- "project:read",- "project:manage",- "resource:read",- "resource:manage",-)-MANAGEMENT_SCOPE = " ".join(MANAGEMENT_SCOPES)-MANAGEMENT_TOKEN_MAX_TTL_SECONDS = 600-HANDSHAKE_TTL_SECONDS = 300-MAX_HANDSHAKES = 512-MAX_GRANTS = 2048-MAX_RESPONSE_BYTES = 2 * 1024 * 1024-MAX_REQUEST_BYTES = 1024 * 1024--HANDLE_COOKIE_NAME = "vibe_cloud_management"-BROWSER_COOKIE_NAME = "vibe_cloud_management_browser"-MANUAL_COOKIE_NAME = "vibe_cloud_management_manual"---@dataclass(frozen=True)-class ManagementHandshake:- state: str- browser_id: str- expected_subject: str | None- code_verifier: str- nonce: str- redirect_uri: str- next_path: str- silent: bool- expires_at: float---@dataclass(frozen=True)-class ManagementGrant:- handle: str- browser_id: str- subject: str- email: str- token: str- expires_at: float---class CloudManagementError(RuntimeError):- def __init__(self, code: str, *, status: int = 503, retryable: bool = False) -> None:- super().__init__(code)- self.code = code- self.status = status- self.retryable = retryable---class CloudResponseError(RuntimeError):- def __init__(self, status: int, payload: dict[str, Any]) -> None:- super().__init__(str(payload.get("error") or "cloud_management_upstream_error"))- self.status = status- self.payload = payload---_lock = threading.RLock()-_handshakes: OrderedDict[str, ManagementHandshake] = OrderedDict()-_grants: OrderedDict[str, ManagementGrant] = OrderedDict()-_browser_subjects: OrderedDict[str, str] = OrderedDict()---def _token(size: int = 32) -> str:- return secrets.token_urlsafe(size)---def _b64url_digest(value: str) -> str:- digest = hashlib.sha256(value.encode("ascii")).digest()- return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")---def _prune_locked(now: float) -> None:- for state, handshake in list(_handshakes.items()):- if handshake.expires_at <= now:- _handshakes.pop(state, None)- for handle, grant in list(_grants.items()):- if grant.expires_at <= now:- _grants.pop(handle, None)- while len(_handshakes) > MAX_HANDSHAKES:- _handshakes.popitem(last=False)- while len(_grants) > MAX_GRANTS:- _grants.popitem(last=False)- while len(_browser_subjects) > MAX_GRANTS:- _browser_subjects.popitem(last=False)---def reset_for_tests() -> None:- """Clear process-owned state; tests must never share grants or handshakes."""- with _lock:- _handshakes.clear()- _grants.clear()- _browser_subjects.clear()---def cloud_is_configured(config: V2Config | None) -> bool:- if config is None:- return False- cloud = config.remote_access.vibe_cloud- return bool(- cloud.enabled- and cloud.backend_url- and cloud.instance_id- and cloud.client_id- and cloud.issuer- and cloud.jwks_uri- and cloud.public_url- )---def validate_next_path(value: object) -> str:- path = str(value or "/admin/organization/overview")- parsed = urllib.parse.urlsplit(path)- is_organization_path = parsed.path == "/admin/organization" or parsed.path.startswith(- "/admin/organization/"- )- is_workbench_chat = re.fullmatch(r"/chat/[^/]+", parsed.path) is not None- if parsed.scheme or parsed.netloc or not (is_organization_path or is_workbench_chat):- return "/admin/organization/overview"- return urllib.parse.urlunsplit(("", "", parsed.path, parsed.query, ""))---def new_browser_id() -> str:- return _token(24)---def _bound_subject(browser_id: str) -> str | None:- with _lock:- subject = _browser_subjects.get(browser_id)- if subject is not None:- _browser_subjects.move_to_end(browser_id)- return subject---def authorization_subject(- browser_id: str | None,- remote_subject: str | None,-) -> str | None:- """Return the subject that can safely bind a management authorization."""- return remote_subject or (_bound_subject(browser_id) if browser_id else None)---def can_silent_reauthorize(- browser_id: str | None,- remote_subject: str | None,-) -> bool:- """Silent authorization is safe only when it cannot switch Cloud users."""- return authorization_subject(browser_id, remote_subject) is not None---def begin_authorization(- config: V2Config,- *,- browser_id: str,- remote_subject: str | None,- callback_origin: str,- next_path: str,- silent: bool,-) -> tuple[str, str]:- if not cloud_is_configured(config):- raise CloudManagementError("cloud_management_not_connected", status=409)- backend = _validated_backend(config)- verifier = _token(48)- state = _token(32)- nonce = _token(24)- redirect_uri = f"{callback_origin.rstrip('/')}/auth/organization/callback"- expected_subject = authorization_subject(browser_id, remote_subject)- if silent and expected_subject is None:- raise CloudManagementError(- "cloud_management_authorization_required",- status=401,- )- handshake = ManagementHandshake(- state=state,- browser_id=browser_id,- expected_subject=expected_subject,- code_verifier=verifier,- nonce=nonce,- redirect_uri=redirect_uri,- next_path=validate_next_path(next_path),- silent=silent,- expires_at=time.time() + HANDSHAKE_TTL_SECONDS,- )- with _lock:- _prune_locked(time.time())- _handshakes[state] = handshake- _handshakes.move_to_end(state)- _prune_locked(time.time())- return _authorization_url(config, backend.base_url, handshake), state---def _authorization_url(config: V2Config, backend_url: str, handshake: ManagementHandshake) -> str:- params = {- "client_id": config.remote_access.vibe_cloud.client_id,- "redirect_uri": handshake.redirect_uri,- "response_type": "code",- "scope": MANAGEMENT_SCOPE,- "state": handshake.state,- "nonce": handshake.nonce,- "code_challenge": _b64url_digest(handshake.code_verifier),- "code_challenge_method": "S256",- }- if handshake.silent:- params["prompt"] = "none"- return f"{backend_url}/oauth/management/authorize?{urllib.parse.urlencode(params)}"---def handshake_for_handoff(state: str) -> ManagementHandshake | None:- with _lock:- _prune_locked(time.time())- handshake = _handshakes.get(state)- if handshake is not None:- _handshakes.move_to_end(state)- return handshake---def authorization_url_for_handoff(- config: V2Config, state: str, browser_id: str | None-) -> tuple[str, str] | None:- handshake = handshake_for_handoff(state)- if handshake is None or (- browser_id is not None and not secrets.compare_digest(handshake.browser_id, browser_id)- ):- return None- return _authorization_url(config, _validated_backend(config).base_url, handshake), handshake.browser_id---def handshake_next_path(state: str | None, browser_id: str | None) -> str | None:- """Return a handshake's safe next path only to its bound browser."""- if not state or not browser_id:- return None- handshake = handshake_for_handoff(state)- if handshake is None or not secrets.compare_digest(handshake.browser_id, browser_id):- return None- return validate_next_path(handshake.next_path)---def pop_handshake(state: str) -> ManagementHandshake | None:- with _lock:- _prune_locked(time.time())- return _handshakes.pop(state, None)---def fail_handshake(state: str | None) -> str:- if not state:- return "/admin/organization/overview"- handshake = pop_handshake(state)- return handshake.next_path if handshake is not None else "/admin/organization/overview"---def callback_owns_flow(state: str | None, browser_id: str | None) -> bool:- """Whether a callback proves it belongs to *browser_id*'s own handshake.-- The OAuth callback is intentionally unauthenticated and CSRF-exempt, and the- management cookies are ``SameSite=Lax``, so any site can drive a top-level- navigation to it with attacker-chosen ``state`` / ``code`` / ``error`` and- have the victim's cookies attached. A failure on such a callback says- nothing about the browser's existing grant, so only a live handshake bound- to this exact browser authorizes tearing that grant down. This peeks- without consuming, so an unrelated callback also cannot pop a genuine- pending handshake out from under a real login.- """-- if not state or not browser_id:- return False- handshake = handshake_for_handoff(state)- return handshake is not None and secrets.compare_digest(handshake.browser_id, browser_id)---def complete_authorization(- config: V2Config,- *,- state: str,- code: str,- browser_id: str,- remote_subject: str | None,-) -> tuple[ManagementGrant, str]:- handshake = pop_handshake(state)- if handshake is None or not secrets.compare_digest(handshake.browser_id, browser_id):- raise CloudManagementError("invalid_cloud_management_state", status=400)- if not code:- raise CloudManagementError("invalid_cloud_management_code", status=400)- token_status, payload = _backend_request(- config,- "POST",- "/oauth/management/token",- form_body={- "grant_type": "authorization_code",- "client_id": config.remote_access.vibe_cloud.client_id,- "redirect_uri": handshake.redirect_uri,- "code": code,- "code_verifier": handshake.code_verifier,- },- )- if token_status < 200 or token_status >= 300:- raise CloudManagementError("invalid_cloud_management_code", status=400)- token = str(payload.get("access_token") or "")- claims = _validate_management_token(config, token)- subject = str(claims.get("sub") or "")- email = str(claims.get("email") or "")- response_subject = str(payload.get("subject") or "")- response_instance = str(payload.get("vibe_instance_id") or "")- 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 != subject- or response_instance != config.remote_access.vibe_cloud.instance_id- or str(claims.get("vibe_instance_id") or "") != config.remote_access.vibe_cloud.instance_id- or subject_mismatch- ):- 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"])- grant = ManagementGrant(- handle=_token(32),- browser_id=browser_id,- subject=subject,- email=email,- token=token,- expires_at=expires_at,- )- with _lock:- _prune_locked(time.time())- for handle, existing in list(_grants.items()):- if existing.browser_id == browser_id:- _grants.pop(handle, None)- _grants[grant.handle] = grant- _browser_subjects[browser_id] = subject- _browser_subjects.move_to_end(browser_id)- _prune_locked(time.time())- return grant, handshake.next_path---def resolve_grant(- handle: str | None,- browser_id: str | None,- remote_subject: str | None,-) -> tuple[ManagementGrant | None, str | None]:- if not handle or not browser_id:- return None, None- with _lock:- _prune_locked(time.time())- grant = _grants.get(handle)- if grant is None or not secrets.compare_digest(grant.browser_id, browser_id):- return None, None- if remote_subject is not None and not secrets.compare_digest(grant.subject, remote_subject):- _grants.pop(handle, None)- return None, "cloud_management_subject_mismatch"- _grants.move_to_end(handle)- return grant, None---def invalidate_grant(- handle: str | None,- *,- browser_id: str | None = None,- clear_subject: bool = False,-) -> None:- with _lock:- grant = _grants.pop(handle, None) if handle else None- if clear_subject:- bound_browser_id = grant.browser_id if grant is not None else browser_id- if bound_browser_id:- _browser_subjects.pop(bound_browser_id, None)---def proxy_request(- config: V2Config,- *,- grant: ManagementGrant,- method: str,- upstream_path: str,- query: Sequence[tuple[str, str]],- json_body: Any | None,-) -> tuple[int, dict[str, Any]]:- if not proxy_path_allowed(method, upstream_path):- raise CloudManagementError("cloud_management_route_not_allowed", status=404)- return _backend_request(- config,- method,- upstream_path,- query=query,- json_body=json_body,- bearer_token=grant.token,- )---_PROXY_RULES: tuple[tuple[str, str], ...] = (- ("GET", r"/api/organizations"),- ("GET|PATCH", r"/api/organizations/[^/]+"),- ("GET|POST", r"/api/organizations/[^/]+/members"),- ("GET", r"/api/organizations/[^/]+/members/export"),- ("PATCH", r"/api/organizations/[^/]+/members/[^/]+"),- ("POST", r"/api/organizations/[^/]+/members/[^/]+/resend-invite"),- ("GET|POST", r"/api/organizations/[^/]+/groups"),- ("GET|PATCH|DELETE", r"/api/organizations/[^/]+/groups/[^/]+"),- ("PUT", r"/api/organizations/[^/]+/groups/[^/]+/members"),- ("GET", r"/api/organizations/[^/]+/instances"),- ("GET", r"/api/organizations/[^/]+/resources"),- ("GET|PATCH", r"/api/organizations/[^/]+/resources/[^/]+/[^/]+/[^/]+/access"),- ("GET|POST|PUT|DELETE", r"/api/instances/[^/]+/authorized-users"),- ("GET", r"/api/instances/[^/]+/projects"),- ("GET|PUT", r"/api/instances/[^/]+/projects/[^/]+/access"),-)---def proxy_path_allowed(method: str, path: str) -> bool:- import re-- if "%" in path or "//" in path or ".." in path:- return False- return any(re.fullmatch(methods, method.upper()) and re.fullmatch(pattern, path) for methods, pattern in _PROXY_RULES)---def _validated_backend(config: V2Config) -> Any:- backend, error = remote_access._normalize_pairing_backend_url( # noqa: SLF001- config.remote_access.vibe_cloud.backend_url- )- if error or backend is None:- raise CloudManagementError("cloud_management_backend_invalid", status=503)- return backend---def _backend_request(- config: V2Config,- method: str,- path: str,- *,- query: Sequence[tuple[str, str]] = (),- json_body: Any | None = None,- form_body: Mapping[str, str] | None = None,- bearer_token: str | None = None,-) -> tuple[int, dict[str, Any]]:- backend = _validated_backend(config)- if not path.startswith("/") or "#" in path:- raise CloudManagementError("cloud_management_route_not_allowed", status=404)- encoded_query = urllib.parse.urlencode(list(query), doseq=True)- url = f"{backend.base_url}{path}"- if encoded_query:- url = f"{url}?{encoded_query}"- parsed = urllib.parse.urlsplit(url)- target_path = urllib.parse.urlunsplit(("", "", parsed.path, parsed.query, ""))- headers = {- "Accept": "application/json",- "Host": backend.host_header,- "User-Agent": "avibe/dev",- }- body: bytes | None = None- if json_body is not None:- body = json.dumps(json_body, separators=(",", ":")).encode("utf-8")- headers["Content-Type"] = "application/json"- elif form_body is not None:- body = urllib.parse.urlencode(form_body).encode("ascii")- headers["Content-Type"] = "application/x-www-form-urlencoded"- if body is not None and len(body) > MAX_REQUEST_BYTES:- raise CloudManagementError("cloud_management_request_too_large", status=413)- if bearer_token:- headers["Authorization"] = f"Bearer {bearer_token}"- proxy_url = remote_access._validated_backend_proxy_url(url) # noqa: SLF001- if backend.requires_proxy and not proxy_url:- raise CloudManagementError("cloud_management_unavailable", retryable=True)- last_error: Exception | None = None- for connect_host in backend.connect_hosts:- connection: http.client.HTTPConnection | None = None- try:- connection = remote_access._validated_backend_connection( # noqa: SLF001- connect_host, backend, 20.0, proxy_url- )- connection.connect()- except (OSError, http.client.HTTPException) as exc:- last_error = exc- if connection is not None:- connection.close()- continue- try:- connection.request(method.upper(), target_path, body=body, headers=headers)- response = connection.getresponse()- response_body = response.read(MAX_RESPONSE_BYTES + 1)- if len(response_body) > MAX_RESPONSE_BYTES:- raise CloudManagementError("cloud_management_response_too_large")- if 300 <= response.status < 400:- raise CloudManagementError("cloud_management_redirect_blocked")- content_type = (response.getheader("Content-Type") or "").split(";", 1)[0].strip().lower()- if content_type != "application/json" and not content_type.endswith("+json"):- raise CloudManagementError("cloud_management_invalid_response")- try:- payload = json.loads(response_body.decode("utf-8"))- except (UnicodeDecodeError, ValueError) as exc:- raise CloudManagementError("cloud_management_invalid_response") from exc- if not isinstance(payload, dict):- raise CloudManagementError("cloud_management_invalid_response")- return response.status, payload- except CloudManagementError:- raise- except (OSError, http.client.HTTPException) as exc:- raise CloudManagementError(- "cloud_management_unavailable",- retryable=True,- ) from exc- finally:- connection.close()- raise CloudManagementError("cloud_management_unavailable", retryable=True) from last_error---def _validate_management_token(config: V2Config, token: str) -> dict[str, Any]:- if not token:- raise CloudManagementError("invalid_cloud_management_token", status=400)- cloud = config.remote_access.vibe_cloud- try:- header = jwt.get_unverified_header(token)- kid = str(header.get("kid") or "")- jwks_path = _same_backend_path(config, cloud.jwks_uri)- _, jwks = _backend_request(config, "GET", jwks_path)- key_data = next(- key- for key in jwks.get("keys", [])- if isinstance(key, dict) and str(key.get("kid") or "") == kid- )- signing_key = jwt.PyJWK.from_dict(key_data).key- claims = jwt.decode(- token,- signing_key,- algorithms=["RS256"],- audience=MANAGEMENT_AUDIENCE,- issuer=cloud.issuer,- leeway=5,- )- issued_at = int(claims["iat"])- expires_at = int(claims["exp"])- scopes = set(str(claims.get("scope") or "").split())- if (- not str(claims.get("sub") or "")- or not str(claims.get("email") or "")- or not str(claims.get("jti") or "")- or expires_at <= time.time()- or expires_at - issued_at > MANAGEMENT_TOKEN_MAX_TTL_SECONDS- or not set(MANAGEMENT_SCOPES).issubset(scopes)- ):- raise ValueError("invalid management claims")- return claims- except CloudManagementError:- raise- except Exception as exc:- raise CloudManagementError("invalid_cloud_management_token", status=400) from exc---def _same_backend_path(config: V2Config, absolute_url: str) -> str:- backend = _validated_backend(config)- parsed = urllib.parse.urlsplit(absolute_url)- expected = urllib.parse.urlsplit(backend.base_url)- if (- parsed.scheme.lower() != "https"- or (parsed.hostname or "").rstrip(".").lower() != backend.hostname- or (parsed.port or 443) != backend.port- or parsed.username- or parsed.password- or parsed.fragment- ):- raise CloudManagementError("invalid_cloud_management_token", status=400)- base_path = expected.path.rstrip("/")- if base_path and parsed.path != base_path and not parsed.path.startswith(f"{base_path}/"):- raise CloudManagementError("invalid_cloud_management_token", status=400)- relative_path = parsed.path[len(base_path) :] if base_path else parsed.path- relative_path = relative_path or "/"- if parsed.query:- relative_path = f"{relative_path}?{parsed.query}"- return relative_pathdiff --git a/vibe/permissions.py b/vibe/permissions.pynew file mode 100644index 000000000..bdb11f61a--- /dev/null+++ b/vibe/permissions.py@@ -0,0 +1,278 @@+"""Current paired-instance Permissions client and offline projection cache."""++from __future__ import annotations++from dataclasses import dataclass+import json+import logging+import os+from pathlib import Path+import tempfile+import time+from typing import Any, Mapping+from urllib.parse import quote++import requests++from config import paths+from config.v2_config import V2Config+++CACHE_SCHEMA_VERSION = 1+CACHE_FILENAME = "permissions_projection.json"+DEFAULT_TIMEOUT_SECONDS = 8.0+_SENSITIVE_KEY_PARTS = ("secret", "token", "credential")+logger = logging.getLogger(__name__)+++class PermissionsError(RuntimeError):+ """Base error for the local Permissions boundary."""+++class PermissionsNotPairedError(PermissionsError):+ pass+++class PermissionsUnavailableError(PermissionsError):+ pass+++class PermissionsInvalidResponseError(PermissionsError):+ pass+++class PermissionsBackendError(PermissionsError):+ def __init__(self, status: int, payload: Mapping[str, Any] | None = None):+ self.status = status+ self.payload = _error_payload(payload)+ super().__init__(str(self.payload["error"]))+++@dataclass(frozen=True)+class PermissionsProjectionResult:+ projection: dict[str, Any]+ source: str+ cached_at: int | None = None++ @property+ def offline(self) -> bool:+ return self.source == "cache"+++def _error_payload(payload: Mapping[str, Any] | None) -> dict[str, Any]:+ code = payload.get("error") if isinstance(payload, Mapping) else None+ result: dict[str, Any] = {+ "error": code if isinstance(code, str) and code else "permissions_backend_rejected"+ }+ revision = payload.get("current_revision") if isinstance(payload, Mapping) else None+ if isinstance(revision, int) and not isinstance(revision, bool) and revision >= 0:+ result["current_revision"] = revision+ return result+++def _strip_sensitive(value: Any) -> Any:+ if isinstance(value, Mapping):+ return {+ str(key): _strip_sensitive(item)+ for key, item in value.items()+ if not any(part in str(key).lower() for part in _SENSITIVE_KEY_PARTS)+ }+ if isinstance(value, list):+ return [_strip_sensitive(item) for item in value]+ if value is None or isinstance(value, (str, int, float, bool)):+ return value+ raise PermissionsInvalidResponseError("permissions_backend_invalid_response")+++def _validated_projection(payload: Any, instance_id: str) -> dict[str, Any]:+ if not isinstance(payload, Mapping):+ raise PermissionsInvalidResponseError("permissions_backend_invalid_response")+ sanitized = _strip_sensitive(payload)+ if not isinstance(sanitized, dict) or sanitized.get("schema_version") != 1:+ raise PermissionsInvalidResponseError("permissions_backend_invalid_response")+ instance = sanitized.get("instance")+ if not isinstance(instance, dict) or instance.get("id") != instance_id:+ raise PermissionsInvalidResponseError("permissions_instance_mismatch")+ if instance.get("permission_authority") not in {"instance", "cloud"}:+ raise PermissionsInvalidResponseError("permissions_backend_invalid_response")+ if not isinstance(instance.get("local_mutation_allowed"), bool):+ raise PermissionsInvalidResponseError("permissions_backend_invalid_response")+ revision = instance.get("authorization_revision")+ if not isinstance(revision, int) or isinstance(revision, bool) or revision < 0:+ raise PermissionsInvalidResponseError("permissions_backend_invalid_response")+ for key in ("capabilities", "access", "directory", "projects", "policy_sync"):+ if key not in sanitized:+ raise PermissionsInvalidResponseError("permissions_backend_invalid_response")+ return sanitized+++def _runtime_credentials(config: V2Config) -> tuple[str, str, str]:+ credentials = config.remote_access.vibe_cloud.runtime_credentials()+ if credentials is None:+ raise PermissionsNotPairedError("permissions_not_paired")+ return credentials+++def _cache_path() -> Path:+ return paths.get_state_dir() / CACHE_FILENAME+++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,+ }+ fd, temporary_name = tempfile.mkstemp(+ dir=cache_path.parent,+ prefix=f".{cache_path.name}.",+ )+ try:+ os.fchmod(fd, 0o600)+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ fd = -1+ json.dump(envelope, handle, ensure_ascii=True, separators=(",", ":"))+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary_name, cache_path)+ finally:+ if fd >= 0:+ os.close(fd)+ try:+ os.unlink(temporary_name)+ except FileNotFoundError:+ pass+++def _read_cache(instance_id: str) -> PermissionsProjectionResult | None:+ try:+ envelope = json.loads(_cache_path().read_text(encoding="utf-8"))+ except (FileNotFoundError, OSError, json.JSONDecodeError):+ return None+ if not isinstance(envelope, dict):+ return None+ if envelope.get("cache_schema_version") != CACHE_SCHEMA_VERSION:+ return None+ if envelope.get("instance_id") != instance_id:+ return None+ cached_at = envelope.get("cached_at")+ if not isinstance(cached_at, int) or isinstance(cached_at, bool) or cached_at < 0:+ return None+ try:+ projection = _validated_projection(envelope.get("projection"), instance_id)+ except PermissionsInvalidResponseError:+ return None+ return PermissionsProjectionResult(+ projection=projection,+ source="cache",+ cached_at=cached_at,+ )+++def _backend_request(+ config: V2Config,+ method: str,+ suffix: str,+ payload: Mapping[str, Any] | None = None,+ *,+ timeout: float = DEFAULT_TIMEOUT_SECONDS,+) -> tuple[dict[str, Any], str]:+ backend_url, instance_id, instance_secret = _runtime_credentials(config)+ endpoint = (+ f"{backend_url}/api/v1/instances/{quote(instance_id, safe='')}/permissions"+ f"/{suffix.lstrip('/')}"+ if suffix+ else f"{backend_url}/api/v1/instances/{quote(instance_id, safe='')}/permissions"+ )+ try:+ response = requests.request(+ method,+ endpoint,+ json=dict(payload) if payload is not None else None,+ headers={+ "Accept": "application/json",+ "Content-Type": "application/json",+ "User-Agent": "avibe/dev",+ "X-Vibe-Device-Secret": instance_secret,+ },+ timeout=timeout,+ allow_redirects=False,+ )+ except requests.RequestException as exc:+ raise PermissionsUnavailableError("permissions_backend_unavailable") from exc+ if 300 <= response.status_code < 400:+ raise PermissionsInvalidResponseError("permissions_backend_redirect_blocked")+ try:+ parsed = response.json()+ except ValueError as exc:+ if response.status_code >= 500:+ raise PermissionsUnavailableError("permissions_backend_unavailable") from exc+ raise PermissionsInvalidResponseError("permissions_backend_invalid_response") from exc+ if not isinstance(parsed, dict):+ raise PermissionsInvalidResponseError("permissions_backend_invalid_response")+ if not response.ok:+ raise PermissionsBackendError(response.status_code, parsed)+ return parsed, instance_id+++def get_current_permissions(config: V2Config | None = None) -> PermissionsProjectionResult:+ config = config or V2Config.load()+ _, instance_id, _ = _runtime_credentials(config)+ try:+ payload, _ = _backend_request(config, "GET", "")+ projection = _validated_projection(payload, instance_id)+ try:+ _write_cache(instance_id, projection)+ except OSError:+ logger.warning("Unable to cache the current Permissions projection", exc_info=True)+ return PermissionsProjectionResult(projection=projection, source="live")+ except PermissionsUnavailableError:+ cached = _read_cache(instance_id)+ if cached is not None:+ return cached+ raise+ except PermissionsBackendError as exc:+ if exc.status >= 500:+ cached = _read_cache(instance_id)+ if cached is not None:+ return cached+ raise+++def replace_authorized_users(+ payload: Mapping[str, Any],+ config: V2Config | None = None,+) -> dict[str, Any]:+ config = config or V2Config.load()+ result, _ = _backend_request(config, "PUT", "authorized-users", payload)+ return result+++def update_project_access(+ project_id: str,+ payload: Mapping[str, Any],+ config: V2Config | None = None,+) -> dict[str, Any]:+ if not isinstance(project_id, str) or not project_id or "/" in project_id:+ raise PermissionsInvalidResponseError("invalid_project_id")+ config = config or V2Config.load()+ result, _ = _backend_request(+ config,+ "PUT",+ f"projects/{quote(project_id, safe='')}/access",+ payload,+ )+ return result+++def response_payload(result: PermissionsProjectionResult) -> dict[str, Any]:+ return {+ "ok": True,+ "source": result.source,+ "offline": result.offline,+ "cached_at": result.cached_at,+ "projection": result.projection,+ }diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex b81c74e04..82f86e7c5 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -579,8 +579,6 @@ def _trusted_public_origin_local_request(config: V2Config | None) -> bool:def _is_mutation_guard_exempt() -> bool:if request.path in {"/auth/callback",- "/auth/organization/callback",- "/auth/organization/start","/auth/show-identity/callback",}:return True@@ -1577,8 +1575,6 @@ def _remote_auth_exempt_path() -> bool:path == "/health"or path == "/auth/login"or path == "/auth/callback"- or path == "/auth/organization/callback"- or path == "/auth/organization/start"or path == "/auth/show-identity/callback"or path == "/auth/logout"or path == "/api/session"@@ -1602,8 +1598,6 @@ def _remote_auth_exempt_before_host_validation() -> bool:request.pathin {"/auth/callback",- "/auth/organization/callback",- "/auth/organization/start","/auth/logout","/api/session","/api/csrf-token",@@ -2626,14 +2620,6 @@ def enforce_instance_role_capabilities():except (LookupError, RuntimeError):# This helper is also exercised by pure policy tests outside a request.context = None- # Cloud-management routes re-establish identity themselves (OAuth handshake,- # silent reauthorization). They must admit an authenticated remote principal- # who is not yet an active Organization member, so they bypass the- # Organization-admitted-identity role gate; each handler re-validates cloud- # identity before acting.- is_identity_bootstrap_path = request.path.startswith("/api/cloud-management/")- if is_identity_bootstrap_path:- return Nonetry:if context is None:raise InstanceAuthorizationError(minimum_role)@@ -2649,6 +2635,128 @@ def enforce_instance_role_capabilities():return None+def _permissions_error_response(error: Exception):+ from vibe import permissions++ if isinstance(error, permissions.PermissionsNotPairedError):+ return jsonify({"ok": False, "error": "permissions_not_paired"}), 409+ if isinstance(error, permissions.PermissionsUnavailableError):+ return jsonify(+ {"ok": False, "error": "permissions_unavailable", "offline": True}+ ), 503+ if isinstance(error, permissions.PermissionsBackendError):+ return jsonify({"ok": False, **error.payload}), error.status+ if isinstance(error, permissions.PermissionsInvalidResponseError):+ return jsonify({"ok": False, "error": str(error)}), 502+ logger.warning("Permissions request failed: %s", error.__class__.__name__)+ return jsonify({"ok": False, "error": "permissions_unavailable"}), 503+++def _permissions_mutation_payload(+ payload: Any,+ allowed_keys: set[str],+ item_shapes: dict[str, frozenset[str]],+):+ if not isinstance(payload, dict) or set(payload) != allowed_keys:+ return None+ for field, allowed_item_keys in item_shapes.items():+ items = payload.get(field)+ if not isinstance(items, list) or any(+ not isinstance(item, dict) or set(item) != allowed_item_keys+ for item in items+ ):+ return None+ return payload++[email protected]("/api/permissions", include_in_schema=False)+async def current_instance_permissions_get(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_current_permissions)+ return jsonify(permissions.response_payload(result))+ except Exception as error:+ return _permissions_error_response(error)++ return await _dispatch_native_ui_request(starlette_request, handler)++[email protected]("/api/permissions/authorized-users", include_in_schema=False)+async def current_instance_permissions_authorized_users_put(+ 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 = _permissions_mutation_payload(+ raw_payload,+ {"entries", "if_match_revision"},+ {"entries": frozenset({"kind", "value", "role"})},+ )+ if payload is None:+ return jsonify({"ok": False, "error": "invalid_request"}), 422+ try:+ result = await asyncio.to_thread(permissions.replace_authorized_users, payload)+ return jsonify(result)+ except Exception as error:+ return _permissions_error_response(error)++ return await _dispatch_native_ui_request(starlette_request, handler)++[email protected]("/api/permissions/projects/{project_id}/access", include_in_schema=False)+async def current_instance_permissions_project_access_put(+ project_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 = _permissions_mutation_payload(+ raw_payload,+ {"mode", "bindings", "if_match_revision"},+ {+ "bindings": frozenset(+ {"principal_kind", "principal_value", "access_role"}+ )+ },+ )+ if payload is None:+ return jsonify({"ok": False, "error": "invalid_request"}), 422+ try:+ result = await asyncio.to_thread(+ permissions.update_project_access,+ project_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/([^/]+)(?:/.*)?$")),@@ -6483,477 +6591,6 @@ def remote_access_optimize_route():return jsonify(result), 202 if result.get("ok") else 409-def _cloud_management_subject(config: V2Config | None) -> str | None:- payload = getattr(g, "remote_session_payload", None)- if payload is None and config is not None and _is_remote_access_request(config):- payload = _resolved_remote_session_payload(config)- subject = payload.get("sub") if isinstance(payload, Mapping) else None- return subject if isinstance(subject, str) and subject else None---def _cloud_management_callback_origin(config: V2Config) -> str | None:- if _is_remote_access_request(config):- origin = _remote_access_request_origin(config)- else:- origin = _remote_access_public_origin(config)- return origin if origin and urlsplit(origin).scheme == "https" else None---def _cloud_management_json(payload: dict[str, Any], status: int = 200) -> Response:- response = jsonify(payload)- response.status_code = status- response.headers["Cache-Control"] = "no-store, private"- return response---def _cloud_management_cookie_secure() -> bool:- return urlsplit(_current_origin()).scheme.lower() == "https"---def _set_cloud_management_cookie(- response: Response,- name: str,- value: str,- *,- max_age: int,-) -> None:- response.set_cookie(- name,- value,- max_age=max_age,- httponly=True,- secure=_cloud_management_cookie_secure(),- samesite="Lax",- path="/",- )---def _delete_cloud_management_cookie(response: Response, name: str) -> None:- response.delete_cookie(- name,- path="/",- secure=_cloud_management_cookie_secure(),- samesite="Lax",- )---def _mark_cloud_management_manual(response: Response) -> None:- from vibe import cloud_management-- _set_cloud_management_cookie(- response,- cloud_management.MANUAL_COOKIE_NAME,- secrets.token_urlsafe(16),- max_age=180 * 24 * 60 * 60,- )---def _cloud_management_error_response(error: Exception) -> Response:- from vibe import cloud_management-- if isinstance(error, cloud_management.CloudManagementError):- return _cloud_management_json(- {"error": error.code, "retryable": error.retryable},- error.status,- )- logger.warning("Cloud management request failed: %s", error.__class__.__name__)- return _cloud_management_json(- {"error": "cloud_management_unavailable", "retryable": True},- 503,- )---def _cloud_management_redirect(next_path: str, error: str | None = None) -> Response:- target = urlsplit(next_path)- params = list(parse_qsl(target.query, keep_blank_values=True))- if error:- params.append(("cloud_management_error", error))- location = urlunsplit(("", "", target.path, urlencode(params), ""))- response = redirect(location)- response.headers["Cache-Control"] = "no-store, private"- return response--[email protected]("/api/cloud-management/session", methods=["GET"])-def cloud_management_session_get():- from vibe import cloud_management-- config = _load_remote_access_config()- if not cloud_management.cloud_is_configured(config):- return _cloud_management_json(- {"connected": False, "state": "cloud_not_connected"}- )- handle = request.cookies.get(cloud_management.HANDLE_COOKIE_NAME)- browser_id = request.cookies.get(cloud_management.BROWSER_COOKIE_NAME)- remote_subject = _cloud_management_subject(config)- grant, error = cloud_management.resolve_grant(- handle,- browser_id,- remote_subject,- )- if error:- response = _cloud_management_json(- {"connected": False, "state": "subject_mismatch", "error": error},- 409,- )- _delete_cloud_management_cookie(response, cloud_management.HANDLE_COOKIE_NAME)- _mark_cloud_management_manual(response)- return response- if grant is None:- manual = bool(request.cookies.get(cloud_management.MANUAL_COOKIE_NAME))- return _cloud_management_json(- {- "connected": False,- "state": "authorization_required",- "can_silent_reauthorize": (- not manual- and cloud_management.can_silent_reauthorize(- browser_id,- remote_subject,- )- ),- }- )- return _cloud_management_json(- {- "connected": True,- "state": "connected",- "user": {"subject": grant.subject, "email": grant.email},- "expires_in": max(0, int(grant.expires_at - time.time())),- }- )--[email protected]("/api/cloud-management/session/start", methods=["POST"])-def cloud_management_session_start():- from vibe import cloud_management-- config = _load_remote_access_config()- if config is None:- return _cloud_management_json(- {"error": "cloud_management_not_connected", "retryable": False},- 409,- )- payload = request.json if isinstance(request.json, dict) else {}- silent = payload.get("mode") == "silent"- if silent and request.cookies.get(cloud_management.MANUAL_COOKIE_NAME):- return _cloud_management_json(- {"error": "cloud_management_authorization_required", "retryable": False},- 401,- )- browser_id = request.cookies.get(cloud_management.BROWSER_COOKIE_NAME)- remote_subject = _cloud_management_subject(config)- if silent and not cloud_management.can_silent_reauthorize(- browser_id,- remote_subject,- ):- return _cloud_management_json(- {"error": "cloud_management_authorization_required", "retryable": False},- 401,- )- if not browser_id:- browser_id = cloud_management.new_browser_id()- callback_origin = _cloud_management_callback_origin(config)- if callback_origin is None:- return _cloud_management_json(- {"error": "cloud_management_not_connected", "retryable": False},- 409,- )- try:- authorize_url, state = cloud_management.begin_authorization(- config,- browser_id=browser_id,- remote_subject=remote_subject,- callback_origin=callback_origin,- next_path=cloud_management.validate_next_path(payload.get("next")),- silent=silent,- )- except Exception as exc:- return _cloud_management_error_response(exc)- current_origin = _current_origin()- if not _same_origin(callback_origin, current_origin):- authorize_url = (- f"{callback_origin}/auth/organization/start?"- f"{urlencode({'state': state})}"- )- response = _cloud_management_json(- {"ok": True, "authorize_url": authorize_url, "mode": "silent" if silent else "interactive"},- 202,- )- _set_cloud_management_cookie(- response,- cloud_management.BROWSER_COOKIE_NAME,- browser_id,- max_age=180 * 24 * 60 * 60,- )- if not silent:- _delete_cloud_management_cookie(response, cloud_management.MANUAL_COOKIE_NAME)- return response--[email protected]("/auth/organization/start", methods=["GET"])-def cloud_management_authorization_handoff():- from vibe import cloud_management-- config = _load_remote_access_config()- if config is None or not _is_remote_access_request(config):- return _cloud_management_json({"error": "cloud_management_invalid_callback"}, 400)- if _auth_rate_limited():- return _auth_rate_limit_response()- state = str(request.args.get("state") or "")- try:- result = cloud_management.authorization_url_for_handoff(config, state, None)- except Exception as exc:- return _cloud_management_error_response(exc)- if result is None:- response = _cloud_management_redirect(- "/admin/organization/overview",- "invalid_cloud_management_state",- )- _mark_cloud_management_manual(response)- return response- authorize_url, browser_id = result- response = redirect(authorize_url)- response.headers["Cache-Control"] = "no-store, private"- _set_cloud_management_cookie(- response,- cloud_management.BROWSER_COOKIE_NAME,- browser_id,- max_age=180 * 24 * 60 * 60,- )- return response--[email protected]("/auth/organization/callback", methods=["GET"])-def cloud_management_auth_callback():- from vibe import cloud_management-- config = _load_remote_access_config()- if config is None or not _is_remote_access_request(config):- return _cloud_management_json({"error": "cloud_management_invalid_callback"}, 400)- if _auth_rate_limited():- return _auth_rate_limit_response()- state = str(request.args.get("state") or "")- upstream_error = str(request.args.get("error") or "")- browser_id = request.cookies.get(cloud_management.BROWSER_COOKIE_NAME) or ""- # This route is unauthenticated and CSRF-exempt, so a cross-site top-level- # link reaches it with the `SameSite=Lax` management cookies attached. Only- # a callback that resolves to this browser's own live handshake may tear- # down its existing grant; an unrelated or forged one leaves the current- # session exactly as it was instead of forcing a logout.- owns_flow = cloud_management.callback_owns_flow(state, browser_id)- if upstream_error:- if not owns_flow:- return _cloud_management_redirect("/admin/organization/overview", upstream_error)- next_path = cloud_management.fail_handshake(state)- response = _cloud_management_redirect(next_path, upstream_error)- _delete_cloud_management_cookie(response, cloud_management.HANDLE_COOKIE_NAME)- _mark_cloud_management_manual(response)- return response- browser_id = request.cookies.get(cloud_management.BROWSER_COOKIE_NAME) or ""- failure_next_path = (- cloud_management.handshake_next_path(state, browser_id)- or "/admin/organization/overview"- )- try:- grant, next_path = cloud_management.complete_authorization(- config,- state=state,- code=str(request.args.get("code") or ""),- browser_id=browser_id,- remote_subject=_cloud_management_subject(config),- )- except Exception as exc:- code = (- exc.code- if isinstance(exc, cloud_management.CloudManagementError)- else "cloud_management_unavailable"- )- response = _cloud_management_redirect(- failure_next_path,- code,- )- if not owns_flow:- return response- cloud_management.invalidate_grant(- request.cookies.get(cloud_management.HANDLE_COOKIE_NAME)- )- _delete_cloud_management_cookie(response, cloud_management.HANDLE_COOKIE_NAME)- _mark_cloud_management_manual(response)- return response- response = _cloud_management_redirect(next_path)- _set_cloud_management_cookie(- response,- cloud_management.HANDLE_COOKIE_NAME,- grant.handle,- max_age=cloud_management.MANAGEMENT_TOKEN_MAX_TTL_SECONDS,- )- _set_cloud_management_cookie(- response,- cloud_management.BROWSER_COOKIE_NAME,- grant.browser_id,- max_age=180 * 24 * 60 * 60,- )- _delete_cloud_management_cookie(response, cloud_management.MANUAL_COOKIE_NAME)- return response--[email protected]("/api/cloud-management/session", methods=["DELETE"])-def cloud_management_session_delete():- from vibe import cloud_management-- cloud_management.invalidate_grant(- request.cookies.get(cloud_management.HANDLE_COOKIE_NAME),- browser_id=request.cookies.get(cloud_management.BROWSER_COOKIE_NAME),- clear_subject=True,- )- response = _cloud_management_json({"ok": True, "connected": False})- _delete_cloud_management_cookie(response, cloud_management.HANDLE_COOKIE_NAME)- _mark_cloud_management_manual(response)- return response---async def _read_cloud_management_json_body(starlette_request: FastAPIRequest) -> Any:- from vibe import cloud_management-- body = bytearray()- async for chunk in starlette_request.stream():- if len(body) + len(chunk) > cloud_management.MAX_REQUEST_BYTES:- raise cloud_management.CloudManagementError(- "cloud_management_request_too_large",- status=413,- retryable=False,- )- body.extend(chunk)- if not body:- return {}- try:- payload = json.loads(body)- except json.JSONDecodeError as exc:- raise StarletteHTTPException(status_code=400, detail="Malformed JSON") from exc- return {} if payload is None else payload---async def _cloud_management_proxy(- starlette_request: FastAPIRequest,- upstream_path: str,-) -> Response:- from vibe import cloud_management-- config = _load_remote_access_config()- if not cloud_management.cloud_is_configured(config):- return _cloud_management_json(- {"error": "cloud_management_not_connected", "retryable": False},- 409,- )- handle = request.cookies.get(cloud_management.HANDLE_COOKIE_NAME)- browser_id = request.cookies.get(cloud_management.BROWSER_COOKIE_NAME)- remote_subject = _cloud_management_subject(config)- grant, error = cloud_management.resolve_grant(- handle,- browser_id,- remote_subject,- )- if error:- response = _cloud_management_json({"error": error, "retryable": False}, 409)- _delete_cloud_management_cookie(response, cloud_management.HANDLE_COOKIE_NAME)- _mark_cloud_management_manual(response)- return response- if grant is None:- return _cloud_management_json(- {- "error": "cloud_management_authorization_required",- "retryable": False,- "can_silent_reauthorize": (- not bool(request.cookies.get(cloud_management.MANUAL_COOKIE_NAME))- and cloud_management.can_silent_reauthorize(- browser_id,- remote_subject,- )- ),- },- 401,- )- try:- content_length = int(request.headers.get("Content-Length") or "0")- except ValueError:- content_length = cloud_management.MAX_REQUEST_BYTES + 1- if content_length > cloud_management.MAX_REQUEST_BYTES:- return _cloud_management_json(- {"error": "cloud_management_request_too_large", "retryable": False},- 413,- )- try:- body = (- await _read_cloud_management_json_body(starlette_request)- if request.method in MUTATING_METHODS- else None- )- except cloud_management.CloudManagementError as exc:- return _cloud_management_error_response(exc)- try:- status, payload = await asyncio.to_thread(- cloud_management.proxy_request,- config,- grant=grant,- method=request.method,- upstream_path=upstream_path,- query=list(request.args.multi_items()),- json_body=body,- )- except Exception as exc:- return _cloud_management_error_response(exc)- response = _cloud_management_json(payload, status)- if status == 401:- cloud_management.invalidate_grant(handle)- _delete_cloud_management_cookie(response, cloud_management.HANDLE_COOKIE_NAME)- _mark_cloud_management_manual(response)- return response---async def _dispatch_cloud_management_proxy(- starlette_request: FastAPIRequest,- upstream_path: str,-) -> Response:- async def handler() -> Response:- return await _cloud_management_proxy(starlette_request, upstream_path)-- return await app.dispatch_native_request(starlette_request, handler, parse_json=False)--[email protected]("/api/cloud-management/organizations", include_in_schema=False)-async def cloud_management_organizations_root_proxy(starlette_request: FastAPIRequest):- return await _dispatch_cloud_management_proxy(starlette_request, "/api/organizations")--[email protected]_route(- "/api/cloud-management/organizations/{management_path:path}",- methods=["GET", "POST", "PUT", "PATCH", "DELETE"],- include_in_schema=False,-)-async def cloud_management_organizations_proxy(- starlette_request: FastAPIRequest,- management_path: str,-):- return await _dispatch_cloud_management_proxy(- starlette_request,- f"/api/organizations/{management_path}",- )--[email protected]_route(- "/api/cloud-management/instances/{management_path:path}",- methods=["GET", "POST", "PUT", "PATCH", "DELETE"],- include_in_schema=False,-)-async def cloud_management_instances_proxy(- starlette_request: FastAPIRequest,- management_path: str,-):- return await _dispatch_cloud_management_proxy(- starlette_request,- f"/api/instances/{management_path}",- )@app.route("/api/remote-access/network-interfaces", methods=["GET"])def remote_access_network_interfaces():from vibe import remote_access