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(settings): add Settings › Chat with the tool policy and run modes (#1782)
Cihan150e599389e5
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 628b7bc43..51a8abc75 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -249,7 +249,8 @@"setDefaultAuthor": "Setting a default author needs a plan","setByline": "Changing the byline setting needs a plan","changeContentSettings": "Changing content settings needs a plan",- "disconnectIntegrations": "Disconnecting an integration needs a plan"+ "disconnectIntegrations": "Disconnecting an integration needs a plan",+ "changeChatSettings": "Changing Chat's settings needs a plan"},"plans": {"perMonthBilledYearly": "{price} a month, billed yearly",@@ -3398,6 +3399,7 @@"roleChanged": "Role changed","roleChangeFailed": "Couldn't change the role. Try again.","loadError": "Couldn't load Roles & access. Try again in a moment.",+ "retry": "Retry","throughChat": {"admin": "Everything, incl. policy, keys, connections","manager": "WRITE with approval · EXECUTE after click",@@ -3516,6 +3518,8 @@"leadYours": "What you asked your Admins for, and what they decided.","empty": "No requests.","emptyYours": "You haven't asked for anything.",+ "loadError": "Couldn't load the requests.",+ "retry": "Retry","from": "From {name}","approve": "Approve","dismiss": "Dismiss",@@ -3532,6 +3536,110 @@"withdrawn": "Withdrawn"}},+ "settings": {+ "title": "Chat",+ "lead": "The rules Chat follows in this workspace: which tools it may use, when it asks first, and what Managers may take live.",+ "readOnly": "Read-only · only Admins change the Chat tool policy",+ "readOnlyNote": "You see the rules Chat follows for you",+ "loadError": "Couldn't load Chat's settings. Try again in a moment.",+ "retry": "Retry",+ "saved": "Saved",+ "failures": {+ "chat_off": "Chat isn't on for this workspace.",+ "forbidden": "Only Admins change Chat's settings.",+ "invalid": "That choice isn't available for this tool.",+ "locked": "That needs the Growth plan.",+ "read_only": "This workspace is read-only until a plan is active.",+ "failed": "Couldn't save it. Try again."+ },+ "switches": {+ "title": "Run modes",+ "fullAuto": "Full auto available to Managers and other members",+ "fullAutoNote": "Admins can always pick it. Allowed WRITEs run without a card, logged.",+ "dontAskAgain": "Allow “Don't ask again”",+ "dontAskAgainNote": "Per person, only inside this policy. Off, everyone's ticks stop at once.",+ "mcp": "Full auto over MCP",+ "mcpNote": "MCP writes always ask, in Claude, ChatGPT and Cursor",+ "mcpValue": "Off in v1",+ "untrusted": "Untrusted content in a run",+ "untrustedNote": "Web pages, uploads, AI answer text, mention snippets",+ "untrustedValue": "Every WRITE shows a card",+ "on": "On",+ "off": "Off",+ "locked": "Needs Growth · you're on {current}"+ },+ "precedence": {+ "title": "Who decides",+ "note": "Most restrictive wins. A step can't relax the one above it.",+ "steps": {+ "hard": {+ "name": "Hard rules",+ "detail": "NEVER tools don't exist · EXECUTE needs a click"+ },+ "plan": {+ "name": "Plan gates",+ "detail": "Full auto and “Don't ask again”: Growth and up"+ },+ "role": { "name": "Role", "detail": "Admin · Manager · Analyst · Agency partner" },+ "policy": {+ "name": "Tool policy",+ "detail": "Never · Ask · Ask (auto in Full auto) · Always, per tool"+ },+ "mode": {+ "name": "Run mode",+ "detail": "Ask me first · Auto, ask before changes · Full auto"+ },+ "dontAsk": { "name": "“Don't ask again”", "detail": "One person, inside the steps above" }+ }+ },+ "policy": {+ "title": "Tool policy",+ "reset": "Reset to defaults",+ "resetDone": "Every tool is back to its default",+ "columns": {+ "tool": "Tool",+ "class": "Class",+ "policy": "Policy",+ "fullAuto": "In Full auto"+ },+ "choices": {+ "on": "On",+ "click": "Your click",+ "never": "Never",+ "ask": "Ask",+ "ask_full_auto": "Ask (auto in Full auto)",+ "always": "Always"+ },+ "default": "default",+ "lockedChoice": "Needs Growth",+ "behaviour": {+ "off": "Off",+ "runs": "Runs freely",+ "click": "Needs your click",+ "card": "Card in every mode",+ "always_card": "Always a card",+ "auto_full_auto": "Auto in Full auto",+ "auto_always": "Auto in every mode"+ }+ },+ "execute": {+ "title": "What Managers may take live",+ "note": "EXECUTE always needs a click, whoever runs it. Off, a Manager gets Ask your Admin instead.",+ "groups": {+ "publishing": "Publishing",+ "email_outreach": "Email and outreach",+ "code_prs": "Code and pull requests",+ "feeds": "Product feeds"+ }+ },+ "autoChoices": {+ "title": "Your auto changes",+ "note": "Tools you ticked “Don't ask again” on. They run without a card only where this policy and your plan allow Full auto.",+ "empty": "You haven't ticked “Don't ask again” on any tool.",+ "remove": "Remove",+ "removed": "Removed: it asks again"+ }+ },"yourAccess": {"title": "Your access","brands": "Brands",@@ -3583,6 +3691,8 @@"readAll": "Read: all roles","locked": "Needs {plan}","empty": "No area matches your search.",+ "loadError": "Couldn't load what Chat can do. Try again in a moment.",+ "retry": "Retry","areaNames": {"account": "Account","usage": "AI usage",@@ -9571,6 +9681,7 @@"apiKeys": "API Keys","team": "Team","rolesAccess": "Roles & access",+ "chatSettings": "Chat","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.tsxindex d8c00a4e7..33a1bfb37 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/chat/capabilities/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/chat/capabilities/page.tsx@@ -2,7 +2,10 @@ 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';+import {+ CapabilitiesUnavailable,+ CapabilitiesView,+} from '@/components/chat-access/capabilities-view';/*** "What Chat can do" (CHAT-20 §8, mockup #g-capabilities): every tool in@@ -12,7 +15,9 @@ import { CapabilitiesView } from '@/components/chat-access/capabilities-view';* Chat on for the workspace.*/export default async function ChatCapabilitiesPage() {- const access = await getChatAccess();- if (!access) notFound();- return <CapabilitiesView access={access} areas={capabilityAreas(registryCatalog())} />;+ const result = await getChatAccess();+ if (!result.ok && result.failure === 'chat_off') notFound();+ // The database didn't answer: say so in plain words, with a way to try again.+ if (!result.ok) return <CapabilitiesUnavailable />;+ return <CapabilitiesView access={result.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.tsindex fb8704bc2..9dbaa9325 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts@@ -19,6 +19,8 @@ export const SETTINGS_SECTIONS = ['api-keys','ai-providers','billing',+ // Settings › Chat (CHAT-20 §5): listed only while the new Chat is on.+ 'chat',] as const;export type SettingsSection = (typeof SETTINGS_SECTIONS)[number];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 f80ccc2f2..73b3ef709 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@@ -27,7 +27,7 @@ vi.mock('@/components/providers/chat-agentic-provider', () => ({vi.mock('@/lib/actions/organization', () => ({ updateAccountName: vi.fn() }));let pendingRequests = 0;vi.mock('@/lib/actions/chat-access-requests', () => ({- countPendingAccessRequests: async () => pendingRequests,+ countPendingAccessRequests: async () => ({ ok: true, count: pendingRequests }),}));vi.mock('@/components/ai-usage/ai-usage-meter', () => ({HeaderWithAiUsage: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,@@ -46,6 +46,7 @@ for (const [path, name] of [['@/components/settings/work-areas-card', 'WorkAreasCard'],['@/components/chat-access/roles-access-section', 'RolesAccessSection'],['@/components/chat-access/your-access-card', 'YourAccessSlot'],+ ['@/components/chat-access/chat-settings-section', 'ChatSettingsSection'],]) {vi.doMock(path, () => ({ [name]: () => null }));}@@ -96,8 +97,11 @@ describe('SettingsView', () => {chatAgentic = true;const list = await sections();expect(list.indexOf('Roles & access')).toBe(list.indexOf('Team') + 1);+ expect(list.at(-1)).toBe('Chat');chatAgentic = false;- expect(await sections()).not.toContain('Roles & access');+ const off = await sections();+ expect(off).not.toContain('Roles & access');+ expect(off).not.toContain('Chat');});it("counts an Admin's waiting access requests on Roles & access", async () => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsxindex 1308db8b0..8fb26755d 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 { ChatSettingsSection } from '@/components/chat-access/chat-settings-section';import { countPendingAccessRequests } from '@/lib/actions/chat-access-requests';import { Badge } from '@/components/ui/badge';import { updateAccountName } from '@/lib/actions/organization';@@ -58,17 +59,18 @@ export function SettingsView({ section }: { section: SettingsSection }) {if (!chatAgentic) return;let live = true;countPendingAccessRequests()- .then((count) => {- if (live) setPendingRequests(count);+ .then((read) => {+ // A failed count shows none: the list itself says it couldn't load.+ if (live) setPendingRequests(read.ok ? read.count : 0);}).catch(() => {});return () => {live = false;};}, [chatAgentic, requestsRead]);- // Roles & access is Chat's: with Chat off, its address opens Account.+ // Roles & access and Chat are the new Chat's: with it off, their addresses open Account.const [active, setActive] = useState<SettingsSection>(- section === 'roles-access' && !chatAgentic ? 'account' : section,+ (section === 'roles-access' || section === 'chat') && !chatAgentic ? 'account' : section,);const show = (next: SettingsSection) => {@@ -119,16 +121,17 @@ export function SettingsView({ section }: { section: SettingsSection }) {'api-keys': t('apiKeys'),'ai-providers': t('aiProviders'),billing: t('billing'),+ chat: t('chatSettings'),};// 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,- // Roles & access for everyone while the new Chat is on.+ // Roles & access and Chat for everyone while the new Chat is on.const navItems = SETTINGS_SECTIONS.filter((id) =>hasSettingsSection(id, { isCloud }) &&(id !== 'menu-access' || canManageMenus) &&- (id !== 'roles-access' || chatAgentic),+ ((id !== 'roles-access' && id !== 'chat') || chatAgentic),).map((id) => ({ id, label: labels[id] }));return (@@ -253,6 +256,8 @@ export function SettingsView({ section }: { section: SettingsSection }) {{/* AI Providers (cloud BYOK) */}{active === 'ai-providers' && isCloud && <AiProvidersSection />}+ {active === 'chat' && chatAgentic && <ChatSettingsSection />}+{/* Billing */}{active === 'billing' && isCloud && <BillingSection />}</div>diff --git a/web/src/components/chat-access/capabilities-view.tsx b/web/src/components/chat-access/capabilities-view.tsxindex 6c13c4cff..d6942cd9c 100644--- a/web/src/components/chat-access/capabilities-view.tsx+++ b/web/src/components/chat-access/capabilities-view.tsx@@ -3,6 +3,8 @@import { useMemo, useState } from 'react';import { useTranslations } from 'next-intl';import { Lock, MousePointerClick, SquareCheckBig, Unlock, Zap } from 'lucide-react';+import { useRouter } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Badge } from '@/components/ui/badge';import {@@ -186,3 +188,18 @@ export function CapabilitiesView({</div>);}++/** The page when its facts couldn't be read: plain words and Retry, never the error itself. */+export function CapabilitiesUnavailable() {+ const t = useTranslations('chatAccess.capabilities');+ const router = useRouter();+ return (+ <div role="status" className="space-y-2 text-sm text-muted-foreground">+ <h1 className="text-2xl font-bold tracking-tight text-foreground">{t('title')}</h1>+ <p>{t('loadError')}</p>+ <Button size="sm" variant="outline" onClick={() => router.refresh()}>+ {t('retry')}+ </Button>+ </div>+ );+}diff --git a/web/src/components/chat-access/chat-access.test.tsx b/web/src/components/chat-access/chat-access.test.tsxindex bff64d85e..e4fbe2fd8 100644--- a/web/src/components/chat-access/chat-access.test.tsx+++ b/web/src/components/chat-access/chat-access.test.tsx@@ -68,7 +68,7 @@ beforeEach(() => {fn.mockReset();}listAccessRequests.mockReset();- listAccessRequests.mockResolvedValue({ isAdmin: false, requests: [] });+ listAccessRequests.mockResolvedValue({ ok: true, isAdmin: false, requests: [] });});afterEach(() => {act(() => root.unmount());@@ -202,8 +202,11 @@ describe('YourAccessCard', () => {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 })));+ getChatAccess.mockResolvedValue({ ok: true, access: access() });+ listRoleMembers.mockResolvedValue({+ ok: true,+ members: members.map((m) => ({ ...m, email: null })),+ });await render(<RolesAccessSection />);expect(text()).toContain("You're a Manager · read-only here");expect(text()).not.toContain('@');@@ -218,19 +221,34 @@ describe('RolesAccessSection', () => {});it('gives an Admin the e-mails and a role picker for everyone but themselves', async () => {- getChatAccess.mockResolvedValue(access({ role: 'admin' }));- listRoleMembers.mockResolvedValue(members);+ getChatAccess.mockResolvedValue({ ok: true, access: access({ role: 'admin' }) });+ listRoleMembers.mockResolvedValue({ ok: true, 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([]);+ it('says so in plain words when it cannot be read, and reads again on Retry', async () => {+ getChatAccess.mockResolvedValue({ ok: false, failure: 'failed' });+ listRoleMembers.mockResolvedValue({ ok: true, members: [] });await render(<RolesAccessSection />);expect(text()).toContain("Couldn't load Roles & access");+ getChatAccess.mockResolvedValue({ ok: true, access: access() });+ await act(async () =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === 'Retry')!.click(),+ );+ expect(getChatAccess).toHaveBeenCalledTimes(2);+ expect(text()).toContain('What each role can do');+ });++ it("says the requests couldn't load, apart from the rest of the page", async () => {+ getChatAccess.mockResolvedValue({ ok: true, access: access() });+ listRoleMembers.mockResolvedValue({ ok: true, members: [] });+ listAccessRequests.mockResolvedValue({ ok: false, failure: 'failed' });+ await render(<RolesAccessSection />);+ expect(text()).toContain("Couldn't load the requests.");+ expect(text()).toContain('What each role can do');});});@@ -306,8 +324,8 @@ const button = (label: string, root: ParentNode = container) =>describe('Ask your Admin', () => {it('sends what the person needs, with the rule, after their click', async () => {- getChatAccess.mockResolvedValue(access());- listRoleMembers.mockResolvedValue([]);+ getChatAccess.mockResolvedValue({ ok: true, access: access() });+ listRoleMembers.mockResolvedValue({ ok: true, members: [] });requestAccess.mockResolvedValue({ ok: true, id: 'r1' });await render(<RolesAccessSection />);expect(requestAccess).not.toHaveBeenCalled();@@ -365,9 +383,10 @@ describe('Requests', () => {});it("lets an Admin approve or dismiss a workspace's waiting request, with a count", async () => {- getChatAccess.mockResolvedValue(access({ role: 'admin' }));- listRoleMembers.mockResolvedValue([]);+ getChatAccess.mockResolvedValue({ ok: true, access: access({ role: 'admin' }) });+ listRoleMembers.mockResolvedValue({ ok: true, members: [] });listAccessRequests.mockResolvedValue({+ ok: true,isAdmin: true,requests: [request(), request({ id: 'r2', status: 'approved' })],});@@ -393,9 +412,10 @@ describe('Requests', () => {});it('lets anyone else withdraw their own waiting request', async () => {- getChatAccess.mockResolvedValue(access());- listRoleMembers.mockResolvedValue([]);+ getChatAccess.mockResolvedValue({ ok: true, access: access() });+ listRoleMembers.mockResolvedValue({ ok: true, members: [] });listAccessRequests.mockResolvedValue({+ ok: true,isAdmin: false,requests: [request({ isYours: true })],});diff --git a/web/src/components/chat-access/chat-settings-section.test.tsx b/web/src/components/chat-access/chat-settings-section.test.tsxnew file mode 100644index 000000000..cf11dc24d--- /dev/null+++ b/web/src/components/chat-access/chat-settings-section.test.tsx@@ -0,0 +1,165 @@+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 { ChatSettingsView, PolicyRow } from '@/lib/actions/chat-settings';++/** Settings › Chat (CHAT-20 §5, mockup #g-policy). */++const actions = vi.hoisted(() => ({+ getChatSettingsView: vi.fn(),+ setToolPolicy: vi.fn(),+ resetToolPolicies: vi.fn(),+ setChatSwitch: vi.fn(),+ setManagerExecute: vi.fn(),+ removeAutoChoice: vi.fn(),+}));+vi.mock('@/lib/actions/chat-settings', () => actions);+vi.mock('@/lib/actions/chat-access-requests', () => ({ requestAccess: vi.fn() }));+vi.mock('@/components/providers/upgrade-gate', () => ({+ useUpgradeGate: () => ({ guard: (fn: unknown) => fn }),+}));+vi.mock('@/components/providers/ai-usage-provider', () => ({+ useAiUsage: () => ({ usage: null, refresh: vi.fn() }),+}));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children }: { href: string; children: React.ReactNode }) => (+ <a href={href}>{children}</a>+ ),+}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++const { ChatSettingsSection } = await import('./chat-settings-section');++(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);+ for (const fn of [...Object.values(actions), ...Object.values(toast)]) fn.mockReset();+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++const flags = { alwaysCard: false, costCard: false, adminMayTurnOff: false };+const rows: PolicyRow[] = [+ {+ key: 'trackedPrompts',+ area: 'prompts',+ class: 'read',+ flags,+ policy: 'on',+ defaultPolicy: 'on',+ changed: false,+ choices: [],+ },+ {+ key: 'saveDraft',+ area: 'content',+ class: 'write',+ flags,+ policy: 'ask_full_auto',+ defaultPolicy: 'ask_full_auto',+ changed: false,+ choices: [+ { policy: 'never', locked: false },+ { policy: 'ask', locked: false },+ { policy: 'ask_full_auto', locked: true },+ { policy: 'always', locked: true },+ ],+ },+];+const view = (over: Partial<ChatSettingsView> = {}): ChatSettingsView => ({+ role: 'admin',+ plan: null,+ fullAutoLocked: null,+ fullAutoForMembers: true,+ dontAskAgain: true,+ managerExecuteOff: ['feeds'],+ rows,+ autoChoices: ['saveDraft'],+ ...over,+});++async function render() {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ChatSettingsSection />+ </NextIntlClientProvider>,+ );+ });+}+const text = () => container.textContent ?? '';+const button = (label: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === label);++describe('ChatSettingsSection', () => {+ it("lets an Admin pick a tool's policy, saved and read again", async () => {+ actions.getChatSettingsView.mockResolvedValue({ ok: true, view: view() });+ actions.setToolPolicy.mockResolvedValue({ ok: true });+ await render();+ expect(text()).toContain('Read tracked prompts');+ expect(text()).toContain('Runs freely');+ expect(text()).toContain('Auto in Full auto');+ expect(text()).not.toContain('create_draft');+ await act(async () => button('Never')!.click());+ expect(actions.setToolPolicy).toHaveBeenCalledWith('saveDraft', 'never');+ expect(toast.success).toHaveBeenCalledWith('Saved');+ expect(actions.getChatSettingsView).toHaveBeenCalledTimes(2);+ });++ it('switches a go-live group for Managers, and says why a save failed', async () => {+ actions.getChatSettingsView.mockResolvedValue({ ok: true, view: view() });+ actions.setManagerExecute.mockResolvedValue({ ok: false, failure: 'read_only' });+ await render();+ const feeds = container.querySelector('[role="switch"][aria-label="Product feeds"]')!;+ expect(feeds.getAttribute('aria-checked')).toBe('false');+ await act(async () => (feeds as HTMLButtonElement).click());+ expect(actions.setManagerExecute).toHaveBeenCalledWith('feeds', true);+ expect(toast.error).toHaveBeenCalledWith('This workspace is read-only until a plan is active.');+ });++ it('locks what the plan locks, and Full auto below Growth', async () => {+ actions.getChatSettingsView.mockResolvedValue({+ ok: true,+ view: view({ fullAutoLocked: 'growth', plan: null }),+ });+ await render();+ const always = button('Always') as HTMLButtonElement;+ expect(always.disabled).toBe(true);+ expect(always.title).toBe('Needs Growth');+ expect(container.querySelectorAll('[role="switch"][aria-label^="Full auto"]')).toHaveLength(0);+ expect(text()).toContain('Needs Growth · you');+ expect(text()).toContain('Card in every mode');+ });++ it('is read-only for anyone else, who still removes their own tick', async () => {+ actions.getChatSettingsView.mockResolvedValue({ ok: true, view: view({ role: 'manager' }) });+ actions.removeAutoChoice.mockResolvedValue({ ok: true });+ await render();+ expect(text()).toContain('Read-only · only Admins change the Chat tool policy');+ expect(container.querySelector('[role="radiogroup"]')).toBeNull();+ expect(container.querySelector('[role="switch"]')).toBeNull();+ expect(button('Reset to defaults')).toBeUndefined();+ await act(async () => button('Remove')!.click());+ expect(actions.removeAutoChoice).toHaveBeenCalledWith('saveDraft');+ expect(toast.success).toHaveBeenCalledWith('Removed: it asks again');+ });++ it('says so in plain words when it can’t be read, and reads again on Retry', async () => {+ actions.getChatSettingsView.mockResolvedValue({ ok: false, failure: 'failed' });+ await render();+ expect(text()).toContain("Couldn't load Chat's settings.");+ await act(async () => button('Retry')!.click());+ expect(actions.getChatSettingsView).toHaveBeenCalledTimes(2);+ });+});diff --git a/web/src/components/chat-access/chat-settings-section.tsx b/web/src/components/chat-access/chat-settings-section.tsxnew file mode 100644index 000000000..7f957f10f--- /dev/null+++ b/web/src/components/chat-access/chat-settings-section.tsx@@ -0,0 +1,414 @@+'use client';++import { Fragment, useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Info, Lock } from 'lucide-react';+import { toast } from 'sonner';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import {+ getChatSettingsView,+ removeAutoChoice,+ resetToolPolicies,+ setChatSwitch,+ setManagerExecute,+ setToolPolicy,+ type ChatSettingsView,+ type PolicyRow,+ type SettingsResult,+} from '@/lib/actions/chat-settings';+import { fullAutoBehaviour } from '@/lib/chat/access';+import { EXECUTE_GROUPS, type ToolArea } from '@/lib/chat/registry/define-tool';+import type { AdminPolicy } from '@/lib/chat/precedence';+import { cn } from '@/lib/utils';+import { ClassBadge } from './class-badge';+import { YourPlanCard } from './plan-card';+import { AskAdminButton } from './ask-admin-button';++const PRECEDENCE = ['hard', 'plan', 'role', 'policy', 'mode', 'dontAsk'] as const;++function Switch({+ checked,+ label,+ disabled,+ onChange,+}: {+ checked: boolean;+ label: string;+ disabled: boolean;+ onChange: (next: boolean) => void;+}) {+ return (+ <button+ type="button"+ role="switch"+ aria-checked={checked}+ aria-label={label}+ disabled={disabled}+ onClick={() => onChange(!checked)}+ className={cn(+ 'relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors disabled:cursor-not-allowed disabled:opacity-50',+ checked ? 'bg-primary' : 'bg-muted',+ )}+ >+ <span+ className={cn(+ 'pointer-events-none block h-3.5 w-3.5 rounded-full bg-background shadow-lg transition-transform',+ checked ? 'translate-x-4' : 'translate-x-0.5',+ )}+ />+ </button>+ );+}++/**+ * Settings › Chat (CHAT-20 §5, §8b; mockup #g-policy): the rules Chat+ * follows here. Everyone reads them; an Admin changes the workspace's, only+ * to what each tool and the plan allow; everyone removes their own "Don't+ * ask again" ticks. Tools go by their labels, never their names.+ */+export function ChatSettingsSection() {+ const t = useTranslations('chatAccess.settings');+ const tAccess = useTranslations('chatAccess');+ const tTools = useTranslations('chatTools');+ const tActions = useTranslations('readOnly.actions');+ // A read-only workspace opens the upgrade dialog instead, as Team does.+ const { guard } = useUpgradeGate();+ const [view, setView] = useState<ChatSettingsView | 'failed' | null>(null);+ const [version, setVersion] = useState(0);+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ let live = true;+ getChatSettingsView()+ .then((result) => {+ if (live) setView(result.ok ? result.view : 'failed');+ })+ .catch(() => {+ if (live) setView('failed');+ });+ return () => {+ live = false;+ };+ }, [version]);++ if (view === null) return <Skeleton className="h-96 w-full" />;+ if (view === 'failed') {+ return (+ <div role="status" className="space-y-2 text-sm text-muted-foreground">+ <p>{t('loadError')}</p>+ <Button size="sm" variant="outline" onClick={() => setVersion((n) => n + 1)}>+ {t('retry')}+ </Button>+ </div>+ );+ }++ const isAdmin = view.role === 'admin';+ const fullAutoOpen = view.fullAutoLocked === null;+ const current = view.plan?.planName ?? '';++ async function save(run: () => Promise<SettingsResult>, done = t('saved')) {+ setSaving(true);+ try {+ const result = await run();+ if (result.ok) toast.success(done);+ else toast.error(t(`failures.${result.failure}`));+ } catch {+ toast.error(t('failures.failed'));+ } finally {+ setSaving(false);+ setVersion((n) => n + 1);+ }+ }+ const change = (run: () => Promise<SettingsResult>, done?: string) =>+ guard(() => void save(run, done), { action: tActions('changeChatSettings') })();++ const byArea = new Map<ToolArea, PolicyRow[]>();+ for (const row of view.rows) byArea.set(row.area, [...(byArea.get(row.area) ?? []), row]);++ const policyLabel = (row: PolicyRow) => t(`policy.choices.${row.policy}`);++ return (+ <div className="space-y-6">+ {view.plan && <YourPlanCard plan={view.plan} isAdmin={isAdmin} />}++ <div className="space-y-1">+ <h2 className="text-lg font-semibold">{t('title')}</h2>+ <p className="text-sm text-muted-foreground">{t('lead')}</p>+ </div>++ {!isAdmin && (+ <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('readOnly')}</span>+ <span className="text-muted-foreground">{t('readOnlyNote')}</span>+ <span className="ml-auto">+ <AskAdminButton+ asked={tAccess('askAdmin.defaults.role')}+ ruleKind="policy"+ ruleDetail={t('readOnly')}+ />+ </span>+ </div>+ )}++ <section className="space-y-2">+ <h3 className="text-sm font-semibold">{t('switches.title')}</h3>+ <ul className="divide-y rounded-xl border">+ {(+ [+ ['fullAutoForMembers', 'fullAuto', view.fullAutoForMembers],+ ['dontAskAgain', 'dontAskAgain', view.dontAskAgain],+ ] as const+ ).map(([name, label, on]) => (+ <li key={name} 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">{t(`switches.${label}`)}</span>+ <span className="block text-xs text-muted-foreground">+ {t(`switches.${label}Note`)}+ </span>+ </span>+ {!fullAutoOpen ? (+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">+ <Lock className="h-3 w-3" aria-hidden />+ {t('switches.locked', { current })}+ </span>+ ) : isAdmin ? (+ <Switch+ checked={on}+ label={t(`switches.${label}`)}+ disabled={saving}+ onChange={(next) => change(() => setChatSwitch(name, next))}+ />+ ) : (+ <span className="text-xs font-medium">+ {on ? t('switches.on') : t('switches.off')}+ </span>+ )}+ </li>+ ))}+ {(['mcp', 'untrusted'] as const).map((key) => (+ <li key={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">{t(`switches.${key}`)}</span>+ <span className="block text-xs text-muted-foreground">+ {t(`switches.${key}Note`)}+ </span>+ </span>+ <span className="text-xs font-medium">{t(`switches.${key}Value`)}</span>+ </li>+ ))}+ </ul>+ </section>++ <section className="space-y-2">+ <div className="flex flex-wrap items-baseline gap-2">+ <h3 className="text-sm font-semibold">{t('precedence.title')}</h3>+ <span className="text-xs text-muted-foreground">{t('precedence.note')}</span>+ </div>+ <ol className="divide-y rounded-xl border">+ {PRECEDENCE.map((step, i) => (+ <li key={step} className="flex items-start gap-3 px-3.5 py-2 text-sm">+ <span className="w-4 shrink-0 text-xs text-muted-foreground tabular-nums">+ {i + 1}+ </span>+ <span>+ <span className="font-medium">{t(`precedence.steps.${step}.name`)}</span>+ <span className="block text-xs text-muted-foreground">+ {t(`precedence.steps.${step}.detail`)}+ </span>+ </span>+ </li>+ ))}+ </ol>+ </section>++ <section className="space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <h3 className="text-sm font-semibold">{t('policy.title')}</h3>+ {isAdmin && (+ <Button+ size="sm"+ variant="outline"+ className="ml-auto"+ disabled={saving || view.rows.every((row) => !row.changed)}+ onClick={() => change(resetToolPolicies, t('policy.resetDone'))}+ >+ {t('policy.reset')}+ </Button>+ )}+ </div>+ <div className="overflow-x-auto rounded-xl border">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{t('policy.columns.tool')}</TableHead>+ <TableHead>{t('policy.columns.class')}</TableHead>+ <TableHead>{t('policy.columns.policy')}</TableHead>+ <TableHead>{t('policy.columns.fullAuto')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {[...byArea].map(([area, rows]) => (+ <Fragment key={area}>+ <TableRow className="hover:bg-transparent">+ <TableCell+ colSpan={4}+ className="bg-muted/30 py-1.5 text-[11px] font-medium tracking-wide text-muted-foreground uppercase"+ >+ {tAccess(`capabilities.areaNames.${area}`)}+ </TableCell>+ </TableRow>+ {rows.map((row) => (+ <TableRow key={row.key}>+ <TableCell className="whitespace-normal">+ {tTools(`${row.key}.name`)}+ </TableCell>+ <TableCell>+ <ClassBadge cls={row.class} />+ </TableCell>+ <TableCell>+ {isAdmin && row.choices.length > 0 ? (+ <PolicyPicker+ row={row}+ disabled={saving}+ onPick={(policy) => change(() => setToolPolicy(row.key, policy))}+ />+ ) : (+ <span className="text-xs">{policyLabel(row)}</span>+ )}+ </TableCell>+ <TableCell className="text-xs text-muted-foreground">+ {t(`policy.behaviour.${fullAutoBehaviour(row, fullAutoOpen)}`)}+ </TableCell>+ </TableRow>+ ))}+ </Fragment>+ ))}+ </TableBody>+ </Table>+ </div>+ </section>++ <section className="space-y-2">+ <div className="space-y-0.5">+ <h3 className="text-sm font-semibold">{t('execute.title')}</h3>+ <p className="text-xs text-muted-foreground">{t('execute.note')}</p>+ </div>+ <ul className="divide-y rounded-xl border">+ {EXECUTE_GROUPS.map((group) => {+ const allowed = !view.managerExecuteOff.includes(group);+ return (+ <li key={group} className="flex items-center gap-3 px-3.5 py-2.5 text-sm">+ <span className="min-w-0 flex-1 font-medium">{t(`execute.groups.${group}`)}</span>+ {isAdmin ? (+ <Switch+ checked={allowed}+ label={t(`execute.groups.${group}`)}+ disabled={saving}+ onChange={(next) => change(() => setManagerExecute(group, next))}+ />+ ) : (+ <span className="text-xs font-medium">+ {allowed ? t('switches.on') : t('switches.off')}+ </span>+ )}+ </li>+ );+ })}+ </ul>+ </section>++ <section className="space-y-2">+ <div className="space-y-0.5">+ <h3 className="text-sm font-semibold">{t('autoChoices.title')}</h3>+ <p className="text-xs text-muted-foreground">{t('autoChoices.note')}</p>+ </div>+ {view.autoChoices.length === 0 ? (+ <p className="rounded-xl border px-3.5 py-3 text-sm text-muted-foreground">+ {t('autoChoices.empty')}+ </p>+ ) : (+ <ul className="divide-y rounded-xl border">+ {view.autoChoices.map((key) => (+ <li key={key} className="flex items-center gap-3 px-3.5 py-2 text-sm">+ <span className="min-w-0 flex-1">{tTools(`${key}.name`)}</span>+ <Button+ size="sm"+ variant="outline"+ disabled={saving}+ // Removing a tick takes a right back: open on a read-only workspace too.+ onClick={() => void save(() => removeAutoChoice(key), t('autoChoices.removed'))}+ >+ {t('autoChoices.remove')}+ </Button>+ </li>+ ))}+ </ul>+ )}+ </section>+ </div>+ );+}++/** An Admin's choice for one tool: its default first, then what the row offers. */+function PolicyPicker({+ row,+ disabled,+ onPick,+}: {+ row: PolicyRow;+ disabled: boolean;+ onPick: (policy: AdminPolicy | 'default') => void;+}) {+ const t = useTranslations('chatAccess.settings.policy');+ const options: { value: AdminPolicy | 'default'; label: string; locked: boolean }[] = [+ {+ value: 'default',+ label: `${t(`choices.${row.defaultPolicy}`)} · ${t('default')}`,+ locked: false,+ },+ ...row.choices+ .filter((choice) => choice.policy !== row.defaultPolicy)+ .map((choice) => ({+ value: choice.policy,+ label: t(`choices.${choice.policy}`),+ locked: choice.locked,+ })),+ ];+ const selected = row.changed ? row.policy : 'default';+ return (+ <div role="radiogroup" className="flex flex-wrap gap-1">+ {options.map((option) => (+ <button+ key={option.value}+ type="button"+ role="radio"+ aria-checked={selected === option.value}+ disabled={disabled || option.locked}+ title={option.locked ? t('lockedChoice') : undefined}+ onClick={() => selected !== option.value && onPick(option.value)}+ className={cn(+ 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50',+ selected === option.value+ ? 'border-foreground bg-foreground text-background'+ : 'text-muted-foreground hover:bg-muted',+ )}+ >+ {option.locked && <Lock className="h-3 w-3" aria-hidden />}+ {option.label}+ </button>+ ))}+ </div>+ );+}diff --git a/web/src/components/chat-access/requests-section.tsx b/web/src/components/chat-access/requests-section.tsxindex 727557b6e..cbc6f3cd7 100644--- a/web/src/components/chat-access/requests-section.tsx+++ b/web/src/components/chat-access/requests-section.tsx@@ -35,23 +35,40 @@ export function RequestsSection({}) {const t = useTranslations('chatAccess.requests');const format = useFormatter();- const [data, setData] = useState<{ isAdmin: boolean; requests: AccessRequest[] } | null>(null);+ const [data, setData] = useState<+ { isAdmin: boolean; requests: AccessRequest[] } | 'failed' | 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);+ .then((read) => {+ if (!live) return;+ if (read.ok) setData({ isAdmin: read.isAdmin, requests: read.requests });+ // Chat off: nothing to list; a failed read says so.+ else setData(read.failure === 'failed' ? 'failed' : null);})- .catch(() => {});+ .catch(() => {+ if (live) setData('failed');+ });return () => {live = false;};}, [version, reload]);if (!data) return null;+ if (data === 'failed') {+ return (+ <div role="status" className="flex items-center gap-2 text-sm text-muted-foreground">+ <span>{t('loadError')}</span>+ <Button size="sm" variant="outline" onClick={() => setReload((n) => n + 1)}>+ {t('retry')}+ </Button>+ </div>+ );+ }const pending = data.requests.filter((r) => r.status === 'pending').length;async function act(id: string, run: () => Promise<boolean>, done: string) {diff --git a/web/src/components/chat-access/roles-access-section.tsx b/web/src/components/chat-access/roles-access-section.tsxindex dc39352bd..f17e804ae 100644--- a/web/src/components/chat-access/roles-access-section.tsx+++ b/web/src/components/chat-access/roles-access-section.tsx@@ -7,6 +7,7 @@ import { toast } from 'sonner';import { Link } from '@/i18n/navigation';import { Skeleton } from '@/components/ui/skeleton';import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';import {Select,SelectContent,@@ -64,10 +65,14 @@ export function RolesAccessSection({useEffect(() => {let live = true;Promise.all([getChatAccess(), listRoleMembers()])- .then(([nextAccess, nextMembers]) => {+ .then(([accessRead, membersRead]) => {if (!live) return;- setAccess(nextAccess);- setMembers(nextMembers);+ if (!accessRead.ok || !membersRead.ok) {+ setAccess('failed');+ return;+ }+ setAccess(accessRead.access);+ setMembers(membersRead.members);}).catch(() => {if (live) setAccess('failed');@@ -81,9 +86,12 @@ export function RolesAccessSection({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>+ <div role="status" className="space-y-2 text-sm text-muted-foreground">+ <p>{t('roles.loadError')}</p>+ <Button size="sm" variant="outline" onClick={reload}>+ {t('roles.retry')}+ </Button>+ </div>);}diff --git a/web/src/components/chat-access/your-access-card.tsx b/web/src/components/chat-access/your-access-card.tsxindex 9a2138112..d6e1aeafc 100644--- a/web/src/components/chat-access/your-access-card.tsx+++ b/web/src/components/chat-access/your-access-card.tsx@@ -94,8 +94,8 @@ export function YourAccessSlot({ className }: { className?: string }) {useEffect(() => {let live = true;getChatAccess()- .then((next) => {- if (live) setAccess(next);+ .then((read) => {+ if (live && read.ok) setAccess(read.access);}).catch(() => {});return () => {diff --git a/web/src/lib/actions/chat-access-requests.test.ts b/web/src/lib/actions/chat-access-requests.test.tsindex 44fa41d8c..f0a3d6de1 100644--- a/web/src/lib/actions/chat-access-requests.test.ts+++ b/web/src/lib/actions/chat-access-requests.test.ts@@ -251,8 +251,9 @@ describe('listAccessRequests and countPendingAccessRequests', () => {? { 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([+ if (!listed.ok) throw new Error('expected a list');+ 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'],]);@@ -269,8 +270,19 @@ describe('listAccessRequests and countPendingAccessRequests', () => {it('counts the waiting requests for an Admin only', async () => {answers['chat_access_requests.count'] = { count: 3, error: null };- expect(await countPendingAccessRequests()).toBe(0);+ expect(await countPendingAccessRequests()).toEqual({ ok: true, count: 0 });role = 'admin';- expect(await countPendingAccessRequests()).toBe(3);+ expect(await countPendingAccessRequests()).toEqual({ ok: true, count: 3 });+ });++ it('answers a failed read in its result, never by throwing (#1777)', async () => {+ role = 'admin';+ answers['chat_access_requests.select'] = { data: null, error: { message: 'db down' } };+ answers['chat_access_requests.count'] = { count: null, error: { message: 'db down' } };+ expect(await listAccessRequests()).toEqual({ ok: false, failure: 'failed' });+ expect(await countPendingAccessRequests()).toEqual({ ok: false, failure: 'failed' });+ vi.stubEnv('CHAT_AGENTIC', 'false');+ expect(await listAccessRequests()).toEqual({ ok: false, failure: 'chat_off' });+ expect(await countPendingAccessRequests()).toEqual({ ok: false, failure: 'chat_off' });});});diff --git a/web/src/lib/actions/chat-access-requests.ts b/web/src/lib/actions/chat-access-requests.tsindex ef00aceb3..5811d827e 100644--- a/web/src/lib/actions/chat-access-requests.ts+++ b/web/src/lib/actions/chat-access-requests.ts@@ -195,11 +195,27 @@ export async function decideAccessRequest(return (data ?? []).length > 0;}+/** Why a read gave nothing: Chat is off for the person, or the database didn't answer. */+export type RequestsReadFailure = 'chat_off' | 'failed';+/*** The requests a person sees: an Admin, the workspace's; anyone else, their- * own. Pending first, then the decided ones of the last weeks.+ * own. Pending first, then the decided ones of the last weeks. Never throws+ * (#1777): a failed read is `failed`.*/-export async function listAccessRequests(): Promise<{+export async function listAccessRequests(): Promise<+ | { ok: true; isAdmin: boolean; requests: AccessRequest[] }+ | { ok: false; failure: RequestsReadFailure }+> {+ try {+ const read = await readAccessRequests();+ return read ? { ok: true, ...read } : { ok: false, failure: 'chat_off' };+ } catch {+ return { ok: false, failure: 'failed' };+ }+}++async function readAccessRequests(): Promise<{isAdmin: boolean;requests: AccessRequest[];} | null> {@@ -249,15 +265,24 @@ export async function listAccessRequests(): Promise<{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;+/**+ * How many requests wait for an Admin: the count on Roles & access, 0 for+ * anyone else. Never throws, as above.+ */+export async function countPendingAccessRequests(): Promise<+ { ok: true; count: number } | { ok: false; failure: RequestsReadFailure }+> {+ try {+ const who = await member();+ if (!who) return { ok: false, failure: 'chat_off' };+ if (who.role !== 'admin') return { ok: true, count: 0 };+ const { count, error } = await supabaseAdmin+ .from('chat_access_requests')+ .select('id', { count: 'exact', head: true })+ .eq('organization_id', who.organizationId)+ .eq('status', 'pending');+ return error ? { ok: false, failure: 'failed' } : { ok: true, count: count ?? 0 };+ } catch {+ return { ok: false, failure: 'failed' };+ }}diff --git a/web/src/lib/actions/chat-access.test.ts b/web/src/lib/actions/chat-access.test.tsnew file mode 100644index 000000000..66d9dd016--- /dev/null+++ b/web/src/lib/actions/chat-access.test.ts@@ -0,0 +1,90 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/** Roles & access and Your access reads: a failure in the result, never thrown (#1777). */++const ME = '11111111-1111-4111-8111-111111111111';+const ORG = '22222222-2222-4222-8222-222222222222';++let profilesError: { message: string } | null = null;+let ctxThrows = false;++function from(table: string) {+ let listing = false;+ const chain: Record<string, unknown> = {+ select: () => chain,+ eq: () => chain,+ order: () => {+ listing = true;+ return chain;+ },+ maybeSingle: async () =>+ table === 'profiles'+ ? { data: { organization_id: ORG }, error: null }+ : { data: null, error: null },+ then: (resolve: (value: unknown) => unknown) =>+ Promise.resolve(+ listing+ ? {+ data: profilesError ? null : [{ id: ME, full_name: 'Alex', role: 'admin' }],+ error: profilesError,+ }+ : { data: null, error: null },+ ).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 () => new Map([[ME, { email: '[email protected]', lastSignInAt: null }]]),+}));+vi.mock('@/lib/chat/precedence-context', () => ({+ readPrecedenceContext: async () => {+ if (ctxThrows) throw new Error('db down');+ return null;+ },+}));++const { getChatAccess, listRoleMembers } = await import('./chat-access');++beforeEach(() => {+ vi.stubEnv('CHAT_AGENTIC', 'true');+ profilesError = null;+ ctxThrows = false;+});+afterEach(() => vi.unstubAllEnvs());++describe('getChatAccess', () => {+ it('says the read failed rather than throwing, and Chat off apart', async () => {+ ctxThrows = true;+ expect(await getChatAccess()).toEqual({ ok: false, failure: 'failed' });+ ctxThrows = false;+ // No context: the person isn't a member of the workspace now.+ expect(await getChatAccess()).toEqual({ ok: false, failure: 'chat_off' });+ vi.stubEnv('CHAT_AGENTIC', 'false');+ expect(await getChatAccess()).toEqual({ ok: false, failure: 'chat_off' });+ });+});++describe('listRoleMembers', () => {+ it('lists the members, and a failed read as failed', async () => {+ expect(await listRoleMembers()).toEqual({+ ok: true,+ members: [+ {+ userId: ME,+ name: 'Alex',+ email: '[email protected]',+ role: 'admin',+ lastActiveAt: null,+ isYou: true,+ },+ ],+ });+ profilesError = { message: 'db down' };+ expect(await listRoleMembers()).toEqual({ ok: false, failure: 'failed' });+ });+});diff --git a/web/src/lib/actions/chat-access.ts b/web/src/lib/actions/chat-access.tsindex df5cbc20e..65c08b200 100644--- a/web/src/lib/actions/chat-access.ts+++ b/web/src/lib/actions/chat-access.ts@@ -66,8 +66,25 @@ async function viewer(): Promise<{ userId: string; organizationId: string } | nureturn { 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> {+/** Why a read gave nothing: Chat is off for the person, or the database didn't answer. */+export type AccessReadFailure = 'chat_off' | 'failed';++/**+ * The signed-in person's access and plan card. Never throws (#1777): a+ * failed read is `failed`, Chat off for them `chat_off`.+ */+export async function getChatAccess(): Promise<+ { ok: true; access: ChatAccess } | { ok: false; failure: AccessReadFailure }+> {+ try {+ const access = await readChatAccess();+ return access ? { ok: true, access } : { ok: false, failure: 'chat_off' };+ } catch {+ return { ok: false, failure: 'failed' };+ }+}++async function readChatAccess(): Promise<ChatAccess | null> {const who = await viewer();if (!who) return null;const [ctx, settings] = await Promise.all([@@ -111,11 +128,22 @@ export async function getChatAccess(): Promise<ChatAccess | null> {/*** 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.+ * by the part of their e-mail before the @. Never throws, as above.*/-export async function listRoleMembers(): Promise<RoleMember[]> {+export async function listRoleMembers(): Promise<+ { ok: true; members: RoleMember[] } | { ok: false; failure: AccessReadFailure }+> {+ try {+ const members = await readRoleMembers();+ return members ? { ok: true, members } : { ok: false, failure: 'chat_off' };+ } catch {+ return { ok: false, failure: 'failed' };+ }+}++async function readRoleMembers(): Promise<RoleMember[] | null> {const who = await viewer();- if (!who) return [];+ if (!who) return null;const { data, error } = await supabaseAdmin.from('profiles').select('id, full_name, role, created_at')diff --git a/web/src/lib/actions/chat-settings.test.ts b/web/src/lib/actions/chat-settings.test.tsnew file mode 100644index 000000000..9bf01192b--- /dev/null+++ b/web/src/lib/actions/chat-settings.test.ts@@ -0,0 +1,214 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { PrecedenceContext } from '@/lib/chat/precedence';++/** Settings › Chat (CHAT-20 §5, §8b): the policy an Admin sets, within each tool and the plan. */++const ME = '11111111-1111-4111-8111-111111111111';+const ORG = '22222222-2222-4222-8222-222222222222';++interface Call {+ table: string;+ op: string;+ row?: unknown;+ opts?: unknown;+ filters: unknown[][];+}+let calls: Call[] = [];+let writeError: { message: string } | null = null;+let ctx: PrecedenceContext | null = null;+let ctxThrows = false;++function from(table: string) {+ const call: Call = { table, op: 'select', filters: [] };+ calls.push(call);+ const answer = () =>+ table === 'profiles'+ ? { data: { organization_id: ORG }, error: null }+ : { data: null, error: call.op === 'select' ? null : writeError };+ const chain: Record<string, unknown> = {+ select: () => chain,+ upsert: (row: unknown, opts: unknown) =>+ Object.assign(call, { op: 'upsert', row, opts }) && chain,+ delete: () => Object.assign(call, { op: 'delete' }) && chain,+ eq: (...args: unknown[]) => {+ call.filters.push(['eq', ...args]);+ return chain;+ },+ 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/chat/precedence-context', () => ({+ readPrecedenceContext: async () => {+ if (ctxThrows) throw new Error('db down');+ return ctx;+ },+}));++const {+ getChatSettingsView,+ removeAutoChoice,+ resetToolPolicies,+ setChatSwitch,+ setManagerExecute,+ setToolPolicy,+} = await import('./chat-settings');+const { DEFAULT_CHAT_SETTINGS } = await import('@/lib/chat/precedence');+const { planFactsFromOrgRow } = await import('@/lib/chat/plan-facts');++function context(+ plan: string,+ role: PrecedenceContext['role'] = 'admin',+ settings: Partial<PrecedenceContext['settings']> = {},+): PrecedenceContext {+ return {+ organizationId: ORG,+ role,+ plan: planFactsFromOrgRow({ plan, subscription_status: 'active' }),+ settings: { ...DEFAULT_CHAT_SETTINGS, ...settings },+ mode: 'ask_first',+ surface: 'chat',+ autoChoices: new Set(['saveDraft', 'goneTool']),+ brandAccess: 'all',+ injectionDetected: false,+ };+}+const upsert = () => calls.find((c) => c.op === 'upsert');++beforeEach(() => {+ vi.stubEnv('CHAT_AGENTIC', 'true');+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ calls = [];+ writeError = null;+ ctxThrows = false;+ ctx = context('growth');+});+afterEach(() => vi.unstubAllEnvs());++describe('getChatSettingsView', () => {+ it('lists every tool by its label key, with what an Admin may pick and the plan locks', async () => {+ ctx = context('starter', 'manager', { toolPolicies: { saveDraft: 'ask' } });+ const result = await getChatSettingsView();+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ const { view } = result;+ expect(view).toMatchObject({ role: 'manager', fullAutoLocked: 'growth' });+ expect(JSON.stringify(view.rows)).not.toMatch(/create_draft|get_profile/);+ const draft = view.rows.find((r) => r.key === 'saveDraft')!;+ expect(draft).toMatchObject({ class: 'write', policy: 'ask', changed: true });+ expect(draft.choices).toEqual([+ { policy: 'never', locked: false },+ { policy: 'ask', locked: false },+ { policy: 'ask_full_auto', locked: true },+ { policy: 'always', locked: true },+ ]);+ // Ask your Admin is a card in every mode: never Always.+ expect(view.rows.find((r) => r.key === 'askAdmin')!.choices.map((c) => c.policy)).toEqual([+ 'never',+ 'ask',+ ]);+ // A tick on a tool the registry no longer has isn't listed.+ expect(view.autoChoices).toEqual(['saveDraft']);+ });++ it('says it failed, never throws, when the facts can’t be read', async () => {+ ctxThrows = true;+ expect(await getChatSettingsView()).toEqual({ ok: false, failure: 'failed' });+ vi.stubEnv('CHAT_AGENTIC', 'false');+ expect(await getChatSettingsView()).toEqual({ ok: false, failure: 'chat_off' });+ });+});++describe('setToolPolicy', () => {+ it("saves an Admin's choice, keeping the other settings, and who made it", async () => {+ ctx = context('growth', 'admin', {+ toolPolicies: { dismissSuggestion: 'never' },+ managerExecuteOff: ['feeds'],+ });+ expect(await setToolPolicy('saveDraft', 'always')).toEqual({ ok: true });+ expect(upsert()).toMatchObject({+ table: 'chat_settings',+ row: {+ organization_id: ORG,+ tool_policies: { dismissSuggestion: 'never', saveDraft: 'always' },+ full_auto_for_members: true,+ dont_ask_again: true,+ manager_execute_off: ['feeds'],+ updated_by: ME,+ },+ opts: { onConflict: 'organization_id' },+ });+ });++ it('gives a tool back its default', async () => {+ ctx = context('growth', 'admin', { toolPolicies: { saveDraft: 'never' } });+ await setToolPolicy('saveDraft', 'default');+ expect((upsert()!.row as { tool_policies: object }).tool_policies).toEqual({});+ });++ it("refuses what the row doesn't offer, an unknown tool, and what the plan locks", async () => {+ expect(await setToolPolicy('askAdmin', 'always')).toEqual({ ok: false, failure: 'invalid' });+ expect(await setToolPolicy('create_draft', 'never')).toEqual({ ok: false, failure: 'invalid' });+ ctx = context('starter');+ expect(await setToolPolicy('saveDraft', 'ask_full_auto')).toEqual({+ ok: false,+ failure: 'locked',+ });+ expect(upsert()).toBeUndefined();+ });++ it('is an Admin’s, on an active plan', async () => {+ ctx = context('growth', 'manager');+ expect(await setToolPolicy('saveDraft', 'never')).toEqual({ ok: false, failure: 'forbidden' });+ ctx = { ...context('growth'), plan: { ...context('growth').plan, writable: false } };+ expect(await resetToolPolicies()).toEqual({ ok: false, failure: 'read_only' });+ expect(upsert()).toBeUndefined();+ });++ it('says the save failed, never throws', async () => {+ writeError = { message: 'db down' };+ expect(await setToolPolicy('saveDraft', 'never')).toEqual({ ok: false, failure: 'failed' });+ });+});++describe('the switches and the ticks', () => {+ it('keeps Full auto and "Don\'t ask again" to Growth and up', async () => {+ ctx = context('starter');+ expect(await setChatSwitch('dontAskAgain', false)).toEqual({ ok: false, failure: 'locked' });+ ctx = context('growth');+ expect(await setChatSwitch('fullAutoForMembers', false)).toEqual({ ok: true });+ expect(upsert()!.row).toMatchObject({ full_auto_for_members: false });+ });++ it("switches a go-live group for Managers, in the groups' order", async () => {+ ctx = context('growth', 'admin', { managerExecuteOff: ['feeds'] });+ await setManagerExecute('publishing', false);+ expect(upsert()!.row).toMatchObject({ manager_execute_off: ['publishing', 'feeds'] });+ calls = [];+ await setManagerExecute('feeds', true);+ expect(upsert()!.row).toMatchObject({ manager_execute_off: [] });+ expect(await setManagerExecute('nope' as never, true)).toEqual({+ ok: false,+ failure: 'invalid',+ });+ });++ it("removes only the person's own tick, whatever their role", async () => {+ ctx = context('starter', 'analyst');+ expect(await removeAutoChoice('saveDraft')).toEqual({ ok: true });+ const removed = calls.find((c) => c.op === 'delete')!;+ expect(removed.table).toBe('chat_auto_choices');+ expect(removed.filters).toEqual([+ ['eq', 'user_id', ME],+ ['eq', 'organization_id', ORG],+ ['eq', 'tool_key', 'saveDraft'],+ ]);+ expect(await removeAutoChoice('Bad Key')).toEqual({ ok: false, failure: 'invalid' });+ });+});diff --git a/web/src/lib/actions/chat-settings.ts b/web/src/lib/actions/chat-settings.tsnew file mode 100644index 000000000..61eba0425--- /dev/null+++ b/web/src/lib/actions/chat-settings.ts@@ -0,0 +1,270 @@+'use server';++import { createClient } from '@/lib/supabase/server';+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { TeamRole } from '@/components/providers/role-provider';+import { chatAgenticEnabled } from '@/lib/chat/flag';+import { readPrecedenceContext } from '@/lib/chat/precedence-context';+import {+ ADMIN_POLICIES,+ effectivePolicy,+ policyChoiceLock,+ policyChoices,+ type AdminPolicy,+ type ChatSettings,+ type PrecedenceContext,+} from '@/lib/chat/precedence';+import { CHAT_TOOLS, chatToolByKey } from '@/lib/chat/registry/tools';+import {+ EXECUTE_GROUPS,+ type ExecuteGroup,+ type ToolArea,+ type ToolClass,+ type ToolFlags,+ type ToolPolicy,+} from '@/lib/chat/registry/define-tool';+import { planCardOf, type PlanCard } from '@/lib/chat/access';++/**+ * Settings › Chat (CHAT-20 §5, §8b; mockup #g-policy), behind CHAT_AGENTIC:+ * the tool policy per tool, Full auto for members, "Don't ask again", the+ * go-live groups Managers may click through, and the person's own "Don't+ * ask again" ticks. Everyone reads the rules Chat follows for them; only an+ * Admin changes the workspace's, and only within what each tool and the+ * plan allow (policyChoices, policyChoiceLock), checked here again. The+ * person removes their own ticks.+ *+ * Every action answers { ok } and never throws for a refusal or an+ * unreachable database (#1777): the page says what happened in plain words.+ */++export type SettingsFailure =+ | 'chat_off'+ | 'forbidden'+ | 'invalid'+ | 'locked'+ | 'read_only'+ | 'failed';+export type SettingsResult = { ok: true } | { ok: false; failure: SettingsFailure };++/** A tool as Settings › Chat lists it: by its label key, never its name. */+export interface PolicyRow {+ key: string;+ area: ToolArea;+ class: ToolClass;+ flags: ToolFlags;+ /** What applies now: the Admin's choice, else the row's default. */+ policy: ToolPolicy;+ defaultPolicy: ToolPolicy;+ /** Set by an Admin, not the default. */+ changed: boolean;+ /** What an Admin may pick besides the default, and which the plan locks. */+ choices: { policy: AdminPolicy; locked: boolean }[];+}++export interface ChatSettingsView {+ role: TeamRole;+ plan: PlanCard | null;+ /** Full auto and "Don't ask again" need Growth: the plan, when this workspace's lacks it. */+ fullAutoLocked: 'growth' | null;+ fullAutoForMembers: boolean;+ dontAskAgain: boolean;+ managerExecuteOff: ExecuteGroup[];+ rows: PolicyRow[];+ /** The person's own "Don't ask again" ticks, by label key. */+ autoChoices: string[];+}++interface Who {+ userId: string;+ organizationId: string;+ ctx: PrecedenceContext;+}++async function who(): Promise<Who | 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;+ const ctx = await readPrecedenceContext({+ userId: user.id,+ organizationId,+ mode: 'ask_first',+ surface: 'chat',+ });+ return ctx ? { userId: user.id, organizationId, ctx } : null;+}++function rowsOf(ctx: PrecedenceContext): PolicyRow[] {+ return CHAT_TOOLS.map((tool) => ({+ key: tool.labelKey,+ area: tool.area,+ class: tool.class,+ flags: { ...tool.flags },+ policy: effectivePolicy(tool, ctx.settings),+ defaultPolicy: tool.defaultPolicy,+ changed: tool.labelKey in ctx.settings.toolPolicies,+ choices: policyChoices(tool).map((policy) => ({+ policy,+ locked: policyChoiceLock(ctx.plan, policy) !== null,+ })),+ }));+}++/** The page's facts for the signed-in person; null while Chat is off or the read fails. */+export async function getChatSettingsView(): Promise<+ { ok: true; view: ChatSettingsView } | { ok: false; failure: 'chat_off' | 'failed' }+> {+ try {+ const me = await who();+ if (!me) return { ok: false, failure: 'chat_off' };+ const { ctx } = me;+ return {+ ok: true,+ view: {+ role: ctx.role,+ plan: planCardOf(ctx.plan),+ fullAutoLocked: ctx.plan.fullAuto ? null : 'growth',+ fullAutoForMembers: ctx.settings.fullAutoForMembers,+ dontAskAgain: ctx.settings.dontAskAgain,+ managerExecuteOff: [...ctx.settings.managerExecuteOff],+ rows: rowsOf(ctx),+ autoChoices: [...ctx.autoChoices].filter((key) => chatToolByKey(key)),+ },+ };+ } catch {+ return { ok: false, failure: 'failed' };+ }+}++/** The settings an Admin may change, read and checked; a failure otherwise. */+async function asAdmin(): Promise<{ ok: true; me: Who } | { ok: false; failure: SettingsFailure }> {+ const me = await who();+ if (!me) return { ok: false, failure: 'chat_off' };+ if (me.ctx.role !== 'admin') return { ok: false, failure: 'forbidden' };+ if (!me.ctx.plan.writable) return { ok: false, failure: 'read_only' };+ return { ok: true, me };+}++/** Writes the workspace's row with what changed, keeping the rest, and who changed it. */+async function saveSettings(me: Who, next: Partial<ChatSettings>): Promise<SettingsResult> {+ const settings = { ...me.ctx.settings, ...next };+ const { error } = await supabaseAdmin.from('chat_settings').upsert(+ {+ organization_id: me.organizationId,+ tool_policies: { ...settings.toolPolicies },+ full_auto_for_members: settings.fullAutoForMembers,+ dont_ask_again: settings.dontAskAgain,+ manager_execute_off: [...settings.managerExecuteOff],+ updated_by: me.userId,+ },+ { onConflict: 'organization_id' },+ );+ return error ? { ok: false, failure: 'failed' } : { ok: true };+}++/**+ * Sets a tool's policy, or `default` to give it back its row's default. Only+ * a choice the row offers and the plan allows.+ */+export async function setToolPolicy(+ key: string,+ policy: AdminPolicy | 'default',+): Promise<SettingsResult> {+ try {+ const admin = await asAdmin();+ if (!admin.ok) return admin;+ const tool = chatToolByKey(key);+ if (!tool) return { ok: false, failure: 'invalid' };+ const toolPolicies = { ...admin.me.ctx.settings.toolPolicies };+ if (policy === 'default') {+ delete toolPolicies[key];+ } else {+ if (!ADMIN_POLICIES.includes(policy) || !policyChoices(tool).includes(policy)) {+ return { ok: false, failure: 'invalid' };+ }+ if (policyChoiceLock(admin.me.ctx.plan, policy)) return { ok: false, failure: 'locked' };+ toolPolicies[key] = policy;+ }+ return await saveSettings(admin.me, { toolPolicies });+ } catch {+ return { ok: false, failure: 'failed' };+ }+}++/** Every tool back to its row's default. */+export async function resetToolPolicies(): Promise<SettingsResult> {+ try {+ const admin = await asAdmin();+ if (!admin.ok) return admin;+ return await saveSettings(admin.me, { toolPolicies: {} });+ } catch {+ return { ok: false, failure: 'failed' };+ }+}++/** Full auto for people other than Admins, or "Don't ask again" (both Growth and up). */+export async function setChatSwitch(+ name: 'fullAutoForMembers' | 'dontAskAgain',+ on: boolean,+): Promise<SettingsResult> {+ try {+ const admin = await asAdmin();+ if (!admin.ok) return admin;+ if (name !== 'fullAutoForMembers' && name !== 'dontAskAgain') {+ return { ok: false, failure: 'invalid' };+ }+ // Both are Growth and up (CHAT-20 §7): below it, neither applies.+ if (!admin.me.ctx.plan.fullAuto) return { ok: false, failure: 'locked' };+ return await saveSettings(admin.me, { [name]: on === true });+ } catch {+ return { ok: false, failure: 'failed' };+ }+}++/** Whether Managers may click through a go-live group (CHAT-20 §4). */+export async function setManagerExecute(+ group: ExecuteGroup,+ allowed: boolean,+): Promise<SettingsResult> {+ try {+ const admin = await asAdmin();+ if (!admin.ok) return admin;+ if (!EXECUTE_GROUPS.includes(group)) return { ok: false, failure: 'invalid' };+ const off = new Set(admin.me.ctx.settings.managerExecuteOff);+ if (allowed) off.delete(group);+ else off.add(group);+ // In the switches' order, as the column keeps them distinct.+ return await saveSettings(admin.me, {+ managerExecuteOff: EXECUTE_GROUPS.filter((g) => off.has(g)),+ });+ } catch {+ return { ok: false, failure: 'failed' };+ }+}++/** Removes one of the person's own "Don't ask again" ticks. */+export async function removeAutoChoice(key: string): Promise<SettingsResult> {+ try {+ const me = await who();+ if (!me) return { ok: false, failure: 'chat_off' };+ if (!/^[a-z][A-Za-z0-9]{1,63}$/.test(key)) return { ok: false, failure: 'invalid' };+ const { error } = await supabaseAdmin+ .from('chat_auto_choices')+ .delete()+ .eq('user_id', me.userId)+ .eq('organization_id', me.organizationId)+ .eq('tool_key', key);+ return error ? { ok: false, failure: 'failed' } : { ok: true };+ } catch {+ return { ok: false, failure: 'failed' };+ }+}diff --git a/web/src/lib/chat/access.test.ts b/web/src/lib/chat/access.test.tsindex f35da97c4..7a3a22d45 100644--- a/web/src/lib/chat/access.test.ts+++ b/web/src/lib/chat/access.test.ts@@ -5,6 +5,7 @@ import {ROLE_ORDER,approvalMark,capabilityAreas,+ fullAutoBehaviour,planCardOf,rolesFor,yourAccessRows,@@ -227,3 +228,26 @@ describe('the registry as "What Chat can do" shows it', () => {expect(prompts.writers).not.toContain('agency_partner');});});++describe('fullAutoBehaviour', () => {+ const row = (cls: 'read' | 'write' | 'execute', policy: string, alwaysCard = false) => ({+ class: cls,+ policy: policy as never,+ flags: { alwaysCard },+ });++ it('says what each tool does in Full auto, by its class and policy', () => {+ expect(fullAutoBehaviour(row('read', 'on'), true)).toBe('runs');+ expect(fullAutoBehaviour(row('read', 'never'), true)).toBe('off');+ expect(fullAutoBehaviour(row('execute', 'click'), true)).toBe('click');+ expect(fullAutoBehaviour(row('write', 'ask'), true)).toBe('card');+ expect(fullAutoBehaviour(row('write', 'ask', true), true)).toBe('always_card');+ expect(fullAutoBehaviour(row('write', 'ask_full_auto'), true)).toBe('auto_full_auto');+ expect(fullAutoBehaviour(row('write', 'always'), true)).toBe('auto_always');+ });++ it('asks for every WRITE below Growth, where Full auto is closed', () => {+ expect(fullAutoBehaviour(row('write', 'always'), false)).toBe('card');+ expect(fullAutoBehaviour(row('write', 'ask_full_auto'), false)).toBe('card');+ });+});diff --git a/web/src/lib/chat/access.ts b/web/src/lib/chat/access.tsindex 3078c0202..00c671d77 100644--- a/web/src/lib/chat/access.ts+++ b/web/src/lib/chat/access.ts@@ -331,3 +331,33 @@ export function capabilityAreas(catalog: readonly ToolCatalogEntry[]): Capabilit}return [...areas.values()];}++/**+ * What a tool does in Full auto, as Settings › Chat's last column says it+ * (mockup #g-policy): a read runs, an EXECUTE waits for the click, a WRITE+ * by its policy. Below Growth, Full auto isn't open: a WRITE always asks.+ */+export type FullAutoBehaviour =+ | 'off'+ | 'runs'+ | 'click'+ | 'card'+ | 'always_card'+ | 'auto_full_auto'+ | 'auto_always';++export function fullAutoBehaviour(+ row: {+ class: ToolClass;+ policy: ToolPolicy;+ flags: Pick<ToolCatalogEntry['flags'], 'alwaysCard'>;+ },+ fullAutoOpen: boolean,+): FullAutoBehaviour {+ if (row.policy === 'never') return 'off';+ if (row.class === 'read') return 'runs';+ if (row.class === 'execute') return 'click';+ if (row.flags.alwaysCard) return 'always_card';+ if (!fullAutoOpen || row.policy === 'ask') return 'card';+ return row.policy === 'always' ? 'auto_always' : 'auto_full_auto';+}diff --git a/web/src/lib/subscription-guard-coverage.test.ts b/web/src/lib/subscription-guard-coverage.test.tsindex b793456a7..958fa4164 100644--- a/web/src/lib/subscription-guard-coverage.test.ts+++ b/web/src/lib/subscription-guard-coverage.test.ts@@ -59,6 +59,14 @@ const OPEN_ACTIONS: Record<string, string> = {'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",+ // Chat's settings (Admins): asAdmin() checks the plan itself (ctx.plan.writable,+ // as assertWritable) to answer read_only as a result instead of throwing.+ 'chat-settings.ts:setToolPolicy': 'checks ctx.plan.writable itself, answering read_only',+ 'chat-settings.ts:resetToolPolicies': 'checks ctx.plan.writable itself, answering read_only',+ 'chat-settings.ts:setChatSwitch': 'checks ctx.plan.writable itself, answering read_only',+ 'chat-settings.ts:setManagerExecute': 'checks ctx.plan.writable itself, answering read_only',+ 'chat-settings.ts:removeAutoChoice':+ "removes the person's own Don't ask again tick: takes an auto-approval back, never gives one",};/** Actions that take a brand's own id under another name: file:function → the parameter. */