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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(chat): explain what Chat can't do and let people ask their Admins (#1781)
Cihan02f0cc7839f9
diff --git a/supabase/migrations/00403_chat_access_requests.sql b/supabase/migrations/00403_chat_access_requests.sqlnew file mode 100644index 000000000..0a982bd12--- /dev/null+++ b/supabase/migrations/00403_chat_access_requests.sql@@ -0,0 +1,94 @@+-- ============================================================================+-- 00403: Chat's access requests — "Ask your Admin"+-- ============================================================================+-- When a person's role, the plan or the tool policy keeps Chat from doing+-- what they asked, Chat's out-of-permission answer offers Ask your Admin+-- (CHAT-20 §4c, registry row 80a `access.request`): only after their click,+-- a request goes to the workspace's Admins, who see it in Settings › Team ›+-- Roles & access › Requests with a count. Behind CHAT_AGENTIC: nothing writes+-- here while the flag is off.+--+-- * asked: what was asked, in the answer's words ("Add competitors ·+-- Peec AI"); asked_hash its fingerprint, so a person asks for the same+-- change at most once a day (requested_on, UTC).+-- * tool_key: the registry row's label key, the name the browser knows a+-- tool by (a tool's name never reaches a member, CHAT-03 item 22); null+-- for a request about the plan or the role as a whole.+-- * rule_kind / rule_detail: the rule that refused it (web+-- lib/chat/denial.ts: role, plan, policy, workspace, brand, demo) and its+-- words.+-- * drafted_change: the change Chat had drafted, for an Admin to approve as+-- their own card once Chat runs (C3); null when there was none.+-- * status: pending until an Admin approves or dismisses it (the first one+-- to act decides it for every Admin), or the person withdraws it.+--+-- The server writes every row (service role), after its own checks: a person+-- has at most 10 pending requests and sends at most 20 a day. The person+-- reads their own; the workspace's Admins read all of its requests.++create table if not exists public.chat_access_requests (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ requester_id uuid not null references auth.users(id) on delete cascade,+ brand_id uuid references public.brands(id) on delete set null,+ conversation_id uuid references public.chat_conversations(id) on delete set null,+ asked text not null check (char_length(asked) between 1 and 500),+ asked_hash text not null check (asked_hash ~ '^[0-9a-f]{64}$'),+ tool_key text check (tool_key is null or tool_key ~ '^[a-z][A-Za-z0-9]{1,63}$'),+ rule_kind text not null+ check (rule_kind in ('role', 'plan', 'policy', 'workspace', 'brand', 'demo')),+ rule_detail text not null default '' check (char_length(rule_detail) <= 500),+ -- The server takes at most 8,000 characters of JSON; this is its backstop.+ drafted_change jsonb+ check (+ drafted_change is null+ or (jsonb_typeof(drafted_change) = 'object' and octet_length(drafted_change::text) <= 32768)+ ),+ status text not null default 'pending'+ check (status in ('pending', 'approved', 'rejected', 'withdrawn')),+ decided_by uuid references auth.users(id) on delete set null,+ decided_at timestamptz,+ requested_on date not null default ((now() at time zone 'utc')::date),+ created_at timestamptz not null default now(),+ check ((status = 'pending') = (decided_at is null))+);++-- One request per person per asked change per day.+create unique index if not exists chat_access_requests_once_a_day_uidx+ on public.chat_access_requests (requester_id, asked_hash, requested_on);+-- Roles & access › Requests: the workspace's pending ones first, newest first.+create index if not exists chat_access_requests_org_idx+ on public.chat_access_requests (organization_id, status, created_at desc);+-- A person's own requests, and how many are pending.+create index if not exists chat_access_requests_requester_idx+ on public.chat_access_requests (requester_id, status, created_at desc);++comment on table public.chat_access_requests is+ 'Chat (00403): "Ask your Admin" requests (CHAT-20 §4c). Server writes; the requester reads their own, the workspace''s Admins read all of its.';+comment on column public.chat_access_requests.tool_key is+ 'The registry row''s label key (never a tool''s name); null for a request about the plan or the role.';+comment on column public.chat_access_requests.asked_hash is+ 'sha256 of the asked change (tool key and words): one request per person per change per day.';++-- ─── Who reads and writes ───────────────────────────────────────────────────++alter table public.chat_access_requests enable row level security;+revoke all on table public.chat_access_requests from anon, authenticated;+grant select on table public.chat_access_requests to authenticated;+grant all on table public.chat_access_requests to service_role;++-- The requester reads their own, in the workspace they belong to now; its+-- Admins read all of the workspace's.+drop policy if exists "chat_access_requests: own or admin select" on public.chat_access_requests;+create policy "chat_access_requests: own or admin select"+ on public.chat_access_requests+ for select+ using (+ organization_id in (+ select p.organization_id from public.profiles p+ where p.id = auth.uid()+ and (p.role = 'admin' or chat_access_requests.requester_id = auth.uid())+ )+ );++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex e0cebc8d5..18361bb7b 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -44385,6 +44385,104 @@ create policy "chat_activity_log: own or admin select"notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00403_chat_access_requests.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00403: Chat's access requests — "Ask your Admin"+-- ============================================================================+-- When a person's role, the plan or the tool policy keeps Chat from doing+-- what they asked, Chat's out-of-permission answer offers Ask your Admin+-- (CHAT-20 §4c, registry row 80a `access.request`): only after their click,+-- a request goes to the workspace's Admins, who see it in Settings › Team ›+-- Roles & access › Requests with a count. Behind CHAT_AGENTIC: nothing writes+-- here while the flag is off.+--+-- * asked: what was asked, in the answer's words ("Add competitors ·+-- Peec AI"); asked_hash its fingerprint, so a person asks for the same+-- change at most once a day (requested_on, UTC).+-- * tool_key: the registry row's label key, the name the browser knows a+-- tool by (a tool's name never reaches a member, CHAT-03 item 22); null+-- for a request about the plan or the role as a whole.+-- * rule_kind / rule_detail: the rule that refused it (web+-- lib/chat/denial.ts: role, plan, policy, workspace, brand, demo) and its+-- words.+-- * drafted_change: the change Chat had drafted, for an Admin to approve as+-- their own card once Chat runs (C3); null when there was none.+-- * status: pending until an Admin approves or dismisses it (the first one+-- to act decides it for every Admin), or the person withdraws it.+--+-- The server writes every row (service role), after its own checks: a person+-- has at most 10 pending requests and sends at most 20 a day. The person+-- reads their own; the workspace's Admins read all of its requests.++create table if not exists public.chat_access_requests (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ requester_id uuid not null references auth.users(id) on delete cascade,+ brand_id uuid references public.brands(id) on delete set null,+ conversation_id uuid references public.chat_conversations(id) on delete set null,+ asked text not null check (char_length(asked) between 1 and 500),+ asked_hash text not null check (asked_hash ~ '^[0-9a-f]{64}$'),+ tool_key text check (tool_key is null or tool_key ~ '^[a-z][A-Za-z0-9]{1,63}$'),+ rule_kind text not null+ check (rule_kind in ('role', 'plan', 'policy', 'workspace', 'brand', 'demo')),+ rule_detail text not null default '' check (char_length(rule_detail) <= 500),+ -- The server takes at most 8,000 characters of JSON; this is its backstop.+ drafted_change jsonb+ check (+ drafted_change is null+ or (jsonb_typeof(drafted_change) = 'object' and octet_length(drafted_change::text) <= 32768)+ ),+ status text not null default 'pending'+ check (status in ('pending', 'approved', 'rejected', 'withdrawn')),+ decided_by uuid references auth.users(id) on delete set null,+ decided_at timestamptz,+ requested_on date not null default ((now() at time zone 'utc')::date),+ created_at timestamptz not null default now(),+ check ((status = 'pending') = (decided_at is null))+);++-- One request per person per asked change per day.+create unique index if not exists chat_access_requests_once_a_day_uidx+ on public.chat_access_requests (requester_id, asked_hash, requested_on);+-- Roles & access › Requests: the workspace's pending ones first, newest first.+create index if not exists chat_access_requests_org_idx+ on public.chat_access_requests (organization_id, status, created_at desc);+-- A person's own requests, and how many are pending.+create index if not exists chat_access_requests_requester_idx+ on public.chat_access_requests (requester_id, status, created_at desc);++comment on table public.chat_access_requests is+ 'Chat (00403): "Ask your Admin" requests (CHAT-20 §4c). Server writes; the requester reads their own, the workspace''s Admins read all of its.';+comment on column public.chat_access_requests.tool_key is+ 'The registry row''s label key (never a tool''s name); null for a request about the plan or the role.';+comment on column public.chat_access_requests.asked_hash is+ 'sha256 of the asked change (tool key and words): one request per person per change per day.';++-- ─── Who reads and writes ───────────────────────────────────────────────────++alter table public.chat_access_requests enable row level security;+revoke all on table public.chat_access_requests from anon, authenticated;+grant select on table public.chat_access_requests to authenticated;+grant all on table public.chat_access_requests to service_role;++-- The requester reads their own, in the workspace they belong to now; its+-- Admins read all of the workspace's.+drop policy if exists "chat_access_requests: own or admin select" on public.chat_access_requests;+create policy "chat_access_requests: own or admin select"+ on public.chat_access_requests+ for select+ using (+ organization_id in (+ select p.organization_id from public.profiles p+ where p.id = auth.uid()+ and (p.role = 'admin' or chat_access_requests.requester_id = auth.uid())+ )+ );++notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00404_chat_model_prices.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 1d9116b0a..21ee76188 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3101,7 +3101,8 @@"dismissSuggestion": {"name": "Dismiss prompt suggestions","step": "Dismissed prompt suggestion"- }+ },+ "askAdmin": { "name": "Ask your Admin", "step": "Sent to your Admins" }},"agentic": {"avatar": {@@ -3387,6 +3388,48 @@}}},+ "askAdmin": {+ "button": "Ask your Admin",+ "title": "Ask your Admin",+ "lead": "Your Admins get this in Settings › Team › Roles & access. They can change your role, or make the change themselves.",+ "label": "What do you need?",+ "send": "Send",+ "cancel": "Cancel",+ "sent": "Sent to your Admins",+ "tooMany": "You have {count} requests waiting. Withdraw one, or wait for your Admins.",+ "dailyLimit": "You've sent {count} requests today. Try again tomorrow.",+ "alreadyToday": "You already asked for this today.",+ "failed": "Couldn't send it. Try again.",+ "defaults": {+ "role": "Change my role so I can make changes in this workspace",+ "plan": "Upgrade to {plan}"+ },+ "roleDetail": "Your role is {role}.",+ "planDetail": "Needs {plan} · you're on {current}"+ },+ "requests": {+ "title": "Requests",+ "yours": "Your requests",+ "lead": "Ask your Admin requests from Chat and Settings. The first Admin who acts decides it.",+ "leadYours": "What you asked your Admins for, and what they decided.",+ "empty": "No requests.",+ "emptyYours": "You haven't asked for anything.",+ "from": "From {name}",+ "approve": "Approve",+ "dismiss": "Dismiss",+ "withdraw": "Withdraw",+ "approved": "Approved. Change their role in Members, or make the change yourself.",+ "dismissed": "Dismissed",+ "withdrawn": "Withdrawn",+ "alreadyDecided": "Another Admin already decided it.",+ "failed": "Couldn't update it. Try again.",+ "status": {+ "pending": "Waiting",+ "approved": "Approved",+ "rejected": "Dismissed",+ "withdrawn": "Withdrawn"+ }+ },"yourAccess": {"title": "Your access","brands": "Brands",@@ -3465,6 +3508,8 @@"opportunityStatusUndo": "Put the opportunity “{title}” back as it was","dismissSuggestion": "Dismissed the prompt suggestion “{text}”","dismissSuggestionUndo": "Brought back the prompt suggestion “{text}”",+ "askAdmin": "Asked your Admins: “{asked}”",+ "askAdminUndo": "Withdrew the request “{asked}”","accessDenied": "Not allowed: {tool}"},"undo": {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.tsxindex 148e03c52..f80ccc2f2 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@@ -25,6 +25,10 @@ vi.mock('@/components/providers/chat-agentic-provider', () => ({useChatAgentic: () => chatAgentic,}));vi.mock('@/lib/actions/organization', () => ({ updateAccountName: vi.fn() }));+let pendingRequests = 0;+vi.mock('@/lib/actions/chat-access-requests', () => ({+ countPendingAccessRequests: async () => pendingRequests,+}));vi.mock('@/components/ai-usage/ai-usage-meter', () => ({HeaderWithAiUsage: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,}));@@ -95,4 +99,12 @@ describe('SettingsView', () => {chatAgentic = false;expect(await sections()).not.toContain('Roles & access');});++ it("counts an Admin's waiting access requests on Roles & access", async () => {+ chatAgentic = true;+ pendingRequests = 2;+ expect(await sections()).toContain('Roles & access2');+ chatAgentic = false;+ pendingRequests = 0;+ });});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsxindex 166806b03..1308db8b0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx@@ -26,6 +26,7 @@ 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 { countPendingAccessRequests } from '@/lib/actions/chat-access-requests';import { Badge } from '@/components/ui/badge';import { updateAccountName } from '@/lib/actions/organization';import { Loader2 } from 'lucide-react';@@ -50,6 +51,21 @@ export function SettingsView({ section }: { section: SettingsSection }) {const { isCloud } = usePlanContext();const canManageMenus = useCanManageMenus();const chatAgentic = useChatAgentic();+ // Ask your Admin requests waiting for an Admin: the count on Roles & access.+ const [pendingRequests, setPendingRequests] = useState(0);+ const [requestsRead, setRequestsRead] = useState(0);+ useEffect(() => {+ if (!chatAgentic) return;+ let live = true;+ countPendingAccessRequests()+ .then((count) => {+ if (live) setPendingRequests(count);+ })+ .catch(() => {});+ return () => {+ live = false;+ };+ }, [chatAgentic, requestsRead]);// Roles & access is Chat's: with Chat off, its address opens Account.const [active, setActive] = useState<SettingsSection>(section === 'roles-access' && !chatAgentic ? 'account' : section,@@ -141,6 +157,11 @@ export function SettingsView({ section }: { section: SettingsSection }) {)}>{item.label}+ {item.id === 'roles-access' && pendingRequests > 0 && (+ <Badge className="ml-2 px-1.5 py-0 text-[10px] tabular-nums">+ {pendingRequests}+ </Badge>+ )}{item.id === 'menu-access' && (<Badge variant="secondary" className="ml-2 px-1.5 py-0 text-[10px]">{t('menuAccess.new')}@@ -212,7 +233,9 @@ export function SettingsView({ section }: { section: SettingsSection }) {{/* Team */}{active === 'team' && <TeamSection />}- {active === 'roles-access' && chatAgentic && <RolesAccessSection />}+ {active === 'roles-access' && chatAgentic && (+ <RolesAccessSection onRequestsChanged={() => setRequestsRead((n) => n + 1)} />+ )}{active === 'menu-access' && <MenuAccessSection />}diff --git a/web/src/components/chat-access/ask-admin-button.tsx b/web/src/components/chat-access/ask-admin-button.tsxnew file mode 100644index 000000000..f63bf096b--- /dev/null+++ b/web/src/components/chat-access/ask-admin-button.tsx@@ -0,0 +1,119 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { Loader2 } from 'lucide-react';+import { toast } from 'sonner';+import { Button } from '@/components/ui/button';+import { Textarea } from '@/components/ui/textarea';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { requestAccess } from '@/lib/actions/chat-access-requests';+import {+ MAX_PENDING_REQUESTS,+ MAX_REQUESTS_PER_DAY,+ type AccessRequest,+} from '@/lib/chat/access-requests';++/**+ * Ask your Admin (CHAT-20 §4c): the person says what they need, starting+ * from what was asked, and their click sends it to the workspace's Admins+ * with the rule that stopped it. Admins don't see it: they have no one to+ * ask.+ */+export function AskAdminButton({+ asked,+ ruleKind,+ ruleDetail = '',+ toolKey = null,+ size = 'sm',+ variant = 'outline',+ onSent,+}: {+ asked: string;+ ruleKind: AccessRequest['ruleKind'];+ ruleDetail?: string;+ toolKey?: string | null;+ size?: 'sm' | 'default';+ variant?: 'outline' | 'default';+ onSent?: () => void;+}) {+ const t = useTranslations('chatAccess.askAdmin');+ const [open, setOpen] = useState(false);+ const [text, setText] = useState(asked);+ const [sending, setSending] = useState(false);++ async function send() {+ setSending(true);+ try {+ const result = await requestAccess({ asked: text, ruleKind, ruleDetail, toolKey });+ if (result.ok) {+ toast.success(t('sent'));+ setOpen(false);+ onSent?.();+ } else if (result.reason === 'too_many') {+ toast.error(t('tooMany', { count: MAX_PENDING_REQUESTS }));+ } else if (result.reason === 'daily_limit') {+ toast.error(t('dailyLimit', { count: MAX_REQUESTS_PER_DAY }));+ } else if (result.reason === 'already_today') {+ toast.info(t('alreadyToday'));+ setOpen(false);+ } else {+ toast.error(t('failed'));+ }+ } catch {+ toast.error(t('failed'));+ } finally {+ setSending(false);+ }+ }++ return (+ <>+ <Button+ type="button"+ size={size}+ variant={variant}+ onClick={() => {+ setText(asked);+ setOpen(true);+ }}+ >+ {t('button')}+ </Button>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ <DialogDescription>{t('lead')}</DialogDescription>+ </DialogHeader>+ <label className="space-y-1.5 text-sm">+ <span className="font-medium">{t('label')}</span>+ <Textarea+ value={text}+ onChange={(e) => setText(e.target.value)}+ maxLength={500}+ rows={3}+ />+ </label>+ {ruleDetail && <p className="text-xs text-muted-foreground">{ruleDetail}</p>}+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => setOpen(false)}>+ {t('cancel')}+ </Button>+ <Button type="button" onClick={() => void send()} disabled={sending || !text.trim()}>+ {sending && <Loader2 className="h-4 w-4 animate-spin" />}+ {t('send')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/web/src/components/chat-access/chat-access.test.tsx b/web/src/components/chat-access/chat-access.test.tsxindex 5d0c79595..bff64d85e 100644--- a/web/src/components/chat-access/chat-access.test.tsx+++ b/web/src/components/chat-access/chat-access.test.tsx@@ -16,6 +16,18 @@ vi.mock('@/lib/actions/chat-access', () => ({listRoleMembers: () => listRoleMembers(),}));vi.mock('@/lib/actions/team', () => ({ updateMemberRole: vi.fn() }));+const requestAccess = vi.fn();+const listAccessRequests = vi.fn();+const decideAccessRequest = vi.fn();+const withdrawAccessRequest = vi.fn();+vi.mock('@/lib/actions/chat-access-requests', () => ({+ requestAccess: (...args: unknown[]) => requestAccess(...args),+ listAccessRequests: () => listAccessRequests(),+ decideAccessRequest: (...args: unknown[]) => decideAccessRequest(...args),+ withdrawAccessRequest: (...args: unknown[]) => withdrawAccessRequest(...args),+}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }));+vi.mock('sonner', () => ({ toast }));vi.mock('@/components/providers/upgrade-gate', () => ({useUpgradeGate: () => ({ guard: (fn: unknown) => fn }),}));@@ -47,6 +59,16 @@ beforeEach(() => {root = createRoot(container);getChatAccess.mockReset();listRoleMembers.mockReset();+ for (const fn of [+ requestAccess,+ decideAccessRequest,+ withdrawAccessRequest,+ ...Object.values(toast),+ ]) {+ fn.mockReset();+ }+ listAccessRequests.mockReset();+ listAccessRequests.mockResolvedValue({ isAdmin: false, requests: [] });});afterEach(() => {act(() => root.unmount());@@ -278,3 +300,112 @@ describe('CapabilitiesView', () => {expect(text()).not.toContain('Read tracked prompts');});});++const button = (label: string, root: ParentNode = container) =>+ [...root.querySelectorAll('button')].find((b) => b.textContent === label);++describe('Ask your Admin', () => {+ it('sends what the person needs, with the rule, after their click', async () => {+ getChatAccess.mockResolvedValue(access());+ listRoleMembers.mockResolvedValue([]);+ requestAccess.mockResolvedValue({ ok: true, id: 'r1' });+ await render(<RolesAccessSection />);+ expect(requestAccess).not.toHaveBeenCalled();+ // The plan card has its own (for the next plan); this is the read-only bar's.+ const bar = [...container.querySelectorAll('div')].find((d) =>+ d.textContent?.startsWith("You're a Manager"),+ )!;+ await act(async () => button('Ask your Admin', bar)!.click());+ const box = document.body.querySelector('textarea')!;+ expect(box.value).toBe('Change my role so I can make changes in this workspace');+ await act(async () => button('Send', document.body)!.click());+ expect(requestAccess).toHaveBeenCalledWith({+ asked: 'Change my role so I can make changes in this workspace',+ ruleKind: 'role',+ ruleDetail: 'Your role is Manager.',+ toolKey: null,+ });+ expect(toast.success).toHaveBeenCalledWith('Sent to your Admins');+ });++ it('says when ten requests already wait, or this one was asked today', async () => {+ await render(<YourAccessCard access={access()} />);+ requestAccess.mockResolvedValue({ ok: false, reason: 'too_many' });+ await act(async () => button('Ask your Admin')!.click());+ await act(async () => button('Send', document.body)!.click());+ expect(toast.error).toHaveBeenCalledWith(+ 'You have 10 requests waiting. Withdraw one, or wait for your Admins.',+ );+ requestAccess.mockResolvedValue({ ok: false, reason: 'already_today' });+ await act(async () => button('Send', document.body)!.click());+ expect(toast.info).toHaveBeenCalledWith('You already asked for this today.');+ });++ it("puts Ask your Admin in Upgrade's place on the plan card, for the next plan", async () => {+ await render(<YourPlanCard plan={starter} isAdmin={false} />);+ await act(async () => button('Ask your Admin')!.click());+ expect(document.body.querySelector('textarea')!.value).toBe('Upgrade to Growth');+ expect(document.body.textContent).toContain("Needs Growth · you're on Starter");+ });+});++describe('Requests', () => {+ const request = (over = {}) => ({+ id: 'r1',+ requester: 'Taylor Brooks',+ isYours: false,+ asked: 'Add competitors · Peec AI',+ toolKey: 'addCompetitors',+ ruleKind: 'role',+ ruleDetail: 'Your role is Analyst.',+ status: 'pending',+ createdAt: '2026-10-29T11:00:00Z',+ decidedAt: null,+ ...over,+ });++ it("lets an Admin approve or dismiss a workspace's waiting request, with a count", async () => {+ getChatAccess.mockResolvedValue(access({ role: 'admin' }));+ listRoleMembers.mockResolvedValue([]);+ listAccessRequests.mockResolvedValue({+ isAdmin: true,+ requests: [request(), request({ id: 'r2', status: 'approved' })],+ });+ decideAccessRequest.mockResolvedValue(true);+ const changed = vi.fn();+ await render(<RolesAccessSection onRequestsChanged={changed} />);+ const section = container.querySelector('[aria-labelledby="chat-access-requests"]')!;+ expect(section.textContent).toContain('Requests1');+ expect(section.textContent).toContain(+ 'From Taylor Brooks · Your role is Analyst. · 1 hour ago',+ );+ expect(section.textContent).toContain('Approved');+ expect([...section.querySelectorAll('button')].map((b) => b.textContent)).toEqual([+ 'Approve',+ 'Dismiss',+ ]);+ await act(async () => button('Approve', section)!.click());+ expect(decideAccessRequest).toHaveBeenCalledWith('r1', 'approved');+ expect(changed).toHaveBeenCalled();+ decideAccessRequest.mockResolvedValue(false);+ await act(async () => button('Dismiss', section)!.click());+ expect(toast.info).toHaveBeenCalledWith('Another Admin already decided it.');+ });++ it('lets anyone else withdraw their own waiting request', async () => {+ getChatAccess.mockResolvedValue(access());+ listRoleMembers.mockResolvedValue([]);+ listAccessRequests.mockResolvedValue({+ isAdmin: false,+ requests: [request({ isYours: true })],+ });+ withdrawAccessRequest.mockResolvedValue(true);+ await render(<RolesAccessSection />);+ const section = container.querySelector('[aria-labelledby="chat-access-requests"]')!;+ expect(section.textContent).toContain('Your requests');+ expect(section.textContent).not.toContain('From ');+ await act(async () => button('Withdraw', section)!.click());+ expect(withdrawAccessRequest).toHaveBeenCalledWith('r1');+ expect(toast.success).toHaveBeenCalledWith('Withdrawn');+ });+});diff --git a/web/src/components/chat-access/plan-card.tsx b/web/src/components/chat-access/plan-card.tsxindex ada32efb1..22f5880db 100644--- a/web/src/components/chat-access/plan-card.tsx+++ b/web/src/components/chat-access/plan-card.tsx@@ -9,17 +9,19 @@ 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';+import { AskAdminButton } from './ask-admin-button';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).+ * add. No upsell on Enterprise. Admins get Upgrade; the others Ask your+ * Admin in its place.*/export function YourPlanCard({ plan, isAdmin }: { plan: PlanCard; isAdmin: boolean }) {const t = useTranslations('chatAccess.plan');+ const tAsk = useTranslations('chatAccess.askAdmin');const format = useFormatter();const { usage } = useAiUsage();const money = (value: number) =>@@ -118,10 +120,16 @@ export function YourPlanCard({ plan, isAdmin }: { plan: PlanCard; isAdmin: boole? t('priceDiff', { price: money(next.priceDiff) }): t('customPrice')}</span>- {isAdmin && (+ {isAdmin ? (<Link href={BILLING} className={cn(buttonVariants({ size: 'sm' }), 'shrink-0')}>{next.afterTrial ? t('choosePlan') : t('upgrade')}</Link>+ ) : (+ <AskAdminButton+ asked={tAsk('defaults.plan', { plan: next.planName })}+ ruleKind="plan"+ ruleDetail={tAsk('planDetail', { plan: next.planName, current: plan.planName })}+ />)}</div>)}diff --git a/web/src/components/chat-access/requests-section.tsx b/web/src/components/chat-access/requests-section.tsxnew file mode 100644index 000000000..727557b6e--- /dev/null+++ b/web/src/components/chat-access/requests-section.tsx@@ -0,0 +1,166 @@+'use client';++import { useEffect, useState } from 'react';+import { useFormatter, useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import {+ decideAccessRequest,+ listAccessRequests,+ withdrawAccessRequest,+} from '@/lib/actions/chat-access-requests';+import type { AccessRequest } from '@/lib/chat/access-requests';+import { cn } from '@/lib/utils';++const STATUS_TONE: Record<AccessRequest['status'], string> = {+ pending: 'bg-amber-100 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300',+ approved: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/60 dark:text-emerald-300',+ rejected: 'bg-muted text-muted-foreground',+ withdrawn: 'bg-muted text-muted-foreground',+};++/**+ * Roles & access › Requests (CHAT-20 §4c, P0 decision 12): an Admin sees the+ * workspace's Ask your Admin requests and approves or dismisses them; anyone+ * else sees their own and may withdraw one while it waits. `version` reads+ * them again (a request just sent); `onChanged` tells the page a count moved.+ */+export function RequestsSection({+ version = 0,+ onChanged,+}: {+ version?: number;+ onChanged?: () => void;+}) {+ const t = useTranslations('chatAccess.requests');+ const format = useFormatter();+ const [data, setData] = useState<{ isAdmin: boolean; requests: AccessRequest[] } | null>(null);+ const [reload, setReload] = useState(0);+ const [busy, setBusy] = useState<string | null>(null);++ useEffect(() => {+ let live = true;+ listAccessRequests()+ .then((next) => {+ if (live) setData(next);+ })+ .catch(() => {});+ return () => {+ live = false;+ };+ }, [version, reload]);++ if (!data) return null;+ const pending = data.requests.filter((r) => r.status === 'pending').length;++ async function act(id: string, run: () => Promise<boolean>, done: string) {+ setBusy(id);+ try {+ const changed = await run();+ if (changed) toast.success(done);+ else toast.info(t('alreadyDecided'));+ setReload((n) => n + 1);+ onChanged?.();+ } catch {+ toast.error(t('failed'));+ } finally {+ setBusy(null);+ }+ }++ return (+ <section className="space-y-2" aria-labelledby="chat-access-requests">+ <div className="flex flex-wrap items-center gap-2">+ <h3 id="chat-access-requests" className="text-sm font-semibold">+ {data.isAdmin ? t('title') : t('yours')}+ </h3>+ {pending > 0 && (+ <Badge className="tabular-nums" aria-label={t('status.pending')}>+ {pending}+ </Badge>+ )}+ <span className="text-xs text-muted-foreground">+ {data.isAdmin ? t('lead') : t('leadYours')}+ </span>+ </div>+ {data.requests.length === 0 ? (+ <p className="rounded-xl border px-3.5 py-3 text-sm text-muted-foreground">+ {data.isAdmin ? t('empty') : t('emptyYours')}+ </p>+ ) : (+ <ul className="divide-y rounded-xl border">+ {data.requests.map((request) => (+ <li+ key={request.id}+ className="flex flex-col gap-2 px-3.5 py-2.5 text-sm sm:flex-row sm:items-center"+ >+ <div className="min-w-0 flex-1">+ <p className="font-medium break-words">{request.asked}</p>+ <p className="text-xs text-muted-foreground">+ {[+ data.isAdmin && t('from', { name: request.requester }),+ request.ruleDetail,+ format.relativeTime(new Date(request.createdAt)),+ ]+ .filter(Boolean)+ .join(' · ')}+ </p>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ <span+ className={cn('rounded-full px-2 py-0.5 text-xs', STATUS_TONE[request.status])}+ >+ {t(`status.${request.status}`)}+ </span>+ {request.status === 'pending' && data.isAdmin && (+ <>+ <Button+ size="sm"+ disabled={busy === request.id}+ onClick={() =>+ void act(+ request.id,+ () => decideAccessRequest(request.id, 'approved'),+ t('approved'),+ )+ }+ >+ {t('approve')}+ </Button>+ <Button+ size="sm"+ variant="outline"+ disabled={busy === request.id}+ onClick={() =>+ void act(+ request.id,+ () => decideAccessRequest(request.id, 'rejected'),+ t('dismissed'),+ )+ }+ >+ {t('dismiss')}+ </Button>+ </>+ )}+ {request.status === 'pending' && !data.isAdmin && request.isYours && (+ <Button+ size="sm"+ variant="outline"+ disabled={busy === request.id}+ onClick={() =>+ void act(request.id, () => withdrawAccessRequest(request.id), t('withdrawn'))+ }+ >+ {t('withdraw')}+ </Button>+ )}+ </div>+ </li>+ ))}+ </ul>+ )}+ </section>+ );+}diff --git a/web/src/components/chat-access/roles-access-section.tsx b/web/src/components/chat-access/roles-access-section.tsxindex d4f9d0e5b..dc39352bd 100644--- a/web/src/components/chat-access/roles-access-section.tsx+++ b/web/src/components/chat-access/roles-access-section.tsx@@ -36,6 +36,8 @@ 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 { AskAdminButton } from './ask-admin-button';+import { RequestsSection } from './requests-section';import { CAPABILITIES_PATH } from './your-access-card';/**@@ -45,8 +47,14 @@ import { CAPABILITIES_PATH } from './your-access-card';* Admins change a role here (the rest of the team's management stays in* Team).*/-export function RolesAccessSection() {+export function RolesAccessSection({+ onRequestsChanged,+}: {+ /** A request was decided or sent: Settings' count reads again. */+ onRequestsChanged?: () => void;+} = {}) {const t = useTranslations('chatAccess');+ const [requestsVersion, setRequestsVersion] = useState(0);const [access, setAccess] = useState<ChatAccess | null | 'failed' | undefined>(undefined);const [members, setMembers] = useState<RoleMember[]>([]);@@ -97,13 +105,23 @@ export function RolesAccessSection() {</div>{!isAdmin && (- <div className="flex items-center gap-2.5 rounded-xl border bg-muted/40 px-3.5 py-2.5 text-sm">+ <div className="flex flex-wrap 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>+ <span className="ml-auto">+ <AskAdminButton+ asked={t('askAdmin.defaults.role')}+ ruleKind="role"+ ruleDetail={t('askAdmin.roleDetail', { role: t(`roleNames.${access.role}`) })}+ onSent={() => setRequestsVersion((n) => n + 1)}+ />+ </span></div>)}+ <RequestsSection version={requestsVersion} onChanged={onRequestsChanged} />+<MembersTable members={members} isAdmin={isAdmin} onChanged={reload} /><RoleMatrix role={access.role} /><AdminSwitches access={access} />diff --git a/web/src/components/chat-access/your-access-card.tsx b/web/src/components/chat-access/your-access-card.tsxindex 0f33dcffa..9a2138112 100644--- a/web/src/components/chat-access/your-access-card.tsx+++ b/web/src/components/chat-access/your-access-card.tsx@@ -9,6 +9,7 @@ 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';+import { AskAdminButton } from './ask-admin-button';export const ROLES_ACCESS_PATH = '/dashboard/settings/roles-access';export const CAPABILITIES_PATH = '/dashboard/chat/capabilities';@@ -59,7 +60,14 @@ export function YourAccessCard({ access }: { access: ChatAccess }) {))}</ul></div>- <div className="flex flex-wrap gap-x-4 gap-y-1">+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1">+ {access.role !== 'admin' && (+ <AskAdminButton+ asked={t('askAdmin.defaults.role')}+ ruleKind="role"+ ruleDetail={t('askAdmin.roleDetail', { role: t(`roleNames.${access.role}`) })}+ />+ )}<Linkhref={ROLES_ACCESS_PATH}className="inline-flex items-center gap-0.5 text-xs font-medium underline-offset-2 hover:underline"diff --git a/web/src/lib/actions/chat-access-requests.test.ts b/web/src/lib/actions/chat-access-requests.test.tsnew file mode 100644index 000000000..44fa41d8c--- /dev/null+++ b/web/src/lib/actions/chat-access-requests.test.ts@@ -0,0 +1,276 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/** Ask your Admin (CHAT-20 §4c, chat_access_requests 00403). */++const ME = '11111111-1111-4111-8111-111111111111';+const ORG = '22222222-2222-4222-8222-222222222222';+const BRAND = '33333333-3333-4333-8333-333333333333';+const REQUEST = '44444444-4444-4444-8444-444444444444';+const OTHER = '55555555-5555-4555-8555-555555555555';++interface Call {+ table: string;+ op: string;+ row?: unknown;+ filters: unknown[][];+}+let calls: Call[] = [];+let role = 'analyst';+/** What each table and operation answers. */+let answers: Record<string, unknown> = {};++function from(table: string) {+ const call: Call = { table, op: 'select', filters: [] };+ calls.push(call);+ const answer = () => {+ const found = answers[`${table}.${call.op}`];+ return typeof found === 'function' ? found(call) : (found ?? { data: null, error: null });+ };+ const chain: Record<string, unknown> = {+ select: (_cols?: string, opts?: { head?: boolean }) => {+ if (opts?.head) call.op = call.op === 'select' ? 'count' : call.op;+ return chain;+ },+ insert: (row: unknown) => Object.assign(call, { op: 'insert', row }) && chain,+ update: (row: unknown) => Object.assign(call, { op: 'update', row }) && chain,+ ...Object.fromEntries(+ ['eq', 'in', 'or', 'order', 'limit'].map((name) => [+ name,+ (...args: unknown[]) => {+ call.filters.push([name, ...args]);+ return chain;+ },+ ]),+ ),+ single: async () => answer(),+ maybeSingle: async () => answer(),+ then: (resolve: (value: unknown) => unknown) => Promise.resolve(answer()).then(resolve),+ };+ return chain;+}++vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({ auth: { getUser: async () => ({ data: { user: { id: ME } } }) } }),+}));+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: { from: (t: string) => from(t) } }));+vi.mock('@/lib/member-emails', () => ({+ readMemberAuth: async (ids: string[]) =>+ new Map(ids.map((id) => [id, { email: `${id.slice(0, 4)}@x.example`, lastSignInAt: null }])),+}));++const {+ countPendingAccessRequests,+ decideAccessRequest,+ listAccessRequests,+ requestAccess,+ withdrawAccessRequest,+} = await import('./chat-access-requests');++beforeEach(() => {+ vi.stubEnv('CHAT_AGENTIC', 'true');+ calls = [];+ role = 'analyst';+ answers = {+ 'profiles.select': () => ({ data: { organization_id: ORG, role }, error: null }),+ 'chat_access_requests.count': { count: 0, error: null },+ 'chat_access_requests.insert': { data: { id: REQUEST }, error: null },+ };+});+afterEach(() => vi.unstubAllEnvs());++const ask = {+ asked: 'Add competitors · Peec AI',+ ruleKind: 'role' as const,+ toolKey: 'addCompetitors',+};+const inserted = () => calls.find((c) => c.op === 'insert')?.row as Record<string, unknown>;++describe('requestAccess', () => {+ it("sends the person's request with the rule and a fingerprint of what was asked", async () => {+ answers['brands.select'] = { data: { id: BRAND }, error: null };+ expect(+ await requestAccess({ ...ask, ruleDetail: 'Your role is Analyst.', brandId: BRAND }),+ ).toEqual({ ok: true, id: REQUEST });+ expect(inserted()).toEqual({+ organization_id: ORG,+ requester_id: ME,+ brand_id: BRAND,+ conversation_id: null,+ asked: 'Add competitors · Peec AI',+ asked_hash: expect.stringMatching(/^[0-9a-f]{64}$/),+ tool_key: 'addCompetitors',+ rule_kind: 'role',+ rule_detail: 'Your role is Analyst.',+ drafted_change: null,+ });+ });++ it('asks the same change once: the fingerprint ignores case and spacing', async () => {+ await requestAccess(ask);+ const first = inserted().asked_hash;+ calls = [];+ await requestAccess({ ...ask, asked: ' add competitors · PEEC AI ' });+ expect(inserted().asked_hash).toBe(first);+ calls = [];+ await requestAccess({ ...ask, toolKey: 'saveDraft' });+ expect(inserted().asked_hash).not.toBe(first);+ });++ it("drops a brand or a chat that isn't the person's", async () => {+ answers['brands.select'] = { data: null, error: null };+ answers['chat_conversations.select'] = { data: null, error: null };+ await requestAccess({ ...ask, brandId: BRAND, conversationId: OTHER });+ expect(inserted()).toMatchObject({ brand_id: null, conversation_id: null });+ const conversation = calls.find((c) => c.table === 'chat_conversations')!;+ expect(conversation.filters).toEqual(+ expect.arrayContaining([+ ['eq', 'user_id', ME],+ ['eq', 'organization_id', ORG],+ ]),+ );+ });++ it('refuses past ten waiting requests, and the same ask twice a day', async () => {+ answers['chat_access_requests.count'] = { count: 10, error: null };+ expect(await requestAccess(ask)).toEqual({ ok: false, reason: 'too_many' });+ expect(inserted()).toBeUndefined();+ answers['chat_access_requests.count'] = { count: 3, error: null };+ answers['chat_access_requests.insert'] = {+ data: null,+ error: { code: '23505', message: 'dup' },+ };+ expect(await requestAccess(ask)).toEqual({ ok: false, reason: 'already_today' });+ });++ it('refuses past twenty requests a day, withdrawn ones too', async () => {+ const today = new Date().toISOString().slice(0, 10);+ answers['chat_access_requests.count'] = (call: Call) =>+ call.filters.some(+ ([op, col, value]) => op === 'eq' && col === 'requested_on' && value === today,+ )+ ? { count: 20, error: null }+ : { count: 0, error: null };+ expect(await requestAccess(ask)).toEqual({ ok: false, reason: 'daily_limit' });+ expect(inserted()).toBeUndefined();+ const daily = calls.find((c) => c.filters.some(([, col]) => col === 'requested_on'))!;+ expect(daily.filters).toContainEqual(['eq', 'requester_id', ME]);+ expect(daily.filters.some(([, col]) => col === 'status')).toBe(false);+ });++ it('refuses a drafted change longer than 8,000 characters of JSON', async () => {+ expect(await requestAccess({ ...ask, draftedChange: { body: 'x'.repeat(8_000) } })).toEqual({+ ok: false,+ reason: 'invalid',+ });+ expect(inserted()).toBeUndefined();+ expect(await requestAccess({ ...ask, draftedChange: { body: 'x'.repeat(100) } })).toEqual({+ ok: true,+ id: REQUEST,+ });+ expect(inserted().drafted_change).toEqual({ body: 'x'.repeat(100) });+ });++ it('turns an Admin away, and does nothing while Chat is off or for a bad ask', async () => {+ role = 'admin';+ expect(await requestAccess(ask)).toEqual({ ok: false, reason: 'admin' });+ role = 'manager';+ expect(await requestAccess({ ...ask, asked: ' ' })).toEqual({ ok: false, reason: 'invalid' });+ expect(await requestAccess({ ...ask, ruleKind: 'nope' as never })).toEqual({+ ok: false,+ reason: 'invalid',+ });+ vi.stubEnv('CHAT_AGENTIC', 'false');+ expect(await requestAccess(ask)).toEqual({ ok: false, reason: 'chat_off' });+ expect(inserted()).toBeUndefined();+ });+});++describe('withdrawAccessRequest and decideAccessRequest', () => {+ it('withdraws only the person’s own waiting request', async () => {+ answers['chat_access_requests.update'] = { data: [{ id: REQUEST }], error: null };+ expect(await withdrawAccessRequest(REQUEST)).toBe(true);+ const update = calls.find((c) => c.op === 'update')!;+ expect(update.row).toMatchObject({ status: 'withdrawn', decided_by: ME });+ expect(update.filters).toEqual(+ expect.arrayContaining([+ ['eq', 'requester_id', ME],+ ['eq', 'status', 'pending'],+ ]),+ );+ answers['chat_access_requests.update'] = { data: [], error: null };+ expect(await withdrawAccessRequest(REQUEST)).toBe(false);+ expect(await withdrawAccessRequest('not-an-id')).toBe(false);+ });++ it("lets the first Admin decide a workspace's waiting request", async () => {+ role = 'admin';+ answers['chat_access_requests.update'] = { data: [{ id: REQUEST }], error: null };+ expect(await decideAccessRequest(REQUEST, 'approved')).toBe(true);+ const update = calls.find((c) => c.op === 'update')!;+ expect(update.row).toMatchObject({ status: 'approved', decided_by: ME });+ expect(update.filters).toEqual(+ expect.arrayContaining([+ ['eq', 'organization_id', ORG],+ ['eq', 'status', 'pending'],+ ]),+ );+ answers['chat_access_requests.update'] = { data: [], error: null };+ expect(await decideAccessRequest(REQUEST, 'rejected')).toBe(false);+ });++ it('refuses anyone but an Admin a decision', async () => {+ role = 'manager';+ await expect(decideAccessRequest(REQUEST, 'approved')).rejects.toThrow(/Only Admins/);+ });+});++describe('listAccessRequests and countPendingAccessRequests', () => {+ const row = (id: string, requester: string, status: string, created_at: string) => ({+ id,+ requester_id: requester,+ asked: 'Upgrade to Growth',+ tool_key: null,+ rule_kind: 'plan',+ rule_detail: "Needs Growth · you're on Starter",+ status,+ created_at,+ decided_at: status === 'pending' ? null : created_at,+ });++ it("gives an Admin the workspace's requests, waiting ones first, with who asked", async () => {+ role = 'admin';+ answers['chat_access_requests.select'] = {+ data: [+ row('r2', OTHER, 'approved', '2026-10-29T10:00:00Z'),+ row('r1', OTHER, 'pending', '2026-10-28T10:00:00Z'),+ ],+ error: null,+ };+ answers['profiles.select'] = (call: Call) =>+ call.filters.some((f) => f[0] === 'in')+ ? { data: [{ id: OTHER, full_name: 'Taylor Brooks' }], error: null }+ : { data: { organization_id: ORG, role }, error: null };+ const listed = await listAccessRequests();+ expect(listed?.isAdmin).toBe(true);+ expect(listed?.requests.map((r) => [r.id, r.status, r.requester])).toEqual([+ ['r1', 'pending', 'Taylor Brooks'],+ ['r2', 'approved', 'Taylor Brooks'],+ ]);+ const read = calls.find((c) => c.table === 'chat_access_requests')!;+ expect(read.filters.some((f) => f[0] === 'eq' && f[1] === 'requester_id')).toBe(false);+ });++ it('gives anyone else only their own', async () => {+ answers['chat_access_requests.select'] = { data: [], error: null };+ await listAccessRequests();+ const read = calls.find((c) => c.table === 'chat_access_requests')!;+ expect(read.filters).toContainEqual(['eq', 'requester_id', ME]);+ });++ it('counts the waiting requests for an Admin only', async () => {+ answers['chat_access_requests.count'] = { count: 3, error: null };+ expect(await countPendingAccessRequests()).toBe(0);+ role = 'admin';+ expect(await countPendingAccessRequests()).toBe(3);+ });+});diff --git a/web/src/lib/actions/chat-access-requests.ts b/web/src/lib/actions/chat-access-requests.tsnew file mode 100644index 000000000..ef00aceb3--- /dev/null+++ b/web/src/lib/actions/chat-access-requests.ts@@ -0,0 +1,263 @@+'use server';++import { createHash } from 'crypto';+import { z } from 'zod';+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 { chatAgenticEnabled } from '@/lib/chat/flag';+import { parseTeamRole } from '@/lib/chat/precedence';+import {+ ACCESS_REQUEST_RULES,+ MAX_DRAFTED_CHANGE_CHARS,+ MAX_PENDING_REQUESTS,+ MAX_REQUESTS_PER_DAY,+ REQUEST_HISTORY_DAYS,+ type AccessRequest,+ type AccessRequestStatus,+} from '@/lib/chat/access-requests';++/**+ * "Ask your Admin" (CHAT-20 §4c, registry row 80a `access.request`), behind+ * CHAT_AGENTIC: a person whose role, plan or tool policy kept Chat from a+ * change asks the workspace's Admins, only by their own click. Admins see+ * the requests in Settings › Team › Roles & access › Requests and approve+ * or dismiss them; the first to act decides for all. The requester sees+ * theirs, and may withdraw one while it is pending. Rows in+ * chat_access_requests (00403), written here with the service role after+ * these checks.+ */++interface Member {+ userId: string;+ organizationId: string;+ role: TeamRole;+}++async function member(): Promise<Member | 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, role')+ .eq('id', user.id)+ .maybeSingle();+ const role = parseTeamRole(profile?.role);+ const organizationId = profile?.organization_id;+ if (!organizationId || !role || !chatAgenticEnabled(organizationId)) return null;+ return { userId: user.id, organizationId, role };+}++const requestSchema = z.object({+ asked: z.string().trim().min(1).max(500),+ ruleKind: z.enum(ACCESS_REQUEST_RULES),+ ruleDetail: z.string().trim().max(500).default(''),+ toolKey: z+ .string()+ .regex(/^[a-z][A-Za-z0-9]{1,63}$/)+ .nullish(),+ brandId: z.string().uuid().nullish(),+ conversationId: z.string().uuid().nullish(),+ draftedChange: z+ .record(z.string(), z.unknown())+ .nullish()+ .refine(+ (change) => change == null || JSON.stringify(change).length <= MAX_DRAFTED_CHANGE_CHARS,+ ),+});++export type AccessRequestInput = z.input<typeof requestSchema>;++export type RequestAccessResult =+ | { ok: true; id: string }+ | {+ ok: false;+ reason: 'chat_off' | 'admin' | 'invalid' | 'too_many' | 'daily_limit' | 'already_today';+ };++/** The fingerprint of an asked change: one request a day for the same one. */+function askedHash(toolKey: string | null, asked: string): string {+ return createHash('sha256')+ .update(`${toolKey ?? ''}\n${asked.toLowerCase().replace(/\s+/g, ' ')}`)+ .digest('hex');+}++/** Sends a request to the workspace's Admins. Admins don't need to ask. */+export async function requestAccess(input: AccessRequestInput): Promise<RequestAccessResult> {+ const who = await member();+ if (!who) return { ok: false, reason: 'chat_off' };+ if (who.role === 'admin') return { ok: false, reason: 'admin' };+ const parsed = requestSchema.safeParse(input);+ if (!parsed.success) return { ok: false, reason: 'invalid' };+ const req = parsed.data;++ const [pending, sentToday, brand, conversation] = await Promise.all([+ supabaseAdmin+ .from('chat_access_requests')+ .select('id', { count: 'exact', head: true })+ .eq('requester_id', who.userId)+ .eq('status', 'pending'),+ // The table's requested_on: today in UTC.+ supabaseAdmin+ .from('chat_access_requests')+ .select('id', { count: 'exact', head: true })+ .eq('requester_id', who.userId)+ .eq('requested_on', new Date().toISOString().slice(0, 10)),+ req.brandId+ ? supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', req.brandId)+ .eq('organization_id', who.organizationId)+ .maybeSingle()+ : null,+ req.conversationId+ ? supabaseAdmin+ .from('chat_conversations')+ .select('id')+ .eq('id', req.conversationId)+ .eq('user_id', who.userId)+ .eq('organization_id', who.organizationId)+ .maybeSingle()+ : null,+ ]);+ if (pending.error) throw new Error(pending.error.message);+ if ((pending.count ?? 0) >= MAX_PENDING_REQUESTS) return { ok: false, reason: 'too_many' };+ if (sentToday.error) throw new Error(sentToday.error.message);+ if ((sentToday.count ?? 0) >= MAX_REQUESTS_PER_DAY) return { ok: false, reason: 'daily_limit' };++ const toolKey = req.toolKey ?? null;+ const { data, error } = await supabaseAdmin+ .from('chat_access_requests')+ .insert({+ organization_id: who.organizationId,+ requester_id: who.userId,+ // A brand or chat that isn't theirs is dropped, not trusted.+ brand_id: brand?.data ? req.brandId! : null,+ conversation_id: conversation?.data ? req.conversationId! : null,+ asked: req.asked,+ asked_hash: askedHash(toolKey, req.asked),+ tool_key: toolKey,+ rule_kind: req.ruleKind,+ rule_detail: req.ruleDetail,+ drafted_change: (req.draftedChange ?? null) as never,+ })+ .select('id')+ .single();+ if (error) {+ if (error.code === '23505') return { ok: false, reason: 'already_today' };+ throw new Error(error.message);+ }+ return { ok: true, id: data.id };+}++/** Withdraws the person's own pending request. False when it isn't one any more. */+export async function withdrawAccessRequest(id: string): Promise<boolean> {+ const who = await member();+ if (!who || !z.string().uuid().safeParse(id).success) return false;+ const { data, error } = await supabaseAdmin+ .from('chat_access_requests')+ .update({ status: 'withdrawn', decided_by: who.userId, decided_at: new Date().toISOString() })+ .eq('id', id)+ .eq('requester_id', who.userId)+ .eq('organization_id', who.organizationId)+ .eq('status', 'pending')+ .select('id');+ if (error) throw new Error(error.message);+ return (data ?? []).length > 0;+}++/**+ * An Admin approves or dismisses a pending request of their workspace. The+ * first Admin to act decides it: false when another already had.+ */+export async function decideAccessRequest(+ id: string,+ decision: 'approved' | 'rejected',+): Promise<boolean> {+ const who = await member();+ if (!who || who.role !== 'admin') throw new Error('Only Admins decide access requests');+ if (!z.string().uuid().safeParse(id).success || !['approved', 'rejected'].includes(decision)) {+ return false;+ }+ const { data, error } = await supabaseAdmin+ .from('chat_access_requests')+ .update({ status: decision, decided_by: who.userId, decided_at: new Date().toISOString() })+ .eq('id', id)+ .eq('organization_id', who.organizationId)+ .eq('status', 'pending')+ .select('id');+ if (error) throw new Error(error.message);+ return (data ?? []).length > 0;+}++/**+ * The requests a person sees: an Admin, the workspace's; anyone else, their+ * own. Pending first, then the decided ones of the last weeks.+ */+export async function listAccessRequests(): Promise<{+ isAdmin: boolean;+ requests: AccessRequest[];+} | null> {+ const who = await member();+ if (!who) return null;+ const isAdmin = who.role === 'admin';+ const since = new Date(Date.now() - REQUEST_HISTORY_DAYS * 86_400_000).toISOString();+ let query = supabaseAdmin+ .from('chat_access_requests')+ .select(+ 'id, requester_id, asked, tool_key, rule_kind, rule_detail, status, created_at, decided_at',+ )+ .eq('organization_id', who.organizationId)+ .or(`status.eq.pending,created_at.gte."${since}"`)+ .order('created_at', { ascending: false })+ .limit(100);+ if (!isAdmin) query = query.eq('requester_id', who.userId);+ const { data, error } = await query;+ if (error) throw new Error(error.message);+ const rows = data ?? [];++ const ids = [...new Set(rows.map((row) => row.requester_id))];+ const [profiles, auth] = await Promise.all([+ ids.length+ ? supabaseAdmin.from('profiles').select('id, full_name').in('id', ids)+ : { data: [], error: null },+ readMemberAuth(ids),+ ]);+ if (profiles.error) throw new Error(profiles.error.message);+ const names = new Map((profiles.data ?? []).map((p) => [p.id, p.full_name?.trim() || null]));++ const requests = rows.map((row) => ({+ id: row.id,+ requester:+ names.get(row.requester_id) || auth.get(row.requester_id)?.email?.split('@')[0] || '',+ isYours: row.requester_id === who.userId,+ asked: row.asked,+ toolKey: row.tool_key,+ ruleKind: row.rule_kind as AccessRequest['ruleKind'],+ ruleDetail: row.rule_detail,+ status: row.status as AccessRequestStatus,+ createdAt: row.created_at,+ decidedAt: row.decided_at,+ }));+ // Pending ones first, each part newest first.+ requests.sort((a, b) => Number(b.status === 'pending') - Number(a.status === 'pending'));+ return { isAdmin, requests };+}++/** How many requests wait for an Admin: the count on Roles & access. 0 for anyone else. */+export async function countPendingAccessRequests(): Promise<number> {+ const who = await member();+ if (!who || who.role !== 'admin') return 0;+ const { count, error } = await supabaseAdmin+ .from('chat_access_requests')+ .select('id', { count: 'exact', head: true })+ .eq('organization_id', who.organizationId)+ .eq('status', 'pending');+ if (error) throw new Error(error.message);+ return count ?? 0;+}diff --git a/web/src/lib/chat/access-log.test.ts b/web/src/lib/chat/access-log.test.tsnew file mode 100644index 000000000..67270aa07--- /dev/null+++ b/web/src/lib/chat/access-log.test.ts@@ -0,0 +1,57 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';+import { accessDeniedEvent, recordAccessDenied, type AccessDeniedContext } from './access-log';++/** Every denial is an `access.denied` event (CHAT-20 §4c). */++const ctx: AccessDeniedContext = {+ userId: 'u1',+ organizationId: 'o1',+ brandId: 'b1',+ toolKey: 'saveDraft',+ toolClass: 'write',+ surface: 'chat',+ conversationId: 'c1',+};++afterEach(() => vi.restoreAllMocks());++describe('accessDeniedEvent', () => {+ it('keeps who, which tool by its label key, why, where and in which run', () => {+ expect(accessDeniedEvent(ctx, { code: 'plan_locked', needs: 'growth' })).toEqual({+ kind: 'access.denied',+ userId: 'u1',+ organizationId: 'o1',+ brandId: 'b1',+ toolKey: 'saveDraft',+ toolClass: 'write',+ surface: 'chat',+ reason: 'plan_locked',+ detail: { needs: 'growth' },+ conversationId: 'c1',+ runId: null,+ });+ });++ it("names no brand the person can't see", () => {+ expect(accessDeniedEvent(ctx, { code: 'brand_scope' }).brandId).toBeNull();+ });+});++describe('recordAccessDenied', () => {+ it('writes the event to the server log', async () => {+ const info = vi.spyOn(console, 'info').mockImplementation(() => {});+ await recordAccessDenied(ctx, { code: 'forbidden_role', role: 'analyst', roles: ['admin'] });+ expect(info).toHaveBeenCalledWith(+ '[chat] access.denied',+ expect.stringContaining('"forbidden_role"'),+ );+ });++ it('never fails the run', async () => {+ vi.spyOn(console, 'info').mockImplementation(() => {+ throw new Error('log down');+ });+ await expect(recordAccessDenied(ctx, { code: 'policy_never' })).resolves.toBeUndefined();+ });+});diff --git a/web/src/lib/chat/access-log.ts b/web/src/lib/chat/access-log.tsnew file mode 100644index 000000000..ada90a9bf--- /dev/null+++ b/web/src/lib/chat/access-log.ts@@ -0,0 +1,59 @@+import type { ChatSurface, ToolDenial } from './precedence';+import type { ToolClass } from './registry/define-tool';++/**+ * Every denial Chat gives is recorded as an `access.denied` event (CHAT-20+ * §4c): who was refused which tool, why, on which brand and surface. It+ * shows in the person's own Activity log rows and to Admins, and feeds the+ * gap log (CHAT-19). A denial has no Undo.+ *+ * One way in for every place that refuses a call: the run's tool-call step+ * when the precedence denies (decideOrDeny, then buildDenial for the+ * answer), and MCP's. Until the Activity log lands (A4, 00402) the event+ * goes to the server's log only; then this writes its row, and no caller+ * changes. Server only.+ */++export interface AccessDeniedContext {+ userId: string;+ organizationId: string;+ /** The brand the call was about; null for none, or one out of the person's scope. */+ brandId: string | null;+ /** The registry row's label key (chatTools.{key}): never a tool's name. */+ toolKey: string;+ toolClass: ToolClass;+ surface: ChatSurface;+ conversationId?: string | null;+ runId?: string | null;+}++/** The event as the log keeps it: ids, the label key and the rule, nothing a person wrote. */+export function accessDeniedEvent(ctx: AccessDeniedContext, denial: ToolDenial) {+ const { code, ...detail } = denial;+ return {+ kind: 'access.denied' as const,+ userId: ctx.userId,+ organizationId: ctx.organizationId,+ // Out of scope, the brand isn't the person's to see named, even in their own log.+ brandId: code === 'brand_scope' ? null : ctx.brandId,+ toolKey: ctx.toolKey,+ toolClass: ctx.toolClass,+ surface: ctx.surface,+ reason: code,+ detail,+ conversationId: ctx.conversationId ?? null,+ runId: ctx.runId ?? null,+ };+}++/** Records one denial. Never throws: a failed record doesn't change the answer. */+export async function recordAccessDenied(+ ctx: AccessDeniedContext,+ denial: ToolDenial,+): Promise<void> {+ try {+ console.info('[chat] access.denied', JSON.stringify(accessDeniedEvent(ctx, denial)));+ } catch {+ // Logging must not fail the run.+ }+}diff --git a/web/src/lib/chat/access-requests.ts b/web/src/lib/chat/access-requests.tsnew file mode 100644index 000000000..70c5092bc--- /dev/null+++ b/web/src/lib/chat/access-requests.ts@@ -0,0 +1,50 @@+import type { DenialRuleKind } from './denial';++/**+ * "Ask your Admin" requests (CHAT-20 §4c, chat_access_requests 00403), as+ * the server actions (lib/actions/chat-access-requests.ts) and Roles &+ * access › Requests share them.+ */++/** Pending requests a person may have at once. */+export const MAX_PENDING_REQUESTS = 10;++/**+ * Requests a person may send in a UTC day, withdrawn ones too: withdrawing+ * frees a pending place, so this is what bounds a day's rows.+ */+export const MAX_REQUESTS_PER_DAY = 20;++/** The longest drafted change a request keeps, as JSON text. */+export const MAX_DRAFTED_CHANGE_CHARS = 8_000;++/** How far back Requests lists the decided ones. */+export const REQUEST_HISTORY_DAYS = 30;++/** The rules a request may be about: the denial's (denial.ts), as the table checks them. */+export const ACCESS_REQUEST_RULES = [+ 'role',+ 'plan',+ 'policy',+ 'workspace',+ 'brand',+ 'demo',+] as const satisfies readonly DenialRuleKind[];++export const ACCESS_REQUEST_STATUSES = ['pending', 'approved', 'rejected', 'withdrawn'] as const;+export type AccessRequestStatus = (typeof ACCESS_REQUEST_STATUSES)[number];++export interface AccessRequest {+ id: string;+ /** The requester's name, or the part of their e-mail before the @. */+ requester: string;+ isYours: boolean;+ asked: string;+ /** The registry row's label key; null for a request about the plan or the role. */+ toolKey: string | null;+ ruleKind: (typeof ACCESS_REQUEST_RULES)[number];+ ruleDetail: string;+ status: AccessRequestStatus;+ createdAt: string;+ decidedAt: string | null;+}diff --git a/web/src/lib/chat/registry/tools.test.ts b/web/src/lib/chat/registry/tools.test.tsindex d33511e17..12972e53e 100644--- a/web/src/lib/chat/registry/tools.test.ts+++ b/web/src/lib/chat/registry/tools.test.ts@@ -57,6 +57,9 @@ vi.mock('@/lib/actions/content-drafts', () => ({vi.mock('@/lib/actions/prompt-suggestions', () => ({dismissSuggestion: tracked.track('actions/prompt-suggestions.dismissSuggestion'),}));+vi.mock('@/lib/actions/chat-access-requests', () => ({+ requestAccess: tracked.track('actions/chat-access-requests.requestAccess'),+}));const { CHAT_TOOLS, chatTool, chatToolByKey, registryCatalog } = await import('./tools');const { BRAND_LOOKUP_TABLES, FIXTURE_IDS, defineTool } = await import('./define-tool');@@ -266,6 +269,9 @@ describe('approval policies', () => {for (const tool of CHAT_TOOLS) {if (tool.class === 'read') {expect([tool.defaultPolicy, tool.maxPolicy]).toEqual(['on', 'on']);+ } else if (tool.class === 'write' && tool.flags.alwaysCard) {+ // Ask your Admin: only the person's click sends it (CHAT-20 row 80a).+ expect([tool.defaultPolicy, tool.maxPolicy]).toEqual(['ask', 'ask']);} else if (tool.class === 'write') {expect([tool.defaultPolicy, tool.maxPolicy]).toEqual(['ask_full_auto', 'always']);}@@ -279,6 +285,7 @@ describe('approval policies', () => {create_draft: ['admin', 'manager', 'analyst', 'agency_partner'],update_opportunity: ['admin', 'manager'],dismiss_prompt_suggestion: ['admin', 'manager', 'analyst'],+ request_access: ['admin', 'manager', 'analyst', 'agency_partner'],});for (const tool of CHAT_TOOLS.filter((t) => t.class === 'read')) {expect(allowedRoles(tool)).toEqual(['admin', 'manager', 'analyst', 'agency_partner']);@@ -473,14 +480,16 @@ describe("the model's tool list on the registry's rows", () => {...withoutShopping,'create_draft','dismiss_prompt_suggestion',+ 'request_access',]);- expect(list('agency_partner', growth)).toEqual([...reads, 'create_draft']);+ expect(list('agency_partner', growth)).toEqual([...reads, 'create_draft', 'request_access']);expect(list('manager', starter)).toEqual([...withoutShopping, ...writes]);expect(list('admin', growth)).toEqual([...reads, ...writes]);expect(list('analyst', facts(null, false))).toEqual([...reads,'create_draft','dismiss_prompt_suggestion',+ 'request_access',]);});@@ -495,6 +504,7 @@ describe("the model's tool list on the registry's rows", () => {expect(list('agency_partner', growth, undefined, [FIXTURE_IDS.brand])).toEqual([...reads,'create_draft',+ 'request_access',]);});});diff --git a/web/src/lib/chat/registry/write-tools.ts b/web/src/lib/chat/registry/write-tools.tsindex cc96bd1d6..0791a887c 100644--- a/web/src/lib/chat/registry/write-tools.ts+++ b/web/src/lib/chat/registry/write-tools.ts@@ -2,6 +2,8 @@ import { z } from 'zod';import { updateOpportunityStatus } from '@/lib/actions/content';import { createContentDraft } from '@/lib/actions/content-drafts';import { dismissSuggestion } from '@/lib/actions/prompt-suggestions';+import { requestAccess } from '@/lib/actions/chat-access-requests';+import { ACCESS_REQUEST_RULES } from '@/lib/chat/access-requests';import { PAGE_TYPES } from '@/lib/content/drafts';import { MAX_BODY_HTML_LENGTH, MAX_TITLE_LENGTH } from '@/lib/content/editor';import { contentUuid, isHttpUrl } from '@/lib/mcp/content-schemas';@@ -140,4 +142,43 @@ export const WRITE_TOOLS = [run: (_ctx, input) => dismissSuggestion(input.suggestion_id),fixture: { input: { suggestion_id: ITEM } },}),+ defineTool({+ name: 'request_access',+ class: 'write',+ area: 'account',+ description:+ "Ask the workspace's Admins for a change the person's role, the plan or the tool policy keeps Chat from making: what was asked, and the rule that refused it, as the out-of-permission answer gave them. Only when the person clicks Ask your Admin on that answer.",+ // Only the person's click sends it, in every mode (CHAT-20 row 80a: "Ask (fixed)").+ defaultPolicy: 'ask',+ maxPolicy: 'ask',+ flags: { alwaysCard: true },+ // Every role; the server turns an Admin's away, who has no one to ask.+ minRole: 'analyst',+ planGate: null,+ // About the person and the workspace: the chat it came from is the run's own.+ brandOf: null,+ costClass: 'C0',+ labelKey: 'askAdmin',+ route: '/dashboard/settings/roles-access',+ mcpTool: null,+ specRow: '80a',+ inputSchema: z.object({+ asked: z.string().trim().min(1).max(500).describe("What was asked, in the answer's words."),+ rule_kind: z.enum(ACCESS_REQUEST_RULES).describe('The rule that refused it.'),+ rule_detail: z.string().trim().max(500).optional().describe("The rule's words."),+ tool_key: z+ .string()+ .regex(/^[a-z][A-Za-z0-9]{1,63}$/)+ .optional()+ .describe("The refused tool's label key, when one was."),+ }),+ run: (_ctx, input) =>+ requestAccess({+ asked: input.asked,+ ruleKind: input.rule_kind,+ ruleDetail: input.rule_detail,+ toolKey: input.tool_key,+ }),+ fixture: { input: { asked: 'Add competitors · Peec AI', rule_kind: 'role' } },+ }),];diff --git a/web/src/lib/chat/undo.test.ts b/web/src/lib/chat/undo.test.tsindex 866417f73..00d0f9fb5 100644--- a/web/src/lib/chat/undo.test.ts+++ b/web/src/lib/chat/undo.test.ts@@ -420,3 +420,32 @@ describe('a double-clicked Undo', () => {expect(db.tables.chat_activity_log.filter((r) => r.undoes_id === row.id)).toHaveLength(1);});});++describe('request_access: withdraw it while it waits', () => {+ const rule = UNDO_RULES.request_access;+ const REQUEST = '66666666-6666-4666-8666-666666666666';++ it('records the request it sent, and nothing to undo for one it refused', async () => {+ const sent = await rule.record({ asked: 'Change my role' }, { ok: true, id: REQUEST }, null);+ expect(sent).toMatchObject({+ target: { type: 'access_request', id: REQUEST },+ summaryParams: { asked: 'Change my role' },+ });+ expect(sent.undo).not.toBeNull();+ const refused = await rule.record({ asked: 'x' }, { ok: false, reason: 'too_many' }, null);+ expect(refused).toMatchObject({ target: { id: null }, undo: null });+ });++ it('withdraws a waiting request, and leaves one an Admin decided', async () => {+ db.tables.chat_access_requests = [+ { id: REQUEST, status: 'pending', decided_at: null },+ { id: OPPORTUNITY, status: 'approved', decided_at: '2026-10-29T00:00:00Z' },+ ];+ expect(await rule.inverse({ id: REQUEST, brandId: null, data: {} })).toBe('ok');+ expect(db.tables.chat_access_requests[0]).toMatchObject({ status: 'withdrawn' });+ expect(db.tables.chat_access_requests[0].decided_at).toEqual(expect.any(String));+ expect(await rule.inverse({ id: OPPORTUNITY, brandId: null, data: {} })).toBe('changed');+ expect(db.tables.chat_access_requests[1]).toMatchObject({ status: 'approved' });+ expect(await rule.inverse({ id: SUGGESTION, brandId: null, data: {} })).toBe('gone');+ });+});diff --git a/web/src/lib/chat/undo.ts b/web/src/lib/chat/undo.tsindex 8fb0b770a..bb56eb46f 100644--- a/web/src/lib/chat/undo.ts+++ b/web/src/lib/chat/undo.ts@@ -288,11 +288,53 @@ const dismissSuggestion: UndoRule = {href: () => '/dashboard/prompts/suggestions',};+// ─── request_access: withdraw it while it waits ────────────────────────────++const requestAccessRule: UndoRule = {+ targetType: 'access_request',+ // As long as a dismissed suggestion's; a request an Admin decided stays.+ windowMs: 7 * DAY_MS,+ async before() {+ return null;+ },+ async record(input, output) {+ const result = asObject(output);+ const id = result.ok === true ? textOf(result.id) : null;+ return {+ target: { type: 'access_request', id },+ summaryParams: { asked: summaryValue(asObject(input).asked) },+ // Refused (too many, already asked today, an Admin): nothing was sent.+ undo: id ? { before: { status: null }, after: { status: 'pending' } } : null,+ };+ },+ async inverse({ id }) {+ // Only while it waits: once an Admin decided it, it's theirs.+ const { data: withdrawn, error } = await supabaseAdmin+ .from('chat_access_requests')+ .update({ status: 'withdrawn', decided_at: new Date().toISOString() })+ .eq('id', id)+ .eq('status', 'pending')+ .select('id')+ .maybeSingle();+ if (error) throw new Error(`Could not withdraw the request: ${error.message}`);+ if (withdrawn) return 'ok';+ const { data: row, error: readError } = await supabaseAdmin+ .from('chat_access_requests')+ .select('id')+ .eq('id', id)+ .maybeSingle();+ check(readError, 'the request');+ return row ? 'changed' : 'gone';+ },+ href: () => '/dashboard/settings/roles-access',+};+/** Each WRITE row's Undo, by tool name. A WRITE without one has no Undo. */export const UNDO_RULES: Readonly<Record<string, UndoRule>> = {create_draft: createDraft,update_opportunity: updateOpportunity,dismiss_prompt_suggestion: dismissSuggestion,+ request_access: requestAccessRule,};/** A tool's Undo, or null: a read or an EXECUTE has none (§10b). */diff --git a/web/src/lib/chat/write.test.ts b/web/src/lib/chat/write.test.tsindex 2e7611739..e69b31f15 100644--- a/web/src/lib/chat/write.test.ts+++ b/web/src/lib/chat/write.test.ts@@ -100,7 +100,10 @@ async function runAs(}describe('every WRITE that ran is in the Activity log (§21)', () => {- it.each(WRITES.map((tool) => [tool.name, tool] as const))(+ // Ask your Admin is always a card, in Full auto too (CHAT-20 row 80a).+ it.each(+ WRITES.filter((tool) => !tool.flags.alwaysCard).map((tool) => [tool.name, tool] as const),+ )('%s in Full auto: mode, approval, Undo window, label key, target and summary',async (name, tool) => {const { decision, outcome } = await runAs(PEOPLE.admin, tool, 'full_auto');@@ -466,3 +469,15 @@ describe('00402', () => {}});});++describe('Ask your Admin in Full auto', () => {+ it('is still a card: only the person’s click sends it', async () => {+ const tool = chatTool('request_access')!;+ const { decision, outcome } = await runAs(PEOPLE.manager, tool, 'full_auto', {+ input: { asked: 'Change my role', rule_kind: 'role' },+ });+ expect(decision).toMatchObject({ kind: 'ask', reason: 'always_card' });+ expect(outcome).toBeNull();+ expect(db.tables.chat_activity_log ?? []).toHaveLength(0);+ });+});diff --git a/web/src/lib/subscription-guard-coverage.test.ts b/web/src/lib/subscription-guard-coverage.test.tsindex 242140603..cd2899858 100644--- a/web/src/lib/subscription-guard-coverage.test.ts+++ b/web/src/lib/subscription-guard-coverage.test.ts@@ -49,6 +49,11 @@ const OPEN_ACTIONS: Record<string, string> = {'a column layout: costs nothing, and read-only shows the data the same way','menu-access.ts:setMyWorkAreas':'the person\'s own profile; it answers "What do you work on?", which /dashboard/welcome waits on',+ 'chat-access-requests.ts:requestAccess':+ 'asking an Admin costs nothing, and a read-only workspace is one of the things to ask about',+ 'chat-access-requests.ts:withdrawAccessRequest': 'takes back a request, never gives access',+ 'chat-access-requests.ts:decideAccessRequest':+ "marks a request decided; it changes no one's access",};/** Write routes that stay open while read-only: path:METHOD → why. */diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 79c37343e..7f4985d2b 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -1370,6 +1370,85 @@ export type Database = {},]}+ chat_access_requests: {+ Row: {+ asked: string+ asked_hash: string+ brand_id: string | null+ conversation_id: string | null+ created_at: string+ decided_at: string | null+ decided_by: string | null+ drafted_change: Json | null+ id: string+ organization_id: string+ requested_on: string+ requester_id: string+ rule_detail: string+ rule_kind: string+ status: string+ tool_key: string | null+ }+ Insert: {+ asked: string+ asked_hash: string+ brand_id?: string | null+ conversation_id?: string | null+ created_at?: string+ decided_at?: string | null+ decided_by?: string | null+ drafted_change?: Json | null+ id?: string+ organization_id: string+ requested_on?: string+ requester_id: string+ rule_detail?: string+ rule_kind: string+ status?: string+ tool_key?: string | null+ }+ Update: {+ asked?: string+ asked_hash?: string+ brand_id?: string | null+ conversation_id?: string | null+ created_at?: string+ decided_at?: string | null+ decided_by?: string | null+ drafted_change?: Json | null+ id?: string+ organization_id?: string+ requested_on?: string+ requester_id?: string+ rule_detail?: string+ rule_kind?: string+ status?: string+ tool_key?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "chat_access_requests_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "chat_access_requests_conversation_id_fkey"+ columns: ["conversation_id"]+ isOneToOne: false+ referencedRelation: "chat_conversations"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "chat_access_requests_organization_id_fkey"+ columns: ["organization_id"]+ isOneToOne: false+ referencedRelation: "organizations"+ referencedColumns: ["id"]+ },+ ]+ }chat_activity_log: {Row: {approval_kind: string | null