Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(show-page-acl): single sharing control with heterogeneous limited list (#1592)

Max446798869c30
diff --git a/tests/scenarios/permissions/catalog.yaml b/tests/scenarios/permissions/catalog.yaml
index dab204469..169bf82c1 100644
--- a/tests/scenarios/permissions/catalog.yaml
+++ b/tests/scenarios/permissions/catalog.yaml
@@ -100,7 +100,7 @@ scenarios:
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 remains
+ then: No Management OAuth proxy, embedded Organization route, or Show Page Workspace-access control remains
- id: PERMISSIONS-011
name: Resource ACL round-trips through exact-instance boundary
status: covered
diff --git a/tests/scenarios/permissions/test_permissions_scenarios.py b/tests/scenarios/permissions/test_permissions_scenarios.py
index efaf1b5dd..5da5145a9 100644
--- a/tests/scenarios/permissions/test_permissions_scenarios.py
+++ b/tests/scenarios/permissions/test_permissions_scenarios.py
@@ -220,7 +220,7 @@ def test_permissions_010_legacy_management_surfaces_are_absent() -> None:
show_control = root / "ui" / "src" / "components" / "workbench" / "ShowPageShareControl.tsx"
source = show_control.read_text(encoding="utf-8")
assert "cloud-management" not in source
- assert "ShowPageWorkspaceAccessControl" in source
+ assert "ShowPageWorkspaceAccessControl" not in source
assert "ShowPageSharingSettings" in source
diff --git a/ui/src/components/workbench/ShowPageShareControl.test.tsx b/ui/src/components/workbench/ShowPageShareControl.test.tsx
index 0375da25d..855b2b1ee 100644
--- a/ui/src/components/workbench/ShowPageShareControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.test.tsx
@@ -28,8 +28,6 @@ const api = {
getShowPageAccess: vi.fn(),
getShowAccessSettings: vi.fn(),
applyShowAccess: vi.fn(),
- listOrganizationResources: vi.fn(),
- listOrganizationGroups: vi.fn(),
setShowPageAvailability: vi.fn(),
};
@@ -168,7 +166,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
});
});
- it('keeps Link access usable while Organization access is still loading', async () => {
+ it('gives an Organization page one sharing axis and no Resource policy block', async () => {
const organizationAccess = showPageAccess({
mode: 'organization',
ownership_status: 'unchanged',
@@ -213,13 +211,16 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
fireEvent.click(screen.getByRole('button', { name: 'Share' }));
expect(await screen.findByRole('button', { name: 'Access: Private' })).toBeTruthy();
- expect(screen.getByText('Loading Organization access…')).toBeTruthy();
expect(api.getShowAccessSettings).toHaveBeenCalledWith('ses-1');
- expect(permissionsApi.getPermissions).toHaveBeenCalledOnce();
- expect(permissionsApi.getResourceAccess).toHaveBeenCalledWith({
- resource_kind: 'show_page',
- resource_id: 'ses-1',
- });
+ // The Organization axis and its Resource sync/ACK status are gone.
+ expect(screen.queryByText('Organization access')).toBeNull();
+ expect(screen.queryByText('Loading Organization access…')).toBeNull();
+ expect(screen.queryByText(/has not acknowledged the latest policy/)).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Apply' })).toBeNull();
+ expect(permissionsApi.getResourceAccess).not.toHaveBeenCalled();
+ expect(permissionsApi.updateResourceAccess).not.toHaveBeenCalled();
+ // Private needs no audience, so not even the directory is read.
+ expect(permissionsApi.getPermissions).not.toHaveBeenCalled();
const popover = document.querySelector('.overflow-y-auto');
expect(popover?.classList.contains('max-h-[var(--radix-popover-content-available-height)]')).toBe(true);
});
@@ -354,7 +355,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
expect(screen.queryByDisplayValue(/\/p\/stable-link\/$/)).toBeNull();
});
- it('keeps the online toggle and custom link out while showing Organization access', async () => {
+ it('shares an Organization page through the same Limited audience as any other', async () => {
const organizationAccess = showPageAccess({
mode: 'organization',
ownership_status: 'unchanged',
@@ -365,14 +366,40 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
can_manage: true,
can_publish_public: true,
});
- const pending = new Promise(() => undefined);
- permissionsApi.getPermissions.mockReturnValue(pending);
- permissionsApi.getResourceAccess.mockReturnValue(pending);
+ permissionsApi.getPermissions.mockResolvedValue({
+ ok: true,
+ source: 'live',
+ offline: false,
+ cached_at: null,
+ projection: {
+ schema_version: 1,
+ instance: {
+ id: 'inst-1',
+ organization: { id: 'org-1', name: 'Acme' },
+ access_mode: 'allowlist',
+ permission_authority: 'cloud',
+ local_mutation_allowed: false,
+ authorization_revision: 2,
+ },
+ capabilities: [],
+ access: { owner: { email: null, role: 'owner' }, entries: [] },
+ directory: {
+ members: [],
+ groups: [{ id: 'grp-eng', name: 'Engineering', archived_at: null }],
+ },
+ projects: [],
+ policy_sync: {
+ status: 'in_sync',
+ projects: { active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 },
+ resources: { active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 },
+ },
+ },
+ });
api.getShowPageAccess.mockResolvedValue(organizationAccess);
api.getShowPage.mockResolvedValue({
session_id: 'ses-1',
- visibility: 'private',
- active_url: '/show/ses-1/',
+ visibility: 'limited',
+ active_url: '/p/stable-link/',
share_id: 'stable-link',
url_available: true,
offline: false,
@@ -381,10 +408,14 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
api.getShowAccessSettings.mockResolvedValue({
show_access: {
page_id: 'ses-1',
- access_mode: 'private',
+ access_mode: 'limited',
share_id: 'stable-link',
revision: 0,
- normalized_emails: [],
+ normalized_emails: ['[email protected]'],
+ access_entries: [
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ],
},
});
@@ -399,11 +430,18 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
);
fireEvent.click(screen.getByRole('button', { name: 'Share' }));
- expect(await screen.findByRole('button', { name: 'Access: Private' })).toBeTruthy();
- expect(screen.getByText('Organization access')).toBeTruthy();
- expect(screen.queryByRole('textbox', { name: 'Custom link' })).toBeNull();
- expect(screen.queryByText('Page online')).toBeNull();
- expect(api.setShowPageAvailability).not.toHaveBeenCalled();
+ expect(await screen.findByRole('button', { name: 'Access: Limited' })).toBeTruthy();
+ // Custom-link editing is no longer withheld from Organization pages.
+ expect((screen.getByRole('textbox', { name: 'Custom link' }) as HTMLInputElement).value).toBe(
+ 'stable-link',
+ );
+ // Group, email, and the Organization switch are peers in one audience list.
+ expect(await screen.findByRole('switch', { name: 'This Organization' })).toBeTruthy();
+ expect(screen.getByText('Engineering')).toBeTruthy();
+ expect(screen.getByText('[email protected]')).toBeTruthy();
+ expect(screen.queryByText('Organization access')).toBeNull();
+ expect(permissionsApi.getResourceAccess).not.toHaveBeenCalled();
+ expect(permissionsApi.updateResourceAccess).not.toHaveBeenCalled();
});
it('does not mount Organization access for a normal Personal Avibe', async () => {
@@ -454,7 +492,9 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
expect(permissionsApi.getResourceAccess).not.toHaveBeenCalled();
});
- it('shows a Personal ownership conflict through the Workspace control', async () => {
+ it('does not resurrect an ownership-domain block on a Personal conflict', async () => {
+ // Ownership conflict used to open the Resource-policy control. Sharing no
+ // longer depends on ownership, so the conflict adds no second block at all.
const conflict = showPageAccess({
mode: 'personal',
ownership_status: 'conflict',
@@ -483,10 +523,12 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
);
fireEvent.click(screen.getByRole('button', { name: 'Share' }));
- expect(await screen.findByText('This Show Page is bound to a different ownership domain. Access remains private until the conflict is resolved.')).toBeTruthy();
- expect(screen.queryByText('This Show Page belongs to a Personal Avibe.')).toBeNull();
+ await waitFor(() => expect(api.getShowPage).toHaveBeenCalledWith('ses-1'));
+ expect(screen.queryByText(/bound to a different ownership domain/)).toBeNull();
+ expect(screen.queryByText('Organization access')).toBeNull();
expect(permissionsApi.getPermissions).not.toHaveBeenCalled();
expect(permissionsApi.getResourceAccess).not.toHaveBeenCalled();
+ expect(permissionsApi.updateResourceAccess).not.toHaveBeenCalled();
});
it('keeps explicit custom-link saving while online and Organization controls stay out', async () => {
@@ -547,7 +589,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
expected_revision: 0,
target_access_mode: 'public',
target_share_id: 'new-link',
- target_emails: [],
+ target_entries: [],
});
});
expect(screen.queryByText('Organization access')).toBeNull();
@@ -601,8 +643,6 @@ describe('ShowPageShareControl request surface', () => {
'getShowPage',
'getShowPageAccess',
'getShowAccessSettings',
- 'listOrganizationResources',
- 'listOrganizationGroups',
]);
const mutatingCallsSoFar = () => Object.entries(api)
diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsx
index 9a074bf97..dbbbabd8b 100644
--- a/ui/src/components/workbench/ShowPageShareControl.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.tsx
@@ -15,7 +15,6 @@ import { copyHref, type ShowPageLinkInfo, type ShowPagePayload } from '../../lib
import { copyTextToClipboard } from '../../lib/utils';
import { useShowPageInventory, type ShowPage } from '../useShowPages';
import { ShowPageSharingSettings } from './ShowPageSharingSettings';
-import { ShowPageWorkspaceAccessControl } from './ShowPageWorkspaceAccessControl';
export const ShowPageShareControl: React.FC<{
sessionId: string;
@@ -288,24 +287,6 @@ export const ShowPageShareControl: React.FC<{
sessionId={sessionId}
onApplied={handleShowAccessApplied}
ownerWindowId={ownerWindowId}
- showCustomLink={access.mode !== 'organization' && access.mode !== 'organization_pending'}
- />
- </div>
- ) : null}
-
- {access && (
- access.ownership_status === 'conflict'
- || access.mode === 'organization'
- || access.mode === 'organization_pending'
- || access.mode === 'configuration_unavailable'
- ) ? (
- <div className="border-t border-border pt-3">
- <ShowPageWorkspaceAccessControl
- access={access}
- active={open}
- canManageInstance={canManageInstance}
- sessionId={sessionId}
- ownerWindowId={ownerWindowId}
/>
</div>
) : null}
diff --git a/ui/src/components/workbench/ShowPageSharingSettings.i18n.test.tsx b/ui/src/components/workbench/ShowPageSharingSettings.i18n.test.tsx
new file mode 100644
index 000000000..915255ba4
--- /dev/null
+++ b/ui/src/components/workbench/ShowPageSharingSettings.i18n.test.tsx
@@ -0,0 +1,129 @@
+/** @vitest-environment jsdom */
+import { createInstance } from 'i18next';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
+import type { PermissionsResponse } from '../../features/permissions/types';
+import { ShowPageSharingSettings } from './ShowPageSharingSettings';
+
+const api = {
+ getShowAccessSettings: vi.fn(),
+ applyShowAccess: vi.fn(),
+};
+
+const getPermissions = vi.fn();
+
+vi.mock('../../context/ApiContext', () => ({ useApi: () => api }));
+vi.mock('@/context/ApiContext', () => ({ useApi: () => api }));
+vi.mock('@/features/permissions/api', () => ({
+ getPermissions: (...args: unknown[]) => getPermissions(...args),
+}));
+
+const ORGANIZATION = {
+ ok: true,
+ source: 'live',
+ offline: false,
+ cached_at: null,
+ projection: {
+ schema_version: 1,
+ instance: {
+ id: 'inst-1',
+ organization: { id: 'org-1', name: 'Acme' },
+ access_mode: 'allowlist',
+ permission_authority: 'cloud',
+ local_mutation_allowed: false,
+ authorization_revision: 1,
+ },
+ capabilities: [],
+ access: { owner: { email: null, role: 'owner' }, entries: [] },
+ directory: { members: [], groups: [] },
+ projects: [],
+ policy_sync: {
+ status: 'in_sync',
+ projects: { active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 },
+ resources: { active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 },
+ },
+ },
+} as unknown as PermissionsResponse;
+
+const keyPaths = (value: unknown, prefix = ''): string[] => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return [prefix];
+ return Object.entries(value as Record<string, unknown>)
+ .flatMap(([key, child]) => keyPaths(child, prefix ? `${prefix}.${key}` : key));
+};
+
+const renderSharing = (language: 'en' | 'zh') => {
+ const i18n = createInstance();
+ void i18n.use(initReactI18next).init({
+ lng: language,
+ fallbackLng: 'en',
+ resources: { en: { translation: en }, zh: { translation: zh } },
+ interpolation: { escapeValue: false },
+ });
+ render(
+ <I18nextProvider i18n={i18n}>
+ <ShowPageSharingSettings active canManage sessionId="ses-1" />
+ </I18nextProvider>,
+ );
+};
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('Show Page sharing copy', () => {
+ it('keeps the Show Page locale trees at parity', () => {
+ const enKeys = keyPaths(en.chat.showPage);
+ const zhKeys = keyPaths(zh.chat.showPage);
+
+ expect(zhKeys).toEqual(enKeys);
+ // The retired Organization axis takes its Resource sync/ACK copy with it.
+ expect(enKeys.filter((key) => key.startsWith('workspace'))).toEqual([]);
+ expect(zhKeys.filter((key) => key.startsWith('workspace'))).toEqual([]);
+ expect(JSON.stringify(zh.chat.showPage)).not.toContain('尚未确认最新策略');
+ expect(JSON.stringify(en.chat.showPage)).not.toContain('acknowledged the latest policy');
+ // The audience is no longer email-shaped, so its email-only copy is gone.
+ for (const retired of ['limitedEmails', 'limitedEmailHint', 'keepOneLimitedEmail']) {
+ expect(enKeys).not.toContain(retired);
+ expect(zhKeys).not.toContain(retired);
+ }
+ // `limit` is an interpolation slot, not i18next's reserved `count` plural
+ // selector — using `count` can drop the string in CI even when local tests pass.
+ expect(en.chat.showPage.shareAudienceHint.organization).toContain('{{limit}}');
+ expect(en.chat.showPage.shareAudienceHint.email).toContain('{{limit}}');
+ expect(JSON.stringify(en.chat.showPage.shareAudienceHint)).not.toContain('{{count}}');
+ expect(JSON.stringify(zh.chat.showPage.shareAudienceHint)).not.toContain('{{count}}');
+ });
+
+ it.each([
+ ['en', ['Private', 'Limited', 'Fully public'], 'This Organization'],
+ ['zh', ['私有', '有限访问', '完全公开'], '本组织'],
+ ] as const)('renders the three tiers and the Organization row in %s', async (
+ language,
+ tiers,
+ organizationLabel,
+ ) => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: {
+ page_id: 'ses-1',
+ access_mode: 'limited',
+ share_id: 'stable-link',
+ revision: 0,
+ normalized_emails: ['[email protected]'],
+ },
+ });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ renderSharing(language);
+
+ const trigger = await screen.findByRole('button', { name: new RegExp(tiers[1]) });
+ fireEvent.click(trigger);
+ expect(screen.getAllByRole('option').map((option) => (
+ option.querySelector('span > span')?.textContent
+ ))).toEqual([...tiers]);
+ expect(await screen.findByRole('switch', { name: organizationLabel })).toBeTruthy();
+ });
+});
diff --git a/ui/src/components/workbench/ShowPageSharingSettings.test.tsx b/ui/src/components/workbench/ShowPageSharingSettings.test.tsx
index a9270c8bb..3c27b7817 100644
--- a/ui/src/components/workbench/ShowPageSharingSettings.test.tsx
+++ b/ui/src/components/workbench/ShowPageSharingSettings.test.tsx
@@ -5,6 +5,7 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, describe, expect, it, vi } from 'vitest';
import en from '../../i18n/en.json';
+import type { PermissionsResponse } from '../../features/permissions/types';
import type { ShowAccess, ShowAccessApplyResult } from '../../lib/showPageAccess';
import { ShowPageSharingSettings } from './ShowPageSharingSettings';
@@ -13,6 +14,8 @@ const api = {
applyShowAccess: vi.fn(),
};
+const getPermissions = vi.fn();
+
vi.mock('../../context/ApiContext', () => ({
useApi: () => api,
}));
@@ -21,6 +24,12 @@ vi.mock('@/context/ApiContext', () => ({
useApi: () => api,
}));
+// The Organization directory is the only permissions read this control makes.
+// It is never a show_page Resource request.
+vi.mock('@/features/permissions/api', () => ({
+ getPermissions: (...args: unknown[]) => getPermissions(...args),
+}));
+
const i18n = createInstance();
void i18n.use(initReactI18next).init({
lng: 'en',
@@ -38,9 +47,49 @@ const showAccess = (overrides: Partial<ShowAccess> = {}): ShowAccess => ({
...overrides,
});
+const permissions = (
+ organization: { id: string; name: string } | null,
+): PermissionsResponse => ({
+ ok: true,
+ source: 'live',
+ offline: false,
+ cached_at: null,
+ projection: {
+ schema_version: 1,
+ instance: {
+ id: 'inst-1',
+ organization,
+ access_mode: 'allowlist',
+ permission_authority: 'cloud',
+ local_mutation_allowed: false,
+ authorization_revision: 3,
+ },
+ capabilities: [],
+ access: { owner: { email: null, role: 'owner' }, entries: [] },
+ directory: {
+ members: [
+ { id: 'u1', email: '[email protected]', organization_role: 'member', group_ids: [] },
+ { id: 'u2', email: '[email protected]', organization_role: 'member', group_ids: [] },
+ ],
+ groups: [
+ { id: 'grp-eng', name: 'Engineering', archived_at: null },
+ { id: 'grp-old', name: 'Legacy', archived_at: '2026-01-01T00:00:00Z' },
+ ],
+ },
+ projects: [],
+ policy_sync: {
+ status: 'in_sync',
+ projects: { active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 },
+ resources: { active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 },
+ },
+ },
+});
+
+const ORGANIZATION = permissions({ id: 'org-1', name: 'Acme' });
+const PERSONAL = permissions(null);
+
const settings = (
sessionId = 'ses-1',
- showCustomLink = true,
onApplied?: (showAccess: ShowAccess) => void,
) => (
<I18nextProvider i18n={i18n}>
@@ -48,17 +97,15 @@ const settings = (
active
canManage
sessionId={sessionId}
- showCustomLink={showCustomLink}
onApplied={onApplied}
/>
</I18nextProvider>
);
const renderSettings = (
sessionId = 'ses-1',
- showCustomLink = true,
onApplied?: (showAccess: ShowAccess) => void,
) => (
- render(settings(sessionId, showCustomLink, onApplied))
+ render(settings(sessionId, onApplied))
);
const chooseMode = async (name: 'Private' | 'Limited' | 'Fully public') => {
@@ -66,49 +113,135 @@ const chooseMode = async (name: 'Private' | 'Limited' | 'Fully public') => {
fireEvent.click(screen.getByRole('option', { name: new RegExp(name) }));
};
+const audience = async () => screen.findByRole('combobox', { name: 'People with access' });
+
+const openAudience = async () => {
+ const input = await audience();
+ fireEvent.focus(input);
+ return input;
+};
+
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe('ShowPageSharingSettings', () => {
- it('uses semantic icons instead of radio controls for the three access modes', async () => {
+ it('offers exactly the three sharing tiers in order, with no second access axis', async () => {
api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ getPermissions.mockResolvedValue(ORGANIZATION);
renderSettings();
const trigger = await screen.findByRole('button', { name: 'Access: Private' });
expect(trigger.className).toContain('w-40');
- expect(trigger.className).not.toContain('w-full');
expect(screen.queryAllByRole('radio')).toHaveLength(0);
- fireEvent.click(screen.getByRole('button', { name: 'Access: Private' }));
+ fireEvent.click(trigger);
- expect(screen.getByRole('option', { name: /Private/ })).toBeTruthy();
- expect(screen.getByRole('option', { name: /Limited/ })).toBeTruthy();
- expect(screen.getByRole('option', { name: /Fully public/ })).toBeTruthy();
+ expect(screen.getAllByRole('option').map((option) => option.textContent)).toEqual([
+ 'PrivateOnly you can access this page',
+ 'LimitedOnly people in the list can access',
+ 'Fully publicAnyone can access without signing in',
+ ]);
expect(document.querySelector('[data-access-icon="private"]')).toBeTruthy();
expect(document.querySelector('[data-access-icon="limited"]')).toBeTruthy();
expect(document.querySelector('[data-access-icon="public"]')).toBeTruthy();
+ // The Organization axis is gone: no second access block, no sync/ACK status.
+ expect(screen.queryByText('Organization access')).toBeNull();
+ expect(screen.queryByText(/has not acknowledged the latest policy/)).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Apply' })).toBeNull();
+ });
+
+ it('starts an Organization page as Private with no audience field', async () => {
+ api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ renderSettings();
+
+ expect(await screen.findByRole('button', { name: 'Access: Private' })).toBeTruthy();
+ expect(screen.queryByRole('combobox', { name: 'People with access' })).toBeNull();
+ expect(screen.queryByRole('switch')).toBeNull();
+ // Private is not a shared mode, so nothing reads the directory yet.
+ expect(getPermissions).not.toHaveBeenCalled();
});
- it('saves a Limited audience as soon as an email is added', async () => {
+ it('starts a Personal page as Private too', async () => {
api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ getPermissions.mockResolvedValue(PERSONAL);
+ renderSettings();
+
+ expect(await screen.findByRole('button', { name: 'Access: Private' })).toBeTruthy();
+ expect(screen.queryByRole('combobox', { name: 'People with access' })).toBeNull();
+ });
+
+ it('opens the directory on focus and lets a group be picked straight from it', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ access_entries: [{ kind: 'email', value: '[email protected]' }],
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ getPermissions.mockResolvedValue(ORGANIZATION);
api.applyShowAccess.mockResolvedValue({
status: 'applied',
show_access: showAccess({
access_mode: 'limited',
revision: 1,
normalized_emails: ['[email protected]'],
+ access_entries: [
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ],
}),
});
renderSettings();
+ await waitFor(() => expect(getPermissions).toHaveBeenCalledTimes(1));
+
+ const input = await openAudience();
+ expect(input.getAttribute('aria-expanded')).toBe('true');
+ const options = await waitFor(() => screen.getAllByRole('option'));
+ // Groups and people are searchable side by side; an archived group is not.
+ expect(options.map((option) => option.textContent)).toEqual([
+ 'EngineeringGroup',
+ ]);
+ fireEvent.click(screen.getByRole('option', { name: /Engineering/ }));
- await chooseMode('Limited');
- expect(screen.queryByRole('button', { name: 'Apply' })).toBeNull();
- const emailInput = screen.getByRole('textbox', { name: 'People with access' });
- expect(emailInput.parentElement?.parentElement?.className).toContain('max-w-[17.5rem]');
- fireEvent.change(emailInput, {
- target: { value: ' [email protected] ' },
+ await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
+ expect(api.applyShowAccess).toHaveBeenCalledWith('ses-1', {
+ expected_revision: 0,
+ target_access_mode: 'limited',
+ target_share_id: 'stable-link',
+ target_entries: [
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ],
});
+ expect(await screen.findByText('Engineering')).toBeTruthy();
+ });
+
+ it('narrows the directory from a half-typed query and still accepts any typed email', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({ access_mode: 'limited' }),
+ });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ api.applyShowAccess.mockResolvedValue({
+ status: 'applied',
+ show_access: showAccess({
+ access_mode: 'limited',
+ revision: 1,
+ normalized_emails: ['[email protected]'],
+ access_entries: [{ kind: 'email', value: '[email protected]' }],
+ }),
+ });
+ renderSettings();
+
+ const input = await openAudience();
+ fireEvent.change(input, { target: { value: 'eng' } });
+ await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(1));
+ expect(screen.getByRole('option', { name: /Engineering/ })).toBeTruthy();
+
+ fireEvent.change(input, { target: { value: ' [email protected] ' } });
fireEvent.click(screen.getByRole('button', { name: 'Add email' }));
await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
@@ -116,60 +249,384 @@ describe('ShowPageSharingSettings', () => {
expected_revision: 0,
target_access_mode: 'limited',
target_share_id: 'stable-link',
- target_emails: ['[email protected]'],
+ target_entries: [{ kind: 'email', value: '[email protected]' }],
});
});
- it('saves a direct mode change without an Apply button', async () => {
- api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ it('keeps the audience list open with empty-state copy when a directory query matches nothing', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ renderSettings();
+
+ const input = await openAudience();
+ fireEvent.change(input, { target: { value: 'zzz-no-match' } });
+ expect(await screen.findByRole('listbox', { name: 'People and group suggestions' })).toBeTruthy();
+ expect(screen.getByText('No matching person or group. Type a full email to add it.')).toBeTruthy();
+ expect(screen.queryAllByRole('option')).toHaveLength(0);
+ });
+
+ it('keeps the audience combobox keyboard cursor queryable for assistive tech and scrolling', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ const originalScrollIntoView = Element.prototype.scrollIntoView;
+ const scrollIntoView = vi.fn();
+ Element.prototype.scrollIntoView = scrollIntoView;
+ renderSettings();
+
+ try {
+ const input = await openAudience();
+ const list = await screen.findByRole('listbox', { name: 'People and group suggestions' });
+ const engineering = await screen.findByRole('option', { name: /Engineering/ });
+ const alice = screen.getByRole('option', { name: '[email protected]' });
+ const bob = screen.getByRole('option', { name: '[email protected]' });
+ const activeOption = () => list.querySelector('[data-active="true"]');
+
+ expect(input.getAttribute('aria-activedescendant')).toBeNull();
+ expect(activeOption()).toBeNull();
+
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ expect(engineering.getAttribute('id')).toBeTruthy();
+ expect(activeOption()).toBe(engineering);
+ expect(engineering.getAttribute('aria-selected')).toBe('true');
+ expect(input.getAttribute('aria-activedescendant')).toBe(engineering.getAttribute('id'));
+ await waitFor(() => expect(scrollIntoView).toHaveBeenCalled());
+
+ fireEvent.mouseEnter(alice);
+ expect(activeOption()).toBe(alice);
+ expect(alice.getAttribute('aria-selected')).toBe('true');
+ expect(engineering.getAttribute('aria-selected')).toBe('false');
+ expect(input.getAttribute('aria-activedescendant')).toBe(alice.getAttribute('id'));
+
+ fireEvent.keyDown(input, { key: 'End' });
+ expect(activeOption()).toBe(bob);
+ expect(bob.getAttribute('aria-selected')).toBe('true');
+ expect(input.getAttribute('aria-activedescendant')).toBe(bob.getAttribute('id'));
+
+ fireEvent.keyDown(input, { key: 'Home' });
+ expect(activeOption()).toBe(engineering);
+ expect(engineering.getAttribute('aria-selected')).toBe('true');
+ expect(input.getAttribute('aria-activedescendant')).toBe(engineering.getAttribute('id'));
+ } finally {
+ Element.prototype.scrollIntoView = originalScrollIntoView;
+ }
+ });
+
+ it('closes the audience list when focus leaves the field from the add button', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ renderSettings();
+
+ const input = await openAudience();
+ fireEvent.change(input, { target: { value: 'alice' } });
+ const add = await screen.findByRole('button', { name: 'Add email' });
+ fireEvent.focus(add);
+ fireEvent.blur(input, { relatedTarget: add });
+ expect(screen.getByRole('option', { name: '[email protected]' })).toBeTruthy();
+
+ const outside = document.createElement('button');
+ document.body.appendChild(outside);
+ fireEvent.blur(add, { relatedTarget: outside });
+ await waitFor(() => {
+ expect(screen.queryByRole('listbox', { name: 'People and group suggestions' })).toBeNull();
+ });
+ outside.remove();
+ });
+
+ it('keeps the Organization switch and the narrower entries as peers', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: ['[email protected]'],
+ access_entries: [
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ],
+ }),
+ });
+ getPermissions.mockResolvedValue(ORGANIZATION);
api.applyShowAccess.mockResolvedValue({
status: 'applied',
- show_access: showAccess({ access_mode: 'public', revision: 1 }),
+ show_access: showAccess({
+ access_mode: 'limited',
+ revision: 1,
+ normalized_emails: ['[email protected]'],
+ access_entries: [
+ { kind: 'organization', value: 'org-1' },
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ],
+ }),
});
renderSettings();
- await chooseMode('Limited');
- fireEvent.change(screen.getByRole('textbox', { name: 'People with access' }), {
- target: { value: '[email protected]' },
- });
- await chooseMode('Fully public');
+ const toggle = await screen.findByRole('switch', { name: 'This Organization' });
+ expect(toggle.getAttribute('aria-checked')).toBe('false');
+ expect(screen.getByText('This Organization (Acme)')).toBeTruthy();
+ fireEvent.click(toggle);
await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
+ // Turning the Organization on supersedes nothing: the group and the email stay.
expect(api.applyShowAccess).toHaveBeenCalledWith('ses-1', {
expected_revision: 0,
- target_access_mode: 'public',
+ target_access_mode: 'limited',
target_share_id: 'stable-link',
- target_emails: [],
+ target_entries: [
+ { kind: 'organization', value: 'org-1' },
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ],
});
- expect(screen.queryByRole('button', { name: 'Apply' })).toBeNull();
+ await waitFor(() => {
+ expect((screen.getByRole('switch', { name: 'This Organization' }))
+ .getAttribute('aria-checked')).toBe('true');
+ });
+ expect(screen.getByText('Engineering')).toBeTruthy();
+ expect(screen.getByText('[email protected]')).toBeTruthy();
+ });
+
+ it('gives a Personal page an email-only audience', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ getPermissions.mockResolvedValue(PERSONAL);
+ renderSettings();
+ await waitFor(() => expect(getPermissions).toHaveBeenCalledTimes(1));
+
+ const input = await openAudience();
+ expect(input.getAttribute('placeholder')).toBe('[email protected]');
+ expect(screen.getByText('Enter an email and press Enter to add · up to 64')).toBeTruthy();
+ // No Organization to share with, so no switch and nothing to search.
+ expect(screen.queryByRole('switch')).toBeNull();
+ expect(screen.queryByRole('option')).toBeNull();
+ expect(screen.getByText('[email protected]')).toBeTruthy();
+ });
+
+ it('degrades to email-only entry when the directory cannot be read', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ getPermissions.mockRejectedValue(new Error('permissions offline'));
+ renderSettings();
+ await waitFor(() => expect(getPermissions).toHaveBeenCalledTimes(1));
+
+ const input = await openAudience();
+ expect((input as HTMLInputElement).disabled).toBe(false);
+ expect(screen.queryByRole('switch')).toBeNull();
+ expect(screen.getByText('[email protected]')).toBeTruthy();
+ });
+
+ it('rejects an unusable typed audience without calling the API', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ getPermissions.mockResolvedValue(PERSONAL);
+ renderSettings();
+
+ const input = await audience();
+ fireEvent.change(input, { target: { value: 'not-an-email' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ expect(await screen.findByText('Enter a valid email address.')).toBeTruthy();
+ expect(api.applyShowAccess).not.toHaveBeenCalled();
});
- it('disables new Limited email input at the audience limit', async () => {
+ it('disables new audience input at the entry limit', async () => {
api.getShowAccessSettings.mockResolvedValue({
show_access: showAccess({
access_mode: 'limited',
normalized_emails: Array.from({ length: 64 }, (_, index) => `guest-${index}@example.com`),
}),
});
+ getPermissions.mockResolvedValue(ORGANIZATION);
renderSettings();
- const input = await screen.findByRole('textbox', { name: 'People with access' });
+ const input = await audience();
expect((input as HTMLInputElement).disabled).toBe(true);
- expect(screen.getByText('Enter an email and press Enter to add · up to 64')).toBeTruthy();
+ // Directory-backed copy only appears after getPermissions lands; asserting
+ // the organization hint too early races the email-only fallback that CI
+ // still shows on first paint.
+ expect(
+ (await screen.findByRole('switch', { name: 'This Organization' }) as HTMLButtonElement).disabled,
+ ).toBe(true);
+ expect(screen.getByText((content) => (
+ content.includes('Pick a person or group, or type any email')
+ && content.includes('64')
+ ))).toBeTruthy();
});
- it('does not allow removing the last email while Limited is selected', async () => {
+ it('does not allow removing the last entry while Limited is selected', async () => {
api.getShowAccessSettings.mockResolvedValue({
show_access: showAccess({
access_mode: 'limited',
normalized_emails: ['[email protected]'],
}),
});
+ getPermissions.mockResolvedValue(ORGANIZATION);
renderSettings();
const remove = await screen.findByRole('button', { name: 'Remove [email protected]' });
expect((remove as HTMLButtonElement).disabled).toBe(true);
- expect(remove.getAttribute('title')).toBe('Switch to Private to remove the last email');
+ expect(remove.getAttribute('title')).toBe('Switch to Private to remove the last entry');
+ // The same guard covers an Organization that is the only entry left.
+ expect((await screen.findByRole('switch', { name: 'This Organization' })).getAttribute(
+ 'aria-checked',
+ )).toBe('false');
+ });
+
+ it('saves group-only Limited and reads the group back', async () => {
+ api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ api.applyShowAccess.mockResolvedValue({
+ status: 'applied',
+ show_access: showAccess({
+ access_mode: 'limited',
+ revision: 1,
+ normalized_emails: [],
+ entries: [{ kind: 'group', value: 'grp-eng' }],
+ }),
+ });
+ renderSettings();
+
+ await chooseMode('Limited');
+ expect(await screen.findByText(
+ 'Add at least one person, group, or Organization.',
+ )).toBeTruthy();
+ expect(api.applyShowAccess).not.toHaveBeenCalled();
+
+ await openAudience();
+ fireEvent.click(await screen.findByRole('option', { name: /Engineering/ }));
+ await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
+ expect(api.applyShowAccess).toHaveBeenCalledWith('ses-1', {
+ expected_revision: 0,
+ target_access_mode: 'limited',
+ target_share_id: 'stable-link',
+ target_entries: [{ kind: 'group', value: 'grp-eng' }],
+ });
+ expect(await screen.findByText('Engineering')).toBeTruthy();
+ expect(screen.queryByText(
+ 'Add at least one person, group, or Organization.',
+ )).toBeNull();
+ expect((screen.getByRole('button', { name: 'Remove Engineering' }) as HTMLButtonElement)
+ .disabled).toBe(true);
+ });
+
+ it('saves Organization-only Limited and reads the switch back', async () => {
+ api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ api.applyShowAccess.mockResolvedValue({
+ status: 'applied',
+ show_access: showAccess({
+ access_mode: 'limited',
+ revision: 1,
+ normalized_emails: [],
+ entries: [{ kind: 'organization', value: 'org-1' }],
+ }),
+ });
+ renderSettings();
+
+ await chooseMode('Limited');
+ fireEvent.click(await screen.findByRole('switch', { name: 'This Organization' }));
+ await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
+ expect(api.applyShowAccess).toHaveBeenCalledWith('ses-1', {
+ expected_revision: 0,
+ target_access_mode: 'limited',
+ target_share_id: 'stable-link',
+ target_entries: [{ kind: 'organization', value: 'org-1' }],
+ });
+ await waitFor(() => {
+ expect((screen.getByRole('switch', { name: 'This Organization' }))
+ .getAttribute('aria-checked')).toBe('true');
+ });
+ expect(screen.queryByText(
+ 'Add at least one person, group, or Organization.',
+ )).toBeNull();
+ });
+
+ it('lets the last email be removed while another Limited entry remains', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: ['[email protected]'],
+ entries: [
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ],
+ }),
+ });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ api.applyShowAccess.mockResolvedValue({
+ status: 'applied',
+ show_access: showAccess({
+ access_mode: 'limited',
+ revision: 1,
+ normalized_emails: [],
+ entries: [{ kind: 'group', value: 'grp-eng' }],
+ }),
+ });
+ renderSettings();
+
+ const removeEmail = await screen.findByRole('button', { name: 'Remove [email protected]' });
+ const removeGroup = await screen.findByRole('button', { name: 'Remove Engineering' });
+ expect((removeEmail as HTMLButtonElement).disabled).toBe(false);
+ expect((removeGroup as HTMLButtonElement).disabled).toBe(false);
+ fireEvent.click(removeEmail);
+ await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
+ expect(api.applyShowAccess).toHaveBeenCalledWith('ses-1', {
+ expected_revision: 0,
+ target_access_mode: 'limited',
+ target_share_id: 'stable-link',
+ target_entries: [{ kind: 'group', value: 'grp-eng' }],
+ });
+ expect(screen.queryByRole('button', { name: 'Remove [email protected]' })).toBeNull();
+ expect((screen.getByRole('button', { name: 'Remove Engineering' }) as HTMLButtonElement)
+ .disabled).toBe(true);
+ });
+
+ it('saves a direct mode change without an Apply button', async () => {
+ api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ getPermissions.mockResolvedValue(ORGANIZATION);
+ api.applyShowAccess.mockResolvedValue({
+ status: 'applied',
+ show_access: showAccess({ access_mode: 'public', revision: 1 }),
+ });
+ renderSettings();
+
+ await chooseMode('Limited');
+ fireEvent.change(await audience(), { target: { value: '[email protected]' } });
+ await chooseMode('Fully public');
+
+ await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
+ expect(api.applyShowAccess).toHaveBeenCalledWith('ses-1', {
+ expected_revision: 0,
+ target_access_mode: 'public',
+ target_share_id: 'stable-link',
+ target_entries: [],
+ });
+ expect(screen.queryByRole('button', { name: 'Apply' })).toBeNull();
});
it('reloads the latest access snapshot without dropping a custom-link draft after a CAS conflict', async () => {
@@ -183,6 +640,7 @@ describe('ShowPageSharingSettings', () => {
.mockResolvedValueOnce({
show_access: showAccess({ access_mode: 'public', revision: 3 }),
});
+ getPermissions.mockResolvedValue(ORGANIZATION);
api.applyShowAccess.mockResolvedValue({
status: 'conflict',
show_access: showAccess({ access_mode: 'limited', revision: 2 }),
@@ -209,6 +667,7 @@ describe('ShowPageSharingSettings', () => {
.mockResolvedValueOnce({
show_access: showAccess({ access_mode: 'public', revision: 2, share_id: 'server-link' }),
});
+ getPermissions.mockResolvedValue(ORGANIZATION);
api.applyShowAccess.mockResolvedValue({
status: 'conflict',
show_access: showAccess({ access_mode: 'public', revision: 1, share_id: 'other-link' }),
@@ -237,6 +696,7 @@ describe('ShowPageSharingSettings', () => {
.mockResolvedValueOnce({
show_access: showAccess({ access_mode: 'public', revision: 2, share_id: 'server-link' }),
});
+ getPermissions.mockResolvedValue(ORGANIZATION);
api.applyShowAccess.mockResolvedValue({
status: 'conflict',
show_access: showAccess({ access_mode: 'limited', revision: 1 }),
@@ -263,6 +723,7 @@ describe('ShowPageSharingSettings', () => {
.mockResolvedValueOnce({
show_access: showAccess({ access_mode: 'public', revision: 2, share_id: 'server-link' }),
});
+ getPermissions.mockResolvedValue(ORGANIZATION);
api.applyShowAccess.mockRejectedValueOnce(new Error('network unavailable'));
renderSettings();
@@ -284,6 +745,7 @@ describe('ShowPageSharingSettings', () => {
api.getShowAccessSettings.mockResolvedValue({
show_access: showAccess({ access_mode: 'public' }),
});
+ getPermissions.mockResolvedValue(ORGANIZATION);
api.applyShowAccess.mockResolvedValue({
status: 'share_id_taken',
show_access: showAccess({ access_mode: 'public' }),
@@ -292,7 +754,6 @@ describe('ShowPageSharingSettings', () => {
const input = await screen.findByRole('textbox', { name: 'Custom link' });
expect(screen.getByText('Custom link')).toBeTruthy();
- expect(input.parentElement?.className).toContain('max-w-[17.5rem]');
expect(screen.queryByRole('button', { name: 'Save' })).toBeNull();
fireEvent.change(input, { target: { value: 'taken-link' } });
fireEvent.blur(input);
@@ -311,6 +772,7 @@ describe('ShowPageSharingSettings', () => {
api.getShowAccessSettings.mockResolvedValue({
show_access: showAccess({ access_mode: 'public' }),
});
+ getPermissions.mockResolvedValue(ORGANIZATION);
api.applyShowAccess.mockResolvedValue({
status: 'applied',
show_access: showAccess({ access_mode: 'public', revision: 1, share_id: 'canonical-link' }),
@@ -332,12 +794,13 @@ describe('ShowPageSharingSettings', () => {
api.getShowAccessSettings.mockResolvedValue({
show_access: showAccess({ access_mode: 'public' }),
});
+ getPermissions.mockResolvedValue(ORGANIZATION);
let resolveApply = (_result: ShowAccessApplyResult) => undefined;
api.applyShowAccess.mockReturnValue(new Promise<ShowAccessApplyResult>((resolve) => {
resolveApply = resolve;
}));
const onApplied = vi.fn();
- const view = renderSettings('ses-1', true, onApplied);
+ const view = renderSettings('ses-1', onApplied);
const input = await screen.findByRole('textbox', { name: 'Custom link' });
fireEvent.change(input, { target: { value: 'new-link' } });
@@ -367,6 +830,7 @@ describe('ShowPageSharingSettings', () => {
normalized_emails: ['[email protected]'],
}),
});
+ getPermissions.mockResolvedValue(PERSONAL);
api.applyShowAccess.mockResolvedValue({
status: 'applied',
show_access: showAccess({
@@ -379,9 +843,7 @@ describe('ShowPageSharingSettings', () => {
const customLink = await screen.findByRole('textbox', { name: 'Custom link' });
fireEvent.change(customLink, { target: { value: 'unsaved-link' } });
- fireEvent.change(screen.getByRole('textbox', { name: 'People with access' }), {
- target: { value: '[email protected]' },
- });
+ fireEvent.change(await audience(), { target: { value: '[email protected]' } });
fireEvent.click(screen.getByRole('button', { name: 'Add email' }));
await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
@@ -389,7 +851,10 @@ describe('ShowPageSharingSettings', () => {
expected_revision: 0,
target_access_mode: 'limited',
target_share_id: 'stable-link',
- target_emails: ['[email protected]', '[email protected]'],
+ target_entries: [
+ { kind: 'email', value: '[email protected]' },
+ { kind: 'email', value: '[email protected]' },
+ ],
});
expect((screen.getByRole('textbox', { name: 'Custom link' }) as HTMLInputElement).value).toBe(
'unsaved-link',
@@ -397,18 +862,53 @@ describe('ShowPageSharingSettings', () => {
expect(screen.getByRole('button', { name: 'Save' })).toBeTruthy();
});
- it('can hide custom-link editing when embedded in the share popover', async () => {
- api.getShowAccessSettings.mockResolvedValue({
- show_access: showAccess({ access_mode: 'public' }),
+ it('keeps the Organization directory after a CAS reload overlaps the first fetch', async () => {
+ api.getShowAccessSettings
+ .mockResolvedValueOnce({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: ['[email protected]'],
+ }),
+ })
+ .mockResolvedValueOnce({
+ show_access: showAccess({
+ access_mode: 'limited',
+ revision: 3,
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ let resolvePermissions = (_value: PermissionsResponse) => undefined;
+ getPermissions.mockReturnValue(new Promise<PermissionsResponse>((resolve) => {
+ resolvePermissions = resolve;
+ }));
+ api.applyShowAccess.mockResolvedValue({
+ status: 'conflict',
+ show_access: showAccess({ access_mode: 'limited', revision: 2 }),
+ });
+ renderSettings();
+
+ await waitFor(() => expect(getPermissions).toHaveBeenCalledTimes(1));
+ const input = await openAudience();
+ expect(screen.getByText('Loading Organization directory…')).toBeTruthy();
+
+ fireEvent.change(input, { target: { value: '[email protected]' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add email' }));
+ await waitFor(() => expect(api.getShowAccessSettings).toHaveBeenCalledTimes(2));
+
+ await act(async () => {
+ resolvePermissions(ORGANIZATION);
+ await Promise.resolve();
});
- renderSettings('ses-1', false);
- expect(await screen.findByRole('button', { name: 'Access: Fully public' })).toBeTruthy();
- expect(screen.queryByRole('textbox', { name: 'Custom link' })).toBeNull();
+ await openAudience();
+ await waitFor(() => expect(screen.getByRole('option', { name: /Engineering/ })).toBeTruthy());
+ expect(screen.queryByText('Loading Organization directory…')).toBeNull();
+ expect(getPermissions).toHaveBeenCalledTimes(1);
});
- it('rejects a mismatched result identity without adopting its email list', async () => {
+ it('rejects a mismatched result identity without adopting its audience', async () => {
api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ getPermissions.mockResolvedValue(ORGANIZATION);
api.applyShowAccess.mockResolvedValue({
status: 'applied',
show_access: showAccess({
@@ -433,6 +933,7 @@ describe('ShowPageSharingSettings', () => {
share_id: sessionId === 'ses-1' ? 'first-link' : 'second-link',
}),
}));
+ getPermissions.mockResolvedValue(ORGANIZATION);
let resolveApply = (_result: ShowAccessApplyResult) => undefined;
api.applyShowAccess.mockReturnValue(new Promise<ShowAccessApplyResult>((resolve) => {
resolveApply = resolve;
diff --git a/ui/src/components/workbench/ShowPageSharingSettings.tsx b/ui/src/components/workbench/ShowPageSharingSettings.tsx
index 3acac72f0..0f794d2a6 100644
--- a/ui/src/components/workbench/ShowPageSharingSettings.tsx
+++ b/ui/src/components/workbench/ShowPageSharingSettings.tsx
@@ -1,11 +1,13 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import clsx from 'clsx';
import {
+ Building2,
Check,
ChevronDown,
Globe2,
Loader2,
LockKeyhole,
+ Mail,
Plus,
RefreshCw,
Users,
@@ -16,20 +18,33 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { Switch } from '@/components/ui/switch';
import { useApi } from '@/context/ApiContext';
+import { getPermissions } from '@/features/permissions/api';
import {
normalizeShowAccessEmail,
+ showAccessDirectoryOf,
showAccessDraftChanged,
- showAccessTargetEmails,
- SHOW_ACCESS_EMAIL_MAX_COUNT,
+ showAccessEntriesKey,
+ showAccessEntriesOf,
+ showAccessEntryKey,
+ showAccessSuggestions,
+ showAccessApplyPayload,
+ showAccessTargetEntries,
+ withoutShowAccessEntry,
+ withShowAccessEntry,
+ SHOW_ACCESS_ENTRY_MAX_COUNT,
type ShowAccess,
+ type ShowAccessDirectory,
+ type ShowAccessEntry,
type ShowAccessMode,
+ type ShowAccessSuggestion,
} from '@/lib/showPageAccess';
import { isValidShareId, SHARE_ID_MAX_LENGTH } from '@/lib/showPageLinks';
type Gate = 'idle' | 'loading' | 'ready' | 'conflict' | 'share_id_taken' | 'invalid' | 'error';
-const normalizedSet = (emails: string[]): string[] => [...new Set(emails)].sort();
+type DirectoryGate = 'idle' | 'loading' | 'ready' | 'unavailable';
const MODE_ICONS = {
private: LockKeyhole,
@@ -121,20 +136,243 @@ function AccessModeSelect({
);
}
+/** The audience field. Focusing or clicking it opens the Organization directory
+ * (members + groups); a partial query narrows it; anything that normalizes to an
+ * email can be typed in full. The dropdown is rendered in flow — not in a
+ * portal — because this field itself lives inside the share popover, where a
+ * nested portal would fight it for focus and dismissal. */
+function AudienceCombobox({
+ disabled,
+ directoryLoading,
+ suggestions,
+ truncated,
+ placeholder,
+ query,
+ invalid,
+ onQueryChange,
+ onSelect,
+ onSubmitTypedEmail,
+}: {
+ disabled: boolean;
+ directoryLoading: boolean;
+ suggestions: ShowAccessSuggestion[];
+ truncated: boolean;
+ placeholder: string;
+ query: string;
+ invalid: boolean;
+ onQueryChange: (value: string) => void;
+ onSelect: (suggestion: ShowAccessSuggestion) => void;
+ onSubmitTypedEmail: () => void;
+}) {
+ const { t } = useTranslation();
+ const listId = useId();
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const listRef = useRef<HTMLDivElement | null>(null);
+ const [focused, setFocused] = useState(false);
+ // The keyboard cursor tracks an option KEY, not an index: the option list is
+ // recomputed from the query on every keystroke, so an index would silently
+ // point at a different row (and a reset effect would cascade renders).
+ const [activeKey, setActiveKey] = useState<string | null>(null);
+
+ const typedEmail = normalizeShowAccessEmail(query);
+ const typedOption: ShowAccessSuggestion | null = typedEmail
+ && !suggestions.some((option) => option.kind === 'email' && option.value === typedEmail)
+ ? { kind: 'email', value: typedEmail, label: typedEmail }
+ : null;
+ const options = typedOption ? [...suggestions, typedOption] : suggestions;
+ // A focused unmatched query (not a complete email) has zero options and is
+ // not loading, so the empty-state copy inside the listbox is unreachable
+ // unless the list stays open for that case too.
+ const open = focused && !disabled && (
+ options.length > 0 || directoryLoading || query.trim().length > 0
+ );
+ const activeIndex = options.findIndex((option) => showAccessEntryKey(option) === activeKey);
+ const active = activeIndex >= 0 ? options[activeIndex] : null;
+ const optionDomId = (option: ShowAccessSuggestion) => (
+ `${listId}-${showAccessEntryKey(option).replace(/[^A-Za-z0-9_-]+/g, '-')}`
+ );
+ const activeDescendantId = open && active ? optionDomId(active) : undefined;
+
+ const moveActive = (delta: number) => {
+ if (!options.length) return;
+ const next = activeIndex < 0
+ ? (delta > 0 ? 0 : options.length - 1)
+ : (activeIndex + delta + options.length) % options.length;
+ setActiveKey(showAccessEntryKey(options[next]));
+ };
+
+ const activateAt = (index: number) => {
+ if (!options.length) return;
+ setActiveKey(showAccessEntryKey(options[index]));
+ };
+
+ useEffect(() => {
+ if (!open) return;
+ const el = listRef.current?.querySelector<HTMLElement>('[data-active="true"]');
+ el?.scrollIntoView({ block: 'nearest' });
+ }, [activeKey, open]);
+
+ const commit = (option: ShowAccessSuggestion) => {
+ setActiveKey(null);
+ onSelect(option);
+ };
+
+ return (
+ <div
+ ref={containerRef}
+ className="relative w-full max-w-[17.5rem]"
+ onBlur={(event) => {
+ if (containerRef.current?.contains(event.relatedTarget as Node | null)) return;
+ setFocused(false);
+ setActiveKey(null);
+ }}
+ >
+ <div className="flex items-start gap-1.5">
+ <div className="min-w-0 flex-1">
+ <Input
+ role="combobox"
+ aria-expanded={open}
+ aria-controls={open ? listId : undefined}
+ aria-activedescendant={activeDescendantId}
+ aria-autocomplete="list"
+ aria-label={t('chat.showPage.shareAudience')}
+ aria-invalid={invalid || undefined}
+ autoComplete="off"
+ spellCheck={false}
+ value={query}
+ disabled={disabled}
+ placeholder={placeholder}
+ className={clsx('h-8 text-xs', invalid && 'border-destructive')}
+ onFocus={() => setFocused(true)}
+ onClick={() => setFocused(true)}
+ onBlur={(event) => {
+ // Clicking an option or the add button moves focus inside the field;
+ // only leaving the field entirely closes the list. The container's
+ // own onBlur is what actually closes it when focus then leaves
+ // from those child controls.
+ if (containerRef.current?.contains(event.relatedTarget as Node | null)) return;
+ setFocused(false);
+ setActiveKey(null);
+ }}
+ onChange={(event) => {
+ setFocused(true);
+ setActiveKey(null);
+ onQueryChange(event.target.value);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') {
+ setFocused(false);
+ setActiveKey(null);
+ return;
+ }
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ if (!options.length) return;
+ event.preventDefault();
+ setFocused(true);
+ moveActive(event.key === 'ArrowDown' ? 1 : -1);
+ return;
+ }
+ if (event.key === 'Home' || event.key === 'End') {
+ if (!options.length) return;
+ event.preventDefault();
+ setFocused(true);
+ activateAt(event.key === 'Home' ? 0 : options.length - 1);
+ return;
+ }
+ if (event.key !== 'Enter') return;
+ event.preventDefault();
+ if (active) {
+ commit(active);
+ return;
+ }
+ onSubmitTypedEmail();
+ }}
+ />
+ </div>
+ <Button
+ type="button"
+ size="icon"
+ variant="outline"
+ className="size-8 shrink-0"
+ disabled={disabled || !query}
+ onClick={onSubmitTypedEmail}
+ aria-label={t('chat.showPage.addEmail')}
+ >
+ <Plus className="size-3.5" />
+ </Button>
+ </div>
+
+ {open ? (
+ <div
+ id={listId}
+ ref={listRef}
+ role="listbox"
+ aria-label={t('chat.showPage.shareAudienceOptions')}
+ className="absolute left-0 top-9 z-50 max-h-44 w-[calc(100%-2.375rem)] overflow-y-auto rounded-md border border-border bg-background p-1 shadow-lg"
+ >
+ {directoryLoading ? (
+ <div className="flex items-center gap-1.5 px-2 py-1.5 text-[11px] text-muted">
+ <Loader2 className="size-3 animate-spin" />
+ {t('chat.showPage.loadingShareDirectory')}
+ </div>
+ ) : null}
+ {options.map((option, index) => {
+ const OptionIcon = option.kind === 'group' ? Users : Mail;
+ return (
+ <button
+ key={showAccessEntryKey(option)}
+ id={optionDomId(option)}
+ type="button"
+ role="option"
+ aria-selected={index === activeIndex}
+ data-active={index === activeIndex}
+ // Keeps the field from blurring before the click lands.
+ onMouseDown={(event) => event.preventDefault()}
+ onMouseEnter={() => setActiveKey(showAccessEntryKey(option))}
+ onClick={() => commit(option)}
+ className={clsx(
+ 'flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs transition-colors',
+ index === activeIndex ? 'bg-mint/[0.1]' : 'hover:bg-foreground/[0.05]',
+ )}
+ >
+ <OptionIcon className="size-3.5 shrink-0 text-muted" />
+ <span className="min-w-0 flex-1 truncate text-foreground">{option.label}</span>
+ {option.kind === 'group' ? (
+ <span className="shrink-0 text-[10px] uppercase tracking-wide text-muted">
+ {t('chat.showPage.shareGroupBadge')}
+ </span>
+ ) : null}
+ </button>
+ );
+ })}
+ {!directoryLoading && options.length === 0 ? (
+ <p className="px-2 py-1.5 text-[11px] leading-snug text-muted">
+ {t('chat.showPage.shareSuggestionEmpty')}
+ </p>
+ ) : null}
+ {truncated ? (
+ <p className="px-2 py-1.5 text-[11px] leading-snug text-muted">
+ {t('chat.showPage.shareSuggestionNarrow')}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
export function ShowPageSharingSettings({
active,
canManage,
sessionId,
onApplied,
ownerWindowId,
- showCustomLink = true,
}: {
active: boolean;
canManage: boolean;
sessionId: string;
onApplied?: (showAccess: ShowAccess) => void;
ownerWindowId?: string;
- showCustomLink?: boolean;
}) {
const { t } = useTranslation();
const api = useApi();
@@ -142,13 +380,21 @@ export function ShowPageSharingSettings({
const [saved, setSaved] = useState<ShowAccess | null>(null);
const [mode, setMode] = useState<ShowAccessMode>('private');
const [shareId, setShareId] = useState('');
- const [emails, setEmails] = useState<string[]>([]);
- const [emailDraft, setEmailDraft] = useState('');
+ const [entries, setEntries] = useState<ShowAccessEntry[]>([]);
+ const [query, setQuery] = useState('');
const [emailInvalid, setEmailInvalid] = useState(false);
const [saving, setSaving] = useState(false);
+ const [directory, setDirectory] = useState<ShowAccessDirectory | null>(null);
+ const [directoryGate, setDirectoryGate] = useState<DirectoryGate>('idle');
const generationRef = useRef(0);
const savingRef = useRef(false);
const savedRef = useRef<ShowAccess | null>(null);
+ const directoryRequestedRef = useRef(false);
+ // Directory is instance-level (`getPermissions`), not page-revision-level.
+ // Tying it to generationRef let a CAS `load()` discard an in-flight
+ // directory response while the latch stayed true, so the combobox spun
+ // until remount. This counter only advances with the session effect.
+ const directoryGenerationRef = useRef(0);
const sessionIdRef = useRef(sessionId);
sessionIdRef.current = sessionId;
@@ -159,8 +405,8 @@ export function ShowPageSharingSettings({
setSaved(showAccess);
setMode(showAccess.access_mode);
if (!preserveShareIdDraft) setShareId(showAccess.share_id ?? '');
- setEmails(showAccess.normalized_emails);
- setEmailDraft('');
+ setEntries(showAccessEntriesOf(showAccess));
+ setQuery('');
setEmailInvalid(false);
},
[sessionId],
@@ -185,53 +431,95 @@ export function ShowPageSharingSettings({
useEffect(() => {
generationRef.current += 1;
+ directoryGenerationRef.current += 1;
savingRef.current = false;
savedRef.current = null;
setSaved(null);
setMode('private');
setShareId('');
- setEmails([]);
- setEmailDraft('');
+ setEntries([]);
+ setQuery('');
setEmailInvalid(false);
setSaving(false);
setGate('idle');
+ setDirectory(null);
+ setDirectoryGate('idle');
+ directoryRequestedRef.current = false;
if (active && canManage) void load();
return () => {
generationRef.current += 1;
+ directoryGenerationRef.current += 1;
savingRef.current = false;
};
}, [active, canManage, load, sessionId]);
+ // The Organization directory is only needed to search an audience, so it is
+ // read when Limited is actually in play. A failure degrades to email-only
+ // entry instead of blocking the audience the owner can still type out.
+ // The "already requested" latch is a ref, not the gate state: keying it off
+ // the gate would let this effect's own `loading` write re-run and cancel the
+ // request it just started.
+ useEffect(() => {
+ if (!active || !canManage || mode !== 'limited' || directoryRequestedRef.current) return;
+ directoryRequestedRef.current = true;
+ const generation = directoryGenerationRef.current;
+ setDirectoryGate('loading');
+ void (async () => {
+ try {
+ const permissions = await getPermissions();
+ if (generation !== directoryGenerationRef.current) return;
+ const next = showAccessDirectoryOf(permissions);
+ setDirectory(next);
+ setDirectoryGate(next ? 'ready' : 'unavailable');
+ } catch {
+ if (generation !== directoryGenerationRef.current) return;
+ setDirectory(null);
+ setDirectoryGate('unavailable');
+ }
+ })();
+ }, [active, canManage, mode]);
+
const normalizedShareId = shareId.trim() || null;
const sharedMode = mode === 'limited' || mode === 'public';
const shareIdInvalid = sharedMode && (!normalizedShareId || !isValidShareId(normalizedShareId));
const accessDirty = Boolean(
- saved && showAccessDraftChanged(saved, mode, saved.share_id, emails),
+ saved && showAccessDraftChanged(saved, mode, saved.share_id, entries),
);
const shareIdDirty = Boolean(saved && normalizedShareId !== saved.share_id);
- const emailLimitReached = emails.length >= SHOW_ACCESS_EMAIL_MAX_COUNT;
+ const entryLimitReached = entries.length >= SHOW_ACCESS_ENTRY_MAX_COUNT;
const editable = canManage && gate !== 'loading' && !saving;
+ const lastEntryPinned = mode === 'limited' && entries.length <= 1;
+
+ const { suggestions, truncated } = useMemo(
+ () => showAccessSuggestions(directory, query, entries),
+ [directory, entries, query],
+ );
+ const organizationEntry = entries.find((entry) => entry.kind === 'organization') ?? null;
+ const organizationId = organizationEntry?.value ?? directory?.organization_id ?? null;
+ const groupName = (groupId: string) => (
+ directory?.groups.find((group) => group.id === groupId)?.name ?? groupId
+ );
const commit = async (
nextMode: ShowAccessMode,
nextShareId: string,
- nextEmails: string[],
+ nextEntries: ShowAccessEntry[],
preserveShareIdDraftOnConflict = false,
preserveShareIdDraftOnSuccess = preserveShareIdDraftOnConflict,
) => {
const current = savedRef.current;
const targetShareId = nextShareId.trim() || null;
- const nextTargetEmails = showAccessTargetEmails(nextMode, nextEmails);
+ const targetEntries = showAccessTargetEntries(nextMode, nextEntries);
const nextInvalid =
(nextMode !== 'private' && (!targetShareId || !isValidShareId(targetShareId)))
- || (nextMode === 'limited' && nextTargetEmails.length === 0);
+ || (nextMode === 'limited' && targetEntries.length === 0);
if (
!current
|| savingRef.current
|| nextInvalid
|| !canManage
|| gate === 'loading'
- || !showAccessDraftChanged(current, nextMode, targetShareId, nextEmails)
+ || !showAccessDraftChanged(current, nextMode, targetShareId, nextEntries)
) {
return;
}
@@ -242,12 +530,10 @@ export function ShowPageSharingSettings({
savingRef.current = true;
setSaving(true);
try {
- const result = await api.applyShowAccess(requestSessionId, {
- expected_revision: current.revision,
- target_access_mode: nextMode,
- target_share_id: targetShareId,
- target_emails: nextTargetEmails,
- });
+ const result = await api.applyShowAccess(
+ requestSessionId,
+ showAccessApplyPayload(current.revision, nextMode, targetShareId, nextEntries),
+ );
if (result.show_access.page_id !== requestSessionId) {
throw new Error('ShowAccess page identity mismatch');
}
@@ -288,42 +574,59 @@ export function ShowPageSharingSettings({
if (!editable || nextMode === mode) return;
setMode(nextMode);
setEmailInvalid(false);
- if (nextMode === 'limited' && emails.length === 0) return;
- void commit(nextMode, savedRef.current?.share_id ?? shareId, emails, shareIdDirty);
+ if (nextMode === 'limited' && entries.length === 0) return;
+ void commit(nextMode, savedRef.current?.share_id ?? shareId, entries, shareIdDirty);
+ };
+
+ const applyEntries = (nextEntries: ShowAccessEntry[]) => {
+ if (showAccessEntriesKey(nextEntries) === showAccessEntriesKey(entries)) return;
+ setEntries(nextEntries);
+ if (mode === 'limited') {
+ void commit(mode, savedRef.current?.share_id ?? shareId, nextEntries, shareIdDirty);
+ }
+ };
+
+ const addEntry = (entry: ShowAccessEntry) => {
+ if (!editable || entryLimitReached) return;
+ setQuery('');
+ setEmailInvalid(false);
+ applyEntries(withShowAccessEntry(entries, entry));
};
- const addEmail = () => {
- if (!editable || emailLimitReached) return;
- const normalized = normalizeShowAccessEmail(emailDraft);
+ const submitTypedEmail = () => {
+ if (!editable || entryLimitReached) return;
+ const normalized = normalizeShowAccessEmail(query);
if (!normalized) {
setEmailInvalid(true);
return;
}
- const nextEmails = normalizedSet([...emails, normalized]);
- setEmails(nextEmails);
- setEmailDraft('');
- setEmailInvalid(false);
- if (mode === 'limited') {
- void commit(mode, savedRef.current?.share_id ?? shareId, nextEmails, shareIdDirty);
- }
+ addEntry({ kind: 'email', value: normalized });
};
- const removeEmail = (email: string) => {
- if (!editable || (mode === 'limited' && emails.length <= 1)) return;
- const nextEmails = emails.filter((value) => value !== email);
- setEmails(nextEmails);
- if (mode === 'limited') {
- void commit(mode, savedRef.current?.share_id ?? shareId, nextEmails, shareIdDirty);
+ const removeEntry = (entry: ShowAccessEntry) => {
+ if (!editable) return;
+ if (lastEntryPinned) return;
+ applyEntries(withoutShowAccessEntry(entries, entry));
+ };
+
+ const toggleOrganization = (next: boolean) => {
+ if (!editable || !organizationId) return;
+ if (next) {
+ addEntry({ kind: 'organization', value: organizationId });
+ return;
}
+ removeEntry({ kind: 'organization', value: organizationId });
};
const saveShareId = () => {
if (!editable || shareIdInvalid) return;
- void commit(mode, shareId, emails, true, false);
+ void commit(mode, shareId, entries, true, false);
};
if (!canManage) return null;
+ const audienceVariant = directory ? 'organization' : 'email';
+
return (
<div className="space-y-2.5">
{gate === 'loading' || gate === 'idle' ? (
@@ -336,7 +639,7 @@ export function ShowPageSharingSettings({
</div>
) : saved ? (
<>
- {showCustomLink && sharedMode ? (
+ {sharedMode ? (
<section
className="space-y-1.5"
aria-label={t('showPages.shareId.label')}
@@ -372,7 +675,7 @@ export function ShowPageSharingSettings({
disabled={
!editable
|| shareIdInvalid
- || (mode === 'limited' && emails.length === 0)
+ || (mode === 'limited' && entries.length === 0)
}
onClick={saveShareId}
aria-label={t('common.save')}
@@ -395,10 +698,7 @@ export function ShowPageSharingSettings({
<section
aria-label={t('chat.showPage.sharingAccess')}
- className={clsx(
- 'space-y-2.5',
- showCustomLink && sharedMode && 'border-t border-border pt-3',
- )}
+ className={clsx('space-y-2.5', sharedMode && 'border-t border-border pt-3')}
>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
@@ -429,7 +729,7 @@ export function ShowPageSharingSettings({
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<span className="text-[11px] font-medium text-foreground">
- {t('chat.showPage.limitedEmails')}
+ {t('chat.showPage.shareAudience')}
</span>
{saved.access_mode === 'limited' && !accessDirty && !saving ? (
<span className="flex items-center gap-1 text-[11px] text-mint-ink">
@@ -438,79 +738,108 @@ export function ShowPageSharingSettings({
</span>
) : null}
</div>
- <div className="flex w-full max-w-[17.5rem] items-start gap-1.5">
- <div className="min-w-0 flex-1">
- <Input
- type="email"
- value={emailDraft}
- disabled={!editable || emailLimitReached}
- onChange={(event) => {
- setEmailDraft(event.target.value);
- setEmailInvalid(false);
- }}
- onKeyDown={(event) => {
- if (event.key !== 'Enter') return;
- event.preventDefault();
- addEmail();
- }}
- placeholder={t('chat.showPage.emailPlaceholder')}
- aria-label={t('chat.showPage.limitedEmails')}
- aria-invalid={emailInvalid || undefined}
- className={clsx('h-8 text-xs', emailInvalid && 'border-destructive')}
- />
- {emailInvalid ? (
- <p className="mt-1 text-[11px] text-destructive-ink">
- {t('chat.showPage.emailInvalid')}
- </p>
- ) : null}
- </div>
- <Button
- type="button"
- size="icon"
- variant="outline"
- className="size-8 shrink-0"
- disabled={!editable || !emailDraft || emailLimitReached}
- onClick={addEmail}
- aria-label={t('chat.showPage.addEmail')}
- >
- <Plus className="size-3.5" />
- </Button>
- </div>
- {emails.length ? (
- <div className="flex max-h-32 flex-wrap gap-1.5 overflow-y-auto">
- {emails.map((email) => {
- const lastLimitedEmail = mode === 'limited' && emails.length === 1;
- return (
+
+ <AudienceCombobox
+ disabled={!editable || entryLimitReached}
+ directoryLoading={directoryGate === 'loading'}
+ suggestions={suggestions}
+ truncated={truncated}
+ placeholder={t(`chat.showPage.shareAudiencePlaceholder.${audienceVariant}`)}
+ query={query}
+ invalid={emailInvalid}
+ onQueryChange={(value) => {
+ setQuery(value);
+ setEmailInvalid(false);
+ }}
+ onSelect={(suggestion) => addEntry({
+ kind: suggestion.kind,
+ value: suggestion.value,
+ })}
+ onSubmitTypedEmail={submitTypedEmail}
+ />
+ {emailInvalid ? (
+ <p className="text-[11px] text-destructive-ink">
+ {t('chat.showPage.emailInvalid')}
+ </p>
+ ) : null}
+
+ {/* One flat audience: the Organization switch sits at the top of
+ the very list it belongs to, level with the group and email
+ entries it neither replaces nor absorbs. */}
+ <div className="max-h-40 space-y-1 overflow-y-auto">
+ {organizationId ? (
+ <div className="flex min-h-8 items-center gap-2 rounded-md border border-border bg-foreground/[0.03] px-2 py-1.5">
+ <Building2 className="size-3.5 shrink-0 text-cyan-ink" />
+ <span className="min-w-0 flex-1 truncate text-[11px] text-foreground">
+ {directory?.organization_name
+ ? t('chat.showPage.shareOrganizationNamed', {
+ name: directory.organization_name,
+ })
+ : t('chat.showPage.shareOrganizationGeneric')}
+ </span>
+ <Switch
+ checked={Boolean(organizationEntry)}
+ disabled={
+ !editable
+ || (Boolean(organizationEntry) && lastEntryPinned)
+ || (!organizationEntry && entryLimitReached)
+ }
+ onCheckedChange={toggleOrganization}
+ label={t('chat.showPage.shareOrganizationGeneric')}
+ />
+ </div>
+ ) : null}
+
+ {entries.filter((entry) => entry.kind !== 'organization').map((entry) => {
+ const label = entry.kind === 'group' ? groupName(entry.value) : entry.value;
+ const EntryIcon = entry.kind === 'group' ? Users : Mail;
+ return (
+ <div
+ key={showAccessEntryKey(entry)}
+ className="flex min-h-8 items-center gap-2 rounded-md border border-border bg-foreground/[0.03] px-2 py-1.5"
+ >
+ <EntryIcon className="size-3.5 shrink-0 text-muted" />
<span
- key={email}
- className="inline-flex h-7 max-w-full items-center gap-1 rounded-md border border-border bg-foreground/[0.04] pl-2.5 pr-1 text-[11px] text-foreground"
+ className={clsx(
+ 'min-w-0 flex-1 truncate text-[11px] text-foreground',
+ entry.kind === 'email' && 'font-mono',
+ )}
>
- <span className="min-w-0 truncate font-mono">{email}</span>
- <Button
- type="button"
- size="icon"
- variant="ghost"
- className="size-5 shrink-0"
- disabled={!editable || lastLimitedEmail}
- onClick={() => removeEmail(email)}
- aria-label={t('chat.showPage.removeEmail', { email })}
- title={lastLimitedEmail
- ? t('chat.showPage.keepOneLimitedEmail')
- : t('chat.showPage.removeEmail', { email })}
- >
- <X className="size-3" />
- </Button>
+ {label}
</span>
- );
- })}
- </div>
- ) : (
+ {entry.kind === 'group' ? (
+ <span className="shrink-0 text-[10px] uppercase tracking-wide text-muted">
+ {t('chat.showPage.shareGroupBadge')}
+ </span>
+ ) : null}
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-5 shrink-0"
+ disabled={!editable || lastEntryPinned}
+ onClick={() => removeEntry(entry)}
+ aria-label={t('chat.showPage.removeShareEntry', { label })}
+ title={lastEntryPinned
+ ? t('chat.showPage.keepOneShareEntry')
+ : t('chat.showPage.removeShareEntry', { label })}
+ >
+ <X className="size-3" />
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+
+ {entries.length === 0 ? (
<p className="text-[11px] text-destructive-ink">
- {t('chat.showPage.limitedEmailRequired')}
+ {t('chat.showPage.shareAudienceRequired')}
</p>
- )}
+ ) : null}
<p className="text-[11px] text-muted">
- {t('chat.showPage.limitedEmailHint', { count: SHOW_ACCESS_EMAIL_MAX_COUNT })}
+ {t(`chat.showPage.shareAudienceHint.${audienceVariant}`, {
+ limit: SHOW_ACCESS_ENTRY_MAX_COUNT,
+ })}
</p>
</div>
) : null}
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
deleted file mode 100644
index 9373d06e1..000000000
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
+++ /dev/null
@@ -1,689 +0,0 @@
-/** @vitest-environment jsdom */
-
-import { act, cleanup, render, screen, within } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { PermissionsApiError } from '@/features/permissions/api';
-import { requiresResourcePolicyNarrowing } from '@/features/permissions/policy';
-import type {
- DirectoryGroup,
- PermissionResource,
- PermissionsResponse,
- ResourceAccessResponse,
-} from '@/features/permissions/types';
-import type { ShowPageAccess } from '@/lib/showPageAccess';
-
-import { ShowPageWorkspaceAccessControl } from './ShowPageWorkspaceAccessControl';
-
-const api = vi.hoisted(() => ({
- getPermissions: vi.fn(),
- getResourceAccess: vi.fn(),
- updateResourceAccess: vi.fn(),
-}));
-
-vi.mock('@/features/permissions/api', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/features/permissions/api')>()),
- getPermissions: api.getPermissions,
- getResourceAccess: api.getResourceAccess,
- updateResourceAccess: api.updateResourceAccess,
-}));
-
-const translations: Record<string, string> = {
- 'chat.showPage.workspaceAccess': 'Organization access',
- 'chat.showPage.workspaceAccessDesc': 'Controls authenticated access inside this Organization. Link access remains separate.',
- 'chat.showPage.loadingWorkspaceAccess': 'Loading Organization access...',
- 'chat.showPage.workspacePersonal': 'This Show Page belongs to a Personal Avibe.',
- 'chat.showPage.workspaceUnmanaged': 'Organization access is unavailable until this Avibe is paired.',
- 'chat.showPage.workspacePending': 'Organization ownership is known, but its exact binding is temporarily unavailable. Access remains private.',
- 'chat.showPage.workspaceConfigurationUnavailable': 'Organization access cannot be verified while Avibe configuration is unavailable. Access remains private.',
- 'chat.showPage.workspaceOwnershipConflict': 'This Show Page is bound to a different ownership domain. Access remains private until the conflict is resolved.',
- 'chat.showPage.workspaceModes.private': 'Private',
- 'chat.showPage.workspaceModes.organization': 'Organization members',
- 'chat.showPage.workspaceModes.scope': 'Selected groups',
- 'chat.showPage.workspaceHelp.private': 'Only the page owner and Instance Owner can use it.',
- 'chat.showPage.workspaceHelp.public': 'Authenticated members of this Organization can use it.',
- 'chat.showPage.workspaceHelp.scope': 'Only members of the selected Organization groups can use it.',
- 'chat.showPage.workspaceGroups': 'Organization groups',
- 'chat.showPage.workspaceArchived': 'Archived',
- 'chat.showPage.workspaceNoGroups': 'No active groups are available.',
- 'chat.showPage.workspaceGroupRequired': 'Select at least one group.',
- 'chat.showPage.workspaceRevisionConflict': 'Organization access changed elsewhere. Your draft was kept on the latest revision.',
- 'chat.showPage.workspaceOffline': 'The last known Organization policy is shown while Permissions is offline. Editing is disabled.',
- 'chat.showPage.workspaceReadOnly': 'Avibe Cloud owns this Organization policy. Edit it in Avibe Cloud.',
- 'chat.showPage.workspaceOwnerOnly': 'Only the Instance Owner can change Organization access.',
- 'chat.showPage.workspaceLoadError': 'Organization access could not be loaded.',
- 'chat.showPage.workspaceNarrowTitle': 'Narrow Organization access?',
- 'chat.showPage.workspaceNarrowBody': 'Some people may lose access as soon as this policy is applied.',
- 'chat.showPage.applyWorkspaceAccess': 'Apply',
- 'chat.showPage.workspaceSync.pending': 'The policy is waiting for this Avibe to apply it.',
- 'chat.showPage.workspaceSync.offline': 'This Avibe has not acknowledged the latest policy.',
- 'chat.showPage.workspaceSync.error': 'The latest policy could not be applied.',
- 'common.retry': 'Retry',
-};
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string, options?: { defaultValue?: string }) => (
- translations[key] ?? options?.defaultValue ?? key
- ),
- }),
-}));
-
-const activeGroup: DirectoryGroup = {
- id: 'group-active',
- name: 'Design',
- archived_at: null,
-};
-
-const archivedGroup: DirectoryGroup = {
- id: 'group-archived',
- name: 'Retired Team',
- archived_at: '2026-08-18T00:00:00Z',
-};
-
-const newArchivedGroup: DirectoryGroup = {
- id: 'group-new-archived',
- name: 'Former Operations',
- archived_at: '2026-08-18T01:00:00Z',
-};
-
-const showPageAccess = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({
- ok: true,
- mode: 'organization',
- ownership_status: 'unchanged',
- instance_id: 'inst-1',
- organization_id: 'org-1',
- policy_organization_id: 'org-1',
- access_level: 'private',
- group_ids: [],
- policy_revision: 4,
- last_applied_control_plane_revision: 4,
- can_use: true,
- can_manage: true,
- can_publish_public: true,
- ...overrides,
-});
-
-const permissions = ({
- groups = [activeGroup],
- members = [{
- id: 'owner-1',
- email: '[email protected]',
- organization_role: 'owner' as const,
- group_ids: [],
- }],
- offline = false,
- permissionAuthority = 'instance',
- localMutationAllowed = true,
-}: {
- groups?: DirectoryGroup[];
- members?: PermissionsResponse['projection']['directory']['members'];
- offline?: boolean;
- permissionAuthority?: 'instance' | 'cloud';
- localMutationAllowed?: boolean;
-} = {}): PermissionsResponse => ({
- ok: true,
- source: offline ? 'cache' : 'live',
- offline,
- cached_at: offline ? 1 : null,
- projection: {
- schema_version: 1,
- instance: {
- id: 'inst-1',
- organization: { id: 'org-1', name: 'Example Organization' },
- access_mode: 'allowlist',
- permission_authority: permissionAuthority,
- local_mutation_allowed: localMutationAllowed,
- authorization_revision: 7,
- },
- capabilities: ['instance.permissions.read', 'instance.permissions.mutate'],
- access: { owner: { email: '[email protected]', role: 'owner' }, entries: [] },
- directory: { members, groups },
- projects: [],
- policy_sync: {
- status: offline ? 'offline' : 'in_sync',
- projects: { active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 },
- resources: { active: 1, error: 0, offline: 0, applying: 0, in_sync: 1 },
- },
- },
-});
-
-const resource = ({
- sessionId = 'ses-1',
- level = 'private',
- groupIds = [],
- ownerUserId = 'owner-1',
- revision = 4,
- status = 'in_sync',
-}: {
- sessionId?: string;
- level?: PermissionResource['access']['access_level'];
- groupIds?: string[];
- ownerUserId?: string | null;
- revision?: number;
- status?: PermissionResource['sync']['status'];
-} = {}): PermissionResource => ({
- instance_id: 'inst-1',
- resource_kind: 'show_page',
- resource_id: sessionId,
- display_name: sessionId,
- owner_user_id: ownerUserId,
- access: { access_level: level, group_ids: groupIds, revision },
- sync: {
- status,
- desired_acl_revision: revision,
- applied_acl_revision: status === 'in_sync' ? revision : Math.max(0, revision - 1),
- last_synced_at: null,
- },
-});
-
-const renderControl = (
- access: ShowPageAccess = showPageAccess(),
- options: { sessionId?: string; canManageInstance?: boolean; ownerWindowId?: string } = {},
-) => render(
- <ShowPageWorkspaceAccessControl
- access={access}
- active
- canManageInstance={options.canManageInstance ?? true}
- sessionId={options.sessionId ?? 'ses-1'}
- ownerWindowId={options.ownerWindowId}
- />,
-);
-
-function deferred<T>() {
- let resolve: (value: T) => void = () => undefined;
- const promise = new Promise<T>((next) => {
- resolve = next;
- });
- return { promise, resolve };
-}
-
-beforeEach(() => {
- api.getPermissions.mockReset();
- api.getPermissions.mockResolvedValue(permissions());
- api.getResourceAccess.mockReset();
- api.getResourceAccess.mockResolvedValue({ resource: resource() });
- api.updateResourceAccess.mockReset();
-});
-
-afterEach(() => {
- cleanup();
- vi.clearAllMocks();
-});
-
-describe('ShowPageWorkspaceAccessControl', () => {
- it('prioritizes an ownership conflict over the Personal mode message', () => {
- renderControl(showPageAccess({ mode: 'personal', ownership_status: 'conflict' }));
-
- expect(screen.getByText('This Show Page is bound to a different ownership domain. Access remains private until the conflict is resolved.')).toBeTruthy();
- expect(screen.queryByText('This Show Page belongs to a Personal Avibe.')).toBeNull();
- expect(api.getPermissions).not.toHaveBeenCalled();
- expect(api.getResourceAccess).not.toHaveBeenCalled();
- });
-
- it('keeps the requested policy order while narrowing stays owner-aware', async () => {
- renderControl();
-
- const radios = await screen.findAllByRole('radio');
- expect(radios.map((radio) => radio.textContent)).toEqual([
- 'Private',
- 'Selected groups',
- 'Organization members',
- ]);
- });
-
- it('polls a pending Resource until the exact instance reports a terminal sync state', async () => {
- vi.useFakeTimers();
- try {
- api.getResourceAccess
- .mockResolvedValueOnce({ resource: resource({ status: 'pending' }) })
- .mockResolvedValueOnce({ resource: resource({ status: 'offline' }) });
- renderControl();
-
- await act(async () => {
- await Promise.resolve();
- await Promise.resolve();
- });
- expect(api.getResourceAccess).toHaveBeenCalledTimes(1);
- expect(screen.getByText('The policy is waiting for this Avibe to apply it.')).toBeTruthy();
-
- await act(async () => {
- vi.advanceTimersByTime(2_000);
- await Promise.resolve();
- await Promise.resolve();
- });
- expect(api.getResourceAccess).toHaveBeenCalledTimes(2);
- expect(screen.getByText('This Avibe has not acknowledged the latest policy.')).toBeTruthy();
- } finally {
- vi.useRealTimers();
- }
- });
-
- it('classifies every Organization policy reduction at the shared boundary', () => {
- expect(requiresResourcePolicyNarrowing('public', [], 'private', [])).toBe(true);
- expect(requiresResourcePolicyNarrowing('public', [], 'scope', ['group-active'])).toBe(true);
- expect(requiresResourcePolicyNarrowing('scope', ['group-active'], 'private', [])).toBe(true);
- expect(requiresResourcePolicyNarrowing(
- 'scope',
- ['group-active', 'group-archived'],
- 'scope',
- ['group-active'],
- )).toBe(true);
- expect(requiresResourcePolicyNarrowing('scope', ['group-active'], 'public', [])).toBe(false);
- expect(requiresResourcePolicyNarrowing('private', [], 'public', [])).toBe(false);
- expect(requiresResourcePolicyNarrowing('private', [], 'scope', ['group-active'])).toBe(true);
- expect(requiresResourcePolicyNarrowing(
- 'private',
- [],
- 'scope',
- ['group-active'],
- { isInstanceOwner: true },
- )).toBe(false);
- expect(requiresResourcePolicyNarrowing(
- 'private',
- [],
- 'scope',
- ['group-active'],
- { organizationGroupIds: ['group-active'] },
- )).toBe(false);
- });
-
- it('confirms an Organization policy reduction before sending it', async () => {
- api.getResourceAccess.mockResolvedValue({
- resource: resource({ level: 'public' }),
- });
- api.updateResourceAccess.mockResolvedValue({
- ok: true,
- resource: resource({ level: 'private', revision: 5 }),
- });
- const user = userEvent.setup();
- renderControl();
-
- await user.click(await screen.findByRole('radio', { name: 'Private' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
-
- const dialog = screen.getByText('Narrow Organization access?').closest('[role="dialog"]');
- expect(dialog).toBeTruthy();
- expect(api.updateResourceAccess).not.toHaveBeenCalled();
-
- await user.click(within(dialog as HTMLElement).getByRole('button', { name: 'Apply' }));
- expect(api.updateResourceAccess).toHaveBeenCalledWith(
- { resource_kind: 'show_page', resource_id: 'ses-1' },
- 'private',
- [],
- 4,
- 'inst-1',
- );
- });
-
- it('associates the narrowing confirmation with its owning app window', async () => {
- api.getResourceAccess.mockResolvedValue({
- resource: resource({ level: 'public' }),
- });
- const user = userEvent.setup();
- renderControl(showPageAccess(), { ownerWindowId: 'window-42' });
-
- await user.click(await screen.findByRole('radio', { name: 'Private' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
-
- const dialog = screen.getByText('Narrow Organization access?').closest('[role="dialog"]');
- expect(dialog?.getAttribute('data-window-owner-id')).toBe('window-42');
- });
-
- it('saves Organization and selected-group policies and reloads the canonical group selection', async () => {
- api.updateResourceAccess
- .mockResolvedValueOnce({ ok: true, resource: resource({ level: 'public', revision: 5 }) })
- .mockResolvedValueOnce({
- ok: true,
- resource: resource({ level: 'scope', groupIds: ['group-active'], revision: 6 }),
- });
- const user = userEvent.setup();
- const view = renderControl();
-
- await user.click(await screen.findByRole('radio', { name: 'Organization members' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
- expect(api.updateResourceAccess).toHaveBeenLastCalledWith(
- { resource_kind: 'show_page', resource_id: 'ses-1' },
- 'public',
- [],
- 4,
- 'inst-1',
- );
-
- await user.click(screen.getByRole('radio', { name: 'Selected groups' }));
- await user.click(screen.getByRole('checkbox', { name: 'Design' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
- const narrowingDialog = screen.getByText('Narrow Organization access?').closest('[role="dialog"]');
- await user.click(within(narrowingDialog as HTMLElement).getByRole('button', { name: 'Apply' }));
- expect(api.updateResourceAccess).toHaveBeenLastCalledWith(
- { resource_kind: 'show_page', resource_id: 'ses-1' },
- 'scope',
- ['group-active'],
- 5,
- 'inst-1',
- );
-
- view.unmount();
- api.getResourceAccess.mockResolvedValue({
- resource: resource({ level: 'scope', groupIds: ['group-active'], revision: 6 }),
- });
- renderControl();
-
- expect((await screen.findByRole('radio', { name: 'Selected groups' })).getAttribute('aria-checked')).toBe('true');
- expect(screen.getByRole('checkbox', { name: 'Design' }).getAttribute('aria-checked')).toBe('true');
- });
-
- it('applies private-to-scope audience expansion without a narrowing confirmation', async () => {
- api.updateResourceAccess.mockResolvedValue({
- ok: true,
- resource: resource({ level: 'scope', groupIds: ['group-active'], revision: 5 }),
- });
- const user = userEvent.setup();
- renderControl();
-
- await user.click(await screen.findByRole('radio', { name: 'Selected groups' }));
- await user.click(screen.getByRole('checkbox', { name: 'Design' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
-
- expect(screen.queryByText('Narrow Organization access?')).toBeNull();
- expect(api.updateResourceAccess).toHaveBeenCalledWith(
- { resource_kind: 'show_page', resource_id: 'ses-1' },
- 'scope',
- ['group-active'],
- 4,
- 'inst-1',
- );
- });
-
- it('confirms private-to-scope when the resource owner is outside the selected groups', async () => {
- api.getPermissions.mockResolvedValue(permissions({
- members: [{
- id: 'project-owner',
- email: '[email protected]',
- organization_role: 'member',
- group_ids: ['group-other'],
- }],
- }));
- api.getResourceAccess.mockResolvedValue({
- resource: resource({ ownerUserId: 'project-owner' }),
- });
- const user = userEvent.setup();
- renderControl();
-
- await user.click(await screen.findByRole('radio', { name: 'Selected groups' }));
- await user.click(screen.getByRole('checkbox', { name: 'Design' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
-
- expect(screen.getByText('Narrow Organization access?')).toBeTruthy();
- expect(api.updateResourceAccess).not.toHaveBeenCalled();
- });
-
- it('keeps bound archived groups visible and selected without offering unbound archived groups', async () => {
- api.getPermissions.mockResolvedValue(permissions({
- groups: [activeGroup, archivedGroup, newArchivedGroup],
- }));
- api.getResourceAccess.mockResolvedValue({
- resource: resource({ level: 'scope', groupIds: ['group-archived'] }),
- });
- api.updateResourceAccess.mockResolvedValue({
- ok: true,
- resource: resource({
- level: 'scope',
- groupIds: ['group-active', 'group-archived'],
- revision: 5,
- }),
- });
- const user = userEvent.setup();
- renderControl();
-
- const archived = await screen.findByRole('checkbox', { name: 'Retired Team' });
- expect(archived.getAttribute('aria-checked')).toBe('true');
- expect((archived as HTMLButtonElement).disabled).toBe(true);
- expect(screen.getByText('Archived')).toBeTruthy();
- expect(screen.queryByText('Former Operations')).toBeNull();
-
- await user.click(screen.getByRole('radio', { name: 'Organization members' }));
- await user.click(screen.getByRole('radio', { name: 'Selected groups' }));
- expect(screen.getByRole('checkbox', { name: 'Retired Team' }).getAttribute('aria-checked')).toBe('true');
-
- await user.click(screen.getByRole('checkbox', { name: 'Design' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
- expect(api.updateResourceAccess).toHaveBeenCalledWith(
- { resource_kind: 'show_page', resource_id: 'ses-1' },
- 'scope',
- ['group-active', 'group-archived'],
- 4,
- 'inst-1',
- );
- });
-
- it('preserves the draft across a 409 and folds newly bound archived groups into the retry', async () => {
- api.getPermissions
- .mockResolvedValueOnce(permissions())
- .mockResolvedValueOnce(permissions({ groups: [activeGroup, archivedGroup] }));
- api.getResourceAccess
- .mockResolvedValueOnce({ resource: resource() })
- .mockResolvedValueOnce({
- resource: resource({ level: 'scope', groupIds: ['group-archived'], revision: 5 }),
- });
- api.updateResourceAccess
- .mockRejectedValueOnce(new PermissionsApiError(409, {
- error: 'permission_revision_conflict',
- current_revision: 5,
- }))
- .mockResolvedValueOnce({
- ok: true,
- resource: resource({
- level: 'scope',
- groupIds: ['group-active', 'group-archived'],
- revision: 6,
- }),
- });
- const user = userEvent.setup();
- renderControl();
-
- await user.click(await screen.findByRole('radio', { name: 'Selected groups' }));
- await user.click(screen.getByRole('checkbox', { name: 'Design' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
-
- expect(await screen.findByText(/Your draft was kept/)).toBeTruthy();
- expect(screen.getByRole('checkbox', { name: 'Design' }).getAttribute('aria-checked')).toBe('true');
- const archived = screen.getByRole('checkbox', { name: 'Retired Team' });
- expect(archived.getAttribute('aria-checked')).toBe('true');
- expect((archived as HTMLButtonElement).disabled).toBe(true);
-
- await user.click(screen.getByRole('button', { name: 'Apply' }));
- expect(api.updateResourceAccess).toHaveBeenLastCalledWith(
- { resource_kind: 'show_page', resource_id: 'ses-1' },
- 'scope',
- ['group-active', 'group-archived'],
- 5,
- 'inst-1',
- );
- });
-
- it('disables the mounted editor when the authoritative conflict refresh fails', async () => {
- api.getPermissions
- .mockResolvedValueOnce(permissions())
- .mockRejectedValueOnce(new PermissionsApiError(503, {
- error: 'permissions_backend_unavailable',
- }));
- api.updateResourceAccess.mockRejectedValueOnce(new PermissionsApiError(409, {
- error: 'permission_revision_conflict',
- current_revision: 5,
- }));
- const user = userEvent.setup();
- renderControl();
-
- await user.click(await screen.findByRole('radio', { name: 'Organization members' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
-
- expect(await screen.findByText('Organization access could not be loaded.')).toBeTruthy();
- expect((screen.getByRole('radio', { name: 'Private' }) as HTMLButtonElement).disabled).toBe(true);
- const apply = screen.getByRole('button', { name: 'Apply' }) as HTMLButtonElement;
- expect(apply.disabled).toBe(true);
- await user.click(apply);
- expect(api.updateResourceAccess).toHaveBeenCalledTimes(1);
- });
-
- it('preserves the draft when a failed PUT is recovered with Retry', async () => {
- api.getPermissions.mockResolvedValueOnce(permissions()).mockResolvedValueOnce(permissions());
- api.getResourceAccess
- .mockResolvedValueOnce({ resource: resource() })
- .mockResolvedValueOnce({ resource: resource() });
- api.updateResourceAccess.mockRejectedValueOnce(new PermissionsApiError(503, {
- error: 'permissions_backend_unavailable',
- }));
- const user = userEvent.setup();
- renderControl();
-
- await user.click(await screen.findByRole('radio', { name: 'Selected groups' }));
- await user.click(screen.getByRole('checkbox', { name: 'Design' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
- expect(await screen.findByText('Organization access could not be loaded.')).toBeTruthy();
-
- await user.click(screen.getByRole('button', { name: 'Retry' }));
- await screen.findByRole('checkbox', { name: 'Design' });
- expect(screen.getByRole('radio', { name: 'Selected groups' }).getAttribute('aria-checked')).toBe('true');
- expect(screen.getByRole('checkbox', { name: 'Design' }).getAttribute('aria-checked')).toBe('true');
- expect(api.updateResourceAccess).toHaveBeenCalledOnce();
- });
-
- it('preserves the draft when the conflict refresh fails before a Retry', async () => {
- api.getPermissions
- .mockResolvedValueOnce(permissions())
- .mockRejectedValueOnce(new PermissionsApiError(503, {
- error: 'permissions_backend_unavailable',
- }))
- .mockResolvedValueOnce(permissions());
- api.getResourceAccess
- .mockResolvedValueOnce({ resource: resource() })
- .mockResolvedValueOnce({ resource: resource() })
- .mockResolvedValueOnce({ resource: resource() });
- api.updateResourceAccess.mockRejectedValueOnce(new PermissionsApiError(409, {
- error: 'permission_revision_conflict',
- current_revision: 5,
- }));
- const user = userEvent.setup();
- renderControl();
-
- await user.click(await screen.findByRole('radio', { name: 'Selected groups' }));
- await user.click(screen.getByRole('checkbox', { name: 'Design' }));
- await user.click(screen.getByRole('button', { name: 'Apply' }));
- expect(await screen.findByText('Organization access could not be loaded.')).toBeTruthy();
-
- await user.click(screen.getByRole('button', { name: 'Retry' }));
- await screen.findByRole('checkbox', { name: 'Design' });
- expect(screen.getByRole('radio', { name: 'Selected groups' }).getAttribute('aria-checked')).toBe('true');
- expect(screen.getByRole('checkbox', { name: 'Design' }).getAttribute('aria-checked')).toBe('true');
- expect(api.updateResourceAccess).toHaveBeenCalledOnce();
- });
-
- it('fails closed for personal, pending, unavailable, and conflicting ownership without contacting Permissions', () => {
- const personal = renderControl(showPageAccess({
- mode: 'personal',
- ownership_status: 'unchanged',
- organization_id: null,
- policy_organization_id: null,
- }));
- expect(screen.getByText(/belongs to a Personal Avibe/)).toBeTruthy();
- personal.unmount();
-
- const pending = renderControl(showPageAccess({
- mode: 'organization_pending',
- ownership_status: 'pending',
- organization_id: null,
- policy_organization_id: null,
- }));
- expect(screen.getByText(/temporarily unavailable/)).toBeTruthy();
- pending.unmount();
-
- const unavailable = renderControl(showPageAccess({
- mode: 'configuration_unavailable',
- ownership_status: 'configuration_unavailable',
- instance_id: null,
- organization_id: null,
- policy_organization_id: null,
- }));
- expect(screen.getByText(/cannot be verified/)).toBeTruthy();
- unavailable.unmount();
-
- renderControl(showPageAccess({
- ownership_status: 'conflict',
- policy_organization_id: 'org-other',
- }));
- expect(screen.getByText(/different ownership domain/)).toBeTruthy();
- expect(api.getPermissions).not.toHaveBeenCalled();
- expect(api.getResourceAccess).not.toHaveBeenCalled();
- });
-
- it('renders offline, Cloud-owned, and non-owner policy as read-only', async () => {
- api.getPermissions.mockResolvedValue(permissions({ offline: true }));
- const offline = renderControl();
- expect(await screen.findByText(/last known Organization policy/)).toBeTruthy();
- expect((screen.getByRole('radio', { name: 'Private' }) as HTMLButtonElement).disabled).toBe(true);
- offline.unmount();
-
- api.getPermissions.mockResolvedValue(permissions({
- permissionAuthority: 'cloud',
- localMutationAllowed: false,
- }));
- const cloud = renderControl();
- expect(await screen.findByText(/Avibe Cloud owns this Organization policy/)).toBeTruthy();
- expect((screen.getByRole('button', { name: 'Apply' }) as HTMLButtonElement).disabled).toBe(true);
- cloud.unmount();
-
- api.getPermissions.mockResolvedValue(permissions());
- renderControl(showPageAccess(), { canManageInstance: false });
- expect(await screen.findByText(/Only the Instance Owner/)).toBeTruthy();
- expect((screen.getByRole('radio', { name: 'Private' }) as HTMLButtonElement).disabled).toBe(true);
- });
-
- it('ignores an older session response after the control switches pages', async () => {
- const oldPermissions = deferred<PermissionsResponse>();
- const oldResource = deferred<ResourceAccessResponse>();
- const oldGroup = { id: 'group-old', name: 'Old Page Group', archived_at: null };
- const nextGroup = { id: 'group-next', name: 'Next Page Group', archived_at: null };
- api.getPermissions
- .mockImplementationOnce(() => oldPermissions.promise)
- .mockResolvedValueOnce(permissions({ groups: [nextGroup] }));
- api.getResourceAccess.mockImplementation((identity: { resource_id: string }) => (
- identity.resource_id === 'ses-old'
- ? oldResource.promise
- : Promise.resolve({
- resource: resource({
- sessionId: 'ses-next',
- level: 'scope',
- groupIds: ['group-next'],
- }),
- })
- ));
- const view = renderControl(showPageAccess(), { sessionId: 'ses-old' });
-
- view.rerender(
- <ShowPageWorkspaceAccessControl
- access={showPageAccess()}
- active
- canManageInstance
- sessionId="ses-next"
- />,
- );
- expect(await screen.findByRole('checkbox', { name: 'Next Page Group' })).toBeTruthy();
-
- await act(async () => {
- oldPermissions.resolve(permissions({ groups: [oldGroup] }));
- oldResource.resolve({
- resource: resource({
- sessionId: 'ses-old',
- level: 'scope',
- groupIds: ['group-old'],
- }),
- });
- await Promise.resolve();
- });
-
- expect(screen.getByRole('checkbox', { name: 'Next Page Group' })).toBeTruthy();
- expect(screen.queryByText('Old Page Group')).toBeNull();
- });
-});
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
deleted file mode 100644
index 0c9d5f77f..000000000
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
+++ /dev/null
@@ -1,515 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { CloudOff, Loader2, RefreshCw, Save, TriangleAlert } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
-
-import { Button } from '@/components/ui/button';
-import { Checkbox } from '@/components/ui/checkbox';
-import { ConfirmDialog } from '@/components/ui/confirm-dialog';
-import { SegmentedRadio } from '@/components/ui/segmented';
-import {
- getPermissions,
- getResourceAccess,
- isRevisionConflict,
- PermissionsApiError,
- updateResourceAccess,
-} from '@/features/permissions/api';
-import { requiresResourcePolicyNarrowing } from '@/features/permissions/policy';
-import type {
- DirectoryGroup,
- PermissionResource,
- PermissionsResponse,
- ResourceAccessLevel,
-} from '@/features/permissions/types';
-import type { ShowPageAccess } from '@/lib/showPageAccess';
-
-type Gate = 'idle' | 'loading' | 'ready' | 'conflict' | 'error';
-
-type Draft = {
- level: ResourceAccessLevel;
- groupIds: string[];
-};
-
-const RESOURCE_SYNC_POLL_INTERVAL_MS = 2_000;
-
-const uniqueSorted = (values: string[]): string[] => [...new Set(values)].sort();
-
-const resourceIdentityMatches = (
- resource: PermissionResource,
- sessionId: string,
- instanceId: string,
-): boolean => resource.instance_id === instanceId
- && resource.resource_kind === 'show_page'
- && resource.resource_id === sessionId;
-
-const organizationMatches = (
- permissions: PermissionsResponse,
- instanceId: string,
- organizationId: string,
-): boolean => permissions.projection.instance.id === instanceId
- && permissions.projection.instance.organization?.id === organizationId;
-
-export function ShowPageWorkspaceAccessControl({
- access,
- active,
- canManageInstance,
- sessionId,
- ownerWindowId,
-}: {
- access: ShowPageAccess | null;
- active: boolean;
- canManageInstance: boolean;
- sessionId: string;
- ownerWindowId?: string;
-}) {
- const { t } = useTranslation();
- const [gate, setGate] = useState<Gate>('idle');
- const [resource, setResource] = useState<PermissionResource | null>(null);
- const [permissions, setPermissions] = useState<PermissionsResponse | null>(null);
- const [groups, setGroups] = useState<DirectoryGroup[]>([]);
- const [level, setLevel] = useState<ResourceAccessLevel>('private');
- const [groupIds, setGroupIds] = useState<string[]>([]);
- const [saving, setSaving] = useState(false);
- const [confirmNarrowing, setConfirmNarrowing] = useState(false);
- const [errorCode, setErrorCode] = useState<string | null>(null);
- const generationRef = useRef(0);
- const sessionIdRef = useRef(sessionId);
- const resourceRef = useRef<PermissionResource | null>(resource);
- const pollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const draftRef = useRef<Draft>({ level, groupIds });
- sessionIdRef.current = sessionId;
- resourceRef.current = resource;
- draftRef.current = { level, groupIds };
-
- const instanceId = access?.instance_id ?? null;
- const organizationId = access?.organization_id ?? null;
- const resourceSyncStatus = resource?.sync.status;
- const ownershipConflict = access?.ownership_status === 'conflict';
- const organizationReady = access?.mode === 'organization'
- && !ownershipConflict
- && Boolean(instanceId && organizationId);
-
- const adopt = useCallback((next: PermissionResource, nextGroups: DirectoryGroup[]) => {
- setResource(next);
- setGroups(nextGroups);
- setLevel(next.access.access_level);
- setGroupIds(uniqueSorted(next.access.group_ids));
- }, []);
-
- const load = useCallback(async (
- settledGate: Gate = 'ready',
- preservedDraft?: Draft,
- ) => {
- if (!instanceId || !organizationId) return;
- const generation = ++generationRef.current;
- const requestSessionId = sessionId;
- setGate('loading');
- setErrorCode(null);
- try {
- const [nextPermissions, nextResource] = await Promise.all([
- getPermissions(),
- getResourceAccess({ resource_kind: 'show_page', resource_id: requestSessionId }),
- ]);
- if (
- generation !== generationRef.current
- || requestSessionId !== sessionIdRef.current
- ) return;
- if (
- !organizationMatches(nextPermissions, instanceId, organizationId)
- || !resourceIdentityMatches(nextResource.resource, requestSessionId, instanceId)
- ) {
- throw new Error('Show Page Organization identity mismatch');
- }
- const directoryGroups = [...nextPermissions.projection.directory.groups];
- const knownIds = new Set(directoryGroups.map((group) => group.id));
- for (const boundId of nextResource.resource.access.group_ids) {
- if (!knownIds.has(boundId)) {
- directoryGroups.push({ id: boundId, name: boundId, archived_at: 'unknown' });
- }
- }
- setPermissions(nextPermissions);
- if (preservedDraft) {
- const archivedIds = new Set(
- directoryGroups
- .filter((group) => group.archived_at !== null)
- .map((group) => group.id),
- );
- const newlyBoundArchived = nextResource.resource.access.group_ids.filter(
- (groupId) => archivedIds.has(groupId),
- );
- setResource(nextResource.resource);
- setGroups(directoryGroups);
- setLevel(preservedDraft.level);
- setGroupIds(preservedDraft.level === 'scope'
- ? uniqueSorted([...preservedDraft.groupIds, ...newlyBoundArchived])
- : []);
- } else {
- adopt(nextResource.resource, directoryGroups);
- }
- setGate(settledGate);
- } catch (caught) {
- if (
- generation !== generationRef.current
- || requestSessionId !== sessionIdRef.current
- ) return;
- setErrorCode(caught instanceof PermissionsApiError ? caught.code : 'permissions_unavailable');
- setGate('error');
- }
- }, [adopt, instanceId, organizationId, sessionId]);
-
- useEffect(() => {
- generationRef.current += 1;
- setGate('idle');
- setResource(null);
- setPermissions(null);
- setGroups([]);
- setLevel('private');
- setGroupIds([]);
- setSaving(false);
- setConfirmNarrowing(false);
- setErrorCode(null);
- if (active && organizationReady) void load();
- return () => {
- generationRef.current += 1;
- };
- }, [active, load, organizationReady, sessionId]);
-
- useEffect(() => {
- if (
- !active
- || !organizationReady
- || !instanceId
- || resourceSyncStatus !== 'pending'
- ) {
- return undefined;
- }
- let cancelled = false;
- const generation = generationRef.current;
- const requestSessionId = sessionId;
- const requestInstanceId = instanceId;
-
- const schedule = () => {
- if (!cancelled) {
- pollTimerRef.current = setTimeout(() => void poll(), RESOURCE_SYNC_POLL_INTERVAL_MS);
- }
- };
- const poll = async () => {
- if (cancelled) return;
- try {
- const next = await getResourceAccess({
- resource_kind: 'show_page',
- resource_id: requestSessionId,
- });
- if (
- cancelled
- || generation !== generationRef.current
- || requestSessionId !== sessionIdRef.current
- || requestInstanceId !== instanceId
- || !resourceIdentityMatches(next.resource, requestSessionId, requestInstanceId)
- ) return;
- const currentResource = resourceRef.current;
- const currentDraft = draftRef.current;
- const draftIsDirty = Boolean(
- currentResource
- && (
- currentResource.access.access_level !== currentDraft.level
- || uniqueSorted(currentResource.access.group_ids).join('\u0000')
- !== uniqueSorted(currentDraft.groupIds).join('\u0000')
- )
- );
- setResource(next.resource);
- if (!draftIsDirty) {
- setLevel(next.resource.access.access_level);
- setGroupIds(uniqueSorted(next.resource.access.group_ids));
- }
- if (next.resource.sync.status === 'pending') schedule();
- } catch {
- // A transient transport failure must not discard the pending resource;
- // retry while this exact instance remains mounted.
- schedule();
- }
- };
-
- schedule();
- return () => {
- cancelled = true;
- if (pollTimerRef.current !== null) {
- clearTimeout(pollTimerRef.current);
- pollTimerRef.current = null;
- }
- };
- }, [active, instanceId, organizationReady, resourceSyncStatus, sessionId]);
-
- const visibleGroups = useMemo(() => {
- const bound = new Set(resource?.access.group_ids ?? []);
- return groups.filter((group) => group.archived_at === null || bound.has(group.id));
- }, [groups, resource]);
- const targetGroupIds = level === 'scope' ? uniqueSorted(groupIds) : [];
- const ownerMember = useMemo(
- () => permissions?.projection.directory.members.find(
- (member) => member.id === resource?.owner_user_id,
- ) ?? null,
- [permissions, resource],
- );
- const ownerContext = useMemo(() => ({
- isInstanceOwner: resource?.owner_user_id === null
- || Boolean(
- ownerMember
- && permissions?.projection.access.owner.email
- && ownerMember.email.trim().toLowerCase()
- === permissions.projection.access.owner.email.trim().toLowerCase(),
- ),
- organizationGroupIds: ownerMember?.group_ids ?? null,
- }), [ownerMember, permissions, resource]);
- const dirty = Boolean(
- resource
- && (
- resource.access.access_level !== level
- || uniqueSorted(resource.access.group_ids).join('\u0000') !== targetGroupIds.join('\u0000')
- )
- );
- const localMutationAllowed = Boolean(
- permissions
- && !permissions.offline
- && permissions.projection.instance.local_mutation_allowed
- && permissions.projection.capabilities.includes('instance.permissions.mutate')
- );
- const editable = canManageInstance
- && localMutationAllowed
- && (gate === 'ready' || gate === 'conflict')
- && !saving;
- const invalid = level === 'scope' && targetGroupIds.length === 0;
-
- const commit = async () => {
- if (!resource || !instanceId || !dirty || invalid || !editable) return;
- const generation = generationRef.current;
- const requestSessionId = sessionId;
- const draft = draftRef.current;
- setSaving(true);
- setErrorCode(null);
- try {
- const result = await updateResourceAccess(
- { resource_kind: 'show_page', resource_id: requestSessionId },
- draft.level,
- draft.level === 'scope' ? uniqueSorted(draft.groupIds) : [],
- resource.access.revision,
- instanceId,
- );
- if (
- generation !== generationRef.current
- || requestSessionId !== sessionIdRef.current
- ) return;
- if (!resourceIdentityMatches(result.resource, requestSessionId, instanceId)) {
- throw new Error('Show Page Organization identity mismatch');
- }
- adopt(result.resource, groups);
- setGate('ready');
- } catch (caught) {
- if (
- generation !== generationRef.current
- || requestSessionId !== sessionIdRef.current
- ) return;
- if (isRevisionConflict(caught)) {
- setSaving(false);
- setConfirmNarrowing(false);
- await load('conflict', draft);
- return;
- }
- setErrorCode(caught instanceof PermissionsApiError ? caught.code : 'permissions_unavailable');
- setGate('error');
- } finally {
- if (
- generation === generationRef.current
- && requestSessionId === sessionIdRef.current
- ) {
- setSaving(false);
- setConfirmNarrowing(false);
- }
- }
- };
-
- const save = async () => {
- if (!resource || !instanceId || !dirty || invalid || !editable) return;
- const draft = draftRef.current;
- if (requiresResourcePolicyNarrowing(
- resource.access.access_level,
- resource.access.group_ids,
- draft.level,
- draft.level === 'scope' ? uniqueSorted(draft.groupIds) : [],
- ownerContext,
- )) {
- setConfirmNarrowing(true);
- return;
- }
- await commit();
- };
-
- const retryLoad = useCallback(() => {
- void load('ready', resource ? draftRef.current : undefined);
- }, [load, resource]);
-
- return (
- <section className="space-y-2.5" aria-label={t('chat.showPage.workspaceAccess')}>
- <div>
- <div className="text-sm font-medium">{t('chat.showPage.workspaceAccess')}</div>
- <p className="mt-0.5 text-[11px] leading-snug text-muted">
- {t('chat.showPage.workspaceAccessDesc')}
- </p>
- </div>
-
- {ownershipConflict ? (
- <div className="flex items-start gap-1.5 text-[11px] leading-snug text-destructive-ink">
- <TriangleAlert className="mt-0.5 size-3.5 shrink-0" />
- {t('chat.showPage.workspaceOwnershipConflict')}
- </div>
- ) : access?.mode === 'configuration_unavailable' ? (
- <div className="flex items-start gap-1.5 text-[11px] leading-snug text-gold-ink">
- <CloudOff className="mt-0.5 size-3.5 shrink-0" />
- {t('chat.showPage.workspaceConfigurationUnavailable')}
- </div>
- ) : access?.mode === 'personal' || access?.mode === 'unmanaged' ? (
- <p className="text-[11px] leading-snug text-muted">
- {t(access.mode === 'personal'
- ? 'chat.showPage.workspacePersonal'
- : 'chat.showPage.workspaceUnmanaged')}
- </p>
- ) : access?.mode === 'organization_pending' ? (
- <div className="flex items-start gap-1.5 text-[11px] leading-snug text-gold-ink">
- <CloudOff className="mt-0.5 size-3.5 shrink-0" />
- {t('chat.showPage.workspacePending')}
- </div>
- ) : gate === 'loading' || gate === 'idle' ? (
- <div className="flex h-9 items-center gap-1.5 text-[11px] text-muted">
- <Loader2 className="size-3.5 animate-spin" />
- {t('chat.showPage.loadingWorkspaceAccess')}
- </div>
- ) : resource ? (
- <>
- <SegmentedRadio<ResourceAccessLevel>
- value={level}
- onChange={(next) => {
- if (!editable) return;
- setLevel(next);
- }}
- disabled={!editable}
- ariaLabel={t('chat.showPage.workspaceAccess')}
- tone="muted"
- className="max-w-full [&>button]:min-w-0 [&>button]:whitespace-normal [&>button]:px-1.5 [&>button]:text-center [&>button]:leading-tight"
- options={[
- { id: 'private', label: t('chat.showPage.workspaceModes.private') },
- { id: 'scope', label: t('chat.showPage.workspaceModes.scope') },
- { id: 'public', label: t('chat.showPage.workspaceModes.organization') },
- ]}
- />
- <p className="text-[11px] leading-snug text-muted">
- {t(`chat.showPage.workspaceHelp.${level}`)}
- </p>
-
- {level === 'scope' ? (
- <div className="space-y-1" aria-label={t('chat.showPage.workspaceGroups')}>
- {visibleGroups.length ? visibleGroups.map((group) => {
- const checked = groupIds.includes(group.id);
- const archived = group.archived_at !== null;
- return (
- <div
- key={group.id}
- className="flex min-h-8 items-center gap-2 rounded-md px-1.5 py-1 text-xs"
- >
- <Checkbox
- checked={checked}
- disabled={!editable || archived}
- onCheckedChange={(next) => {
- if (!editable || archived) return;
- setGroupIds((current) => uniqueSorted(
- next
- ? [...current, group.id]
- : current.filter((value) => value !== group.id),
- ));
- }}
- label={group.name}
- />
- <span className="min-w-0 flex-1 truncate">{group.name}</span>
- {archived ? (
- <span className="shrink-0 text-[10px] text-muted">
- {t('chat.showPage.workspaceArchived')}
- </span>
- ) : null}
- </div>
- );
- }) : (
- <p className="text-[11px] text-muted">{t('chat.showPage.workspaceNoGroups')}</p>
- )}
- {invalid ? (
- <p className="text-[11px] text-gold-ink">
- {t('chat.showPage.workspaceGroupRequired')}
- </p>
- ) : null}
- </div>
- ) : null}
-
- {gate === 'conflict' ? (
- <div className="flex items-start gap-1.5 text-[11px] leading-snug text-gold-ink">
- <TriangleAlert className="mt-0.5 size-3.5 shrink-0" />
- {t('chat.showPage.workspaceRevisionConflict')}
- </div>
- ) : null}
- {!localMutationAllowed ? (
- <p className="text-[11px] leading-snug text-muted">
- {t(permissions?.offline
- ? 'chat.showPage.workspaceOffline'
- : 'chat.showPage.workspaceReadOnly')}
- </p>
- ) : !canManageInstance ? (
- <p className="text-[11px] leading-snug text-muted">
- {t('chat.showPage.workspaceOwnerOnly')}
- </p>
- ) : null}
- {resource.sync.status !== 'in_sync' ? (
- <p className="text-[11px] leading-snug text-muted">
- {t(`chat.showPage.workspaceSync.${resource.sync.status}`)}
- </p>
- ) : null}
- <div className="flex justify-end">
- <Button
- type="button"
- size="sm"
- className="h-7"
- disabled={!dirty || invalid || !editable}
- onClick={() => void save()}
- >
- {saving ? <Loader2 className="size-3.5 animate-spin" /> : <Save className="size-3.5" />}
- {t('chat.showPage.applyWorkspaceAccess')}
- </Button>
- </div>
- </>
- ) : null}
-
- {gate === 'error' ? (
- <div className="flex items-start justify-between gap-2 text-[11px] leading-snug text-destructive-ink">
- <span>{t(`permissions.errors.${errorCode}`, {
- defaultValue: t('chat.showPage.workspaceLoadError'),
- })}</span>
- <Button
- type="button"
- size="icon"
- variant="ghost"
- className="size-7 shrink-0"
- onClick={retryLoad}
- aria-label={t('common.retry')}
- >
- <RefreshCw className="size-3.5" />
- </Button>
- </div>
- ) : null}
- <ConfirmDialog
- open={confirmNarrowing}
- onOpenChange={setConfirmNarrowing}
- title={t('chat.showPage.workspaceNarrowTitle')}
- description={t('chat.showPage.workspaceNarrowBody')}
- confirmLabel={t('chat.showPage.applyWorkspaceAccess')}
- confirmDisabled={!editable}
- onConfirm={commit}
- windowOwnerId={ownerWindowId}
- />
- </section>
- );
-}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 2e66fe48f..de248c132 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3624,53 +3624,31 @@
"limited": "Only people in the list can access",
"public": "Anyone can access without signing in"
},
- "limitedEmails": "People with access",
- "limitedEmailRequired": "Add at least one email address.",
- "limitedEmailHint": "Enter an email and press Enter to add · up to {{count}}",
- "keepOneLimitedEmail": "Switch to Private to remove the last email",
+ "shareAudience": "People with access",
+ "shareAudienceOptions": "People and group suggestions",
+ "shareAudiencePlaceholder": {
+ "organization": "Search people or groups, or type an email",
+ "email": "[email protected]"
+ },
+ "shareAudienceHint": {
+ "organization": "Pick a person or group, or type any email · up to {{limit}}",
+ "email": "Enter an email and press Enter to add · up to {{limit}}"
+ },
+ "shareAudienceRequired": "Add at least one person, group, or Organization.",
+ "shareOrganizationGeneric": "This Organization",
+ "shareOrganizationNamed": "This Organization ({{name}})",
+ "shareGroupBadge": "Group",
+ "shareSuggestionEmpty": "No matching person or group. Type a full email to add it.",
+ "shareSuggestionNarrow": "More results — keep typing to narrow them down.",
+ "loadingShareDirectory": "Loading Organization directory…",
+ "removeShareEntry": "Remove {{label}}",
+ "keepOneShareEntry": "Switch to Private to remove the last entry",
"sharingErrors": {
"conflict": "Link access changed elsewhere. The latest version has been loaded.",
- "invalid": "Review the mode, link, and email list.",
+ "invalid": "Review the mode, link, and access list.",
"error": "Link access could not be loaded."
},
- "workspaceAccess": "Organization access",
- "workspaceAccessDesc": "Controls authenticated access inside this Organization. Link access remains separate.",
- "loadingWorkspaceAccess": "Loading Organization access…",
- "workspacePersonal": "This Show Page belongs to a Personal Avibe.",
- "workspaceUnmanaged": "Organization access is unavailable until this Avibe is paired.",
- "workspacePending": "Organization ownership is known, but its exact binding is temporarily unavailable. Access remains private.",
- "workspaceConfigurationUnavailable": "Organization access cannot be verified while Avibe configuration is unavailable. Access remains private.",
- "workspaceOwnershipConflict": "This Show Page is bound to a different ownership domain. Access remains private until the conflict is resolved.",
- "workspaceModes": {
- "private": "Private",
- "organization": "Organization members",
- "scope": "Selected groups"
- },
- "workspaceHelp": {
- "private": "Only the page owner and Instance Owner can use it.",
- "public": "Authenticated members of this Organization can use it.",
- "scope": "Only members of the selected Organization groups can use it."
- },
- "workspaceGroups": "Organization groups",
- "workspaceArchived": "Archived",
- "workspaceNoGroups": "No active groups are available.",
- "workspaceGroupRequired": "Select at least one group.",
- "workspaceRevisionConflict": "Organization access changed elsewhere. Your draft was kept on the latest revision.",
- "workspaceOffline": "The last known Organization policy is shown while Permissions is offline. Editing is disabled.",
- "workspaceReadOnly": "Avibe Cloud owns this Organization policy. Edit it in Avibe Cloud.",
- "workspaceOwnerOnly": "Only the Instance Owner can change Organization access.",
- "workspaceLoadError": "Organization access could not be loaded.",
- "workspaceNarrowTitle": "Narrow Organization access?",
- "workspaceNarrowBody": "Some people may lose access as soon as this policy is applied.",
- "applyWorkspaceAccess": "Apply",
- "workspaceSync": {
- "pending": "The policy is waiting for this Avibe to apply it.",
- "offline": "This Avibe has not acknowledged the latest policy.",
- "error": "The latest policy could not be applied."
- },
- "emailPlaceholder": "[email protected]",
"addEmail": "Add email",
- "removeEmail": "Remove {{email}}",
"emailInvalid": "Enter a valid email address.",
"accessLoadError": "Access details could not be loaded. Sharing changes are disabled.",
"availability": "Page online",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c79c27bb8..028dc88a4 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3624,53 +3624,31 @@
"limited": "仅允许列表中的用户访问",
"public": "任何人无需登录即可访问"
},
- "limitedEmails": "允许访问的用户",
- "limitedEmailRequired": "请至少添加一个邮箱。",
- "limitedEmailHint": "输入邮箱后按回车添加 · 最多 {{count}} 个",
- "keepOneLimitedEmail": "切换为私有后可移除最后一个邮箱",
+ "shareAudience": "允许访问的对象",
+ "shareAudienceOptions": "成员与群组建议",
+ "shareAudiencePlaceholder": {
+ "organization": "搜索成员或群组,也可输入邮箱",
+ "email": "[email protected]"
+ },
+ "shareAudienceHint": {
+ "organization": "可选择成员、群组,或输入任意邮箱 · 最多 {{limit}} 项",
+ "email": "输入邮箱后按回车添加 · 最多 {{limit}} 项"
+ },
+ "shareAudienceRequired": "请至少添加一个访问对象。",
+ "shareOrganizationGeneric": "本组织",
+ "shareOrganizationNamed": "本组织({{name}})",
+ "shareGroupBadge": "群组",
+ "shareSuggestionEmpty": "没有匹配的成员或群组;输入完整邮箱即可添加。",
+ "shareSuggestionNarrow": "结果较多,请继续输入以缩小范围。",
+ "loadingShareDirectory": "正在加载组织目录…",
+ "removeShareEntry": "移除 {{label}}",
+ "keepOneShareEntry": "切换为私有后可移除最后一项",
"sharingErrors": {
"conflict": "链接访问设置已在其他位置更新,已载入最新版本。",
- "invalid": "请检查访问模式、链接和邮箱列表。",
+ "invalid": "请检查访问模式、链接和访问对象列表。",
"error": "无法加载链接访问设置。"
},
- "workspaceAccess": "组织内访问",
- "workspaceAccessDesc": "控制此组织内的已登录访问;与链接访问相互独立。",
- "loadingWorkspaceAccess": "正在加载组织内访问设置…",
- "workspacePersonal": "此 Show Page 属于 Personal Avibe。",
- "workspaceUnmanaged": "此 Avibe 配对后才能使用组织内访问。",
- "workspacePending": "已知此 Avibe 属于组织,但暂时无法取得精确绑定;访问保持私有。",
- "workspaceConfigurationUnavailable": "Avibe 配置暂时不可用,无法验证组织内访问;访问保持私有。",
- "workspaceOwnershipConflict": "此 Show Page 绑定到了其他所有权域;解决冲突前访问保持私有。",
- "workspaceModes": {
- "private": "私有",
- "organization": "组织成员",
- "scope": "指定群组"
- },
- "workspaceHelp": {
- "private": "只有页面所有者和 Instance Owner 可以使用。",
- "public": "此组织的已登录成员可以使用。",
- "scope": "只有所选组织群组的成员可以使用。"
- },
- "workspaceGroups": "组织群组",
- "workspaceArchived": "已归档",
- "workspaceNoGroups": "暂无可选的活跃群组。",
- "workspaceGroupRequired": "请至少选择一个群组。",
- "workspaceRevisionConflict": "组织内访问已在其他位置更新;你的草稿已保留到最新版本。",
- "workspaceOffline": "Permissions 离线时显示上次已知组织策略,暂不可编辑。",
- "workspaceReadOnly": "此组织策略由 Avibe Cloud 管理,请前往 Avibe Cloud 修改。",
- "workspaceOwnerOnly": "只有 Instance Owner 可以修改组织内访问。",
- "workspaceLoadError": "无法加载组织内访问设置。",
- "workspaceNarrowTitle": "收紧组织内访问权限?",
- "workspaceNarrowBody": "策略应用后,部分用户可能立即失去访问权限。",
- "applyWorkspaceAccess": "应用",
- "workspaceSync": {
- "pending": "策略正在等待此 Avibe 应用。",
- "offline": "此 Avibe 尚未确认最新策略。",
- "error": "无法应用最新策略。"
- },
- "emailPlaceholder": "[email protected]",
"addEmail": "添加邮箱",
- "removeEmail": "移除 {{email}}",
"emailInvalid": "请输入有效的邮箱地址。",
"accessLoadError": "无法加载权限详情,分享设置已停用。",
"availability": "页面在线",
diff --git a/ui/src/lib/showPageAccess.test.ts b/ui/src/lib/showPageAccess.test.ts
index bcb9fff06..a2faa15f2 100644
--- a/ui/src/lib/showPageAccess.test.ts
+++ b/ui/src/lib/showPageAccess.test.ts
@@ -1,17 +1,27 @@
import { describe, expect, it } from 'vitest';
import {
- SHOW_ACCESS_EMAIL_MAX_COUNT,
+ SHOW_ACCESS_ENTRY_MAX_COUNT,
+ SHOW_ACCESS_SUGGESTION_LIMIT,
classifyShowPageAccessProbe,
normalizeShowAccessEmail,
normalizeShowAccessEmails,
+ showAccessApplyPayload,
+ showAccessDirectoryOf,
showAccessDraftChanged,
+ showAccessEntriesOf,
+ showAccessSuggestions,
showAccessTargetEmails,
+ showAccessTargetEntries,
showPageHeaderAccess,
showPageRestoreAccessDecision,
+ withShowAccessEntry,
+ withoutShowAccessEntry,
type ShowAccess,
+ type ShowAccessDirectory,
type ShowPageAccess,
} from './showPageAccess';
+import type { PermissionsResponse } from '@/features/permissions/types';
const access = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({
ok: true,
@@ -30,6 +40,16 @@ const access = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({
...overrides,
});
+const directory: ShowAccessDirectory = {
+ organization_id: 'org-1',
+ organization_name: 'Acme',
+ groups: [
+ { id: 'grp-design', name: 'Design' },
+ { id: 'grp-eng', name: 'Engineering' },
+ ],
+};
+
describe('Show Page access policy helpers', () => {
it('normalizes ShowAccess emails with the frozen ASCII contract', () => {
expect(normalizeShowAccessEmail(' [email protected] ')).toBe(
@@ -52,33 +72,232 @@ describe('Show Page access policy helpers', () => {
expect(normalizeShowAccessEmail(invalid)).toBeNull();
}
expect(normalizeShowAccessEmails(
- Array.from({ length: SHOW_ACCESS_EMAIL_MAX_COUNT + 1 }, (_, index) => (
+ Array.from({ length: SHOW_ACCESS_ENTRY_MAX_COUNT + 1 }, (_, index) => (
`guest-${index}@example.com`
)),
)).toBeNull();
});
- it('keeps emails only for Limited and compares canonical drafts', () => {
+ it('reads a pre-heterogeneous audience as email entries', () => {
+ const saved: ShowAccess = {
+ page_id: 'ses-1',
+ access_mode: 'limited',
+ share_id: 'stable-link',
+ revision: 4,
+ normalized_emails: ['[email protected]', '[email protected]'],
+ };
+ expect(showAccessEntriesOf(saved)).toEqual([
+ { kind: 'email', value: '[email protected]' },
+ { kind: 'email', value: '[email protected]' },
+ ]);
+ // A2 serializes `entries`; the pre-A2 `access_entries` alias still reads.
+ expect(showAccessEntriesOf({
+ ...saved,
+ entries: [
+ { kind: 'email', value: '[email protected]' },
+ { kind: 'organization', value: 'org-1' },
+ { kind: 'group', value: 'grp-eng' },
+ ],
+ })).toEqual([
+ { kind: 'organization', value: 'org-1' },
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ]);
+ expect(showAccessEntriesOf({
+ ...saved,
+ access_entries: [
+ { kind: 'email', value: '[email protected]' },
+ { kind: 'organization', value: 'org-1' },
+ { kind: 'group', value: 'grp-eng' },
+ ],
+ })).toEqual([
+ { kind: 'organization', value: 'org-1' },
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ]);
+ // `entries` wins when both fields are present.
+ expect(showAccessEntriesOf({
+ ...saved,
+ entries: [{ kind: 'group', value: 'grp-eng' }],
+ access_entries: [{ kind: 'email', value: '[email protected]' }],
+ })).toEqual([{ kind: 'group', value: 'grp-eng' }]);
+ });
+
+ it('keeps email, group, and Organization entries as peers', () => {
+ const entries = withShowAccessEntry(
+ withShowAccessEntry(
+ [{ kind: 'email' as const, value: '[email protected]' }],
+ { kind: 'group', value: 'grp-eng' },
+ ),
+ { kind: 'organization', value: 'org-1' },
+ );
+ // Adding the Organization neither absorbs nor supersedes the narrower entries.
+ expect(entries).toEqual([
+ { kind: 'organization', value: 'org-1' },
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ]);
+ // At most one Organization entry can exist, so a second one replaces it.
+ expect(withShowAccessEntry(entries, { kind: 'organization', value: 'org-2' })
+ .filter((entry) => entry.kind === 'organization')).toEqual([
+ { kind: 'organization', value: 'org-2' },
+ ]);
+ expect(withoutShowAccessEntry(entries, { kind: 'organization', value: 'org-1' })).toEqual([
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ]);
+ });
+
+ it('sends the audience only for Limited and compares canonical drafts', () => {
+ const entries = [
+ { kind: 'email' as const, value: '[email protected]' },
+ { kind: 'organization' as const, value: 'org-1' },
+ { kind: 'email' as const, value: '[email protected]' },
+ ];
const saved: ShowAccess = {
page_id: 'ses-1',
access_mode: 'limited',
share_id: 'stable-link',
revision: 4,
normalized_emails: ['[email protected]', '[email protected]'],
+ entries: [
+ { kind: 'organization', value: 'org-1' },
+ { kind: 'email', value: '[email protected]' },
+ { kind: 'email', value: '[email protected]' },
+ ],
};
- expect(showAccessTargetEmails('private', saved.normalized_emails)).toEqual([]);
- expect(showAccessTargetEmails('public', saved.normalized_emails)).toEqual([]);
- expect(showAccessTargetEmails('limited', ['[email protected]', '[email protected]'])).toEqual([
+ expect(showAccessTargetEntries('private', entries)).toEqual([]);
+ expect(showAccessTargetEntries('public', entries)).toEqual([]);
+ expect(showAccessTargetEmails('limited', entries)).toEqual([
]);
+ expect(showAccessTargetEmails('private', entries)).toEqual([]);
+ expect(showAccessDraftChanged(saved, 'limited', 'stable-link', entries)).toBe(false);
+ expect(showAccessDraftChanged(saved, 'public', 'stable-link', entries)).toBe(true);
expect(showAccessDraftChanged(
saved,
'limited',
'stable-link',
- )).toBe(false);
- expect(showAccessDraftChanged(saved, 'public', 'stable-link', [])).toBe(true);
+ withoutShowAccessEntry(entries, { kind: 'organization', value: 'org-1' }),
+ )).toBe(true);
+ // A2's apply contract is XOR: exactly one of target_emails / target_entries.
+ // The helper sends entries so group/org grants persist.
+ expect(showAccessApplyPayload(4, 'limited', 'stable-link', entries)).toEqual({
+ expected_revision: 4,
+ target_access_mode: 'limited',
+ target_share_id: 'stable-link',
+ target_entries: [
+ { kind: 'organization', value: 'org-1' },
+ { kind: 'email', value: '[email protected]' },
+ { kind: 'email', value: '[email protected]' },
+ ],
+ });
+ expect(Object.keys(showAccessApplyPayload(4, 'limited', 'stable-link', entries))).toEqual([
+ 'expected_revision',
+ 'target_access_mode',
+ 'target_share_id',
+ 'target_entries',
+ ]);
+ expect(showAccessApplyPayload(4, 'public', 'stable-link', entries)).toEqual({
+ expected_revision: 4,
+ target_access_mode: 'public',
+ target_share_id: 'stable-link',
+ target_entries: [],
+ });
+ expect(showAccessApplyPayload(4, 'limited', 'stable-link', [
+ { kind: 'group', value: 'grp-eng' },
+ ])).toEqual({
+ expected_revision: 4,
+ target_access_mode: 'limited',
+ target_share_id: 'stable-link',
+ target_entries: [{ kind: 'group', value: 'grp-eng' }],
+ });
+ expect(showAccessApplyPayload(4, 'limited', 'stable-link', [
+ { kind: 'organization', value: 'org-1' },
+ ])).toEqual({
+ expected_revision: 4,
+ target_access_mode: 'limited',
+ target_share_id: 'stable-link',
+ target_entries: [{ kind: 'organization', value: 'org-1' }],
+ });
+ });
+
+ it('derives the audience directory only for an Organization Avibe', () => {
+ const permissions = (organization: { id: string; name: string } | null) => ({
+ ok: true,
+ source: 'live',
+ offline: false,
+ cached_at: null,
+ projection: {
+ schema_version: 1,
+ instance: {
+ id: 'inst-1',
+ organization,
+ access_mode: 'allowlist',
+ permission_authority: 'cloud',
+ local_mutation_allowed: false,
+ authorization_revision: 3,
+ },
+ capabilities: [],
+ access: { owner: { email: null, role: 'owner' }, entries: [] },
+ directory: {
+ members: [
+ { id: 'u1', email: '[email protected]', organization_role: 'member', group_ids: [] },
+ { id: 'u2', email: 'not-an-email', organization_role: 'member', group_ids: [] },
+ ],
+ groups: [
+ { id: 'grp-eng', name: 'Engineering', archived_at: null },
+ { id: 'grp-old', name: 'Legacy', archived_at: '2026-01-01T00:00:00Z' },
+ ],
+ },
+ projects: [],
+ policy_sync: { status: 'in_sync', projects: {}, resources: {} },
+ },
+ } as unknown as PermissionsResponse);
+
+ expect(showAccessDirectoryOf(permissions({ id: 'org-1', name: 'Acme' }))).toEqual({
+ organization_id: 'org-1',
+ organization_name: 'Acme',
+ groups: [{ id: 'grp-eng', name: 'Engineering' }],
+ emails: ['[email protected]'],
+ });
+ // A Personal Avibe has no Organization, which is what hides the Organization
+ // toggle and group search.
+ expect(showAccessDirectoryOf(permissions(null))).toBeNull();
+ });
+
+ it('searches groups and people, and never re-offers a selected entry', () => {
+ expect(showAccessSuggestions(null, '', [])).toEqual({ suggestions: [], truncated: false });
+ expect(showAccessSuggestions(directory, '', []).suggestions).toEqual([
+ { kind: 'group', value: 'grp-design', label: 'Design' },
+ { kind: 'group', value: 'grp-eng', label: 'Engineering' },
+ { kind: 'email', value: '[email protected]', label: '[email protected]' },
+ { kind: 'email', value: '[email protected]', label: '[email protected]' },
+ ]);
+ // A partial query narrows both kinds.
+ expect(showAccessSuggestions(directory, 'eng', []).suggestions).toEqual([
+ { kind: 'group', value: 'grp-eng', label: 'Engineering' },
+ ]);
+ expect(showAccessSuggestions(directory, 'ali', []).suggestions).toEqual([
+ { kind: 'email', value: '[email protected]', label: '[email protected]' },
+ ]);
+ expect(showAccessSuggestions(directory, '', [
+ { kind: 'group', value: 'grp-eng' },
+ { kind: 'email', value: '[email protected]' },
+ ]).suggestions).toEqual([
+ { kind: 'group', value: 'grp-design', label: 'Design' },
+ { kind: 'email', value: '[email protected]', label: '[email protected]' },
+ ]);
+
+ const crowded = showAccessSuggestions({
+ ...directory,
+ emails: Array.from({ length: 20 }, (_, index) => `guest-${index}@example.com`),
+ }, '', []);
+ expect(crowded.suggestions).toHaveLength(SHOW_ACCESS_SUGGESTION_LIMIT);
+ // Groups keep their slots even against a long member list.
+ expect(crowded.suggestions.filter((option) => option.kind === 'group')).toHaveLength(2);
+ expect(crowded.truncated).toBe(true);
});
it('separates page use from page-specific access management in the chat header', () => {
diff --git a/ui/src/lib/showPageAccess.ts b/ui/src/lib/showPageAccess.ts
index 3f194bd13..e8f2411dc 100644
--- a/ui/src/lib/showPageAccess.ts
+++ b/ui/src/lib/showPageAccess.ts
@@ -1,4 +1,4 @@
-import type { ResourceAccessLevel } from '@/features/permissions/types';
+import type { PermissionsResponse, ResourceAccessLevel } from '@/features/permissions/types';
export type ShowPageAccess = {
ok: true;
mode: 'unmanaged' | 'personal' | 'organization' | 'organization_pending' | 'configuration_unavailable';
@@ -22,12 +22,27 @@ export type ShowPageAccessProbe =
export type ShowAccessMode = 'private' | 'limited' | 'public';
+/** A `limited` audience is a heterogeneous set: an email, an Organization group,
+ * or the page's own Organization. The three kinds are peers — any hit admits a
+ * read-only `/p` visitor, and none of them supersedes or dedupes another. */
+export type ShowAccessEntryKind = 'email' | 'group' | 'organization';
+
+export type ShowAccessEntry = {
+ kind: ShowAccessEntryKind;
+ value: string;
+};
+
export type ShowAccess = {
page_id: string;
access_mode: ShowAccessMode;
share_id: string | null;
revision: number;
+ /** Email projection of the audience. Always present on the live snapshot. */
normalized_emails: string[];
+ /** A2 live field: heterogeneous `email | group | organization` entries. */
+ entries?: ShowAccessEntry[];
+ /** Pre-A2 / test alias. Read only when `entries` is absent. */
+ access_entries?: ShowAccessEntry[];
};
export type ShowAccessSettingsResult = {
@@ -38,15 +53,34 @@ export type ShowAccessApplyRequest = {
expected_revision: number;
target_access_mode: ShowAccessMode;
target_share_id: string | null;
- target_emails: string[];
+ /** Heterogeneous audience. A2's apply contract is XOR with `target_emails`;
+ * this helper always sends entries so group/org grants persist. */
+ target_entries: ShowAccessEntry[];
};
+/** Wire payload for `/access-settings/apply`. A2 accepts exactly one of
+ * `target_emails` or `target_entries`; sending both 400s. This helper emits
+ * the entry form so a Limited audience of any kind is persistable. */
+export function showAccessApplyPayload(
+ expectedRevision: number,
+ mode: ShowAccessMode,
+ shareId: string | null,
+ entries: ShowAccessEntry[],
+): ShowAccessApplyRequest {
+ return {
+ expected_revision: expectedRevision,
+ target_access_mode: mode,
+ target_share_id: shareId,
+ target_entries: showAccessTargetEntries(mode, entries),
+ };
+}
+
export type ShowAccessApplyResult = {
status: 'applied' | 'no_change' | 'conflict' | 'share_id_taken' | 'invalid';
show_access: ShowAccess;
};
-export const SHOW_ACCESS_EMAIL_MAX_COUNT = 64;
+export const SHOW_ACCESS_ENTRY_MAX_COUNT = 64;
const SHOW_ACCESS_EMAIL_PATTERN = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
const ASCII_SURROUNDING_WHITESPACE = /^[\t\n\f\r\v ]+|[\t\n\f\r\v ]+$/g;
@@ -60,28 +94,164 @@ export function normalizeShowAccessEmail(raw: string): string | null {
}
export function normalizeShowAccessEmails(emails: string[]): string[] | null {
- if (emails.length > SHOW_ACCESS_EMAIL_MAX_COUNT) return null;
+ if (emails.length > SHOW_ACCESS_ENTRY_MAX_COUNT) return null;
const normalized = emails.map(normalizeShowAccessEmail);
if (normalized.some((email) => email === null)) return null;
return [...new Set(normalized as string[])].sort();
}
+const ENTRY_KIND_RANK: Record<ShowAccessEntryKind, number> = {
+ organization: 0,
+ group: 1,
+ email: 2,
+};
+
+export function showAccessEntryKey(entry: ShowAccessEntry): string {
+ return `${entry.kind}:${entry.value}`;
+}
+
+export function showAccessEntriesKey(entries: ShowAccessEntry[]): string {
+ return entries.map(showAccessEntryKey).join('\u0000');
+}
+
+/** Canonical audience order: the Organization entry, then groups, then emails.
+ * The wire form has to be stable so a draft comparison never reports a change
+ * the user did not make. */
+export function canonicalShowAccessEntries(entries: ShowAccessEntry[]): ShowAccessEntry[] {
+ const seen = new Set<string>();
+ const unique: ShowAccessEntry[] = [];
+ for (const entry of entries) {
+ const key = showAccessEntryKey(entry);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ unique.push({ kind: entry.kind, value: entry.value });
+ }
+ return unique.sort((left, right) => (
+ ENTRY_KIND_RANK[left.kind] - ENTRY_KIND_RANK[right.kind]
+ || left.value.localeCompare(right.value)
+ ));
+}
+
+export function showAccessEntriesOf(saved: ShowAccess): ShowAccessEntry[] {
+ return canonicalShowAccessEntries(
+ saved.entries
+ ?? saved.access_entries
+ ?? saved.normalized_emails.map((value) => ({ kind: 'email' as const, value })),
+ );
+}
+
+/** Adds one entry. At most one Organization entry can exist, so a second one
+ * replaces the first instead of accumulating a set the backend would reject. */
+export function withShowAccessEntry(
+ entries: ShowAccessEntry[],
+ entry: ShowAccessEntry,
+): ShowAccessEntry[] {
+ const kept = entry.kind === 'organization'
+ ? entries.filter((current) => current.kind !== 'organization')
+ : entries;
+ return canonicalShowAccessEntries([...kept, entry]);
+}
+
+export function withoutShowAccessEntry(
+ entries: ShowAccessEntry[],
+ entry: ShowAccessEntry,
+): ShowAccessEntry[] {
+ const removed = showAccessEntryKey(entry);
+ return canonicalShowAccessEntries(
+ entries.filter((current) => showAccessEntryKey(current) !== removed),
+ );
+}
+
+export function showAccessTargetEntries(
+ mode: ShowAccessMode,
+ entries: ShowAccessEntry[],
+): ShowAccessEntry[] {
+ return mode === 'limited' ? canonicalShowAccessEntries(entries) : [];
+}
+
export function showAccessTargetEmails(
mode: ShowAccessMode,
- emails: string[],
+ entries: ShowAccessEntry[],
): string[] {
- return mode === 'limited' ? [...new Set(emails)].sort() : [];
+ return showAccessTargetEntries(mode, entries)
+ .filter((entry) => entry.kind === 'email')
+ .map((entry) => entry.value);
+}
+
+/** The Organization directory the audience combobox searches. `null` means this
+ * Avibe has no Organization (Personal), which is what hides the Organization
+ * toggle and group search — Personal pages can only list emails. */
+export type ShowAccessDirectory = {
+ organization_id: string;
+ organization_name: string;
+ groups: { id: string; name: string }[];
+ emails: string[];
+};
+
+export function showAccessDirectoryOf(
+ permissions: PermissionsResponse,
+): ShowAccessDirectory | null {
+ const organization = permissions.projection.instance.organization;
+ if (!organization) return null;
+ return {
+ organization_id: organization.id,
+ organization_name: organization.name,
+ groups: permissions.projection.directory.groups
+ .filter((group) => group.archived_at === null)
+ .map((group) => ({ id: group.id, name: group.name })),
+ emails: permissions.projection.directory.members
+ .map((member) => normalizeShowAccessEmail(member.email))
+ .filter((email): email is string => email !== null),
+ };
+}
+
+export type ShowAccessSuggestion = {
+ kind: 'group' | 'email';
+ value: string;
+ label: string;
+};
+
+export const SHOW_ACCESS_SUGGESTION_LIMIT = 8;
+const SHOW_ACCESS_GROUP_SUGGESTION_LIMIT = 4;
+
+/** Search over the Organization directory. Groups keep the first slots so a
+ * large member list can never hide them; `truncated` lets the UI say results
+ * were dropped instead of silently showing a partial list. */
+export function showAccessSuggestions(
+ directory: ShowAccessDirectory | null,
+ query: string,
+ selected: ShowAccessEntry[],
+): { suggestions: ShowAccessSuggestion[]; truncated: boolean } {
+ if (!directory) return { suggestions: [], truncated: false };
+ const taken = new Set(selected.map(showAccessEntryKey));
+ const needle = query.trim().toLowerCase();
+ const matches = (...fields: string[]) => (
+ needle.length === 0 || fields.some((field) => field.toLowerCase().includes(needle))
+ );
+ const groups: ShowAccessSuggestion[] = directory.groups
+ .filter((group) => !taken.has(`group:${group.id}`) && matches(group.name, group.id))
+ .map((group) => ({ kind: 'group', value: group.id, label: group.name }));
+ const people: ShowAccessSuggestion[] = directory.emails
+ .filter((email) => !taken.has(`email:${email}`) && matches(email))
+ .map((email) => ({ kind: 'email', value: email, label: email }));
+ const shownGroups = groups.slice(0, SHOW_ACCESS_GROUP_SUGGESTION_LIMIT);
+ const shownPeople = people.slice(0, SHOW_ACCESS_SUGGESTION_LIMIT - shownGroups.length);
+ return {
+ suggestions: [...shownGroups, ...shownPeople],
+ truncated: shownGroups.length < groups.length || shownPeople.length < people.length,
+ };
}
export function showAccessDraftChanged(
saved: ShowAccess,
mode: ShowAccessMode,
shareId: string | null,
- emails: string[],
+ entries: ShowAccessEntry[],
): boolean {
return saved.access_mode !== mode
|| saved.share_id !== shareId
- || saved.normalized_emails.join('\u0000') !== showAccessTargetEmails(mode, emails).join('\u0000');
+ || showAccessEntriesKey(showAccessEntriesOf(saved))
+ !== showAccessEntriesKey(showAccessTargetEntries(mode, entries));
}
function isShowPageAccess(value: unknown): value is ShowPageAccess {