Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(settings): show Roles & access, your own access and your plan (#1780)

Cihane2587ed992a4
diff --git a/web/messages/en.json b/web/messages/en.json
index 4a8c54b51..1d9116b0a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3229,6 +3229,234 @@
"demo": "No one: the demo brand keeps its sample data."
}
},
+ "chatAccess": {
+ "roleNames": {
+ "admin": "Admin",
+ "manager": "Manager",
+ "analyst": "Analyst",
+ "agency_partner": "Agency partner"
+ },
+ "classes": { "read": "READ", "write": "WRITE", "execute": "EXECUTE", "never": "NEVER" },
+ "plan": {
+ "yourPlan": "Your plan",
+ "perMonth": "{price}/mo",
+ "trial": "Trial",
+ "custom": "Custom contract",
+ "chips": {
+ "platforms": "{count, plural, one {# AI platform} other {# AI platforms}}",
+ "fullAuto": "Full auto",
+ "ownKeys": "Own AI keys",
+ "mcp": "{access, select, read {MCP read} read_write {MCP read + write} other {MCP}}",
+ "openPr": "Open PR",
+ "claude": "Claude tracking"
+ },
+ "locked": "Needs {plan} · you're on {current}",
+ "lockedTrial": "Not in the trial · {plan} and up",
+ "aiLimit": "AI limit",
+ "aiUsed": "{percent} used",
+ "comparePlans": "Compare plans",
+ "upgrade": "Upgrade",
+ "choosePlan": "Choose a plan",
+ "next": "With {plan} you'd also get",
+ "afterTrial": "After your trial",
+ "priceDiff": "+{price}/mo",
+ "afterTrialPrice": "{plan} · {price}/mo after the trial",
+ "customPrice": "Custom price",
+ "benefits": {
+ "morePlatforms": "See your brand in {count, plural, one {# more AI platform} other {# more AI platforms}}",
+ "fullAuto": "Let Chat make routine changes for you with Full auto",
+ "mcpWrite": "Open pull requests and make changes from Claude, ChatGPT or Cursor",
+ "claude": "Track how Claude answers about your brand",
+ "contract": "AI limit, storage and prompt limits set in your contract",
+ "aiLimit": "{times}× the monthly AI limit",
+ "keepEverything": "Keep everything you're using now",
+ "mcp": "Use Ansvisor inside Claude, ChatGPT and Cursor (MCP)",
+ "monthlyLimit": "A monthly AI limit that resets, instead of the trial's one-time limit",
+ "packs": "Buy extra AI credits and storage when you need them"
+ }
+ },
+ "roles": {
+ "title": "Roles & access",
+ "lead": "Who can do what in this workspace, in the app and through Chat. Chat acts as the signed-in person and never has more rights than they do.",
+ "readOnly": "You're {role, select, manager {a Manager} analyst {an Analyst} other {an Agency partner}} · read-only here",
+ "readOnlyNote": "Only Admins change roles",
+ "members": "Members",
+ "manageInTeam": "Invite or remove in Team",
+ "columns": {
+ "member": "Member",
+ "role": "Role",
+ "brands": "Brands",
+ "throughChat": "Through Chat",
+ "lastActive": "Last active"
+ },
+ "you": "You",
+ "allBrands": "All brands",
+ "neverSignedIn": "Not yet",
+ "roleChanged": "Role changed",
+ "roleChangeFailed": "Couldn't change the role. Try again.",
+ "loadError": "Couldn't load Roles & access. Try again in a moment.",
+ "throughChat": {
+ "admin": "Everything, incl. policy, keys, connections",
+ "manager": "WRITE with approval · EXECUTE after click",
+ "analyst": "Read-only composer · asks an Admin",
+ "agency_partner": "Read-only composer · asks an Admin"
+ },
+ "matrix": {
+ "title": "What each role can do",
+ "count": "app and Chat",
+ "actsAsUser": "Chat acts as the signed-in person",
+ "capability": "Capability",
+ "adminNote": "Changes roles",
+ "groups": {
+ "everyone": "Everyone · app and Chat",
+ "workspace": "Workspace changes",
+ "admin": "Admin only",
+ "never": "Never through Chat"
+ },
+ "rows": {
+ "readApp": { "name": "See dashboards, prompts, citations and reports", "scope": "App" },
+ "askChat": {
+ "name": "Ask Chat, create files and downloads for yourself",
+ "scope": "Chat"
+ },
+ "personal": {
+ "name": "Personal memory and personal in-app watch rules",
+ "scope": "Chat · only you"
+ },
+ "actions": {
+ "name": "Create or attach actions · prompts, topics, competitors",
+ "scope": "App and Chat"
+ },
+ "drafts": {
+ "name": "Drafts, briefs, schedules, CMS drafts",
+ "scope": "App and Chat · approval card"
+ },
+ "agents": { "name": "Create triggered agents", "scope": "Run with the creator's role" },
+ "shared": {
+ "name": "Workspace memory, shared skills, marketplace skills",
+ "scope": "Chat"
+ },
+ "execute": {
+ "name": "Publish, open a PR, send external email",
+ "scope": "Always after a click"
+ },
+ "billing": {
+ "name": "Billing, plan, AI credit and storage packs",
+ "scope": "Settings › Billing"
+ },
+ "team": { "name": "Team: invite, change roles, remove", "scope": "Settings › Team" },
+ "policy": {
+ "name": "Chat tool policy, Full auto availability",
+ "scope": "Settings › Chat"
+ },
+ "keys": {
+ "name": "Connections, MCP server keys, API and AI provider keys",
+ "scope": "Settings › Integrations · Keys"
+ },
+ "never": {
+ "name": "Mark a task done, change roles or billing, delete a brand, reveal keys",
+ "scope": "Not a Chat tool"
+ }
+ },
+ "cells": {
+ "yes": "Yes",
+ "approves": "approves",
+ "request": "Request",
+ "after_click": "after click",
+ "no": "No",
+ "not_tool": "Not a tool"
+ }
+ },
+ "switches": {
+ "title": "Admin switches",
+ "onlyAdmins": "Only Admins change these",
+ "managerExecute": "Managers can publish, open PRs and send external email after the click",
+ "managerExecuteNote": "EXECUTE always needs a click, whoever runs it",
+ "fullAuto": "Members can use Full auto",
+ "fullAutoNote": "Chat makes routine changes without asking each time",
+ "on": "On",
+ "off": "Off",
+ "offFor": "Off for {groups}",
+ "needsPlan": "Needs {plan}",
+ "setBy": "Set by {name}",
+ "groups": {
+ "publishing": "publishing",
+ "email_outreach": "email and outreach",
+ "code_prs": "pull requests",
+ "feeds": "feed pushes"
+ }
+ }
+ },
+ "yourAccess": {
+ "title": "Your access",
+ "brands": "Brands",
+ "actsAsYou": "Chat acts as you",
+ "yourRole": "Your role: {role}",
+ "rows": {
+ "read": "Read data, ask Chat, files for yourself",
+ "personal": "Personal memory and in-app watch rules",
+ "workspace": "Actions, prompts, drafts, schedules",
+ "agents": "Create triggered agents",
+ "execute": "Publish, open a PR, external email",
+ "settings": "Billing, team, tool policy, connections, keys"
+ },
+ "values": {
+ "yes": "Yes",
+ "yes_card": "Yes · approval card",
+ "after_click": "After your click",
+ "after_click_except": "After your click, except {groups}",
+ "execute_off": "Off: an Admin turned it off for Managers",
+ "ask_admin": "Ask your Admin"
+ },
+ "seeRoles": "See what each role can do",
+ "seeCapabilities": "What Chat can do"
+ },
+ "capabilities": {
+ "title": "What Chat can do",
+ "areas": "{count, plural, one {# area} other {# areas}}",
+ "lead": "Every tool Chat may use, by area: what it reads, what it may change, and who may change it. Anything not listed here, Chat doesn't do.",
+ "search": "Search areas or actions",
+ "filters": {
+ "all": "All",
+ "write": "Has WRITE",
+ "execute": "Has EXECUTE",
+ "read": "Read only"
+ },
+ "columns": {
+ "area": "Area",
+ "read": "Read",
+ "write": "Write",
+ "execute": "Execute",
+ "who": "Who can change"
+ },
+ "legend": {
+ "none": "No approval",
+ "card": "Approval card",
+ "auto": "Can auto-run in Full auto",
+ "click": "Needs your click"
+ },
+ "readAll": "Read: all roles",
+ "locked": "Needs {plan}",
+ "empty": "No area matches your search.",
+ "areaNames": {
+ "account": "Account",
+ "usage": "AI usage",
+ "brands": "Brands",
+ "visibility": "Visibility",
+ "prompts": "Prompts",
+ "topics": "Topics",
+ "mentions": "Mentions",
+ "citations": "Citations",
+ "competitors": "Competitors",
+ "product_visibility": "Product Visibility",
+ "ai_traffic": "AI Referral Traffic",
+ "site_audit": "Site Audit",
+ "action_center": "Action Center",
+ "content": "Content",
+ "reports": "Reports"
+ }
+ }
+ },
"chatActivity": {
"summary": {
"saveDraft": "Saved the draft “{title}”",
@@ -9147,6 +9375,7 @@
"general": "General",
"apiKeys": "API Keys",
"team": "Team",
+ "rolesAccess": "Roles & access",
"menuAccess": {
"title": "Menu access",
"new": "New",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/chat/capabilities/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/chat/capabilities/page.tsx
new file mode 100644
index 000000000..d8c00a4e7
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/chat/capabilities/page.tsx
@@ -0,0 +1,18 @@
+import { notFound } from 'next/navigation';
+import { getChatAccess } from '@/lib/actions/chat-access';
+import { capabilityAreas } from '@/lib/chat/access';
+import { registryCatalog } from '@/lib/chat/registry/tools';
+import { CapabilitiesView } from '@/components/chat-access/capabilities-view';
+
+/**
+ * "What Chat can do" (CHAT-20 §8, mockup #g-capabilities): every tool in
+ * Chat's registry, by area, with who may use it and how it is approved.
+ * Built from the registry the server checks, so it can't drift from it; a
+ * capability not listed isn't Chat's ("silence = never"). Only with the new
+ * Chat on for the workspace.
+ */
+export default async function ChatCapabilitiesPage() {
+ const access = await getChatAccess();
+ if (!access) notFound();
+ return <CapabilitiesView access={access} areas={capabilityAreas(registryCatalog())} />;
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts b/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts
index 96e08c8e1..fb8704bc2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts
@@ -9,6 +9,8 @@ export const SETTINGS_SECTIONS = [
'account',
'organization',
'team',
+ // Roles & access (CHAT-20 §4a): listed only while the new Chat is on.
+ 'roles-access',
'menu-access',
'authors',
'content',
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx
index 41af8fa21..148e03c52 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx
@@ -20,6 +20,10 @@ let canManageMenus = false;
vi.mock('@/components/providers/menu-access-provider', () => ({
useCanManageMenus: () => canManageMenus,
}));
+let chatAgentic = false;
+vi.mock('@/components/providers/chat-agentic-provider', () => ({
+ useChatAgentic: () => chatAgentic,
+}));
vi.mock('@/lib/actions/organization', () => ({ updateAccountName: vi.fn() }));
vi.mock('@/components/ai-usage/ai-usage-meter', () => ({
HeaderWithAiUsage: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
@@ -36,6 +40,8 @@ for (const [path, name] of [
['@/components/settings/organization-section', 'OrganizationSection'],
['@/components/settings/menu-access-section', 'MenuAccessSection'],
['@/components/settings/work-areas-card', 'WorkAreasCard'],
+ ['@/components/chat-access/roles-access-section', 'RolesAccessSection'],
+ ['@/components/chat-access/your-access-card', 'YourAccessSlot'],
]) {
vi.doMock(path, () => ({ [name]: () => null }));
}
@@ -81,4 +87,12 @@ describe('SettingsView', () => {
expect(list).toContain('Team');
expect(list.some((s) => s?.startsWith('Menu access'))).toBe(false);
});
+
+ it('lists Roles & access, after Team, only while the new Chat is on', async () => {
+ chatAgentic = true;
+ const list = await sections();
+ expect(list.indexOf('Roles & access')).toBe(list.indexOf('Team') + 1);
+ chatAgentic = false;
+ expect(await sections()).not.toContain('Roles & access');
+ });
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx
index a4b0fe52b..166806b03 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx
@@ -23,6 +23,9 @@ import { OrganizationSection } from '@/components/settings/organization-section'
import { MenuAccessSection } from '@/components/settings/menu-access-section';
import { WorkAreasCard } from '@/components/settings/work-areas-card';
import { useCanManageMenus } from '@/components/providers/menu-access-provider';
+import { useChatAgentic } from '@/components/providers/chat-agentic-provider';
+import { RolesAccessSection } from '@/components/chat-access/roles-access-section';
+import { YourAccessSlot } from '@/components/chat-access/your-access-card';
import { Badge } from '@/components/ui/badge';
import { updateAccountName } from '@/lib/actions/organization';
import { Loader2 } from 'lucide-react';
@@ -46,7 +49,11 @@ export function SettingsView({ section }: { section: SettingsSection }) {
const router = useRouter();
const { isCloud } = usePlanContext();
const canManageMenus = useCanManageMenus();
- const [active, setActive] = useState<SettingsSection>(section);
+ const chatAgentic = useChatAgentic();
+ // Roles & access is Chat's: with Chat off, its address opens Account.
+ const [active, setActive] = useState<SettingsSection>(
+ section === 'roles-access' && !chatAgentic ? 'account' : section,
+ );
const show = (next: SettingsSection) => {
setActive(next);
@@ -87,6 +94,7 @@ export function SettingsView({ section }: { section: SettingsSection }) {
account: t('account'),
organization: t('organization'),
team: t('team'),
+ 'roles-access': t('rolesAccess'),
'menu-access': t('menuAccess.title'),
authors: t('authors.title'),
content: t('content.title'),
@@ -98,9 +106,13 @@ export function SettingsView({ section }: { section: SettingsSection }) {
};
// AI Providers (bring your own key) and Billing are cloud-only: self-host
// operators set ANTHROPIC_API_KEY in their own env.
- // Menu access is listed for admins and the managers they let change menus.
+ // Menu access is listed for admins and the managers they let change menus,
+ // Roles & access for everyone while the new Chat is on.
const navItems = SETTINGS_SECTIONS.filter(
- (id) => hasSettingsSection(id, { isCloud }) && (id !== 'menu-access' || canManageMenus),
+ (id) =>
+ hasSettingsSection(id, { isCloud }) &&
+ (id !== 'menu-access' || canManageMenus) &&
+ (id !== 'roles-access' || chatAgentic),
).map((id) => ({ id, label: labels[id] }));
return (
@@ -184,6 +196,9 @@ export function SettingsView({ section }: { section: SettingsSection }) {
</Card>
)}
+ {/* What the person may do, in the app and through Chat (CHAT-20 §4b). */}
+ {active === 'account' && chatAgentic && <YourAccessSlot className="mt-6" />}
+
{/* What the person works on or leads: it narrows their own menu. */}
{active === 'account' && (
<div className="mt-6">
@@ -197,6 +212,8 @@ export function SettingsView({ section }: { section: SettingsSection }) {
{/* Team */}
{active === 'team' && <TeamSection />}
+ {active === 'roles-access' && chatAgentic && <RolesAccessSection />}
+
{active === 'menu-access' && <MenuAccessSection />}
{active === 'authors' && hasSettingsSection('authors', { isCloud }) && <AuthorsSection />}
diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsx
index d0c036668..85072c34d 100644
--- a/web/src/app/[locale]/(dashboard)/layout.tsx
+++ b/web/src/app/[locale]/(dashboard)/layout.tsx
@@ -8,6 +8,8 @@ import { PlanProvider } from '@/components/providers/plan-provider';
import { AiUsageProvider } from '@/components/providers/ai-usage-provider';
import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';
import { MenuAccessProvider } from '@/components/providers/menu-access-provider';
+import { ChatAgenticProvider } from '@/components/providers/chat-agentic-provider';
+import { chatAgenticEnabled } from '@/lib/chat/flag';
import { BrandLoader } from '@/components/providers/brand-loader';
import { BrandGuard } from '@/components/providers/brand-guard';
import { GettingStartedPageOpened } from '@/components/getting-started/page-opened';
@@ -114,34 +116,36 @@ export default async function DashboardLayout({ children }: { children: React.Re
subscriptionStatus={subscriptionStatus}
>
<RoleProvider role={role}>
- <UpgradeDialogProvider adminName={adminName} organizationId={profile.organization_id}>
- {/* Inside the provider: it records nothing while the workspace is read-only. */}
- <GettingStartedPageOpened />
- <MenuAccessProvider hidden={menu.hidden} canManageMenus={menu.canManageMenus}>
- <AiUsageProvider>
- <div className="flex h-screen overflow-hidden">
- {/* Desktop sidebar */}
- <div className="relative hidden md:flex md:flex-shrink-0">
- <SidebarErrorBoundary>
- <Sidebar />
- </SidebarErrorBoundary>
- </div>
+ <ChatAgenticProvider enabled={chatAgenticEnabled(profile.organization_id)}>
+ <UpgradeDialogProvider adminName={adminName} organizationId={profile.organization_id}>
+ {/* Inside the provider: it records nothing while the workspace is read-only. */}
+ <GettingStartedPageOpened />
+ <MenuAccessProvider hidden={menu.hidden} canManageMenus={menu.canManageMenus}>
+ <AiUsageProvider>
+ <div className="flex h-screen overflow-hidden">
+ {/* Desktop sidebar */}
+ <div className="relative hidden md:flex md:flex-shrink-0">
+ <SidebarErrorBoundary>
+ <Sidebar />
+ </SidebarErrorBoundary>
+ </div>
- {/* Main area */}
- <div className="flex flex-1 flex-col overflow-hidden">
- <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">
- <MobileNav />
+ {/* Main area */}
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">
+ <MobileNav />
+ </div>
+ <ReadOnlyBanner />
+ <main className="flex-1 overflow-y-auto bg-background p-6">
+ <BrandGuard>{children}</BrandGuard>
+ </main>
+ <TrackingJobHandoff />
</div>
- <ReadOnlyBanner />
- <main className="flex-1 overflow-y-auto bg-background p-6">
- <BrandGuard>{children}</BrandGuard>
- </main>
- <TrackingJobHandoff />
</div>
- </div>
- </AiUsageProvider>
- </MenuAccessProvider>
- </UpgradeDialogProvider>
+ </AiUsageProvider>
+ </MenuAccessProvider>
+ </UpgradeDialogProvider>
+ </ChatAgenticProvider>
</RoleProvider>
</PlanProvider>
</>
diff --git a/web/src/components/chat-access/capabilities-view.tsx b/web/src/components/chat-access/capabilities-view.tsx
new file mode 100644
index 000000000..6c13c4cff
--- /dev/null
+++ b/web/src/components/chat-access/capabilities-view.tsx
@@ -0,0 +1,188 @@
+'use client';
+
+import { useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Lock, MousePointerClick, SquareCheckBig, Unlock, Zap } from 'lucide-react';
+import { Input } from '@/components/ui/input';
+import { Badge } from '@/components/ui/badge';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { PLANS } from '@/config/plans';
+import type { ChatAccess } from '@/lib/actions/chat-access';
+import { approvalMark, type ApprovalMark, type CapabilityArea } from '@/lib/chat/access';
+import type { ToolCatalogEntry } from '@/lib/chat/registry/tools';
+import { cn } from '@/lib/utils';
+import { YourPlanCard } from './plan-card';
+
+const MARK_ICON: Record<ApprovalMark, typeof Unlock> = {
+ none: Unlock,
+ card: SquareCheckBig,
+ auto: Zap,
+ click: MousePointerClick,
+};
+
+const FILTERS = ['all', 'write', 'execute', 'read'] as const;
+type Filter = (typeof FILTERS)[number];
+
+/** "What Chat can do": the registry by area, searchable, with the plan card on top. */
+export function CapabilitiesView({
+ access,
+ areas,
+}: {
+ access: ChatAccess;
+ areas: CapabilityArea[];
+}) {
+ const t = useTranslations('chatAccess.capabilities');
+ const tAccess = useTranslations('chatAccess');
+ const tTools = useTranslations('chatTools');
+ const [query, setQuery] = useState('');
+ const [filter, setFilter] = useState<Filter>('all');
+
+ const toolName = (entry: ToolCatalogEntry) => tTools(`${entry.key}.name`);
+ const shown = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ return areas.filter((area) => {
+ if (filter === 'write' && area.write.length === 0) return false;
+ if (filter === 'execute' && area.execute.length === 0) return false;
+ if (filter === 'read' && area.write.length + area.execute.length > 0) return false;
+ if (!q) return true;
+ const words = [
+ t(`areaNames.${area.area}`),
+ ...[...area.read, ...area.write, ...area.execute].map(toolName),
+ ];
+ return words.some((word) => word.toLowerCase().includes(q));
+ });
+ // toolName and t read the same messages each render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [areas, filter, query]);
+
+ const entries = (list: ToolCatalogEntry[]) =>
+ list.length === 0 ? (
+ <span aria-hidden className="text-muted-foreground">
+ –
+ </span>
+ ) : (
+ <ul className="space-y-1">
+ {list.map((entry) => {
+ const mark = approvalMark(entry);
+ const Icon = MARK_ICON[mark];
+ const lock = access.toolLocks[entry.key];
+ return (
+ <li key={entry.key} className="flex items-start gap-1.5">
+ {entry.class !== 'read' && (
+ <Icon
+ className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"
+ aria-label={t(`legend.${mark}`)}
+ />
+ )}
+ <span>
+ {toolName(entry)}
+ {lock && (
+ <span className="ml-1 inline-flex items-center gap-0.5 text-xs text-muted-foreground">
+ <Lock className="h-3 w-3" aria-hidden />
+ {t('locked', { plan: PLANS[lock].name })}
+ </span>
+ )}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ );
+
+ return (
+ <div className="space-y-5">
+ <div className="space-y-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <Badge variant="secondary" className="tabular-nums">
+ {t('areas', { count: areas.length })}
+ </Badge>
+ </div>
+ <p className="text-muted-foreground">{t('lead')}</p>
+ </div>
+
+ {access.plan && <YourPlanCard plan={access.plan} isAdmin={access.role === 'admin'} />}
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t('search')}
+ aria-label={t('search')}
+ className="h-8 w-64 max-w-full"
+ />
+ {FILTERS.map((id) => (
+ <button
+ key={id}
+ type="button"
+ onClick={() => setFilter(id)}
+ aria-pressed={filter === id}
+ className={cn(
+ 'rounded-full border px-2.5 py-0.5 text-xs transition-colors',
+ filter === id
+ ? 'border-foreground bg-foreground text-background'
+ : 'text-muted-foreground hover:bg-muted',
+ )}
+ >
+ {t(`filters.${id}`)}
+ </button>
+ ))}
+ <span className="ml-auto flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
+ {(Object.keys(MARK_ICON) as ApprovalMark[]).map((mark) => {
+ const Icon = MARK_ICON[mark];
+ return (
+ <span key={mark} className="inline-flex items-center gap-1">
+ <Icon className="h-3.5 w-3.5" aria-hidden />
+ {t(`legend.${mark}`)}
+ </span>
+ );
+ })}
+ </span>
+ </div>
+
+ <div className="overflow-x-auto rounded-xl border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('columns.area')}</TableHead>
+ <TableHead>{t('columns.read')}</TableHead>
+ <TableHead>{t('columns.write')}</TableHead>
+ <TableHead>{t('columns.execute')}</TableHead>
+ <TableHead>{t('columns.who')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {shown.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={5} className="py-6 text-center text-sm text-muted-foreground">
+ {t('empty')}
+ </TableCell>
+ </TableRow>
+ ) : (
+ shown.map((area) => (
+ <TableRow key={area.area} className="align-top">
+ <TableCell className="font-medium">{t(`areaNames.${area.area}`)}</TableCell>
+ <TableCell className="whitespace-normal">{entries(area.read)}</TableCell>
+ <TableCell className="whitespace-normal">{entries(area.write)}</TableCell>
+ <TableCell className="whitespace-normal">{entries(area.execute)}</TableCell>
+ <TableCell className="text-xs text-muted-foreground">
+ {area.writers.length === 0
+ ? t('readAll')
+ : area.writers.map((role) => tAccess(`roleNames.${role}`)).join(' · ')}
+ </TableCell>
+ </TableRow>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/components/chat-access/chat-access.test.tsx b/web/src/components/chat-access/chat-access.test.tsx
new file mode 100644
index 000000000..5d0c79595
--- /dev/null
+++ b/web/src/components/chat-access/chat-access.test.tsx
@@ -0,0 +1,280 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+import type { ChatAccess, RoleMember } from '@/lib/actions/chat-access';
+import type { CapabilityArea, PlanCard } from '@/lib/chat/access';
+import type { ToolCatalogEntry } from '@/lib/chat/registry/tools';
+
+/** Roles & access, Your access, the plan card and "What Chat can do" (CHAT-20 §4a, §4b, §7a, §8). */
+
+const getChatAccess = vi.fn();
+const listRoleMembers = vi.fn();
+vi.mock('@/lib/actions/chat-access', () => ({
+ getChatAccess: () => getChatAccess(),
+ listRoleMembers: () => listRoleMembers(),
+}));
+vi.mock('@/lib/actions/team', () => ({ updateMemberRole: vi.fn() }));
+vi.mock('@/components/providers/upgrade-gate', () => ({
+ useUpgradeGate: () => ({ guard: (fn: unknown) => fn }),
+}));
+vi.mock('@/components/providers/ai-usage-provider', () => ({
+ useAiUsage: () => ({ usage: { percentUsed: 18 }, refresh: vi.fn() }),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+
+const { RolesAccessSection } = await import('./roles-access-section');
+const { YourAccessCard } = await import('./your-access-card');
+const { YourPlanCard } = await import('./plan-card');
+const { CapabilitiesView } = await import('./capabilities-view');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ getChatAccess.mockReset();
+ listRoleMembers.mockReset();
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function render(node: React.ReactNode) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider
+ locale="en"
+ messages={messages}
+ timeZone="UTC"
+ now={new Date('2026-10-29T12:00:00Z')}
+ >
+ {node}
+ </NextIntlClientProvider>,
+ );
+ });
+}
+const text = () => container.textContent ?? '';
+
+const starter: PlanCard = {
+ planId: 'starter',
+ planName: 'Starter',
+ priceMonthly: 49,
+ isTrial: false,
+ chips: [
+ { key: 'platforms', count: 2, locked: null },
+ { key: 'fullAuto', locked: 'growth' },
+ ],
+ next: {
+ planId: 'growth',
+ planName: 'Growth',
+ priceMonthly: 249,
+ priceDiff: 200,
+ afterTrial: false,
+ benefits: [
+ { key: 'morePlatforms', count: 6 },
+ { key: 'aiLimit', times: 5 },
+ ],
+ },
+};
+
+const access = (over: Partial<ChatAccess> = {}): ChatAccess => ({
+ role: 'manager',
+ plan: starter,
+ yourAccess: [
+ { key: 'read', class: 'read', value: 'yes' },
+ {
+ key: 'execute',
+ class: 'execute',
+ value: 'after_click_except',
+ off: ['publishing', 'feeds'],
+ },
+ { key: 'settings', class: 'write', value: 'ask_admin' },
+ ],
+ switches: {
+ managerExecuteOff: ['publishing'],
+ fullAutoForMembers: true,
+ fullAutoLocked: 'growth',
+ setBy: 'Ayşe',
+ },
+ toolLocks: {},
+ ...over,
+});
+
+const members: RoleMember[] = [
+ {
+ userId: 'u1',
+ name: 'Sam Lee',
+ email: '[email protected]',
+ role: 'admin',
+ lastActiveAt: '2026-10-29T11:48:00Z',
+ isYou: false,
+ },
+ { userId: 'u2', name: 'alex', email: null, role: 'manager', lastActiveAt: null, isYou: true },
+];
+
+describe('YourPlanCard', () => {
+ it('shows the plan, what it locks, the AI limit used, and what Growth adds for an Admin', async () => {
+ await render(<YourPlanCard plan={starter} isAdmin />);
+ expect(text()).toContain('Starter$49/mo');
+ expect(text()).toContain('2 AI platforms');
+ expect(
+ container.querySelector('[title="Needs Growth · you\'re on Starter"]')?.textContent,
+ ).toContain('Full auto');
+ expect(text()).toContain('18% used');
+ expect(text()).toContain("With Growth you'd also get");
+ expect(text()).toContain('See your brand in 6 more AI platforms');
+ expect(text()).toContain('5× the monthly AI limit');
+ expect(text()).toContain('+$200/mo');
+ expect(container.querySelector('a[href="/dashboard/settings/billing"]')).not.toBeNull();
+ expect(text()).toContain('Upgrade');
+ });
+
+ it('leaves Upgrade to Admins, and the next plan off Enterprise', async () => {
+ await render(<YourPlanCard plan={starter} isAdmin={false} />);
+ expect(text()).not.toContain('Upgrade');
+ await render(
+ <YourPlanCard
+ plan={{
+ ...starter,
+ planId: 'enterprise',
+ planName: 'Enterprise',
+ priceMonthly: null,
+ next: null,
+ }}
+ isAdmin
+ />,
+ );
+ expect(text()).toContain('EnterpriseCustom contract');
+ expect(text()).not.toContain("you'd also get");
+ expect(text()).not.toContain('Upgrade');
+ });
+});
+
+describe('YourAccessCard', () => {
+ it("says the person's role and what Chat may do as them", async () => {
+ await render(<YourAccessCard access={access()} />);
+ expect(text()).toContain('Your accessManager');
+ expect(text()).toContain('All brands');
+ expect(text()).toContain('After your click, except publishing, feed pushes');
+ expect(text()).toContain('Ask your Admin');
+ expect(container.querySelector('a[href="/dashboard/settings/roles-access"]')?.textContent).toBe(
+ 'See what each role can do',
+ );
+ expect(container.querySelector('a[href="/dashboard/chat/capabilities"]')).not.toBeNull();
+ });
+});
+
+describe('RolesAccessSection', () => {
+ it("is read-only for a Manager: no e-mails, no role picker, the switches' state", async () => {
+ getChatAccess.mockResolvedValue(access());
+ listRoleMembers.mockResolvedValue(members.map((m) => ({ ...m, email: null })));
+ await render(<RolesAccessSection />);
+ expect(text()).toContain("You're a Manager · read-only here");
+ expect(text()).not.toContain('@');
+ expect(container.querySelector('[aria-label="Role"]')).toBeNull();
+ expect(text()).toContain('WRITE with approval · EXECUTE after click');
+ expect(text()).toContain('12 minutes ago');
+ expect(text()).toContain('Not yet');
+ expect(text()).toContain('What each role can do');
+ expect(text()).toContain('Off for publishing');
+ expect(text()).toContain('Needs Growth');
+ expect(text()).toContain('Set by Ayşe');
+ });
+
+ it('gives an Admin the e-mails and a role picker for everyone but themselves', async () => {
+ getChatAccess.mockResolvedValue(access({ role: 'admin' }));
+ listRoleMembers.mockResolvedValue(members);
+ await render(<RolesAccessSection />);
+ expect(text()).not.toContain('read-only here');
+ expect(text()).toContain('[email protected]');
+ expect(container.querySelectorAll('[aria-label="Role"]')).toHaveLength(1);
+ });
+
+ it('says so when it cannot be read', async () => {
+ getChatAccess.mockRejectedValue(new Error('down'));
+ listRoleMembers.mockResolvedValue([]);
+ await render(<RolesAccessSection />);
+ expect(text()).toContain("Couldn't load Roles & access");
+ });
+});
+
+describe('CapabilitiesView', () => {
+ const entry = (
+ key: string,
+ cls: ToolCatalogEntry['class'],
+ over: Partial<ToolCatalogEntry> = {},
+ ) =>
+ ({
+ key,
+ area: 'prompts',
+ class: cls,
+ defaultPolicy: cls === 'read' ? 'on' : 'ask_full_auto',
+ maxPolicy: cls === 'read' ? 'on' : 'always',
+ flags: { alwaysCard: false, costCard: false, adminMayTurnOff: false },
+ minRole: 'analyst',
+ excludeRoles: [],
+ planGate: null,
+ costClass: 'C1',
+ route: null,
+ ...over,
+ }) as ToolCatalogEntry;
+ const areas: CapabilityArea[] = [
+ {
+ area: 'prompts',
+ read: [entry('trackedPrompts', 'read')],
+ write: [entry('dismissSuggestion', 'write', { excludeRoles: ['agency_partner'] })],
+ execute: [],
+ writers: ['admin', 'manager', 'analyst'],
+ },
+ {
+ area: 'citations',
+ read: [entry('citations', 'read', { area: 'citations' })],
+ write: [],
+ execute: [],
+ writers: [],
+ },
+ ];
+
+ it('lists each area with its tools, who may change it, and what the plan locks', async () => {
+ await render(
+ <CapabilitiesView access={access({ toolLocks: { citations: 'growth' } })} areas={areas} />,
+ );
+ expect(text()).toContain('What Chat can do2 areas');
+ expect(text()).toContain('Read tracked prompts');
+ expect(text()).toContain('Dismiss prompt suggestions');
+ expect(text()).toContain('Admin · Manager · Analyst');
+ expect(text()).toContain('Read: all roles');
+ expect(text()).toContain('Read citationsNeeds Growth');
+ });
+
+ it('narrows to areas with changes, and to a search', async () => {
+ await render(<CapabilitiesView access={access()} areas={areas} />);
+ const button = (label: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === label)!;
+ await act(async () => button('Has WRITE').click());
+ expect(text()).not.toContain('Read citations');
+ await act(async () => button('All').click());
+ const input = container.querySelector('input')!;
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ setter.call(input, 'citat');
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ expect(text()).toContain('Read citations');
+ expect(text()).not.toContain('Read tracked prompts');
+ });
+});
diff --git a/web/src/components/chat-access/class-badge.tsx b/web/src/components/chat-access/class-badge.tsx
new file mode 100644
index 000000000..b3c5a0b9a
--- /dev/null
+++ b/web/src/components/chat-access/class-badge.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { cn } from '@/lib/utils';
+import type { AccessClass } from '@/lib/chat/access';
+
+/** READ / WRITE / EXECUTE / NEVER, as CHAT-20's pages mark a row (mockup .cls). */
+const STYLE: Record<AccessClass, string> = {
+ read: 'bg-muted text-muted-foreground',
+ write: 'bg-amber-100 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300',
+ execute: 'bg-foreground text-background',
+ never: 'border border-dashed text-muted-foreground',
+};
+
+export function ClassBadge({ cls, className }: { cls: AccessClass; className?: string }) {
+ const t = useTranslations('chatAccess.classes');
+ return (
+ <span
+ className={cn(
+ 'inline-flex shrink-0 items-center justify-center rounded-md px-1.5 py-px font-mono text-[10.5px] font-medium tracking-wide whitespace-nowrap',
+ STYLE[cls],
+ className,
+ )}
+ >
+ {t(cls)}
+ </span>
+ );
+}
diff --git a/web/src/components/chat-access/plan-card.tsx b/web/src/components/chat-access/plan-card.tsx
new file mode 100644
index 000000000..ada32efb1
--- /dev/null
+++ b/web/src/components/chat-access/plan-card.tsx
@@ -0,0 +1,130 @@
+'use client';
+
+import { useFormatter, useTranslations } from 'next-intl';
+import { Lock } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { buttonVariants } from '@/components/ui/button-variants';
+import { PLANS } from '@/config/plans';
+import { percentLabel } from '@/lib/billing/ai-usage';
+import { useAiUsage } from '@/components/providers/ai-usage-provider';
+import type { PlanCard, PlanChip } from '@/lib/chat/access';
+import { cn } from '@/lib/utils';
+
+const BILLING = '/dashboard/settings/billing';
+
+/**
+ * "Your plan" (CHAT-20 §7a, mockup .planstrip): the plan and its price,
+ * what it includes, AI usage as a percentage, and what the next plan would
+ * add. No upsell on Enterprise. Admins get Upgrade; the others see the same
+ * card without it (Ask your Admin comes with access requests).
+ */
+export function YourPlanCard({ plan, isAdmin }: { plan: PlanCard; isAdmin: boolean }) {
+ const t = useTranslations('chatAccess.plan');
+ const format = useFormatter();
+ const { usage } = useAiUsage();
+ const money = (value: number) =>
+ format.number(value, { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });
+ const planName = (id: keyof typeof PLANS) => PLANS[id].name;
+
+ const chipLabel = (chip: PlanChip) => {
+ switch (chip.key) {
+ case 'platforms':
+ return t('chips.platforms', { count: chip.count });
+ case 'mcp':
+ return t('chips.mcp', { access: chip.access ?? 'none' });
+ default:
+ return t(`chips.${chip.key}`);
+ }
+ };
+ const lockText = (chip: PlanChip) =>
+ chip.locked
+ ? plan.isTrial && chip.key === 'mcp'
+ ? t('lockedTrial', { plan: planName(chip.locked) })
+ : t('locked', { plan: planName(chip.locked), current: plan.planName })
+ : undefined;
+
+ const next = plan.next;
+ return (
+ <section
+ aria-label={t('yourPlan')}
+ className="overflow-hidden rounded-xl border bg-card shadow-sm"
+ >
+ <div className="grid gap-4 p-4 sm:grid-cols-[minmax(0,10rem)_minmax(0,1fr)_auto] sm:items-center">
+ <div>
+ <p className="text-xs text-muted-foreground">{t('yourPlan')}</p>
+ <p className="text-base font-semibold">
+ {plan.isTrial ? `${t('trial')} · ${plan.planName}` : plan.planName}
+ {!plan.isTrial && (
+ <span className="ml-1.5 text-xs font-normal text-muted-foreground">
+ {plan.priceMonthly !== null
+ ? t('perMonth', { price: money(plan.priceMonthly) })
+ : t('custom')}
+ </span>
+ )}
+ </p>
+ </div>
+ <ul className="flex flex-wrap gap-1.5">
+ {plan.chips.map((chip) => (
+ <li
+ key={chip.key}
+ title={lockText(chip)}
+ className={cn(
+ 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs',
+ chip.locked ? 'text-muted-foreground' : 'bg-muted/50',
+ )}
+ >
+ {chip.locked && <Lock className="h-3 w-3" aria-hidden />}
+ {chipLabel(chip)}
+ {chip.locked && <span className="sr-only">{lockText(chip)}</span>}
+ </li>
+ ))}
+ </ul>
+ <div className="flex items-center gap-4">
+ {usage?.percentUsed !== null && usage?.percentUsed !== undefined && (
+ <div className="text-right">
+ <p className="text-xs text-muted-foreground">{t('aiLimit')}</p>
+ <p className="text-sm font-medium tabular-nums">
+ {t('aiUsed', { percent: percentLabel(usage.percentUsed) })}
+ </p>
+ </div>
+ )}
+ <Link href={BILLING} className={buttonVariants({ variant: 'outline', size: 'sm' })}>
+ {t('comparePlans')}
+ </Link>
+ </div>
+ </div>
+ {next && (
+ <div className="flex flex-col gap-2 border-t bg-muted/30 px-4 py-3 text-xs sm:flex-row sm:items-center sm:gap-4">
+ <p className="shrink-0 font-medium">
+ {next.afterTrial ? t('afterTrial') : t('next', { plan: next.planName })}
+ </p>
+ <ul className="flex min-w-0 flex-1 flex-wrap gap-x-3 gap-y-1 text-muted-foreground">
+ {next.benefits.map((benefit) => (
+ <li key={benefit.key}>
+ {benefit.key === 'morePlatforms'
+ ? t('benefits.morePlatforms', { count: benefit.count })
+ : benefit.key === 'aiLimit'
+ ? t('benefits.aiLimit', { times: benefit.times })
+ : t(`benefits.${benefit.key}`)}
+ </li>
+ ))}
+ </ul>
+ <span className="shrink-0 font-medium tabular-nums">
+ {next.afterTrial
+ ? next.priceMonthly !== null
+ ? t('afterTrialPrice', { plan: next.planName, price: money(next.priceMonthly) })
+ : null
+ : next.priceDiff !== null
+ ? t('priceDiff', { price: money(next.priceDiff) })
+ : t('customPrice')}
+ </span>
+ {isAdmin && (
+ <Link href={BILLING} className={cn(buttonVariants({ size: 'sm' }), 'shrink-0')}>
+ {next.afterTrial ? t('choosePlan') : t('upgrade')}
+ </Link>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/web/src/components/chat-access/roles-access-section.tsx b/web/src/components/chat-access/roles-access-section.tsx
new file mode 100644
index 000000000..d4f9d0e5b
--- /dev/null
+++ b/web/src/components/chat-access/roles-access-section.tsx
@@ -0,0 +1,380 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+import { useFormatter, useTranslations } from 'next-intl';
+import { ArrowUpRight, Check, Info, Loader2, Lock } from 'lucide-react';
+import { toast } from 'sonner';
+import { Link } from '@/i18n/navigation';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Badge } from '@/components/ui/badge';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
+import type { TeamRole } from '@/components/providers/role-provider';
+import { PLANS } from '@/config/plans';
+import { updateMemberRole } from '@/lib/actions/team';
+import {
+ getChatAccess,
+ listRoleMembers,
+ type ChatAccess,
+ type RoleMember,
+} from '@/lib/actions/chat-access';
+import { ROLE_MATRIX, ROLE_ORDER, type RoleCell } from '@/lib/chat/access';
+import { cn } from '@/lib/utils';
+import { ClassBadge } from './class-badge';
+import { YourPlanCard } from './plan-card';
+import { CAPABILITIES_PATH } from './your-access-card';
+
+/**
+ * Settings › Team › Roles & access (CHAT-20 §4a, mockup #g-roles): every
+ * member's role, what each role may do in the app and through Chat, and
+ * the Admin switches that change a role's rights. Everyone reads it; only
+ * Admins change a role here (the rest of the team's management stays in
+ * Team).
+ */
+export function RolesAccessSection() {
+ const t = useTranslations('chatAccess');
+ const [access, setAccess] = useState<ChatAccess | null | 'failed' | undefined>(undefined);
+ const [members, setMembers] = useState<RoleMember[]>([]);
+
+ // Bumped after a role change, to read the members and access again.
+ const [version, setVersion] = useState(0);
+
+ useEffect(() => {
+ let live = true;
+ Promise.all([getChatAccess(), listRoleMembers()])
+ .then(([nextAccess, nextMembers]) => {
+ if (!live) return;
+ setAccess(nextAccess);
+ setMembers(nextMembers);
+ })
+ .catch(() => {
+ if (live) setAccess('failed');
+ });
+ return () => {
+ live = false;
+ };
+ }, [version]);
+ const reload = useCallback(() => setVersion((v) => v + 1), []);
+
+ if (access === undefined) return <Skeleton className="h-96 w-full" />;
+ if (access === 'failed' || access === null) {
+ return (
+ <p role="status" className="text-sm text-muted-foreground">
+ {t('roles.loadError')}
+ </p>
+ );
+ }
+
+ const isAdmin = access.role === 'admin';
+ return (
+ <div className="space-y-6">
+ {access.plan && <YourPlanCard plan={access.plan} isAdmin={isAdmin} />}
+
+ <div className="space-y-1">
+ <h2 className="text-lg font-semibold">{t('roles.title')}</h2>
+ <p className="text-sm text-muted-foreground">{t('roles.lead')}</p>
+ <Link
+ href={CAPABILITIES_PATH}
+ className="inline-flex items-center gap-0.5 text-xs font-medium underline-offset-2 hover:underline"
+ >
+ {t('yourAccess.seeCapabilities')}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ </div>
+
+ {!isAdmin && (
+ <div className="flex items-center gap-2.5 rounded-xl border bg-muted/40 px-3.5 py-2.5 text-sm">
+ <Info className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
+ <span className="font-medium">{t('roles.readOnly', { role: access.role })}</span>
+ <span className="text-muted-foreground">{t('roles.readOnlyNote')}</span>
+ </div>
+ )}
+
+ <MembersTable members={members} isAdmin={isAdmin} onChanged={reload} />
+ <RoleMatrix role={access.role} />
+ <AdminSwitches access={access} />
+ </div>
+ );
+}
+
+function MembersTable({
+ members,
+ isAdmin,
+ onChanged,
+}: {
+ members: RoleMember[];
+ isAdmin: boolean;
+ onChanged: () => void;
+}) {
+ const t = useTranslations('chatAccess');
+ const format = useFormatter();
+ return (
+ <section className="space-y-2">
+ <div className="flex items-center gap-2">
+ <h3 className="text-sm font-semibold">{t('roles.members')}</h3>
+ <Badge variant="secondary" className="tabular-nums">
+ {members.length}
+ </Badge>
+ {isAdmin && (
+ <Link
+ href="/dashboard/settings/team"
+ className="ml-auto text-xs font-medium underline-offset-2 hover:underline"
+ >
+ {t('roles.manageInTeam')}
+ </Link>
+ )}
+ </div>
+ <div className="overflow-x-auto rounded-xl border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('roles.columns.member')}</TableHead>
+ <TableHead>{t('roles.columns.role')}</TableHead>
+ <TableHead>{t('roles.columns.brands')}</TableHead>
+ <TableHead>{t('roles.columns.throughChat')}</TableHead>
+ <TableHead>{t('roles.columns.lastActive')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {members.map((member) => (
+ <TableRow key={member.userId}>
+ <TableCell>
+ <span className="font-medium">{member.name}</span>
+ {member.isYou && (
+ <Badge variant="secondary" className="ml-1.5 text-[10px]">
+ {t('roles.you')}
+ </Badge>
+ )}
+ {member.email && (
+ <span className="block text-xs text-muted-foreground">{member.email}</span>
+ )}
+ </TableCell>
+ <TableCell>
+ {isAdmin && !member.isYou ? (
+ <RoleSelect member={member} onChanged={onChanged} />
+ ) : (
+ t(`roleNames.${member.role}`)
+ )}
+ </TableCell>
+ <TableCell className="text-muted-foreground">{t('roles.allBrands')}</TableCell>
+ <TableCell className="text-xs text-muted-foreground">
+ {t(`roles.throughChat.${member.role}`)}
+ </TableCell>
+ <TableCell className="text-xs whitespace-nowrap text-muted-foreground">
+ {member.lastActiveAt
+ ? format.relativeTime(new Date(member.lastActiveAt))
+ : t('roles.neverSignedIn')}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ </section>
+ );
+}
+
+function RoleSelect({ member, onChanged }: { member: RoleMember; onChanged: () => void }) {
+ const t = useTranslations('chatAccess');
+ const tActions = useTranslations('readOnly.actions');
+ // A read-only workspace opens the upgrade dialog instead, as Team does.
+ const { guard } = useUpgradeGate();
+ const [pending, setPending] = useState(false);
+ const items = ROLE_ORDER.map((role) => ({ value: role, label: t(`roleNames.${role}`) }));
+
+ async function change(role: TeamRole) {
+ if (role === member.role) return;
+ setPending(true);
+ try {
+ await updateMemberRole(member.userId, role);
+ toast.success(t('roles.roleChanged'));
+ onChanged();
+ } catch {
+ toast.error(t('roles.roleChangeFailed'));
+ } finally {
+ setPending(false);
+ }
+ }
+
+ return (
+ <Select
+ items={items}
+ value={member.role}
+ onValueChange={guard((v: string | null) => void change(v as TeamRole), {
+ action: tActions('changeRoles'),
+ })}
+ disabled={pending}
+ >
+ <SelectTrigger size="sm" className="w-36" aria-label={t('roles.columns.role')}>
+ {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : <SelectValue />}
+ </SelectTrigger>
+ <SelectContent>
+ {items.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+function Cell({ cell }: { cell: RoleCell }) {
+ const t = useTranslations('chatAccess.roles.matrix.cells');
+ if (cell === 'yes') {
+ return (
+ <>
+ <Check className="mx-auto h-4 w-4" aria-hidden />
+ <span className="sr-only">{t('yes')}</span>
+ </>
+ );
+ }
+ if (cell === 'no') {
+ return (
+ <>
+ <span aria-hidden className="text-muted-foreground">
+ –
+ </span>
+ <span className="sr-only">{t('no')}</span>
+ </>
+ );
+ }
+ return <span className="text-xs text-muted-foreground">{t(cell)}</span>;
+}
+
+function RoleMatrix({ role }: { role: TeamRole }) {
+ const t = useTranslations('chatAccess');
+ return (
+ <section className="space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="text-sm font-semibold">{t('roles.matrix.title')}</h3>
+ <span className="text-xs text-muted-foreground">{t('roles.matrix.count')}</span>
+ <span className="ml-auto flex flex-wrap items-center gap-1.5">
+ {(['read', 'write', 'execute', 'never'] as const).map((cls) => (
+ <ClassBadge key={cls} cls={cls} />
+ ))}
+ <Badge variant="outline" className="text-[11px]">
+ {t('roles.matrix.actsAsUser')}
+ </Badge>
+ </span>
+ </div>
+ <div className="overflow-x-auto rounded-xl border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('roles.matrix.capability')}</TableHead>
+ {ROLE_ORDER.map((r) => (
+ <TableHead key={r} className={cn('w-28 text-center', r === role && 'bg-muted/60')}>
+ {t(`roleNames.${r}`)}
+ <span className="block text-[10px] font-normal text-muted-foreground">
+ {r === role ? t('roles.you') : r === 'admin' ? t('roles.matrix.adminNote') : ''}
+ </span>
+ </TableHead>
+ ))}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {ROLE_MATRIX.map((group) => [
+ <TableRow key={group.key} className="hover:bg-transparent">
+ <TableCell
+ colSpan={1 + ROLE_ORDER.length}
+ className="bg-muted/30 py-1.5 text-[11px] font-medium tracking-wide text-muted-foreground uppercase"
+ >
+ {t(`roles.matrix.groups.${group.key}`)}
+ </TableCell>
+ </TableRow>,
+ ...group.rows.map((row) => (
+ <TableRow key={row.key}>
+ <TableCell className="whitespace-normal">
+ <span className="flex items-start gap-2">
+ <ClassBadge cls={row.class} className="mt-0.5 w-16" />
+ <span>
+ {t(`roles.matrix.rows.${row.key}.name`)}
+ <span className="block text-xs text-muted-foreground">
+ {t(`roles.matrix.rows.${row.key}.scope`)}
+ </span>
+ </span>
+ </span>
+ </TableCell>
+ {ROLE_ORDER.map((r) => (
+ <TableCell key={r} className={cn('text-center', r === role && 'bg-muted/60')}>
+ <Cell cell={row.cells[r]} />
+ </TableCell>
+ ))}
+ </TableRow>
+ )),
+ ])}
+ </TableBody>
+ </Table>
+ </div>
+ </section>
+ );
+}
+
+function AdminSwitches({ access }: { access: ChatAccess }) {
+ const t = useTranslations('chatAccess.roles.switches');
+ const { managerExecuteOff, fullAutoForMembers, fullAutoLocked, setBy } = access.switches;
+ const execute =
+ managerExecuteOff.length === 0
+ ? t('on')
+ : managerExecuteOff.length >= 4
+ ? t('off')
+ : t('offFor', { groups: managerExecuteOff.map((g) => t(`groups.${g}`)).join(', ') });
+ const fullAuto = fullAutoLocked
+ ? t('needsPlan', { plan: PLANS[fullAutoLocked].name })
+ : fullAutoForMembers
+ ? t('on')
+ : t('off');
+ const rows = [
+ {
+ key: 'managerExecute',
+ name: t('managerExecute'),
+ note: t('managerExecuteNote'),
+ value: execute,
+ },
+ { key: 'fullAuto', name: t('fullAuto'), note: t('fullAutoNote'), value: fullAuto },
+ ];
+ return (
+ <section className="space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="text-sm font-semibold">{t('title')}</h3>
+ <span className="ml-auto inline-flex items-center gap-1 text-xs text-muted-foreground">
+ <Lock className="h-3 w-3" aria-hidden />
+ {t('onlyAdmins')}
+ </span>
+ </div>
+ <ul className="divide-y rounded-xl border">
+ {rows.map((row) => (
+ <li key={row.key} className="flex items-center gap-3 px-3.5 py-2.5 text-sm">
+ <span className="min-w-0 flex-1">
+ <span className="font-medium">{row.name}</span>
+ <span className="block text-xs text-muted-foreground">{row.note}</span>
+ </span>
+ <span className="shrink-0 text-right text-xs font-medium">
+ {row.value}
+ {setBy && (
+ <span className="block font-normal text-muted-foreground">
+ {t('setBy', { name: setBy })}
+ </span>
+ )}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ );
+}
diff --git a/web/src/components/chat-access/your-access-card.tsx b/web/src/components/chat-access/your-access-card.tsx
new file mode 100644
index 000000000..0f33dcffa
--- /dev/null
+++ b/web/src/components/chat-access/your-access-card.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { ArrowUpRight } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { getChatAccess, type ChatAccess } from '@/lib/actions/chat-access';
+import type { YourAccessRow } from '@/lib/chat/access';
+import { ClassBadge } from './class-badge';
+
+export const ROLES_ACCESS_PATH = '/dashboard/settings/roles-access';
+export const CAPABILITIES_PATH = '/dashboard/chat/capabilities';
+
+/**
+ * Settings › Account › Your access (CHAT-20 §4b, mockup #g-my-access): the
+ * person's role, their brands, what Chat may do as them, and the way to
+ * every role's card.
+ */
+export function YourAccessCard({ access }: { access: ChatAccess }) {
+ const t = useTranslations('chatAccess');
+ const value = (row: YourAccessRow) =>
+ row.value === 'after_click_except'
+ ? t('yourAccess.values.after_click_except', {
+ groups: (row.off ?? []).map((g) => t(`roles.switches.groups.${g}`)).join(', '),
+ })
+ : t(`yourAccess.values.${row.value}`);
+ return (
+ <Card>
+ <CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
+ <CardTitle>{t('yourAccess.title')}</CardTitle>
+ <Badge variant="secondary">{t(`roleNames.${access.role}`)}</Badge>
+ </CardHeader>
+ <CardContent className="space-y-3 text-sm">
+ <div className="grid grid-cols-[7rem_minmax(0,1fr)] gap-2">
+ <span className="text-muted-foreground">{t('yourAccess.brands')}</span>
+ <span>{t('roles.allBrands')}</span>
+ </div>
+ <div>
+ <p className="mb-1 text-xs font-medium text-muted-foreground">
+ {t('yourAccess.actsAsYou')}
+ </p>
+ <ul className="divide-y">
+ {access.yourAccess.map((row) => (
+ <li key={row.key} className="flex items-center gap-2 py-1.5">
+ <ClassBadge cls={row.class} className="w-16" />
+ <span className="min-w-0 flex-1">{t(`yourAccess.rows.${row.key}`)}</span>
+ <span
+ className={
+ row.value === 'ask_admin' || row.value === 'execute_off'
+ ? 'text-right text-xs text-muted-foreground'
+ : 'text-right text-xs font-medium'
+ }
+ >
+ {value(row)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ <div className="flex flex-wrap gap-x-4 gap-y-1">
+ <Link
+ href={ROLES_ACCESS_PATH}
+ className="inline-flex items-center gap-0.5 text-xs font-medium underline-offset-2 hover:underline"
+ >
+ {t('yourAccess.seeRoles')}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ <Link
+ href={CAPABILITIES_PATH}
+ className="inline-flex items-center gap-0.5 text-xs font-medium underline-offset-2 hover:underline"
+ >
+ {t('yourAccess.seeCapabilities')}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
+/** The card, read for the signed-in person; nothing while Chat is off or the read fails. */
+export function YourAccessSlot({ className }: { className?: string }) {
+ const [access, setAccess] = useState<ChatAccess | null>(null);
+ useEffect(() => {
+ let live = true;
+ getChatAccess()
+ .then((next) => {
+ if (live) setAccess(next);
+ })
+ .catch(() => {});
+ return () => {
+ live = false;
+ };
+ }, []);
+ if (!access) return null;
+ return (
+ <div className={className}>
+ <YourAccessCard access={access} />
+ </div>
+ );
+}
diff --git a/web/src/components/layout/user-profile-nav-item.tsx b/web/src/components/layout/user-profile-nav-item.tsx
index cebfe7a16..9b157ba6d 100644
--- a/web/src/components/layout/user-profile-nav-item.tsx
+++ b/web/src/components/layout/user-profile-nav-item.tsx
@@ -1,11 +1,14 @@
'use client';
+import { useContext } from 'react';
import { useTranslations } from 'next-intl';
import { Settings } from 'lucide-react';
import { Link, usePathname } from '@/i18n/navigation';
import { cn } from '@/lib/utils';
import { useAuthStore } from '@/stores/use-auth-store';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
+import { RoleContext } from '@/components/providers/role-provider';
+import { useChatAgentic } from '@/components/providers/chat-agentic-provider';
interface UserProfileNavItemProps {
collapsed?: boolean;
@@ -19,6 +22,10 @@ export function UserProfileNavItem({
className,
}: UserProfileNavItemProps) {
const t = useTranslations('nav');
+ const tAccess = useTranslations('chatAccess');
+ // With the new Chat on, the row says the person's role (CHAT-20 §4b).
+ const { role } = useContext(RoleContext);
+ const showRole = useChatAgentic();
const pathname = usePathname();
// The row is the sidebar's way into Settings, so it marks Settings as current.
const active = pathname.startsWith('/dashboard/settings');
@@ -58,7 +65,14 @@ export function UserProfileNavItem({
</Avatar>
{!collapsed && (
<>
- <span className="truncate text-sm font-medium capitalize">{label}</span>
+ <span className="min-w-0">
+ <span className="block truncate text-sm font-medium capitalize">{label}</span>
+ {showRole && (
+ <span className="block truncate text-xs text-muted-foreground">
+ {tAccess(`roleNames.${role}`)}
+ </span>
+ )}
+ </span>
{/* The whole row opens Settings; the gear says so. */}
<Settings
className={cn(
diff --git a/web/src/components/providers/chat-agentic-provider.tsx b/web/src/components/providers/chat-agentic-provider.tsx
new file mode 100644
index 000000000..c4962558d
--- /dev/null
+++ b/web/src/components/providers/chat-agentic-provider.tsx
@@ -0,0 +1,26 @@
+'use client';
+
+import { createContext, useContext, type ReactNode } from 'react';
+
+/**
+ * Whether the new Chat is on for the workspace (CHAT_AGENTIC, lib/chat/flag.ts),
+ * read once by the dashboard's layout on the server: the variables never
+ * reach the browser, only this answer. The pages that show Chat's access
+ * and plan (Roles & access, Your access, the sidebar's role line) appear
+ * only while it's on.
+ */
+const ChatAgenticContext = createContext(false);
+
+export function ChatAgenticProvider({
+ enabled,
+ children,
+}: {
+ enabled: boolean;
+ children: ReactNode;
+}) {
+ return <ChatAgenticContext.Provider value={enabled}>{children}</ChatAgenticContext.Provider>;
+}
+
+export function useChatAgentic(): boolean {
+ return useContext(ChatAgenticContext);
+}
diff --git a/web/src/lib/actions/chat-access.ts b/web/src/lib/actions/chat-access.ts
new file mode 100644
index 000000000..df5cbc20e
--- /dev/null
+++ b/web/src/lib/actions/chat-access.ts
@@ -0,0 +1,143 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { readMemberAuth } from '@/lib/member-emails';
+import type { TeamRole } from '@/components/providers/role-provider';
+import type { PlanId } from '@/config/plans';
+import { chatAgenticEnabled } from '@/lib/chat/flag';
+import { readPrecedenceContext } from '@/lib/chat/precedence-context';
+import { parseTeamRole } from '@/lib/chat/precedence';
+import type { ExecuteGroup } from '@/lib/chat/registry/define-tool';
+import { planCardOf, yourAccessRows, type PlanCard, type YourAccessRow } from '@/lib/chat/access';
+import { planGateLock } from '@/lib/chat/plan-facts';
+import { registryCatalog } from '@/lib/chat/registry/tools';
+
+/**
+ * What Settings › Team › Roles & access and Settings › Account › Your access
+ * show (CHAT-20 §4a, §4b, §7a), read with the same facts the approval
+ * precedence checks a tool call by, so a page and the server never
+ * disagree. Null while the new Chat is off for the workspace (CHAT_AGENTIC):
+ * the pages show nothing new.
+ */
+
+export interface ChatAccess {
+ role: TeamRole;
+ /** Null off the cloud: no plan. */
+ plan: PlanCard | null;
+ yourAccess: YourAccessRow[];
+ /** The workspace switches that change a role's rights (Settings › Chat, 00401). */
+ switches: {
+ managerExecuteOff: ExecuteGroup[];
+ fullAutoForMembers: boolean;
+ /** The plan Full auto needs, when the workspace's doesn't have it. */
+ fullAutoLocked: PlanId | null;
+ /** Who changed them last; null when no one has. */
+ setBy: string | null;
+ };
+ /** The plan each tool needs that the workspace doesn't have, by catalog key (§7a lock lines). */
+ toolLocks: Record<string, PlanId>;
+}
+
+export interface RoleMember {
+ userId: string;
+ name: string;
+ /** Admins only (§4a). */
+ email: string | null;
+ role: TeamRole;
+ /** The last sign-in; null when never. */
+ lastActiveAt: string | null;
+ isYou: boolean;
+}
+
+async function viewer(): Promise<{ userId: string; organizationId: string } | null> {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) return null;
+ const { data: profile } = await supabaseAdmin
+ .from('profiles')
+ .select('organization_id')
+ .eq('id', user.id)
+ .maybeSingle();
+ const organizationId = profile?.organization_id;
+ if (!organizationId || !chatAgenticEnabled(organizationId)) return null;
+ return { userId: user.id, organizationId };
+}
+
+/** The signed-in person's access and plan card; null while Chat is off for them. */
+export async function getChatAccess(): Promise<ChatAccess | null> {
+ const who = await viewer();
+ if (!who) return null;
+ const [ctx, settings] = await Promise.all([
+ readPrecedenceContext({ ...who, mode: 'ask_first', surface: 'chat' }),
+ supabaseAdmin
+ .from('chat_settings')
+ .select('updated_by')
+ .eq('organization_id', who.organizationId)
+ .maybeSingle(),
+ ]);
+ if (!ctx) return null;
+ const setById = settings.data?.updated_by ?? null;
+ const setBy = setById
+ ? await supabaseAdmin
+ .from('profiles')
+ .select('full_name')
+ .eq('id', setById)
+ .eq('organization_id', who.organizationId)
+ .maybeSingle()
+ .then(({ data }) => data?.full_name?.trim() || null)
+ : null;
+ return {
+ role: ctx.role,
+ plan: planCardOf(ctx.plan),
+ yourAccess: yourAccessRows(ctx.role, ctx.settings.managerExecuteOff),
+ switches: {
+ managerExecuteOff: [...ctx.settings.managerExecuteOff],
+ fullAutoForMembers: ctx.settings.fullAutoForMembers,
+ fullAutoLocked: ctx.plan.fullAuto ? null : 'growth',
+ setBy,
+ },
+ toolLocks: Object.fromEntries(
+ registryCatalog().flatMap((entry) => {
+ const lock = planGateLock(ctx.plan, entry.planGate);
+ return lock ? [[entry.key, lock]] : [];
+ }),
+ ),
+ };
+}
+
+/**
+ * The workspace's members for Roles & access: name, role and last sign-in
+ * for everyone, e-mails for Admins only (§4a). A member without a name goes
+ * by the part of their e-mail before the @. Empty while Chat is off.
+ */
+export async function listRoleMembers(): Promise<RoleMember[]> {
+ const who = await viewer();
+ if (!who) return [];
+ const { data, error } = await supabaseAdmin
+ .from('profiles')
+ .select('id, full_name, role, created_at')
+ .eq('organization_id', who.organizationId)
+ .order('created_at', { ascending: true });
+ if (error) throw new Error(error.message);
+ const rows = data ?? [];
+ const viewerRole = parseTeamRole(rows.find((row) => row.id === who.userId)?.role);
+ const auth = await readMemberAuth(rows.map((row) => row.id));
+ return rows.flatMap((row) => {
+ const role = parseTeamRole(row.role);
+ if (!role) return [];
+ const email = auth.get(row.id)?.email ?? null;
+ return [
+ {
+ userId: row.id,
+ name: row.full_name?.trim() || email?.split('@')[0] || '',
+ email: viewerRole === 'admin' ? email : null,
+ role,
+ lastActiveAt: auth.get(row.id)?.lastSignInAt ?? null,
+ isYou: row.id === who.userId,
+ },
+ ];
+ });
+}
diff --git a/web/src/lib/chat/access.test.ts b/web/src/lib/chat/access.test.ts
new file mode 100644
index 000000000..f35da97c4
--- /dev/null
+++ b/web/src/lib/chat/access.test.ts
@@ -0,0 +1,229 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ ROLE_MATRIX,
+ ROLE_ORDER,
+ approvalMark,
+ capabilityAreas,
+ planCardOf,
+ rolesFor,
+ yourAccessRows,
+} from './access';
+import { planFactsFromOrgRow } from './plan-facts';
+import { registryCatalog } from './registry/tools';
+
+// The registry's rows import the MCP data functions, which import the admin client.
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+
+/** Roles & access, Your access, the plan card and "What Chat can do" (CHAT-20 §4a, §4b, §7a, §8). */
+
+describe('ROLE_MATRIX', () => {
+ it('gives every role a cell on every row, and Admins every change Chat may make', () => {
+ for (const group of ROLE_MATRIX) {
+ for (const row of group.rows) {
+ expect(Object.keys(row.cells).sort()).toEqual([...ROLE_ORDER].sort());
+ if (group.key !== 'never') expect(row.cells.admin).not.toBe('no');
+ }
+ }
+ });
+
+ it('keeps Analysts and Agency partners to reading, as the database does', () => {
+ for (const group of ROLE_MATRIX.filter((g) => g.key === 'workspace' || g.key === 'admin')) {
+ for (const row of group.rows) {
+ expect(row.cells.analyst).toBe('no');
+ expect(row.cells.agency_partner).toBe('no');
+ }
+ }
+ });
+});
+
+describe('yourAccessRows', () => {
+ const value = (rows: ReturnType<typeof yourAccessRows>, key: string) =>
+ rows.find((row) => row.key === key);
+
+ it('lets an Admin change everything, going live after a click', () => {
+ const rows = yourAccessRows('admin', ['publishing']);
+ expect(value(rows, 'workspace')?.value).toBe('yes_card');
+ expect(value(rows, 'execute')?.value).toBe('after_click');
+ expect(value(rows, 'settings')?.value).toBe('yes');
+ });
+
+ it('names the go-live groups an Admin switched off for Managers, and all of them as off', () => {
+ expect(value(yourAccessRows('manager', []), 'execute')?.value).toBe('after_click');
+ expect(value(yourAccessRows('manager', ['publishing', 'feeds']), 'execute')).toEqual({
+ key: 'execute',
+ class: 'execute',
+ value: 'after_click_except',
+ off: ['publishing', 'feeds'],
+ });
+ expect(
+ value(
+ yourAccessRows('manager', ['publishing', 'email_outreach', 'code_prs', 'feeds']),
+ 'execute',
+ )?.value,
+ ).toBe('execute_off');
+ expect(value(yourAccessRows('manager', []), 'settings')?.value).toBe('ask_admin');
+ });
+
+ it('sends Analysts and Agency partners to their Admin for any change', () => {
+ for (const role of ['analyst', 'agency_partner'] as const) {
+ const rows = yourAccessRows(role, []);
+ expect(value(rows, 'read')?.value).toBe('yes');
+ for (const key of ['workspace', 'agents', 'execute', 'settings']) {
+ expect(value(rows, key)?.value).toBe('ask_admin');
+ }
+ }
+ });
+});
+
+describe('planCardOf', () => {
+ beforeEach(() => vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true'));
+ afterEach(() => vi.unstubAllEnvs());
+
+ const card = (plan: string, subscription_status = 'active', plan_overrides: unknown = null) =>
+ planCardOf(planFactsFromOrgRow({ plan, subscription_status, plan_overrides }))!;
+ const chip = (c: ReturnType<typeof card>, key: string) => c.chips.find((x) => x.key === key);
+
+ it("shows Starter's locks against Growth, and what Growth adds for its price", () => {
+ const starter = card('starter');
+ expect(starter).toMatchObject({ planId: 'starter', planName: 'Starter', priceMonthly: 49 });
+ expect(chip(starter, 'platforms')).toEqual({ key: 'platforms', count: 2, locked: null });
+ expect(chip(starter, 'fullAuto')?.locked).toBe('growth');
+ expect(chip(starter, 'mcp')).toEqual({ key: 'mcp', access: 'read', locked: 'growth' });
+ expect(chip(starter, 'openPr')?.locked).toBe('growth');
+ expect(starter.next).toEqual({
+ planId: 'growth',
+ planName: 'Growth',
+ priceMonthly: 249,
+ priceDiff: 200,
+ afterTrial: false,
+ benefits: [
+ { key: 'morePlatforms', count: 6 },
+ { key: 'fullAuto' },
+ { key: 'mcpWrite' },
+ { key: 'aiLimit', times: 5 },
+ ],
+ });
+ });
+
+ it("offers Enterprise's Claude tracking and contract from Growth, at a contract price", () => {
+ const growth = card('growth');
+ expect(chip(growth, 'fullAuto')?.locked).toBeNull();
+ expect(chip(growth, 'mcp')).toEqual({ key: 'mcp', access: 'read_write', locked: null });
+ expect(chip(growth, 'claude')?.locked).toBe('enterprise');
+ expect(growth.next).toMatchObject({
+ planId: 'enterprise',
+ priceDiff: null,
+ benefits: [{ key: 'claude' }, { key: 'contract' }],
+ });
+ });
+
+ it('upsells nothing on Enterprise and shows no lock there', () => {
+ const enterprise = card('enterprise');
+ expect(enterprise.next).toBeNull();
+ expect(enterprise.chips.every((c) => c.locked === null)).toBe(true);
+ expect(chip(enterprise, 'claude')).toBeUndefined();
+ const withClaude = card('enterprise', 'active', { allowedModels: ['claude-sonnet-5'] });
+ expect(chip(withClaude, 'claude')).toEqual({ key: 'claude', locked: null });
+ });
+
+ it('keeps MCP out of the trial, and reads paying as the next step', () => {
+ const trial = card('growth', 'trialing');
+ expect(trial.isTrial).toBe(true);
+ expect(chip(trial, 'mcp')).toEqual({ key: 'mcp', access: null, locked: 'starter' });
+ expect(chip(trial, 'fullAuto')?.locked).toBe('growth');
+ expect(trial.next).toMatchObject({
+ planId: 'growth',
+ afterTrial: true,
+ benefits: [
+ { key: 'keepEverything' },
+ { key: 'mcp' },
+ { key: 'monthlyLimit' },
+ { key: 'packs' },
+ ],
+ });
+ });
+
+ it('has no card off the cloud', () => {
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', '');
+ expect(planCardOf(planFactsFromOrgRow(null))).toBeNull();
+ });
+
+ it('carries no AI budget in dollars, only plan prices', () => {
+ expect(JSON.stringify(card('starter'))).not.toMatch(/Budget|Usd/);
+ });
+});
+
+describe('the registry as "What Chat can do" shows it', () => {
+ const catalog = registryCatalog();
+
+ it('marks how each row is approved', () => {
+ expect(
+ approvalMark({
+ class: 'read',
+ defaultPolicy: 'on',
+ flags: { alwaysCard: false, costCard: false, adminMayTurnOff: false },
+ }),
+ ).toBe('none');
+ const flags = { alwaysCard: false, costCard: false, adminMayTurnOff: false };
+ expect(approvalMark({ class: 'write', defaultPolicy: 'ask', flags })).toBe('card');
+ expect(approvalMark({ class: 'write', defaultPolicy: 'ask_full_auto', flags })).toBe('auto');
+ expect(
+ approvalMark({
+ class: 'write',
+ defaultPolicy: 'ask_full_auto',
+ flags: { ...flags, alwaysCard: true },
+ }),
+ ).toBe('card');
+ expect(approvalMark({ class: 'write', defaultPolicy: 'always', flags })).toBe('none');
+ expect(approvalMark({ class: 'execute', defaultPolicy: 'click', flags })).toBe('click');
+ });
+
+ it('opens a row from its minimum role up, less its excluded roles', () => {
+ expect(rolesFor({ minRole: 'analyst', excludeRoles: [] })).toEqual(ROLE_ORDER);
+ expect(rolesFor({ minRole: 'analyst', excludeRoles: ['agency_partner'] })).toEqual([
+ 'admin',
+ 'manager',
+ 'analyst',
+ ]);
+ expect(rolesFor({ minRole: 'manager', excludeRoles: [] })).toEqual(['admin', 'manager']);
+ expect(rolesFor({ minRole: 'admin', excludeRoles: [] })).toEqual(['admin']);
+ });
+
+ it("hands the browser no row's internals: no names, schema, code or brand lookup", () => {
+ for (const entry of catalog) {
+ expect(Object.keys(entry).sort()).toEqual(
+ [
+ 'area',
+ 'class',
+ 'costClass',
+ 'defaultPolicy',
+ 'excludeRoles',
+ 'flags',
+ 'key',
+ 'maxPolicy',
+ 'minRole',
+ 'planGate',
+ 'route',
+ ].sort(),
+ );
+ }
+ });
+
+ it("groups every row once by area, and says who may make an area's changes", () => {
+ const areas = capabilityAreas(catalog);
+ const rows = areas.flatMap((a) => [...a.read, ...a.write, ...a.execute]);
+ expect(rows).toHaveLength(catalog.length);
+ expect(new Set(areas.map((a) => a.area)).size).toBe(areas.length);
+ for (const area of areas) {
+ const changes = [...area.write, ...area.execute];
+ if (changes.length === 0) expect(area.writers).toEqual([]);
+ for (const entry of changes) {
+ for (const role of area.writers) expect(rolesFor(entry)).toContain(role);
+ }
+ }
+ const prompts = areas.find((a) => a.area === 'prompts')!;
+ expect(prompts.write.map((e) => e.key)).toContain('dismissSuggestion');
+ expect(prompts.writers).not.toContain('agency_partner');
+ });
+});
diff --git a/web/src/lib/chat/access.ts b/web/src/lib/chat/access.ts
new file mode 100644
index 000000000..3078c0202
--- /dev/null
+++ b/web/src/lib/chat/access.ts
@@ -0,0 +1,333 @@
+import { PLANS, PLAN_ORDER, type PlanId, type PlanLimits } from '@/config/plans';
+import type { TeamRole } from '@/components/providers/role-provider';
+import type { ExecuteGroup, ToolArea, ToolClass, ToolPolicy } from './registry/define-tool';
+import type { ToolCatalogEntry } from './registry/tools';
+import { planGateLock, type PlanFacts } from './plan-facts';
+
+/**
+ * What each role may do, and what the workspace's plan includes, as Settings
+ * › Team › Roles & access, Settings › Account › Your access and "What Chat
+ * can do" show it (CHAT-20 §4a, §4b, §7a, §8). Pure: the server action
+ * (lib/actions/chat-access.ts) reads the facts, the pages draw them.
+ *
+ * Agency partners use every brand for now and act as Analysts (P0 decision
+ * 7): sharing chosen brands with them is Team's, in Wave 2.
+ */
+
+export const ROLE_ORDER: readonly TeamRole[] = ['admin', 'manager', 'analyst', 'agency_partner'];
+
+/** The class badge a row wears: CHAT-20 §3's classes, and NEVER for what isn't a Chat tool. */
+export type AccessClass = ToolClass | 'never';
+
+/**
+ * A role's cell in "What each role can do": `yes`; `approves` / `request`
+ * for workspace memory and shared skills (an Admin approves what a Manager
+ * requests); `after_click` for EXECUTE; `no`; `not_tool` for what Chat
+ * never does.
+ */
+export type RoleCell = 'yes' | 'approves' | 'request' | 'after_click' | 'no' | 'not_tool';
+
+export interface RoleMatrixRow {
+ /** `chatAccess.matrix.rows.{key}` names it and its scope. */
+ key: string;
+ class: AccessClass;
+ cells: Record<TeamRole, RoleCell>;
+}
+
+export interface RoleMatrixGroup {
+ /** `chatAccess.matrix.groups.{key}`. */
+ key: 'everyone' | 'workspace' | 'admin' | 'never';
+ rows: RoleMatrixRow[];
+}
+
+const every = (cell: RoleCell): Record<TeamRole, RoleCell> => ({
+ admin: cell,
+ manager: cell,
+ analyst: cell,
+ agency_partner: cell,
+});
+const adminsAndManagers: Record<TeamRole, RoleCell> = {
+ admin: 'yes',
+ manager: 'yes',
+ analyst: 'no',
+ agency_partner: 'no',
+};
+const adminsOnly: Record<TeamRole, RoleCell> = {
+ admin: 'yes',
+ manager: 'no',
+ analyst: 'no',
+ agency_partner: 'no',
+};
+
+/**
+ * CHAT-20 §4's role matrix, as the Roles & access page groups it (mockup
+ * #g-roles). The live Team roles; RLS lets Admins and Managers write and
+ * the others read, and Chat follows the same split.
+ */
+export const ROLE_MATRIX: readonly RoleMatrixGroup[] = [
+ {
+ key: 'everyone',
+ rows: [
+ { key: 'readApp', class: 'read', cells: every('yes') },
+ { key: 'askChat', class: 'read', cells: every('yes') },
+ { key: 'personal', class: 'write', cells: every('yes') },
+ ],
+ },
+ {
+ key: 'workspace',
+ rows: [
+ { key: 'actions', class: 'write', cells: adminsAndManagers },
+ { key: 'drafts', class: 'write', cells: adminsAndManagers },
+ { key: 'agents', class: 'write', cells: adminsAndManagers },
+ {
+ key: 'shared',
+ class: 'write',
+ cells: { admin: 'approves', manager: 'request', analyst: 'no', agency_partner: 'no' },
+ },
+ {
+ key: 'execute',
+ class: 'execute',
+ cells: {
+ admin: 'after_click',
+ manager: 'after_click',
+ analyst: 'no',
+ agency_partner: 'no',
+ },
+ },
+ ],
+ },
+ {
+ key: 'admin',
+ rows: [
+ { key: 'billing', class: 'write', cells: adminsOnly },
+ { key: 'team', class: 'write', cells: adminsOnly },
+ { key: 'policy', class: 'write', cells: adminsOnly },
+ { key: 'keys', class: 'write', cells: adminsOnly },
+ ],
+ },
+ { key: 'never', rows: [{ key: 'never', class: 'never', cells: every('not_tool') }] },
+];
+
+/** Whether a role may change workspace data: Admins and Managers (RLS, CHAT-20 §4). */
+export const canWrite = (role: TeamRole) => role === 'admin' || role === 'manager';
+
+/**
+ * A row of the Your access card (mockup #g-my-access): what the person may
+ * do through Chat. `ask_admin` where their role can't (Ask your Admin, B2);
+ * `after_click_except` when an Admin switched some EXECUTE groups off for
+ * Managers.
+ */
+export interface YourAccessRow {
+ /** `chatAccess.yourAccess.rows.{key}`. */
+ key: 'read' | 'personal' | 'workspace' | 'agents' | 'execute' | 'settings';
+ class: AccessClass;
+ value: 'yes' | 'yes_card' | 'after_click' | 'after_click_except' | 'execute_off' | 'ask_admin';
+ /** For `after_click_except`: the groups switched off. */
+ off?: ExecuteGroup[];
+}
+
+/** The Your access rows for a role, with the Manager EXECUTE switches an Admin set. */
+export function yourAccessRows(
+ role: TeamRole,
+ managerExecuteOff: readonly ExecuteGroup[],
+): YourAccessRow[] {
+ const writes = canWrite(role);
+ const execute = (): YourAccessRow => {
+ if (!writes) return { key: 'execute', class: 'execute', value: 'ask_admin' };
+ if (role === 'admin' || managerExecuteOff.length === 0) {
+ return { key: 'execute', class: 'execute', value: 'after_click' };
+ }
+ if (managerExecuteOff.length >= 4) {
+ return { key: 'execute', class: 'execute', value: 'execute_off' };
+ }
+ return {
+ key: 'execute',
+ class: 'execute',
+ value: 'after_click_except',
+ off: [...managerExecuteOff],
+ };
+ };
+ return [
+ { key: 'read', class: 'read', value: 'yes' },
+ { key: 'personal', class: 'write', value: 'yes' },
+ { key: 'workspace', class: 'write', value: writes ? 'yes_card' : 'ask_admin' },
+ { key: 'agents', class: 'write', value: writes ? 'yes' : 'ask_admin' },
+ execute(),
+ { key: 'settings', class: 'write', value: role === 'admin' ? 'yes' : 'ask_admin' },
+ ];
+}
+
+/**
+ * The plan card's features (CHAT-20 §7a item 2): included, or locked with
+ * the plan that has it. `platforms` carries how many AI platforms are
+ * tracked; `mcp` is `read` on Starter, `read_write` from Growth.
+ */
+export type PlanChip =
+ | { key: 'platforms'; count: number; locked: null }
+ | { key: 'fullAuto' | 'ownKeys' | 'openPr' | 'claude'; locked: PlanId | null }
+ | { key: 'mcp'; access: 'read' | 'read_write' | null; locked: PlanId | null };
+
+/** A line of "With {next plan} you'd also get" (§7a item 5), with its numbers. */
+export type PlanBenefit =
+ | { key: 'morePlatforms'; count: number }
+ | { key: 'fullAuto' | 'mcpWrite' | 'claude' | 'contract' }
+ | { key: 'aiLimit'; times: number }
+ | { key: 'keepEverything' | 'mcp' | 'monthlyLimit' | 'packs' };
+
+/**
+ * The "Your plan" card (CHAT-20 §7a), without a dollar of AI budget: the
+ * plan's price is shown, AI usage only as a percentage (DECISIONS R). Null
+ * off the cloud, where there is no plan.
+ */
+export interface PlanCard {
+ planId: PlanId;
+ planName: string;
+ /** Its monthly price; null when set per contract (Enterprise). */
+ priceMonthly: number | null;
+ isTrial: boolean;
+ chips: PlanChip[];
+ /** Null on Enterprise: no upsell. */
+ next: {
+ planId: PlanId;
+ planName: string;
+ priceMonthly: number | null;
+ priceDiff: number | null;
+ afterTrial: boolean;
+ benefits: PlanBenefit[];
+ } | null;
+}
+
+const rank = (id: PlanId) => PLAN_ORDER.indexOf(id);
+
+/** Whether a plan's limits track Claude's answers: no model list, or one with models. */
+const tracksClaude = (limits: PlanLimits) =>
+ limits.allowedModels === undefined || limits.allowedModels.length > 0;
+
+/** What the plan after `from` adds, in the card's benefit lines. */
+function benefitsOf(from: PlanId, to: PlanId, afterTrial: boolean): PlanBenefit[] {
+ if (afterTrial) {
+ return [{ key: 'keepEverything' }, { key: 'mcp' }, { key: 'monthlyLimit' }, { key: 'packs' }];
+ }
+ const own = PLANS[from].limits;
+ const next = PLANS[to].limits;
+ const out: PlanBenefit[] = [];
+ if (next.maxPlatforms > own.maxPlatforms) {
+ out.push({ key: 'morePlatforms', count: next.maxPlatforms - own.maxPlatforms });
+ }
+ if (rank(from) < rank('growth') && rank(to) >= rank('growth')) {
+ out.push({ key: 'fullAuto' }, { key: 'mcpWrite' });
+ }
+ // Claude's answers are tracked on Enterprise, set per contract (plan_overrides).
+ if (!tracksClaude(own) && (to === 'enterprise' || tracksClaude(next))) {
+ out.push({ key: 'claude' });
+ }
+ if (to === 'enterprise') {
+ out.push({ key: 'contract' });
+ } else if (
+ own.improveMonthlyBudgetUsd > 0 &&
+ next.improveMonthlyBudgetUsd > own.improveMonthlyBudgetUsd
+ ) {
+ out.push({
+ key: 'aiLimit',
+ times: Math.round(next.improveMonthlyBudgetUsd / own.improveMonthlyBudgetUsd),
+ });
+ }
+ return out.slice(0, 4);
+}
+
+/** The plan card for the workspace's plan facts; null off the cloud. */
+export function planCardOf(facts: PlanFacts): PlanCard | null {
+ if (facts.selfHosted) return null;
+ // The entitled limits: an Enterprise contract's overrides included.
+ const limits = facts.limits;
+ const growthLock = planGateLock(facts, { minPlan: 'growth' });
+ const mcpAccess: 'read' | 'read_write' | null = facts.isTrial
+ ? null
+ : growthLock
+ ? 'read'
+ : 'read_write';
+ const all: PlanChip[] = [
+ { key: 'platforms', count: limits.maxPlatforms, locked: null },
+ { key: 'fullAuto', locked: facts.fullAuto ? null : 'growth' },
+ { key: 'ownKeys', locked: growthLock },
+ {
+ key: 'mcp',
+ access: mcpAccess,
+ locked: mcpAccess === 'read_write' ? null : facts.isTrial ? 'starter' : 'growth',
+ },
+ { key: 'openPr', locked: growthLock },
+ { key: 'claude', locked: tracksClaude(limits) ? null : 'enterprise' },
+ ];
+ // Enterprise shows what it includes and no lock lines (§7a).
+ const chips = facts.planId === 'enterprise' ? all.filter((chip) => !chip.locked) : all;
+ const next = facts.nextPlan;
+ return {
+ planId: facts.planId,
+ planName: facts.planName,
+ priceMonthly: PLANS[facts.planId].pricing?.monthly ?? null,
+ isTrial: facts.isTrial,
+ chips,
+ next: next
+ ? {
+ planId: next.id,
+ planName: next.name,
+ priceMonthly: next.priceMonthly,
+ priceDiff: next.priceDiff,
+ afterTrial: next.afterTrial,
+ benefits: benefitsOf(facts.planId, next.id, next.afterTrial),
+ }
+ : null,
+ };
+}
+
+/** How a WRITE or EXECUTE row is approved, as "What Chat can do" marks it. */
+export type ApprovalMark = 'none' | 'card' | 'auto' | 'click';
+
+export function approvalMark(
+ entry: Pick<ToolCatalogEntry, 'class' | 'defaultPolicy' | 'flags'>,
+): ApprovalMark {
+ if (entry.class === 'read') return 'none';
+ if (entry.class === 'execute') return 'click';
+ const policy: ToolPolicy = entry.defaultPolicy;
+ if (entry.flags.alwaysCard || policy === 'ask') return 'card';
+ if (policy === 'always') return 'none';
+ return 'auto';
+}
+
+/** The roles that may call a row: its minimum role and up, less its excluded roles. */
+export function rolesFor(entry: Pick<ToolCatalogEntry, 'minRole' | 'excludeRoles'>): TeamRole[] {
+ const lowest = ROLE_ORDER.indexOf(entry.minRole);
+ // `analyst` opens a row to every role, Agency partners included (CHAT-20 §20).
+ const allowed = entry.minRole === 'analyst' ? ROLE_ORDER : ROLE_ORDER.slice(0, lowest + 1);
+ return allowed.filter((role) => !entry.excludeRoles.includes(role));
+}
+
+/** An area of "What Chat can do": its rows by class, in registry order. */
+export interface CapabilityArea {
+ area: ToolArea;
+ read: ToolCatalogEntry[];
+ write: ToolCatalogEntry[];
+ execute: ToolCatalogEntry[];
+ /** Who may make its changes: the roles every WRITE and EXECUTE row allows; empty when it has none. */
+ writers: TeamRole[];
+}
+
+/** The catalog grouped by area, in the order the registry first names each. */
+export function capabilityAreas(catalog: readonly ToolCatalogEntry[]): CapabilityArea[] {
+ const areas = new Map<ToolArea, CapabilityArea>();
+ for (const entry of catalog) {
+ let area = areas.get(entry.area);
+ if (!area) {
+ area = { area: entry.area, read: [], write: [], execute: [], writers: [] };
+ areas.set(entry.area, area);
+ }
+ area[entry.class].push(entry);
+ }
+ for (const area of areas.values()) {
+ const changes = [...area.write, ...area.execute];
+ area.writers = changes.length
+ ? ROLE_ORDER.filter((role) => changes.every((entry) => rolesFor(entry).includes(role)))
+ : [];
+ }
+ return [...areas.values()];
+}
diff --git a/web/src/lib/member-emails.ts b/web/src/lib/member-emails.ts
index 308ead9ac..ff46a1e79 100644
--- a/web/src/lib/member-emails.ts
+++ b/web/src/lib/member-emails.ts
@@ -10,11 +10,30 @@ import { supabaseAdmin } from '@/lib/supabase/admin';
*/
export async function readMemberEmails(userIds: string[]): Promise<Map<string, string>> {
const emails = new Map<string, string>();
+ for (const [id, auth] of await readMemberAuth(userIds)) {
+ if (auth.email) emails.set(id, auth.email);
+ }
+ return emails;
+}
+
+/**
+ * Members' e-mails and when they last signed in, from the same admin call:
+ * what Settings › Team › Roles & access lists (CHAT-20 §4a). Server only, as
+ * above.
+ */
+export async function readMemberAuth(
+ userIds: string[],
+): Promise<Map<string, { email: string | null; lastSignInAt: string | null }>> {
+ const out = new Map<string, { email: string | null; lastSignInAt: string | null }>();
await Promise.all(
[...new Set(userIds)].map(async (id) => {
const { data } = await supabaseAdmin.auth.admin.getUserById(id);
- if (data?.user?.email) emails.set(id, data.user.email);
+ if (!data?.user) return;
+ out.set(id, {
+ email: data.user.email ?? null,
+ lastSignInAt: data.user.last_sign_in_at ?? null,
+ });
}),
);
- return emails;
+ return out;
}