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(web): let a workspace whose plan ended browse read-only, with one "Choose a plan" dialog (#1599)
Cihan7e6489291df7
diff --git a/web/messages/en.json b/web/messages/en.jsonindex ab9a59a5a..04729a1a6 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4,13 +4,15 @@"workspace": "This brand isn't in your workspace. Switch to one of your brands.","not_found": "This no longer exists. Reload the page and start again.","plan": "Your plan doesn't include this. Upgrade to use it.",+ "subscription": "Your workspace's plan isn't active, so changes are paused. Choose a plan to use Ansvisor again.","limit": "You've used this month's allowance. Upgrade, or wait until it resets.","busy": "Too many requests. Wait a minute and try again.","failed": "Something went wrong. Try again.","signIn": "Sign in","yourBrands": "Your brands","reload": "Reload",- "upgrade": "Upgrade"+ "upgrade": "Upgrade",+ "choosePlan": "Choose a plan"},"aiUsage": {"meter": {@@ -53,6 +55,33 @@"exhaustedTrial": "You've used the free trial's AI usage. Starting the plan gives its full monthly allowance; Agent Chat on your own AI key keeps working."}},+ "readOnly": {+ "banner": {+ "ended": "Your workspace is read-only. You can look around; adding, running and AI need a plan.",+ "payment_failed": "Your last payment didn't go through, so your workspace is read-only. You can look around; adding, running and AI need the payment method updated.",+ "seePlans": "See plans"+ },+ "dialog": {+ "title": {+ "ended": "Choose a plan to keep going",+ "payment_failed": "Update your payment method to keep going"+ },+ "body": {+ "ended": "Your workspace has no active plan, so it's read-only. Everything you set up is still here: pick a plan to track, write and run your agents again.",+ "payment_failed": "Your last payment didn't go through, so your workspace is read-only. Everything you set up is still here: update the payment method to track, write and run your agents again."+ },+ "notNow": "Not now"+ },+ "ask": {+ "ended": "Ask your workspace admin to choose a plan.",+ "endedNamed": "Ask {name}, your workspace admin, to choose a plan.",+ "payment_failed": "Ask your workspace admin to update the payment method.",+ "payment_failedNamed": "Ask {name}, your workspace admin, to update the payment method."+ },+ "choosePlan": "Choose a plan",+ "updatePayment": "Update payment method",+ "portalFailed": "Couldn't open the billing page. Try again."+ },"common": {"loading": "Loading...","error": "Something went wrong.",@@ -8226,6 +8255,10 @@"regularPrice": "Regular price","firstMonthOffer": "50% off your first month with code {code}","buyPlanNow": "Buy {plan} now",+ "choosePlanTitle": "Choose a plan",+ "choosePlanFor": "Choose {plan}",+ "planEnded": "Your plan isn't active. Choose one to start it again; you'll pay on Stripe's secure checkout.",+ "checkoutFailed": "Couldn't open the checkout. Try again.","planAdminOnly": "Only admins can buy or change the plan. Ask an admin in your organization.","seeAllPlanFeatures": "See everything each plan includes","switchToAnnual": "Switch to annual billing",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsxindex 78bfb5e61..3ceb8d284 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx@@ -17,6 +17,9 @@ const AgentChart = dynamic(},);import { useFeatureGate } from '@/hooks/use-feature-gate';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import { isSubscriptionInactive } from '@/lib/api-failure';+import { takeBackUnansweredTurn } from '@/lib/agent/unanswered-turn';import { Link } from '@/i18n/navigation';import { Button, buttonVariants } from '@/components/ui/button';import { Markdown } from '@/components/ui/markdown';@@ -149,6 +152,8 @@ function AgentChat(props: {const tc = useTranslations('common');const activeBrandId = useBrandStore((s) => s.activeBrandId);const [pendingConfirm, setPendingConfirm] = useState<string | null>(null);+ // A chat turn is an action: a read-only workspace gets the upgrade dialog.+ const { isLocked, openUpgrade } = useUpgradeGate();// Ref mirrors activeId for prepareSendMessagesRequest. Reading the// state directly from the transport closure gives us a stale snapshot —@@ -160,7 +165,7 @@ function AgentChat(props: {activeIdRef.current = activeId;}, [activeId]);- const { messages, sendMessage, status, setMessages, stop } = useChat({+ const { messages, sendMessage, status, setMessages, stop, error, clearError } = useChat({transport: new DefaultChatTransport({api: '/api/agent/chat',// Always forward the active conversation id alongside the messages@@ -177,6 +182,21 @@ function AgentChat(props: {}),});+ // The server's subscription_inactive (the plan lapsed while the page was+ // open): the upgrade dialog, the person's message back in the input rather+ // than left unanswered in the thread, and the chat ready for the next try.+ useEffect(() => {+ if (error && isSubscriptionInactive(error.message)) {+ const back = takeBackUnansweredTurn(messages);+ if (back) {+ setMessages(back.messages);+ setInput(back.text);+ }+ openUpgrade();+ clearError();+ }+ }, [error, messages, setMessages, setInput, openUpgrade, clearError]);+// Sync hydrated messages into the chat hook whenever we switch conversation.useEffect(() => {setMessages(initialMessages);@@ -248,6 +268,10 @@ function AgentChat(props: {}async function newChat() {+ if (isLocked) {+ openUpgrade();+ return;+ }const res = await fetch('/api/agent/conversations', {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -255,6 +279,10 @@ function AgentChat(props: {});if (!res.ok) {const body = await res.json().catch(() => null);+ if (isSubscriptionInactive(body)) {+ openUpgrade();+ return;+ }toast.error(body?.error ?? 'Failed to create chat');return;@@ -286,6 +314,10 @@ function AgentChat(props: {e.preventDefault();const text = input.trim();if (!text || status !== 'ready') return;+ if (isLocked) {+ openUpgrade();+ return;+ }// Resolve the conversation id we'll send with this message. If no chat// is selected, spin one up. Captured into a local so the sendMessage@@ -300,6 +332,10 @@ function AgentChat(props: {});if (!res.ok) {const body = await res.json().catch(() => null);+ if (isSubscriptionInactive(body)) {+ openUpgrade();+ return;+ }toast.error(body?.error ?? 'Failed to create conversation');return;@@ -310,10 +346,13 @@ function AgentChat(props: {activeIdRef.current = conversation.id;convId = conversation.id;}+ // Emptied as it goes out: a refused turn (a read-only workspace) puts+ // the text back, and so does a send that throws.+ setInput('');try {await sendMessage({ text }, { body: { conversationId: convId } });- setInput('');} catch {+ setInput(text);toast.error('Failed to send message');}}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 05d95283b..763ce4709 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -28,6 +28,7 @@ import { AiUsageBanner } from '@/components/ai-usage/ai-usage-banner';import { AiUsageMeter } from '@/components/ai-usage/ai-usage-meter';import { useAiUsage } from '@/components/providers/ai-usage-provider';import { useUserRole } from '@/hooks/use-user-role';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';import { PLATFORM_LABELS } from '@/config/platform-labels';import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';import { PublishDialog } from '@/components/content/publish-dialog';@@ -761,6 +762,10 @@ export function DraftEditor({const language =languageRule?.on && languageRule.current.trim() ? languageRule.current : brandLanguage;const qualityOn = qualityPhase() >= 1;+ // A read-only workspace (plan not active): the reads the editor asks the+ // API for by itself after a save (links, sources, claims, the page's+ // proof) are left out; the page opens with what is stored.+ const { isLocked } = useUpgradeGate();// Who the page is by (CE-038): page metadata, shown in the header and in a// Page info strip outside the page; with Quality's first phase.@@ -828,7 +833,7 @@ export function DraftEditor({draft.id,autosave.savedAt,linksToCheck(pageBlocks),- qualityOn,+ qualityOn && !isLocked,);const brandDomains = reads.sources?.data?.brandDomains;// The site's trust (Site Audit, CE-043), read once: Trust's last 5 points.@@ -888,13 +893,13 @@ export function DraftEditor({kinds: aiKinds,paused: aiPaused,reading: sourcesReading,- } = useSourceClasses(draft.id, autosave.savedAt, unplaced, sourcesOn);+ } = useSourceClasses(draft.id, autosave.savedAt, unplaced, sourcesOn && !isLocked);// A save waiting or under way: the page's reads follow it. Not a failed// save (or a conflict, a page too large): no new save is coming till it's fixed.const saving = autosave.state === 'unsaved' || autosave.state === 'saving';// The claims in the draft's own words, as the model reads them (CE-045):// asked after a save, leaving the block the person is writing in.- const claimsRead = useClaims(draft.id, autosave.savedAt, sourcesOn, saving, () =>+ const claimsRead = useClaims(draft.id, autosave.savedAt, sourcesOn && !isLocked, saving, () =>editor && !editor.isDestroyed && editor.isFocused ? writingBlock(editor) : null,);const { blocks: claimBlocks, recheck: recheckClaims } = claimsRead;@@ -907,7 +912,7 @@ export function DraftEditor({const pageRead = usePageRead(draft.id,`${autosave.savedAt}\n${pageType ?? ''}`,- sourcesOn,+ sourcesOn && !isLocked,saving,);const proofAsks = useMemo(diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex 2be7dd99e..46eb35bde 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx@@ -5,6 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../../../messages/en.json';import type { Editor } from '@tiptap/core';import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';+import { PlanProvider } from '@/components/providers/plan-provider';+import { UpgradeDialogProvider } from '@/components/providers/upgrade-dialog-provider';import type { ContentDraft } from '@/lib/content/drafts';import type { DraftSuggestion } from '@/lib/content/suggestions';import { passageKey, type CitedPassage } from '@/lib/content/cited-passages';@@ -3431,6 +3433,46 @@ describe('the side panel', () => {vi.useRealTimers();});+ it('asks the API nothing by itself while the workspace is read-only (plan not active)', async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ getContentDraft.mockResolvedValue(+ draft({+ bodyHtml:+ readable.bodyHtml + '<p>See <a href="https://example.com/guide">the guide</a>.</p>',+ }),+ );+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <PlanProvider+ planId="starter"+ subscriptionActive={false}+ subscriptionStatus="canceled"+ >+ <RoleProvider role="admin">+ <UpgradeDialogProvider>+ <ContentEditorPage />+ </UpgradeDialogProvider>+ </RoleProvider>+ </PlanProvider>+ </NextIntlClientProvider>,+ );+ });+ await act(async () => {});+ await act(async () => void (await vi.advanceTimersByTimeAsync(CLAIMS_EVERY_MS + 3_000)));+ // The page opens with what is stored; no link, claim or proof read is asked for.+ expect(container.querySelector('.ProseMirror')).not.toBeNull();+ expect(readDraftPage).not.toHaveBeenCalled();+ expect(checkDraftClaims).not.toHaveBeenCalled();+ expect(checkDraftLinks).not.toHaveBeenCalled();+ } finally {+ vi.unstubAllEnvs();+ }+ });+it('weighs the checks by the page type in phase 3, and follows a type changed from Quality (CE-052)', async () => {process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '3';vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.tsxindex bbb203f77..129b781e8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.tsx@@ -24,6 +24,7 @@ import {} from '@/lib/content/cms-send-client';import type { ContentDraftListItem } from '@/lib/content/drafts';import { CmsTargetPicker, CmsTargetUnchecked, useCmsTarget } from '@/components/content/cms-target';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';import { readCmsSources } from './_cms-sources';/** How often the sends going on in the background are read. */@@ -101,6 +102,7 @@ export function BulkSendDialog({const t = useTranslations('contentEditor.library.bulk');const tEditor = useTranslations('contentEditor.editor');const tFailure = useTranslations('apiFailure');+ const { openUpgrade } = useUpgradeGate();const [phase, setPhase] = useState<Phase>({ kind: 'reading' });const [items, setItems] = useState<BulkItem[]>([]);// The sends made, as last read, by draft.@@ -223,6 +225,8 @@ export function BulkSendDialog({}const result = await sendPagesToCms(brandId, group, target);if (!result.ok) {+ // A read-only workspace: the upgrade dialog, and the rest wait too.+ if (result.code === 'subscription') openUpgrade();// The page a refusal names ("pages.2.html"), as the group's own.const index = Number(/^pages\.(\d+)\./.exec(result.field ?? '')?.[1] ?? NaN);stopped = {@@ -290,7 +294,9 @@ export function BulkSendDialog({};const failureText = ({ code, field, title }: Refusal) => {- if (code === 'session' || code === 'workspace' || code === 'busy') return tFailure(code);+ if (code === 'session' || code === 'workspace' || code === 'busy' || code === 'subscription') {+ return tFailure(code);+ }// A page archived or deleted since the dialog read it.if (code === 'not_found') return t('notFound');if (code === 'invalid' && field) {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsxindex e5ea778a9..934e5c636 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx@@ -66,6 +66,16 @@ vi.mock('@/lib/webflow-client', () => ({readWebflow: async () => ({ ok: true, configured: false, connection: null }),}));vi.mock('@/lib/actions/content-authors', () => ({ getContentAuthors: vi.fn(async () => null) }));+// The workspace's plan: active unless a test says it's read-only.+const gate = vi.hoisted(() => ({ isLocked: false }));+vi.mock('@/components/providers/upgrade-gate', () => ({+ useUpgradeGate: () => ({+ isLocked: gate.isLocked,+ openUpgrade: vi.fn(),+ guard: (fn: () => unknown) => fn,+ }),+ useUpgradeDialog: () => null,+}));/** jsdom's Blob has no text(): read it as a browser's FileReader would. */const readText = (blob: Blob) =>@@ -135,6 +145,7 @@ const tab = (name: string) =>beforeEach(() => {brandState.activeBrandId = 'brand-1';+ gate.isLocked = false;window.history.replaceState(null, '', '/dashboard/content/library');container = document.createElement('div');document.body.appendChild(container);@@ -554,6 +565,30 @@ describe('Send to CMS from a Library row (#1331)', () => {expect(refreshWebflowPublished).toHaveBeenCalledTimes(1);});+ it('doesn’t ask Webflow by itself while the workspace is read-only', async () => {+ gate.isLocked = true;+ getContentDrafts.mockResolvedValue([row({})]);+ readCmsStatuses.mockResolvedValue(+ new Map([+ [+ 'd1',+ {+ status: 'sent',+ target: 'webflow',+ at: '2026-10-24T10:00:00Z',+ httpStatus: null,+ error: null,+ publishedUrl: null,+ },+ ],+ ]),+ );+ await renderPage();+ // What is stored is listed; nothing is asked of the API.+ expect(container.textContent).toContain('Pipeline forecasting');+ expect(refreshWebflowPublished).not.toHaveBeenCalled();+ });+it('doesn’t ask Webflow for a brand with no page there', async () => {getContentDrafts.mockResolvedValue([row({})]);await renderPage();diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsxindex 8059973e2..db6aa65ce 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx@@ -27,6 +27,7 @@ import { NewContentDialog } from '@/components/content/new-content-dialog';import { PublishDialog } from '@/components/content/publish-dialog';import { SendDialog } from '@/components/content/send-to-cms-dialog';import { useUserRole } from '@/hooks/use-user-role';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';import { useRouter } from '@/i18n/navigation';import {archiveContentDraft,@@ -106,6 +107,9 @@ export default function ContentLibraryPage() {const [attempt, setAttempt] = useState(0);const [starting, setStarting] = useState(false);const { canManage } = useUserRole();+ // A read-only workspace (plan not active): the reads the Library asks for+ // by itself are left out, and it lists what is stored.+ const { isLocked } = useUpgradeGate();// The draft whose Delete waits for a confirmation.const [deleting, setDeleting] = useState<ContentDraftListItem | null>(null);const [deletePending, setDeletePending] = useState(false);@@ -210,14 +214,14 @@ export default function ContentLibraryPage() {);const webflowRead = useRef(new Set<string>());useEffect(() => {- if (!inWebflow || !activeBrandId || webflowRead.current.has(activeBrandId)) return;+ if (isLocked || !inWebflow || !activeBrandId || webflowRead.current.has(activeBrandId)) return;webflowRead.current.add(activeBrandId);// Not cancelled with the effect: a filter or search changing meanwhile// still reads the list again, the brand's pages marked.void refreshWebflowPublished(activeBrandId).then((published) => {if (published.length) setAttempt((n) => n + 1);});- }, [inWebflow, activeBrandId]);+ }, [isLocked, inWebflow, activeBrandId]);const reload = () => setAttempt((n) => n + 1);const titleOf = (draft: ContentDraftListItem) => draft.title.trim() || t('untitled');diff --git a/web/src/app/[locale]/(dashboard)/layout.test.tsx b/web/src/app/[locale]/(dashboard)/layout.test.tsxnew file mode 100644index 000000000..2359c525d--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/layout.test.tsx@@ -0,0 +1,174 @@+import { act, type ReactNode } 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';++/**+ * The dashboard's subscription gate on Ansvisor Cloud: a workspace whose plan+ * isn't active opens read-only (the page, with the band across the top);+ * only an admin of a new account that never subscribed goes back to+ * onboarding's plan step.+ */++let profile: Record<string, unknown> | null;+let org: Record<string, unknown> | null;+let orgError: { message: string } | null;+let owner: { full_name: string | null } | null;++vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },+ from: (table: string) => {+ const query = {+ select: () => query,+ eq: () => query,+ order: () => query,+ limit: () => query,+ single: async () =>+ table === 'profiles' ? { data: profile } : { data: org, error: orgError },+ maybeSingle: async () => ({ data: owner }),+ };+ return query;+ },+ }),+}));++const redirect = vi.fn((url: string) => {+ throw new Error(`NEXT_REDIRECT ${url}`);+});+vi.mock('next/navigation', () => ({ redirect: (url: string) => redirect(url) }));++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+ usePathname: () => '/dashboard/insights',+}));++const pass = ({ children }: { children: ReactNode }) => <>{children}</>;+const none = () => null;+vi.mock('@/components/layout/sidebar', () => ({ Sidebar: none }));+vi.mock('@/components/layout/sidebar-error-boundary', () => ({ SidebarErrorBoundary: pass }));+vi.mock('@/components/layout/mobile-nav', () => ({ MobileNav: none }));+vi.mock('@/components/layout/tracking-job-handoff', () => ({ TrackingJobHandoff: none }));+vi.mock('@/components/providers/auth-provider', () => ({ AuthProvider: none }));+vi.mock('@/components/providers/ai-usage-provider', () => ({ AiUsageProvider: pass }));+vi.mock('@/components/providers/brand-loader', () => ({ BrandLoader: none }));+vi.mock('@/components/providers/brand-guard', () => ({ BrandGuard: pass }));+vi.mock('@/components/getting-started/page-opened', () => ({ GettingStartedPageOpened: none }));+vi.mock('@/lib/actions/brand', () => ({ getBrands: async () => [] }));++const { default: DashboardLayout } = await import('./layout');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++/** The layout around a page, drawn; or the address it redirected to. */+async function open(): Promise<string | null> {+ let tree: ReactNode;+ try {+ tree = await DashboardLayout({ children: <p>Page content</p> });+ } catch (err) {+ const match = /^NEXT_REDIRECT (.+)$/.exec((err as Error).message);+ if (match) return match[1];+ throw err;+ }+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ {tree}+ </NextIntlClientProvider>,+ );+ });+ return null;+}++const band = () => container.querySelector('[role="status"]');++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ profile = { organization_id: 'org1', onboarding_completed: true, role: 'admin' };+ org = {+ plan: 'starter',+ subscription_status: 'active',+ plan_overrides: null,+ stripe_subscription_id: 'sub_1',+ };+ orgError = null;+ owner = null;+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.unstubAllEnvs();+});++describe('the dashboard layout', () => {+ it('draws the page with no band while the plan is active', async () => {+ expect(await open()).toBeNull();+ expect(container.textContent).toContain('Page content');+ expect(band()).toBeNull();+ });++ it('opens read-only for an admin whose plan ended, with the band and See plans', async () => {+ org = { ...org, subscription_status: 'canceled' };+ expect(await open()).toBeNull();+ expect(redirect).not.toHaveBeenCalled();+ expect(container.textContent).toContain('Page content');+ expect(band()?.textContent).toContain(+ 'Your workspace is read-only. You can look around; adding, running and AI need a plan.',+ );+ expect(band()?.querySelector('button')?.textContent).toBe('See plans');+ });++ it('opens read-only for another member, naming the admin to ask', async () => {+ profile = { ...profile, role: 'analyst' };+ org = { ...org, subscription_status: 'past_due' };+ owner = { full_name: 'Jane Owner' };+ expect(await open()).toBeNull();+ expect(container.textContent).toContain('Page content');+ expect(band()?.textContent).toContain(+ 'Ask Jane Owner, your workspace admin, to update the payment method.',+ );+ expect(band()?.textContent).toContain("Your last payment didn't go through");+ expect(band()?.querySelector('button')).toBeNull();+ });++ it("sends an admin of a new account that never subscribed to onboarding's plan step", async () => {+ org = { ...org, subscription_status: 'incomplete', stripe_subscription_id: null };+ expect(await open()).toBe('/dashboard/onboarding');+ });++ it('neither redirects nor locks when the organization could not be read', async () => {+ org = null;+ orgError = { message: 'canceling statement due to statement timeout' };+ expect(await open()).toBeNull();+ expect(redirect).not.toHaveBeenCalled();+ expect(container.textContent).toContain('Page content');+ expect(band()).toBeNull();+ });++ it('sends anyone who has not finished onboarding to it', async () => {+ profile = { ...profile, onboarding_completed: false };+ expect(await open()).toBe('/dashboard/onboarding');+ });++ it('never locks self-hosted', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ org = { ...org, subscription_status: 'canceled', stripe_subscription_id: null };+ expect(await open()).toBeNull();+ expect(container.textContent).toContain('Page content');+ expect(band()).toBeNull();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsxindex c838a36bb..19b3ac55f 100644--- a/web/src/app/[locale]/(dashboard)/layout.tsx+++ b/web/src/app/[locale]/(dashboard)/layout.tsx@@ -15,7 +15,8 @@ import { getBrands } from '@/lib/actions/brand';import { menuOfProfile, readRoleHidden } from '@/lib/menu-access';import { getPlan, isCloud, type PlanId } from '@/config/plans';import { evaluateSubscriptionAccess } from '@/lib/billing/subscription-access';-import { SubscriptionExpiredNotice } from '@/components/billing/subscription-expired-notice';+import { UpgradeDialogProvider } from '@/components/providers/upgrade-dialog-provider';+import { ReadOnlyBanner } from '@/components/billing/read-only-banner';import { TrackingJobHandoff } from '@/components/layout/tracking-job-handoff';export default async function DashboardLayout({ children }: { children: React.ReactNode }) {@@ -42,10 +43,10 @@ export default async function DashboardLayout({ children }: { children: React.Reconst role = (profile.role ?? 'analyst') as TeamRole;- const [{ data: org }, brands, roleHidden] = await Promise.all([+ const [{ data: org, error: orgError }, brands, roleHidden] = await Promise.all([supabase.from('organizations')- .select('plan, subscription_status, plan_overrides')+ .select('plan, subscription_status, plan_overrides, stripe_subscription_id').eq('id', profile.organization_id).single(),getBrands(profile.organization_id),@@ -54,23 +55,30 @@ export default async function DashboardLayout({ children }: { children: React.Re]);const menu = menuOfProfile({ ...profile, role }, roleHidden);- // Cloud mode: gate access when the subscription isn't active/trialing.- // Admins (incl. the owner) are routed to the renew/payment flow; everyone- // else is blocked with a contact-your-owner notice — so an invited member- // can neither reach the payment screen nor walk back into onboarding to- // re-create the brand / competitors.- if (isCloud()) {+ // Cloud mode: when the subscription isn't active/trialing, the dashboard is+ // read-only — every page opens (Billing included, to choose a plan), and an+ // action opens the upgrade dialog instead of running. Only an admin of a+ // new account that never had a subscription goes back to onboarding's plan+ // step, where its trial starts. An org row that couldn't be read decides+ // nothing: no redirect and no lock (the API still refuses a lapsed plan's+ // changes with 402).+ const subscriptionStatus = (org?.subscription_status as string | null) ?? null;+ let subscriptionActive = true;+ let adminName: string | null = null;+ if (isCloud() && !orgError) {const access = await evaluateSubscriptionAccess(supabase,profile.organization_id,role,- (org?.subscription_status as string | null) ?? null,+ subscriptionStatus,+ Boolean(org?.stripe_subscription_id),);- if (access.state === 'needs_payment') {+ if (access.state === 'choose_plan') {redirect('/dashboard/onboarding');}- if (access.state === 'blocked') {- return <SubscriptionExpiredNotice ownerName={access.ownerName} />;+ if (access.state === 'read_only') {+ subscriptionActive = false;+ adminName = access.adminName;}}@@ -100,31 +108,39 @@ export default async function DashboardLayout({ children }: { children: React.Re<AuthProvider user={user} /><BrandLoader brands={brands} /><GettingStartedPageOpened />- <PlanProvider planId={planId} allowedModelIds={allowedModelIds}>+ <PlanProvider+ planId={planId}+ allowedModelIds={allowedModelIds}+ subscriptionActive={subscriptionActive}+ subscriptionStatus={subscriptionStatus}+ ><RoleProvider role={role}>- <MenuAccessProvider hidden={menu.hidden} canManageMenus={menu.canManageMenus}>- <AiUsageProvider>- <div className="flex h-screen overflow-hidden">- {/* Desktop sidebar */}- <div className="relative hidden md:flex md:flex-shrink-0">- <SidebarErrorBoundary>- <Sidebar />- </SidebarErrorBoundary>- </div>+ <UpgradeDialogProvider adminName={adminName}>+ <MenuAccessProvider hidden={menu.hidden} canManageMenus={menu.canManageMenus}>+ <AiUsageProvider>+ <div className="flex h-screen overflow-hidden">+ {/* Desktop sidebar */}+ <div className="relative hidden md:flex md:flex-shrink-0">+ <SidebarErrorBoundary>+ <Sidebar />+ </SidebarErrorBoundary>+ </div>- {/* Main area */}- <div className="flex flex-1 flex-col overflow-hidden">- <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">- <MobileNav />+ {/* Main area */}+ <div className="flex flex-1 flex-col overflow-hidden">+ <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">+ <MobileNav />+ </div>+ <ReadOnlyBanner />+ <main className="flex-1 overflow-y-auto bg-background p-6">+ <BrandGuard>{children}</BrandGuard>+ </main>+ <TrackingJobHandoff /></div>- <main className="flex-1 overflow-y-auto bg-background p-6">- <BrandGuard>{children}</BrandGuard>- </main>- <TrackingJobHandoff /></div>- </div>- </AiUsageProvider>- </MenuAccessProvider>+ </AiUsageProvider>+ </MenuAccessProvider>+ </UpgradeDialogProvider></RoleProvider></PlanProvider></>diff --git a/web/src/app/[locale]/(onboarding)/layout.test.tsx b/web/src/app/[locale]/(onboarding)/layout.test.tsxnew file mode 100644index 000000000..b51b1dd7f--- /dev/null+++ b/web/src/app/[locale]/(onboarding)/layout.test.tsx@@ -0,0 +1,81 @@+import { isValidElement, type ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Onboarding on Ansvisor Cloud once a member has finished it: a workspace+ * whose plan ended opens the dashboard read-only instead of the wizard (where+ * the brand could be set up again); only an admin of a new account that never+ * subscribed keeps the plan step.+ */++let profile: Record<string, unknown> | null;+let org: Record<string, unknown> | null;++vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },+ from: (table: string) => {+ const query = {+ select: () => query,+ eq: () => query,+ order: () => query,+ limit: () => query,+ single: async () => ({ data: table === 'profiles' ? profile : org }),+ maybeSingle: async () => ({ data: null }),+ };+ return query;+ },+ }),+}));++const redirect = vi.fn((url: string) => {+ throw new Error(`NEXT_REDIRECT ${url}`);+});+vi.mock('next/navigation', () => ({ redirect: (url: string) => redirect(url) }));+vi.mock('@/components/providers/auth-provider', () => ({ AuthProvider: () => null }));+vi.mock('@/components/auth/onboarding-sign-out-button', () => ({+ OnboardingSignOutButton: () => null,+}));++const { default: OnboardingLayout } = await import('./layout');++/** The wizard drawn (true), or the address the layout redirected to. */+async function open(): Promise<true | string> {+ try {+ const tree: ReactNode = await OnboardingLayout({ children: <p>Wizard</p> });+ expect(isValidElement(tree)).toBe(true);+ return true;+ } catch (err) {+ const match = /^NEXT_REDIRECT (.+)$/.exec((err as Error).message);+ if (match) return match[1];+ throw err;+ }+}++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ profile = { organization_id: 'org1', onboarding_completed: true, role: 'admin' };+ org = { subscription_status: 'canceled', stripe_subscription_id: 'sub_1' };+});++describe('the onboarding layout', () => {+ it('sends a member whose plan ended to the read-only dashboard', async () => {+ profile = { ...profile, role: 'analyst' };+ expect(await open()).toBe('/dashboard');+ });++ it('sends an admin whose plan ended to the dashboard too, where Billing has the plans', async () => {+ expect(await open()).toBe('/dashboard');+ });++ it('keeps the plan step for an admin of a new account that never subscribed', async () => {+ org = { subscription_status: 'incomplete', stripe_subscription_id: null };+ expect(await open()).toBe(true);+ });++ it('lets a new member who has not finished onboarding through', async () => {+ profile = { organization_id: null, onboarding_completed: false, role: 'admin' };+ expect(await open()).toBe(true);+ });+});diff --git a/web/src/app/[locale]/(onboarding)/layout.tsx b/web/src/app/[locale]/(onboarding)/layout.tsxindex 2d69ea539..e1fd989ad 100644--- a/web/src/app/[locale]/(onboarding)/layout.tsx+++ b/web/src/app/[locale]/(onboarding)/layout.tsx@@ -4,7 +4,6 @@ import { AuthProvider } from '@/components/providers/auth-provider';import { OnboardingSignOutButton } from '@/components/auth/onboarding-sign-out-button';import { isCloud } from '@/config/plans';import { evaluateSubscriptionAccess } from '@/lib/billing/subscription-access';-import { SubscriptionExpiredNotice } from '@/components/billing/subscription-expired-notice';import type { TeamRole } from '@/components/providers/role-provider';export default async function OnboardingLayout({ children }: { children: React.ReactNode }) {@@ -17,10 +16,12 @@ export default async function OnboardingLayout({ children }: { children: React.Rredirect('/sign-in');}- // An already-onboarded non-admin whose org subscription has lapsed must not- // re-enter the wizard (they'd otherwise see the payment step and could- // re-create the brand / competitors on the org's existing setup). Admins keep- // the renew flow; not-yet-onboarded users (new org creators) pass through.+ // An already-onboarded member whose org subscription has lapsed must not+ // re-enter the wizard (they could re-create the brand / competitors on the+ // org's existing setup): the dashboard opens read-only for them, and admins+ // choose a plan in Billing. Only an admin of a new account that never had a+ // subscription keeps the plan step; not-yet-onboarded users (new org+ // creators) pass through.if (isCloud()) {const { data: profile } = await supabase.from('profiles')@@ -31,7 +32,7 @@ export default async function OnboardingLayout({ children }: { children: React.Rif (profile?.onboarding_completed && profile.organization_id) {const { data: org } = await supabase.from('organizations')- .select('subscription_status')+ .select('subscription_status, stripe_subscription_id').eq('id', profile.organization_id).single();const access = await evaluateSubscriptionAccess(@@ -39,9 +40,10 @@ export default async function OnboardingLayout({ children }: { children: React.Rprofile.organization_id,(profile.role ?? 'analyst') as TeamRole,(org?.subscription_status as string | null) ?? null,+ Boolean(org?.stripe_subscription_id),);- if (access.state === 'blocked') {- return <SubscriptionExpiredNotice ownerName={access.ownerName} />;+ if (access.state === 'read_only') {+ redirect('/dashboard');}}}diff --git a/web/src/app/api/agent/chat/route.test.ts b/web/src/app/api/agent/chat/route.test.tsnew file mode 100644index 000000000..562f10942--- /dev/null+++ b/web/src/app/api/agent/chat/route.test.ts@@ -0,0 +1,86 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * POST /api/agent/chat on a read-only workspace (Ansvisor Cloud, plan not+ * active): a chat turn is an action, so it answers 402 subscription_inactive+ * before anything else; an active plan, or self-hosted, goes on to the+ * conversation check.+ */++let status: string | null;+vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: (table: string) => {+ const query = {+ select: () => query,+ eq: () => query,+ // No conversation: past the gate, the route answers 404.+ maybeSingle: async () => ({+ data: table === 'organizations' ? { subscription_status: status, plan: 'starter' } : null,+ error: null,+ }),+ };+ return query;+ },+ },+}));+vi.mock('@/lib/agent/auth', () => ({+ resolveAgentAuth: async () => ({+ userId: 'user-1',+ email: '[email protected]',+ organizationId: 'org-1',+ apiKeyId: 'agent-internal',+ }),+}));+vi.mock('@/lib/agent/tools', () => ({ buildAgentTools: vi.fn() }));+vi.mock('@/lib/agent/model', () => ({ AGENT_PROVIDER_OPTIONS: {}, buildAgentModel: vi.fn() }));+vi.mock('@/lib/agent/key', () => ({ resolveAgentModelConfig: vi.fn() }));+vi.mock('@/lib/agent/token-quota', () => ({ recordAgentTokenUsage: vi.fn() }));+vi.mock('@/lib/agent/system-prompt', () => ({ buildAgentSystemPrompt: vi.fn() }));++const { POST } = await import('./route');++const chat = () =>+ POST(+ new Request('http://localhost/api/agent/chat', {+ method: 'POST',+ body: JSON.stringify({+ conversationId: 'conversation-1',+ messages: [{ id: 'm1', role: 'user', parts: [{ type: 'text', text: 'Hi' }] }],+ }),+ }),+ );++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ status = 'canceled';+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('POST /api/agent/chat', () => {+ it('answers 402 subscription_inactive while the workspace is read-only', async () => {+ const res = await chat();+ expect(res.status).toBe(402);+ expect(await res.json()).toMatchObject({+ error: 'plan_limit',+ code: 'subscription_inactive',+ message: expect.any(String),+ });+ });++ it('goes on to the conversation once the plan is active', async () => {+ status = 'active';+ const res = await chat();+ expect(res.status).toBe(404);+ });++ it('never gates self-hosted', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ const res = await chat();+ expect(res.status).toBe(404);+ });+});diff --git a/web/src/app/api/agent/chat/route.ts b/web/src/app/api/agent/chat/route.tsindex 1e00b4c21..1038f5a16 100644--- a/web/src/app/api/agent/chat/route.ts+++ b/web/src/app/api/agent/chat/route.ts@@ -8,6 +8,7 @@ import { AGENT_PROVIDER_OPTIONS, buildAgentModel } from '@/lib/agent/model';import { resolveAgentModelConfig } from '@/lib/agent/key';import { recordAgentTokenUsage } from '@/lib/agent/token-quota';import { getPlan, hasFeature, type PlanId } from '@/config/plans';+import { subscriptionActiveFor, subscriptionInactiveResponse } from '@/lib/mcp/subscription-gate';// Streaming responses up to 5 min — agent loops can run multiple tool// calls plus a final generation, comfortably under this.@@ -22,7 +23,9 @@ interface ChatBody {* POST /api/agent/chat** Streaming chat endpoint for the in-product agent. Verifies the user is- * signed in, the conversation belongs to them, the org's plan unlocks the+ * signed in, the org's plan is active (a chat turn is an action: 402+ * subscription_inactive while the workspace is read-only, Cloud only), the+ * conversation belongs to them, the org's plan unlocks the* `ai_agent` feature, and the user hasn't blown through the monthly token* quota — then runs `streamText` with the MCP-data-backed tool surface and* streams the response back via `toUIMessageStreamResponse()`. Tokens are@@ -38,6 +41,7 @@ export async function POST(req: Request) {return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });}const organizationId: string = auth.organizationId;+ if (!(await subscriptionActiveFor(organizationId))) return subscriptionInactiveResponse();let body: ChatBody;try {diff --git a/web/src/app/api/agent/conversations/route.test.ts b/web/src/app/api/agent/conversations/route.test.tsnew file mode 100644index 000000000..71987185d--- /dev/null+++ b/web/src/app/api/agent/conversations/route.test.ts@@ -0,0 +1,86 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * /api/agent/conversations on a read-only workspace (Ansvisor Cloud, plan not+ * active): starting a conversation answers 402 subscription_inactive, as a+ * chat turn does; the list stays open.+ */++let status: string | null;+vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: (table: string) => {+ const query = {+ select: () => query,+ eq: () => query,+ order: () => query,+ limit: async () => ({ data: [{ id: 'conversation-1' }], error: null }),+ maybeSingle: async () => ({+ data: table === 'organizations' ? { subscription_status: status, plan: 'starter' } : null,+ error: null,+ }),+ };+ return query;+ },+ },+}));+vi.mock('@/lib/agent/auth', () => ({+ resolveAgentAuth: async () => ({+ userId: 'user-1',+ email: '[email protected]',+ organizationId: 'org-1',+ apiKeyId: 'agent-internal',+ }),+}));+// No key: past the gates, starting a conversation answers missing_ai_key.+vi.mock('@/lib/agent/key', () => ({ isAgentKeyConfigured: async () => false }));++const { GET, POST } = await import('./route');++const start = () =>+ POST(+ new Request('http://localhost/api/agent/conversations', {+ method: 'POST',+ body: JSON.stringify({}),+ }),+ );++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ status = 'canceled';+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('/api/agent/conversations', () => {+ it('answers 402 subscription_inactive to a new conversation while read-only', async () => {+ const res = await start();+ expect(res.status).toBe(402);+ expect(await res.json()).toMatchObject({+ error: 'plan_limit',+ code: 'subscription_inactive',+ });+ });++ it('keeps the list open while read-only', async () => {+ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ conversations: [{ id: 'conversation-1' }] });+ });++ it('goes on to the key check once the plan is active', async () => {+ status = 'trialing';+ const res = await start();+ expect(res.status).toBe(403);+ expect(await res.json()).toMatchObject({ code: 'missing_ai_key' });+ });++ it('never gates self-hosted', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ const res = await start();+ expect(res.status).toBe(403);+ });+});diff --git a/web/src/app/api/agent/conversations/route.ts b/web/src/app/api/agent/conversations/route.tsindex 330a3de92..e21043a04 100644--- a/web/src/app/api/agent/conversations/route.ts+++ b/web/src/app/api/agent/conversations/route.ts@@ -3,6 +3,7 @@ import { supabaseAdmin } from '@/lib/supabase/admin';import { resolveAgentAuth } from '@/lib/agent/auth';import { getPlan, hasFeature, type PlanId } from '@/config/plans';import { isAgentKeyConfigured } from '@/lib/agent/key';+import { subscriptionActiveFor, subscriptionInactiveResponse } from '@/lib/mcp/subscription-gate';/*** GET /api/agent/conversations@@ -39,7 +40,9 @@ export async function GET() {** Plan-gated: the chat endpoint already gates on `ai_agent`, but we gate* here too so a non-Growth user clicking "+ New chat" gets the 403- * immediately rather than after typing a message.+ * immediately rather than after typing a message. Likewise a read-only+ * workspace (Cloud, plan not active) gets 402 subscription_inactive here, as+ * the chat does; reading and deleting conversations stay open.*/export async function POST(req: Request) {const auth = await resolveAgentAuth();@@ -47,6 +50,7 @@ export async function POST(req: Request) {return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });}const organizationId: string = auth.organizationId;+ if (!(await subscriptionActiveFor(organizationId))) return subscriptionInactiveResponse();const { data: org } = await supabaseAdmin.from('organizations')diff --git a/web/src/app/api/mcp/content-opportunities/[id]/brief/route.ts b/web/src/app/api/mcp/content-opportunities/[id]/brief/route.tsindex 1524aa66b..cb99674d4 100644--- a/web/src/app/api/mcp/content-opportunities/[id]/brief/route.ts+++ b/web/src/app/api/mcp/content-opportunities/[id]/brief/route.ts@@ -1,6 +1,7 @@import { NextResponse } from 'next/server';import { authenticateMcpRequest } from '@/lib/mcp-auth';import { generateBriefFor } from '@/lib/mcp/data';+import { failedCallResponse } from '@/lib/mcp/subscription-gate';/*** POST /api/mcp/content-opportunities/[id]/brief@@ -26,7 +27,6 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str}return NextResponse.json(result);} catch (err) {- const message = err instanceof Error ? err.message : 'Failed';- return NextResponse.json({ error: message }, { status: 500 });+ return failedCallResponse(err);}}diff --git a/web/src/app/api/mcp/prompts/[id]/improve-action/route.ts b/web/src/app/api/mcp/prompts/[id]/improve-action/route.tsindex 61071acc1..ba6374e42 100644--- a/web/src/app/api/mcp/prompts/[id]/improve-action/route.ts+++ b/web/src/app/api/mcp/prompts/[id]/improve-action/route.ts@@ -1,6 +1,7 @@import { NextResponse } from 'next/server';import { authenticateMcpRequest } from '@/lib/mcp-auth';import { createImproveActionFor, type CreateImproveActionInput } from '@/lib/mcp/data';+import { failedCallResponse } from '@/lib/mcp/subscription-gate';/*** POST /api/mcp/prompts/[id]/improve-action@@ -50,7 +51,6 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str}return NextResponse.json(result);} catch (err) {- const message = err instanceof Error ? err.message : 'Failed';- return NextResponse.json({ error: message }, { status: 500 });+ return failedCallResponse(err);}}diff --git a/web/src/app/api/mcp/route.ts b/web/src/app/api/mcp/route.tsindex 2e8ea9069..edb835893 100644--- a/web/src/app/api/mcp/route.ts+++ b/web/src/app/api/mcp/route.ts@@ -14,7 +14,8 @@ export const dynamic = 'force-dynamic';* memory between requests.*/async function handle(req: Request): Promise<Response> {- const auth = await authenticateMcpRequest(req);+ // Every MCP call is a POST: its tools are gated one by one (createMcpServer).+ const auth = await authenticateMcpRequest(req, { gateWrites: false });if (auth instanceof NextResponse) return auth;const server = createMcpServer(auth);diff --git a/web/src/app/api/mcp/site-audits/route.test.ts b/web/src/app/api/mcp/site-audits/route.test.tsnew file mode 100644index 000000000..301c06084--- /dev/null+++ b/web/src/app/api/mcp/site-audits/route.test.ts@@ -0,0 +1,61 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * POST /api/mcp/site-audits: a Site Audit refused for a read-only workspace+ * (runSiteAuditFor's own check) answers 402 subscription_inactive, as the+ * route's gate does; any other failure is still a 500.+ */++const { runSiteAuditFor } = vi.hoisted(() => ({ runSiteAuditFor: vi.fn() }));+vi.mock('@/lib/mcp-auth', () => ({+ authenticateMcpRequest: vi.fn(async () => ({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ })),+}));+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));+vi.mock('@/lib/mcp/data', () => ({ runSiteAuditFor, listSiteAuditsFor: vi.fn() }));++const { POST } = await import('./route');+const { SubscriptionInactiveError } = await import('@/lib/mcp/subscription-gate');++const post = () =>+ POST(+ new Request('http://localhost/api/mcp/site-audits', {+ method: 'POST',+ body: JSON.stringify({ brand_id: 'brand-1', url: 'https://ansvisor.com' }),+ }),+ );++// Braces: a function returned from beforeEach runs as its teardown.+beforeEach(() => {+ runSiteAuditFor.mockReset();+});++describe('POST /api/mcp/site-audits', () => {+ it('answers 402 subscription_inactive when the audit is refused for a read-only workspace', async () => {+ runSiteAuditFor.mockRejectedValue(new SubscriptionInactiveError());+ const res = await post();+ expect(res.status).toBe(402);+ expect(await res.json()).toMatchObject({+ error: 'plan_limit',+ code: 'subscription_inactive',+ });+ });++ it('keeps any other failure a 500 with its message', async () => {+ runSiteAuditFor.mockRejectedValue(new Error('Internal site-audit endpoint returned 503'));+ const res = await post();+ expect(res.status).toBe(500);+ expect(await res.json()).toEqual({ error: 'Internal site-audit endpoint returned 503' });+ });++ it('starts the audit otherwise', async () => {+ runSiteAuditFor.mockResolvedValue({ id: 'audit-1', status: 'running' });+ const res = await post();+ expect(res.status).toBe(202);+ });+});diff --git a/web/src/app/api/mcp/site-audits/route.ts b/web/src/app/api/mcp/site-audits/route.tsindex e8bc479dc..82ae2c29e 100644--- a/web/src/app/api/mcp/site-audits/route.ts+++ b/web/src/app/api/mcp/site-audits/route.ts@@ -1,6 +1,7 @@import { NextResponse } from 'next/server';import { authenticateMcpRequest } from '@/lib/mcp-auth';import { runSiteAuditFor, listSiteAuditsFor } from '@/lib/mcp/data';+import { failedCallResponse } from '@/lib/mcp/subscription-gate';/*** GET /api/mcp/site-audits?brand_id=…@@ -60,7 +61,6 @@ export async function POST(req: Request) {}return NextResponse.json(result, { status: 202 });} catch (err) {- const message = err instanceof Error ? err.message : 'Failed';- return NextResponse.json({ error: message }, { status: 500 });+ return failedCallResponse(err);}}diff --git a/web/src/app/api/stripe/checkout/route.test.ts b/web/src/app/api/stripe/checkout/route.test.tsnew file mode 100644index 000000000..e492c020f--- /dev/null+++ b/web/src/app/api/stripe/checkout/route.test.ts@@ -0,0 +1,156 @@+import type { NextRequest } from 'next/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * POST /api/stripe/checkout: a Stripe Checkout for a new subscription, from+ * onboarding's plan step (monthly, back to the step on cancel) or from+ * Billing once a plan has ended (either period, back to Billing on cancel).+ * Admins only, and never beside a subscription that is still there.+ */++let role: string;+let org: Record<string, unknown>;++/** A Supabase query that answers `single()` with the row given. */+const row = (data: unknown) => {+ const query = { select: () => query, eq: () => query, single: async () => ({ data }) };+ return query;+};++vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ auth: { getUser: async () => ({ data: { user: { id: 'u1', email: '[email protected]' } } }) },+ from: (table: string) => row(table === 'profiles' ? { organization_id: 'org1', role } : org),+ }),+}));++vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: { from: vi.fn() } }));++const stripeApi = vi.hoisted(() => ({+ createSession: vi.fn(),+ listSubscriptions: vi.fn(),+ annual: true,+}));+vi.mock('@/lib/stripe', () => ({+ stripe: {+ checkout: { sessions: { create: stripeApi.createSession } },+ subscriptions: { list: stripeApi.listSubscriptions },+ customers: { create: vi.fn() },+ },+ PRICE_IDS: {},+ priceIdFor: (planId: string, interval: string) =>+ interval === 'year' && !stripeApi.annual ? undefined : `price_${planId}_${interval}`,+}));++const { POST } = await import('./route');++const post = (body: unknown) =>+ POST(+ new Request('http://localhost/api/stripe/checkout', {+ method: 'POST',+ body: JSON.stringify(body),+ }) as unknown as NextRequest,+ );++/** What Checkout was asked for. */+const session = () => stripeApi.createSession.mock.calls[0][0];++beforeEach(() => {+ vi.clearAllMocks();+ role = 'admin';+ // A plan that ended: Billing starts a new one.+ org = {+ stripe_customer_id: 'cus_1',+ stripe_subscription_id: 'sub_old',+ subscription_status: 'canceled',+ };+ stripeApi.annual = true;+ stripeApi.createSession.mockResolvedValue({ url: 'https://checkout.stripe.com/c/1' });+ // A customer who had a subscription before: no second trial.+ stripeApi.listSubscriptions.mockResolvedValue({ data: [{ id: 'sub_old' }] });+});++describe('POST /api/stripe/checkout', () => {+ it("bills monthly and returns to onboarding's plan step by default", async () => {+ const res = await post({ planId: 'starter', organizationId: 'org1' });+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ url: 'https://checkout.stripe.com/c/1' });+ expect(session().line_items).toEqual([{ price: 'price_starter_month', quantity: 1 }]);+ expect(session().cancel_url).toBe('http://localhost:3000/dashboard/onboarding');+ expect(session().subscription_data.trial_period_days).toBeUndefined();+ });++ it('bills a year up front and returns to Billing, for a plan chosen there', async () => {+ const res = await post({+ planId: 'growth',+ organizationId: 'org1',+ interval: 'year',+ returnTo: 'billing',+ });+ expect(res.status).toBe(200);+ expect(session().line_items).toEqual([{ price: 'price_growth_year', quantity: 1 }]);+ expect(session().cancel_url).toBe('http://localhost:3000/dashboard/settings/billing');+ expect(session().subscription_data.metadata).toEqual({+ organization_id: 'org1',+ plan_id: 'growth',+ });+ });++ it('starts a new account’s first subscription, with no subscription yet', async () => {+ // A customer from an earlier Checkout that was left, and no subscription.+ org = {+ stripe_customer_id: 'cus_1',+ stripe_subscription_id: null,+ subscription_status: 'incomplete',+ };+ stripeApi.listSubscriptions.mockResolvedValue({ data: [] });+ const res = await post({ planId: 'starter', organizationId: 'org1' });+ expect(res.status).toBe(200);+ });++ it("refuses another organization's checkout", async () => {+ const res = await post({ planId: 'starter', organizationId: 'org2' });+ expect(res.status).toBe(403);+ expect(stripeApi.createSession).not.toHaveBeenCalled();+ });++ it('leaves buying a plan to admins', async () => {+ role = 'manager';+ const res = await post({ planId: 'starter', organizationId: 'org1' });+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({+ error: 'Only admins can change the plan',+ code: 'admin_only',+ });+ expect(stripeApi.createSession).not.toHaveBeenCalled();+ });++ it('starts no second subscription beside one still there', async () => {+ for (const status of ['active', 'trialing', 'past_due', 'unpaid']) {+ org = { ...org, subscription_status: status };+ const res = await post({ planId: 'growth', organizationId: 'org1', returnTo: 'billing' });+ expect(res.status).toBe(409);+ expect(await res.json()).toMatchObject({ code: 'subscription_exists' });+ }+ expect(stripeApi.createSession).not.toHaveBeenCalled();+ });++ it('refuses a period or a return it does not know', async () => {+ expect(+ (await post({ planId: 'growth', organizationId: 'org1', interval: 'week' })).status,+ ).toBe(400);+ expect(+ (await post({ planId: 'growth', organizationId: 'org1', returnTo: 'https://evil.example' }))+ .status,+ ).toBe(400);+ expect((await post({ planId: 'enterprise', organizationId: 'org1' })).status).toBe(400);+ expect(stripeApi.createSession).not.toHaveBeenCalled();+ });++ it('refuses a year when its price is not set up', async () => {+ stripeApi.annual = false;+ const res = await post({ planId: 'growth', organizationId: 'org1', interval: 'year' });+ expect(res.status).toBe(400);+ expect(stripeApi.createSession).not.toHaveBeenCalled();+ });+});diff --git a/web/src/app/api/stripe/checkout/route.ts b/web/src/app/api/stripe/checkout/route.tsindex 5417abfd7..82d0c305b 100644--- a/web/src/app/api/stripe/checkout/route.ts+++ b/web/src/app/api/stripe/checkout/route.ts@@ -1,8 +1,20 @@import { NextRequest, NextResponse } from 'next/server';+import { z } from 'zod';import { createClient } from '@/lib/supabase/server';import { supabaseAdmin } from '@/lib/supabase/admin';-import { stripe, PRICE_IDS } from '@/lib/stripe';+import { stripe, PRICE_IDS, priceIdFor } from '@/lib/stripe';import { TRIAL_DAYS, hasUsedTrial } from '@/lib/billing/trial';+import { subscriptionEnded } from '@/lib/billing/plan-purchase';++/** POST /api/stripe/checkout's body. */+const checkoutSchema = z.object({+ planId: z.enum(['starter', 'growth']),+ organizationId: z.string().min(1),+ /** A year up front, from Billing's annual cards; monthly otherwise. */+ interval: z.enum(['month', 'year']).optional(),+ /** Where a canceled checkout goes back to: Billing, or onboarding's plan step. */+ returnTo: z.literal('billing').optional(),+});export async function POST(req: NextRequest) {try {@@ -15,15 +27,11 @@ export async function POST(req: NextRequest) {return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });}- const body = await req.json();- const { planId, organizationId } = body as {- planId: 'starter' | 'growth';- organizationId: string;- };-- if (!planId || !organizationId) {- return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });+ const parsed = checkoutSchema.safeParse(await req.json().catch(() => null));+ if (!parsed.success) {+ return NextResponse.json({ error: 'Invalid request' }, { status: 400 });}+ const { planId, organizationId, interval, returnTo } = parsed.data;// The org id arrives in the request body, so confirm the caller is// actually in it. Row-level security used to be the only thing standing@@ -31,15 +39,23 @@ export async function POST(req: NextRequest) {// written with the service role, which answers to nothing but this check.const { data: callerProfile } = await supabase.from('profiles')- .select('organization_id')+ .select('organization_id, role').eq('id', user.id).single();if (callerProfile?.organization_id !== organizationId) {return NextResponse.json({ error: 'Forbidden' }, { status: 403 });}+ // Buying a plan charges the organization's card: admins only, as the+ // subscription route has it (a new account's creator is its admin).+ if (callerProfile.role !== 'admin') {+ return NextResponse.json(+ { error: 'Only admins can change the plan', code: 'admin_only' },+ { status: 403 },+ );+ }- const priceId = PRICE_IDS[planId]?.monthly;+ const priceId = priceIdFor(planId, interval === 'year' ? 'year' : 'month');if (!priceId) {console.error('[stripe/checkout] Missing price ID for plan:',@@ -53,10 +69,23 @@ export async function POST(req: NextRequest) {// Fetch org to check for existing Stripe customerconst { data: org } = await supabase.from('organizations')- .select('stripe_customer_id')+ .select('stripe_customer_id, stripe_subscription_id, subscription_status').eq('id', organizationId).single();+ // A subscription still there (billing, trialing, or a payment being+ // retried) is changed or fixed in Billing: a second Checkout would start+ // a second subscription on the same card.+ if (+ org?.stripe_subscription_id &&+ !subscriptionEnded(org.subscription_status as string | null)+ ) {+ return NextResponse.json(+ { error: 'This organization already has a subscription', code: 'subscription_exists' },+ { status: 409 },+ );+ }+let customerId = org?.stripe_customer_id as string | null;// Create Stripe customer if none exists@@ -92,7 +121,7 @@ export async function POST(req: NextRequest) {metadata: { organization_id: organizationId, plan_id: planId },},success_url: `${appUrl}/api/stripe/success?session_id={CHECKOUT_SESSION_ID}`,- cancel_url: `${appUrl}/dashboard/onboarding`,+ cancel_url: `${appUrl}${returnTo === 'billing' ? '/dashboard/settings/billing' : '/dashboard/onboarding'}`,allow_promotion_codes: true,// Collect billing address + VAT/tax ID up front so invoices are// complete; later edits happen in the Customer Portal (/api/stripe/portal).diff --git a/web/src/components/billing/read-only-banner.test.tsx b/web/src/components/billing/read-only-banner.test.tsxnew file mode 100644index 000000000..2c41daf47--- /dev/null+++ b/web/src/components/billing/read-only-banner.test.tsx@@ -0,0 +1,116 @@+import { act, type ReactNode } 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 { PlanProvider } from '@/components/providers/plan-provider';+import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';+import { UpgradeDialogProvider } from '@/components/providers/upgrade-dialog-provider';+import { ReadOnlyBanner } from './read-only-banner';++let pathname = '/dashboard/insights';+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+ usePathname: () => pathname,+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++async function render({+ active = false,+ status = 'canceled',+ role = 'admin',+ adminName = null,+}: { active?: boolean; status?: string; role?: TeamRole; adminName?: string | null } = {}) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <PlanProvider planId="starter" subscriptionActive={active} subscriptionStatus={status}>+ <RoleProvider role={role}>+ <UpgradeDialogProvider adminName={adminName}>+ <ReadOnlyBanner />+ </UpgradeDialogProvider>+ </RoleProvider>+ </PlanProvider>+ </NextIntlClientProvider>,+ );+ });+}++const link = () => container.querySelector('a');++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ pathname = '/dashboard/insights';+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.unstubAllEnvs();+});++describe('ReadOnlyBanner', () => {+ const seePlans = () =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === 'See plans');++ it('says the workspace is read-only, and See plans opens the dialog', async () => {+ await render({ status: 'canceled' });+ expect(container.textContent).toContain(+ 'Your workspace is read-only. You can look around; adding, running and AI need a plan.',+ );+ expect(link()).toBeNull();+ await act(async () => {+ seePlans()!.click();+ });+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain(+ 'Choose a plan to keep going',+ );+ });++ it('leaves See plans out on Billing itself', async () => {+ pathname = '/dashboard/settings/billing';+ await render();+ expect(container.textContent).toContain('Your workspace is read-only.');+ expect(seePlans()).toBeUndefined();+ });++ it('offers an admin Update payment method while a payment is being retried, on Billing too', async () => {+ pathname = '/dashboard/settings/billing';+ await render({ status: 'past_due' });+ expect(container.textContent).toContain(+ "Your last payment didn't go through, so your workspace is read-only.",+ );+ expect(container.querySelector('button')?.textContent).toBe('Update payment method');+ expect(seePlans()).toBeUndefined();+ });++ it('asks another member to have the admin update the payment method', async () => {+ await render({ status: 'unpaid', role: 'analyst', adminName: 'Jane Owner' });+ expect(container.textContent).toContain(+ 'Ask Jane Owner, your workspace admin, to update the payment method.',+ );+ expect(container.querySelector('button')).toBeNull();+ });++ it('offers every member See plans once the plan ended', async () => {+ await render({ role: 'analyst' });+ expect(seePlans()).toBeDefined();+ });++ it('shows nothing while the plan is active', async () => {+ await render({ active: true, status: 'active' });+ expect(container.textContent).toBe('');+ });+});diff --git a/web/src/components/billing/read-only-banner.tsx b/web/src/components/billing/read-only-banner.tsxnew file mode 100644index 000000000..6ce223a92--- /dev/null+++ b/web/src/components/billing/read-only-banner.tsx@@ -0,0 +1,63 @@+'use client';++import { AlertTriangle } from 'lucide-react';+import { useTranslations } from 'next-intl';+import { usePathname } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';+import {+ CHOOSE_PLAN_HREF,+ ReadOnlyAction,+ useAskAdmin,+ useUpgradeDialog,+} from '@/components/providers/upgrade-dialog-provider';+import { useUserRole } from '@/hooks/use-user-role';+import type { ReadOnlyReason } from '@/lib/billing/subscription-access';++/**+ * A thin band across the top of the dashboard while the workspace is+ * read-only: that it is, and the way out — See plans (the upgrade dialog; not+ * on Billing, which has them) or, for a payment being retried, Update payment+ * method for admins and an admin to ask for everyone else. Nothing while the+ * plan is active.+ */+export function ReadOnlyBanner() {+ const state = useUpgradeDialog();+ if (!state?.isLocked) return null;+ return <Band reason={state.reason} adminName={state.adminName} openUpgrade={state.openUpgrade} />;+}++function Band({+ reason,+ adminName,+ openUpgrade,+}: {+ reason: ReadOnlyReason;+ adminName: string | null;+ openUpgrade: () => void;+}) {+ const t = useTranslations('readOnly');+ const { canAdmin } = useUserRole();+ const pathname = usePathname();+ const ask = useAskAdmin(reason, adminName);+ const payment = reason === 'payment_failed';++ return (+ <div+ role="status"+ className="flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-amber-200 bg-amber-50 px-4 py-2 text-sm dark:border-amber-900/50 dark:bg-amber-950/30"+ >+ <AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />+ <p className="min-w-0 flex-1 text-amber-900 dark:text-amber-200">+ {t(`banner.${reason}`)}+ {payment && !canAdmin && <> {ask}</>}+ </p>+ {payment ? (+ canAdmin && <ReadOnlyAction reason={reason} variant="outline" size="sm" />+ ) : pathname.startsWith(CHOOSE_PLAN_HREF) ? null : (+ <Button variant="outline" size="sm" onClick={() => openUpgrade()}>+ {t('banner.seePlans')}+ </Button>+ )}+ </div>+ );+}diff --git a/web/src/components/billing/subscription-expired-notice.tsx b/web/src/components/billing/subscription-expired-notice.tsxdeleted file mode 100644index 77cc291e3..000000000--- a/web/src/components/billing/subscription-expired-notice.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { AlertCircle } from 'lucide-react';-import { OnboardingSignOutButton } from '@/components/auth/onboarding-sign-out-button';--/**- * Shown to a non-admin member when their org's subscription has lapsed.- * They can't renew or re-onboard, so instead of the payment / onboarding flow- * they get a clear "contact your account owner" message (plus a way out).- */-export function SubscriptionExpiredNotice({ ownerName }: { ownerName?: string | null }) {- return (- <div className="flex min-h-screen flex-col items-center justify-center bg-background p-6">- <div className="w-full max-w-md rounded-xl border bg-card p-8 text-center shadow-sm">- <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-amber-500/10">- <AlertCircle className="h-6 w-6 text-amber-600 dark:text-amber-400" />- </div>- <h1 className="mt-4 text-lg font-semibold">Subscription required</h1>- <p className="mt-2 text-sm text-muted-foreground">- This account’s subscription has ended, so tracking and dashboard access are paused.- {ownerName- ? ` Please contact your account owner (${ownerName}) to renew it.`- : ' Please contact your account owner or an admin to renew it.'}- </p>- <p className="mt-3 text-xs text-muted-foreground">- You don’t have billing access on this account, so you can’t renew it or make- changes until it’s active again.- </p>- </div>- <OnboardingSignOutButton />- </div>- );-}diff --git a/web/src/components/content/publish-dialog.tsx b/web/src/components/content/publish-dialog.tsxindex 271bb189b..93336e94e 100644--- a/web/src/components/content/publish-dialog.tsx+++ b/web/src/components/content/publish-dialog.tsx@@ -17,6 +17,7 @@ import { Label } from '@/components/ui/label';import { LoadingDots } from '@/components/ui/loading-dots';import { setContentDraftStatus } from '@/lib/actions/content-drafts';import { publishPage, readPublishAddress } from '@/lib/content/publish-client';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';/*** Mark published (CE-013): the person gives the address the page is live@@ -44,6 +45,7 @@ export function PublishDialog({}) {const t = useTranslations('contentEditor.publish');const tFailure = useTranslations('apiFailure');+ const { openUpgrade } = useUpgradeGate();// Undefined while the starting address is read.const [url, setUrl] = useState<string | undefined>(undefined);const [saving, setSaving] = useState(false);@@ -90,10 +92,15 @@ export function PublishDialog({}setSaving(false);if (!result.ok) {+ // A read-only workspace: the upgrade dialog, with the reason kept here.+ if (result.code === 'subscription') openUpgrade();setProblem(result.code === 'invalid_url'? t('invalidUrl')- : result.code === 'session' || result.code === 'workspace' || result.code === 'busy'+ : result.code === 'session' ||+ result.code === 'workspace' ||+ result.code === 'busy' ||+ result.code === 'subscription'? tFailure(result.code): t(result.code === 'not_found' ? 'notFound' : 'failed'),);diff --git a/web/src/components/content/send-to-cms-dialog.tsx b/web/src/components/content/send-to-cms-dialog.tsxindex 5a47b6f85..c38defb33 100644--- a/web/src/components/content/send-to-cms-dialog.tsx+++ b/web/src/components/content/send-to-cms-dialog.tsx@@ -34,6 +34,7 @@ import {type DraftCms,} from '@/lib/content/cms-send-client';import { exportPlaceholders, pageFields, titlePlaceholders } from '@/lib/content/ready-to-publish';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';import { CmsTargetPicker, CmsTargetUnchecked, useCmsTarget } from './cms-target';/**@@ -77,6 +78,7 @@ export function SendDialog({}) {const t = useTranslations('contentEditor.editor.send');const tFailure = useTranslations('apiFailure');+ const { openUpgrade } = useUpgradeGate();const format = useFormatter();const page = useMemo(() => pageFields({ title, html, sourceUrl, author, teamByline }),@@ -167,6 +169,8 @@ export function SendDialog({);setSending(false);if (!result.ok) {+ // A read-only workspace: the upgrade dialog, with the reason kept here.+ if (result.code === 'subscription') openUpgrade();setProblem({ code: result.code, field: result.field });return;}@@ -225,7 +229,9 @@ export function SendDialog({});}const { code, field } = shown;- if (code === 'session' || code === 'workspace' || code === 'busy') return tFailure(code);+ if (code === 'session' || code === 'workspace' || code === 'busy' || code === 'subscription') {+ return tFailure(code);+ }// Webflow not ready sent the page to the webhook: what to fix is Webflow.if (code === 'no_webhook' && webflow && !webflow.ready) return t('errors.no_webhookWebflow');// The server names the path ("pages.0.slug"); the field is its last part.diff --git a/web/src/components/prompts/prompt-improve-tab.test.tsx b/web/src/components/prompts/prompt-improve-tab.test.tsxindex e35508eab..7930b40bb 100644--- a/web/src/components/prompts/prompt-improve-tab.test.tsx+++ b/web/src/components/prompts/prompt-improve-tab.test.tsx@@ -1,11 +1,26 @@-import { act } from 'react';+import { act, useEffect } 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 { PlanId } from '@/config/plans';import type { ImproveQuota, ImproveSet } from '@/lib/prompt-improve';-import { ImproveTab, type ImproveController } from './prompt-improve-tab';+import { ImproveTab, useImprove, type ImproveController } from './prompt-improve-tab';++// The set's read and its generation, as the API answers them.+const actions = vi.hoisted(() => ({+ getImproveSuggestions: vi.fn(),+ generateImproveSuggestions: vi.fn(),+}));+vi.mock('@/lib/actions/prompt-improve', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/actions/prompt-improve')>()),+ ...actions,+}));+// The workspace's plan: active unless a test says it's read-only.+const gate = vi.hoisted(() => ({ isLocked: false, openUpgrade: vi.fn() }));+vi.mock('@/components/providers/upgrade-gate', () => ({+ useUpgradeGate: () => gate,+}));vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (@@ -166,3 +181,46 @@ describe('the Improve tab’s dates', () => {expect(container.textContent).toMatch(/Sent Oct \d{1,2}, 2026 · AC-12/);});});++describe('useImprove on a read-only workspace (plan not active)', () => {+ const range = { preset: '30d', from: '2026-09-27' };+ let improve: ImproveController;+ const keep = (value: ImproveController) => {+ improve = value;+ };+ function Probe({ onImprove }: { onImprove: (value: ImproveController) => void }) {+ const value = useImprove({ promptId: 'prompt-1', range, planId: 'growth' });+ useEffect(() => onImprove(value));+ return null;+ }+ const mount = () =>+ act(async () => {+ root.render(<Probe onImprove={keep} />);+ });++ beforeEach(() => {+ actions.getImproveSuggestions.mockReset().mockResolvedValue({ improve: null, quota: null });+ actions.generateImproveSuggestions.mockReset();+ gate.openUpgrade.mockReset();+ });++ afterEach(() => {+ gate.isLocked = false;+ });++ it('reads the stored set while the plan is active', async () => {+ await mount();+ expect(actions.getImproveSuggestions).toHaveBeenCalledTimes(1);+ });++ it('asks the API nothing by itself, opens empty, and Generate opens the upgrade dialog', async () => {+ gate.isLocked = true;+ await mount();+ expect(actions.getImproveSuggestions).not.toHaveBeenCalled();+ expect(improve.status).toBe('ready');+ expect(improve.set).toBeNull();+ await act(async () => improve.generate());+ expect(gate.openUpgrade).toHaveBeenCalledTimes(1);+ expect(actions.generateImproveSuggestions).not.toHaveBeenCalled();+ });+});diff --git a/web/src/components/prompts/prompt-improve-tab.tsx b/web/src/components/prompts/prompt-improve-tab.tsxindex 01ca07fa7..d4c584654 100644--- a/web/src/components/prompts/prompt-improve-tab.tsx+++ b/web/src/components/prompts/prompt-improve-tab.tsx@@ -37,6 +37,7 @@ import { Skeleton } from '@/components/ui/skeleton';import { Textarea } from '@/components/ui/textarea';import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';import { cn } from '@/lib/utils';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';import { formatDate, formatDateTime } from '@/lib/format';import { PLANS, hasFeature, type PlanId } from '@/config/plans';import {@@ -102,6 +103,9 @@ export function useImprove({planId: PlanId | null;}): ImproveController {const locked = planId !== null && !hasFeature(PLANS[planId], 'prompt_improve');+ // A read-only workspace (plan not active): the set isn't read (the API+ // refuses it), the tab opens empty, and Generate opens the upgrade dialog.+ const { isLocked: readOnly, openUpgrade } = useUpgradeGate();const key = promptId ? `${promptId}|${JSON.stringify(range)}` : '';const [state, setState] = useState<{key: string;@@ -171,22 +175,26 @@ export function useImprove({}, [promptId, range, apply]);useEffect(() => {- if (!promptId || locked) return;+ if (!promptId || locked || readOnly) return;reload();// `key` covers the prompt and the range.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [key, locked]);+ }, [key, locked, readOnly]);const generate = useCallback(() => {if (!promptId) return;+ if (readOnly) {+ openUpgrade();+ return;+ }const forKey = keyRef.current;setState((s) => ({ ...s, key: forKey, status: 'generating', error: null }));generateImproveSuggestions(promptId, range).then((r) => apply(forKey, 'generate', r));- }, [promptId, range, apply]);+ }, [promptId, range, apply, readOnly, openUpgrade]);const current = state.key === key ? state : null;- const status: Status = locked ? 'locked' : (current?.status ?? 'idle');- const set = current?.set ?? null;+ const status: Status = locked ? 'locked' : readOnly ? 'ready' : (current?.status ?? 'idle');+ const set = readOnly ? null : (current?.set ?? null);const send = useCallback(() => {if (!promptId || !state.set || sending) return;diff --git a/web/src/components/providers/plan-provider.tsx b/web/src/components/providers/plan-provider.tsxindex cf85818e0..099b1b3dc 100644--- a/web/src/components/providers/plan-provider.tsx+++ b/web/src/components/providers/plan-provider.tsx@@ -15,21 +15,36 @@ interface PlanContextValue {* per-customer overrides.*/allowedModelIds: string[] | null;+ /**+ * Whether the org's plan is active (or trialing). When it isn't, the+ * dashboard is read-only: every page opens, and an action opens the+ * upgrade dialog instead of running (useUpgradeGate). Always true+ * self-hosted.+ */+ subscriptionActive: boolean;+ /** Stripe's subscription status, for why it isn't active; null self-hosted. */+ subscriptionStatus: string | null;}const PlanContext = createContext<PlanContextValue>({planId: 'self_hosted',isCloud: false,allowedModelIds: null,+ subscriptionActive: true,+ subscriptionStatus: null,});export function PlanProvider({planId,allowedModelIds = null,+ subscriptionActive = true,+ subscriptionStatus = null,children,}: {planId: PlanId;allowedModelIds?: string[] | null;+ subscriptionActive?: boolean;+ subscriptionStatus?: string | null;children: React.ReactNode;}) {const isCloud = process.env.NEXT_PUBLIC_IS_CLOUD === 'true';@@ -41,6 +56,8 @@ export function PlanProvider({planId: effectivePlan,isCloud,allowedModelIds: isCloud ? allowedModelIds : null,+ subscriptionActive: isCloud ? subscriptionActive : true,+ subscriptionStatus: isCloud ? subscriptionStatus : null,}}>{children}diff --git a/web/src/components/providers/upgrade-dialog-provider.test.tsx b/web/src/components/providers/upgrade-dialog-provider.test.tsxnew file mode 100644index 000000000..330615ead--- /dev/null+++ b/web/src/components/providers/upgrade-dialog-provider.test.tsx@@ -0,0 +1,219 @@+import { act, type ReactNode } 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 { PlanProvider } from './plan-provider';+import { RoleProvider, type TeamRole } from './role-provider';+import { UpgradeDialogProvider, useUpgradeGate } from './upgrade-dialog-provider';++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;+const action = vi.fn((label: string) => `ran ${label}`);+let returned: unknown;+// What a guarded button says it does, for the dialog's label; none unless a test says.+let label: string | undefined;++/** A button whose click is guarded, as a page's action button would be. */+function Probe() {+ const { guard, isLocked } = useUpgradeGate();+ return (+ <button+ type="button"+ data-locked={String(isLocked)}+ onClick={() => {+ returned = guard(action, { action: label })('Run all');+ }}+ >+ Run all+ </button>+ );+}++async function render({+ active,+ status = 'canceled',+ role = 'admin',+ adminName = null,+ provider = true,+}: {+ active: boolean;+ status?: string | null;+ role?: TeamRole;+ adminName?: string | null;+ provider?: boolean;+}) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <PlanProvider planId="starter" subscriptionActive={active} subscriptionStatus={status}>+ <RoleProvider role={role}>+ {provider ? (+ <UpgradeDialogProvider adminName={adminName}>+ <Probe />+ </UpgradeDialogProvider>+ ) : (+ <Probe />+ )}+ </RoleProvider>+ </PlanProvider>+ </NextIntlClientProvider>,+ );+ });+}++const probe = () => container.querySelector<HTMLButtonElement>('button[data-locked]')!;+const dialog = () => document.querySelector('[role="dialog"]');+const button = (label: string) =>+ [...document.querySelectorAll('button')].find((b) => b.textContent?.trim() === label);++async function runAll() {+ await act(async () => {+ probe().click();+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ returned = undefined;+ label = undefined;+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.unstubAllEnvs();+});++describe('useUpgradeGate', () => {+ it('runs the action while the plan is active', async () => {+ await render({ active: true, status: 'active' });+ expect(probe().dataset.locked).toBe('false');+ await runAll();+ expect(action).toHaveBeenCalledWith('Run all');+ expect(returned).toBe('ran Run all');+ expect(dialog()).toBeNull();+ });++ it('opens the upgrade dialog instead, without running it, while read-only', async () => {+ await render({ active: false });+ expect(probe().dataset.locked).toBe('true');+ await runAll();+ expect(action).not.toHaveBeenCalled();+ expect(returned).toBeUndefined();+ expect(dialog()?.textContent).toContain('Choose a plan to keep going');+ expect(dialog()?.textContent).toContain(+ "Your workspace has no active plan, so it\'s read-only. Everything you set up is still here: pick a plan to track, write and run your agents again.",+ );+ // No label when the button didn't say what it does.+ expect(document.querySelector('[data-slot="upgrade-action"]')).toBeNull();+ });++ it('closes with Not now, and opens again on the next action', async () => {+ await render({ active: false });+ await runAll();+ await act(async () => {+ button('Not now')!.click();+ });+ await vi.waitFor(() => expect(dialog()).toBeNull());++ await runAll();+ expect(dialog()?.textContent).toContain('Choose a plan to keep going');+ expect(action).not.toHaveBeenCalled();+ });++ it('labels the dialog with what was clicked, when the button says', async () => {+ label = 'Adding prompts needs a plan';+ await render({ active: false });+ await runAll();+ expect(document.querySelector('[data-slot="upgrade-action"]')?.textContent).toBe(+ 'Adding prompts needs a plan',+ );+ });++ it('takes an admin to Billing to choose a plan', async () => {+ await render({ active: false, status: 'canceled' });+ await runAll();+ const link = [...document.querySelectorAll('a')].find((a) => a.textContent === 'Choose a plan');+ expect(link?.getAttribute('href')).toBe('/dashboard/settings/billing');+ expect(button('Update payment method')).toBeUndefined();+ });++ it('takes an admin to Stripe’s billing page while a payment is being retried', async () => {+ // Stripe's billing page; a hash, which jsdom can navigate to.+ const fetchMock = vi.fn(async () => Response.json({ url: '#portal' }));+ vi.stubGlobal('fetch', fetchMock);+ try {+ await render({ active: false, status: 'past_due' });+ await runAll();+ expect(dialog()?.textContent).toContain('Update your payment method to keep going');+ expect(dialog()?.textContent).toContain("Your last payment didn't go through");+ // No new plan beside the one being retried.+ expect(+ [...document.querySelectorAll('a')].some((a) => a.textContent === 'Choose a plan'),+ ).toBe(false);+ await act(async () => {+ button('Update payment method')!.click();+ });+ expect(fetchMock).toHaveBeenCalledWith('/api/stripe/portal', { method: 'POST' });+ await vi.waitFor(() => expect(window.location.hash).toBe('#portal'));+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('asks another member to turn to the admin, by name when known', async () => {+ await render({ active: false, status: null, role: 'manager', adminName: 'Jane Owner' });+ await runAll();+ expect(dialog()?.textContent).toContain('Your workspace has no active plan');+ expect(dialog()?.textContent).toContain(+ 'Ask Jane Owner, your workspace admin, to choose a plan.',+ );+ expect(document.querySelector('a')).toBeNull();+ });++ it('asks another member to have the admin update the payment method', async () => {+ await render({ active: false, status: 'unpaid', role: 'analyst' });+ await runAll();+ expect(dialog()?.textContent).toContain(+ 'Ask your workspace admin to update the payment method.',+ );+ expect(button('Update payment method')).toBeUndefined();+ });++ it('asks for the workspace admin without a name', async () => {+ await render({ active: false, role: 'analyst' });+ await runAll();+ expect(dialog()?.textContent).toContain('Ask your workspace admin to choose a plan.');+ });++ it('never locks self-hosted', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ await render({ active: false });+ await runAll();+ expect(action).toHaveBeenCalledTimes(1);+ expect(dialog()).toBeNull();+ });++ it('runs the action outside the dashboard’s provider', async () => {+ await render({ active: false, provider: false });+ await runAll();+ expect(action).toHaveBeenCalledTimes(1);+ expect(dialog()).toBeNull();+ });+});diff --git a/web/src/components/providers/upgrade-dialog-provider.tsx b/web/src/components/providers/upgrade-dialog-provider.tsxnew file mode 100644index 000000000..0b997aa88--- /dev/null+++ b/web/src/components/providers/upgrade-dialog-provider.tsx@@ -0,0 +1,172 @@+'use client';++import { useCallback, useMemo, useState, type ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Link } from '@/i18n/navigation';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { usePlanContext } from '@/components/providers/plan-provider';+import { useUserRole } from '@/hooks/use-user-role';+import { readOnlyReason, type ReadOnlyReason } from '@/lib/billing/subscription-access';+import { openBillingPortal } from '@/lib/billing/portal-client';+import { CHOOSE_PLAN_HREF, UpgradeDialogContext } from './upgrade-gate';++// The context and its hooks live in ./upgrade-gate, free of this file's UI,+// so a component that only gates an action doesn't load the dialog.+export { CHOOSE_PLAN_HREF, useUpgradeDialog, useUpgradeGate } from './upgrade-gate';++/**+ * Ansvisor Cloud's read-only mode: a workspace whose trial ended or whose+ * plan was canceled can still open every page, but an action (anything that+ * writes, runs or spends) opens "Choose a plan to keep going" instead. The dialog+ * closes with Not now or its ×, and opens again on the next action, until a+ * plan is bought. Admins are taken to Billing; other members are asked to+ * turn to an admin. Self-hosted is never locked.+ */+export function UpgradeDialogProvider({+ adminName = null,+ children,+}: {+ adminName?: string | null;+ children: ReactNode;+}) {+ const { subscriptionActive, subscriptionStatus } = usePlanContext();+ const [open, setOpen] = useState(false);+ // What was clicked, for the dialog's label; none when it wasn't said.+ const [action, setAction] = useState<string | null>(null);+ const openUpgrade = useCallback((label?: string) => {+ // Only a label given: a handler passing its click event gives none.+ setAction(typeof label === 'string' && label ? label : null);+ setOpen(true);+ }, []);+ const value = useMemo(+ () => ({+ isLocked: !subscriptionActive,+ reason: readOnlyReason(subscriptionStatus),+ adminName,+ openUpgrade,+ }),+ [subscriptionActive, subscriptionStatus, adminName, openUpgrade],+ );++ return (+ <UpgradeDialogContext.Provider value={value}>+ {children}+ <UpgradeDialog+ open={open}+ onOpenChange={setOpen}+ reason={value.reason}+ adminName={adminName}+ action={action}+ />+ </UpgradeDialogContext.Provider>+ );+}++/**+ * What a member who isn't an admin is asked to do: have an admin choose a+ * plan, or update the payment method; by the admin's name when known.+ */+export function useAskAdmin(reason: ReadOnlyReason, adminName: string | null): string {+ const t = useTranslations('readOnly.ask');+ return adminName ? t(`${reason}Named`, { name: adminName }) : t(reason);+}++/**+ * An admin's way out: Choose a plan in Billing once the plan ended; Update+ * payment method (Stripe's billing page) while a payment is being retried,+ * since a second plan would mean a second subscription.+ */+export function ReadOnlyAction({+ reason,+ variant = 'default',+ size = 'default',+ onChoose,+}: {+ reason: ReadOnlyReason;+ variant?: 'default' | 'outline';+ size?: 'default' | 'sm';+ /** Called as the admin leaves for Billing: the dialog closes. */+ onChoose?: () => void;+}) {+ const t = useTranslations('readOnly');+ const [opening, setOpening] = useState(false);+ if (reason === 'payment_failed') {+ return (+ <Button+ variant={variant}+ size={size}+ disabled={opening}+ onClick={() => {+ setOpening(true);+ openBillingPortal().catch(() => {+ toast.error(t('portalFailed'));+ setOpening(false);+ });+ }}+ >+ {t('updatePayment')}+ </Button>+ );+ }+ return (+ <Link href={CHOOSE_PLAN_HREF} className={buttonVariants({ variant, size })} onClick={onChoose}>+ {t('choosePlan')}+ </Link>+ );+}++/**+ * "Choose a plan to keep going": the workspace is read-only, what was clicked+ * when the caller said, and the one thing to do. Its plan cards come with+ * Billing's Checkout in the dialog later; for now an admin goes to Billing.+ */+function UpgradeDialog({+ open,+ onOpenChange,+ reason,+ adminName,+ action,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ reason: ReadOnlyReason;+ adminName: string | null;+ action: string | null;+}) {+ const t = useTranslations('readOnly');+ const { canAdmin } = useUserRole();+ const ask = useAskAdmin(reason, adminName);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ {action && (+ <Badge variant="secondary" className="w-fit" data-slot="upgrade-action">+ {action}+ </Badge>+ )}+ <DialogTitle>{t(`dialog.title.${reason}`)}</DialogTitle>+ <DialogDescription>{t(`dialog.body.${reason}`)}</DialogDescription>+ </DialogHeader>+ {!canAdmin && <p className="text-sm">{ask}</p>}+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>{t('dialog.notNow')}</DialogClose>+ {canAdmin && <ReadOnlyAction reason={reason} onChoose={() => onOpenChange(false)} />}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/components/providers/upgrade-gate.ts b/web/src/components/providers/upgrade-gate.tsnew file mode 100644index 000000000..78a582130--- /dev/null+++ b/web/src/components/providers/upgrade-gate.ts@@ -0,0 +1,63 @@+'use client';++import { createContext, useCallback, useContext } from 'react';+import type { ReadOnlyReason } from '@/lib/billing/subscription-access';++/** Where an admin chooses a plan: Settings › Billing, open while the workspace is read-only. */+export const CHOOSE_PLAN_HREF = '/dashboard/settings/billing';++export interface UpgradeDialogState {+ /** The plan isn't active: an action opens the dialog instead of running. */+ isLocked: boolean;+ reason: ReadOnlyReason;+ /** The admin a member is asked to turn to, when their name could be read. */+ adminName: string | null;+ /**+ * Opens the upgrade dialog; `action` is a short label for what was clicked+ * ("Adding prompts needs a plan"), shown above its title. None, no label.+ */+ openUpgrade: (action?: string) => void;+}++/** Given by UpgradeDialogProvider (the dashboard's layout); null outside it. */+export const UpgradeDialogContext = createContext<UpgradeDialogState | null>(null);++/** The read-only state, or null outside the dashboard's provider. */+export function useUpgradeDialog(): UpgradeDialogState | null {+ return useContext(UpgradeDialogContext);+}++const noop = () => {};++/**+ * Gate an action on an active plan. `guard(fn)` gives a function that runs+ * `fn` with its arguments while the plan is active, and opens the upgrade+ * dialog instead (without running it) while the workspace is read-only;+ * `action` labels the dialog with what was clicked:+ *+ * const { guard } = useUpgradeGate();+ * <Button onClick={guard(handleRunAll, { action: t('runAllNeedsPlan') })}>Run all</Button>+ *+ * `isLocked` and `openUpgrade` are there for a flow that decides on its own,+ * such as a form that checks before it submits.+ */+export function useUpgradeGate() {+ const state = useContext(UpgradeDialogContext);+ const isLocked = state?.isLocked ?? false;+ const openUpgrade = state?.openUpgrade ?? noop;+ const guard = useCallback(+ <Args extends unknown[], Result>(+ fn: (...args: Args) => Result,+ options: { action?: string } = {},+ ) =>+ (...args: Args): Result | undefined => {+ if (isLocked) {+ openUpgrade(options.action);+ return undefined;+ }+ return fn(...args);+ },+ [isLocked, openUpgrade],+ );+ return { isLocked, openUpgrade, guard };+}diff --git a/web/src/components/settings/billing-section.tsx b/web/src/components/settings/billing-section.tsxindex e2b109898..61bf2a924 100644--- a/web/src/components/settings/billing-section.tsx+++ b/web/src/components/settings/billing-section.tsx@@ -12,6 +12,7 @@ import { AiUsageCard } from '@/components/settings/ai-usage-card';import { usePlanContext } from '@/components/providers/plan-provider';import { createClient } from '@/lib/supabase/client';import { PLANS, type PlanId } from '@/config/plans';+import { subscriptionEnded } from '@/lib/billing/plan-purchase';interface SubscriptionData {planId: string;@@ -56,6 +57,8 @@ export function BillingSection() {const t = useTranslations('settings');const { planId: contextPlanId } = usePlanContext();const [subscription, setSubscription] = useState<SubscriptionData | null>(null);+ // For a new subscription's Checkout, once the old one has ended.+ const [organizationId, setOrganizationId] = useState<string | null>(null);const [loading, setLoading] = useState(true);useEffect(() => {@@ -75,6 +78,7 @@ export function BillingSection() {.single();if (!profile?.organization_id) return;+ setOrganizationId(profile.organization_id);const { data: org } = await supabase.from('organizations')@@ -154,6 +158,7 @@ export function BillingSection() {}const plan = PLANS[subscription.planId as PlanId] ?? PLANS.starter;+ const ended = subscriptionEnded(subscription.status);return (<div className="space-y-6">@@ -178,7 +183,7 @@ export function BillingSection() {</p>)}- {subscription.currentPeriodEnd && !subscription.cancelAtPeriodEnd && (+ {subscription.currentPeriodEnd && !subscription.cancelAtPeriodEnd && !ended && (<p className="text-sm text-muted-foreground">{t(subscription.status === 'trialing' ? 'trialEndsOn' : 'renewsOn', {date: new Date(subscription.currentPeriodEnd).toLocaleDateString('en-US', {@@ -197,12 +202,13 @@ export function BillingSection() {{/* Plan Switcher */}<Card><CardHeader>- <CardTitle>{t('changePlan')}</CardTitle>+ <CardTitle>{ended ? t('choosePlanTitle') : t('changePlan')}</CardTitle></CardHeader><CardContent><PlanSwitchersubscription={subscription}onUpdate={(data) => setSubscription({ ...subscription, ...data })}+ organizationId={organizationId}/></CardContent></Card>diff --git a/web/src/components/settings/catalog-sources-card.tsx b/web/src/components/settings/catalog-sources-card.tsxindex 95ab507ca..ffa3d5179 100644--- a/web/src/components/settings/catalog-sources-card.tsx+++ b/web/src/components/settings/catalog-sources-card.tsx@@ -9,6 +9,7 @@ import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Skeleton } from '@/components/ui/skeleton';import { useUserRole } from '@/hooks/use-user-role';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';import { addFeedSource, listCatalogSources, removeCatalogSource } from '@/lib/actions/catalog';import { isStoreSource, SIGN_IN_PLATFORM_LABELS, type CatalogSource } from '@/lib/catalog';import {@@ -56,6 +57,8 @@ export function CatalogSourcesCard({const format = useFormatter();const { activeBrandId, brands } = useBrandStore();const { canManage } = useUserRole();+ // A read-only workspace's refusal opens the upgrade dialog, not a toast.+ const { openUpgrade } = useUpgradeGate();const brand = brands.find((b) => b.id === activeBrandId) ?? null;// The sources as read for a brand, and when ("synced 3 hours ago"): another@@ -121,7 +124,8 @@ export function CatalogSourcesCard({/** Says how a sync went, then reads the sources again. */const report = (result: CatalogSyncResult) => {- if (!result.ok) toast.error(t(`errors.${result.code}`));+ if (!result.ok && result.code === 'subscription') openUpgrade();+ else if (!result.ok) toast.error(t(`errors.${result.code}`));else if (result.status === 'ok') {toast.success(t('synced', { count: result.counts?.items ?? 0 }));} else toast.error(result.error ?? t('errors.failed'));@@ -155,7 +159,8 @@ export function CatalogSourcesCard({if (isStoreSource(source.kind)) {// A store goes through the API, which holds its sign-in.const removed = await removeStore(source.id);- if (!removed.ok) toast.error(t(`stores.errors.${removed.code}`));+ if (!removed.ok && removed.code === 'subscription') openUpgrade();+ else if (!removed.ok) toast.error(t(`stores.errors.${removed.code}`));load();} else {try {@@ -170,7 +175,8 @@ export function CatalogSourcesCard({/** Says how a store call went, then reads the sources again. */const reportStore = (result: StoreResult, success: string) => {- if (!result.ok) toast.error(result.message ?? t(`stores.errors.${result.code}`));+ if (!result.ok && result.code === 'subscription') openUpgrade();+ else if (!result.ok) toast.error(result.message ?? t(`stores.errors.${result.code}`));else toast.success(success);load();return result.ok;diff --git a/web/src/components/settings/plan-switcher.test.tsx b/web/src/components/settings/plan-switcher.test.tsxindex f61c4c90d..039d92c92 100644--- a/web/src/components/settings/plan-switcher.test.tsx+++ b/web/src/components/settings/plan-switcher.test.tsx@@ -13,6 +13,8 @@ vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), errvi.mock('@/lib/actions/cancel-feedback', () => ({sendCancelFeedback: vi.fn(async () => ({ ok: true })),}));+const refresh = vi.hoisted(() => vi.fn());+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ refresh }) }));(globalThis as typeof globalThis & {@@ -30,7 +32,8 @@ async function render(status = 'active',interval = 'month',role = 'admin',- }: { status?: string; interval?: string; role?: TeamRole } = {},+ cancelAtPeriodEnd = false,+ }: { status?: string; interval?: string; role?: TeamRole; cancelAtPeriodEnd?: boolean } = {},) {await act(async () => {root.render(@@ -41,11 +44,12 @@ async function render(planId,status,currentPeriodEnd: null,- cancelAtPeriodEnd: false,+ cancelAtPeriodEnd,priceAmount: 49,interval,}}onUpdate={onUpdate}+ organizationId="org1"/></RoleProvider></NextIntlClientProvider>,@@ -263,6 +267,8 @@ describe('buying during the free trial', () => {}),});expect(onUpdate).toHaveBeenCalledWith(expect.objectContaining({ status: 'active' }));+ // The layout reads the plan again: a read-only workspace opens up.+ expect(refresh).toHaveBeenCalledTimes(1);});it('buys a year without a code', async () => {@@ -299,6 +305,80 @@ describe('buying during the free trial', () => {});});+describe('choosing a plan once the old one has ended', () => {+ beforeEach(() => {+ // Checkout's address; a hash, which jsdom can navigate to.+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => Response.json({ url: '#checkout' })),+ );+ });++ it('starts a new subscription through Checkout, in the period chosen', async () => {+ await render('starter', { status: 'canceled', cancelAtPeriodEnd: true });+ expect(container.textContent).toContain(+ "Your plan isn't active. Choose one to start it again; you'll pay on Stripe's secure checkout.",+ );+ // No plan is current, and nothing to cancel or reactivate.+ expect(cardText().Starter).not.toContain('Current Plan');+ expect(button('Reactivate')).toBeUndefined();+ expect(button('Cancel Subscription')).toBeUndefined();++ await click('AnnualSave 20%');+ await click('Choose Growth');++ expect(fetch).toHaveBeenCalledWith('/api/stripe/checkout', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ planId: 'growth',+ organizationId: 'org1',+ interval: 'year',+ returnTo: 'billing',+ }),+ });+ expect(window.location.hash).toBe('#checkout');+ expect(onUpdate).not.toHaveBeenCalled();+ });++ it('says so when Checkout does not open, and lets the admin try again', async () => {+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({}, { status: 500 }));+ await render('starter', { status: 'canceled' });+ await click('Choose Starter');+ expect(toast.error).toHaveBeenCalledWith("Couldn't open the checkout. Try again.");+ expect(button('Choose Starter')?.disabled).toBe(false);+ });++ it('leaves choosing a plan to admins', async () => {+ await render('starter', { status: 'canceled', role: 'analyst' });+ expect(button('Choose Starter')).toBeUndefined();+ expect(button('Choose Growth')).toBeUndefined();+ });+});++describe('a payment being retried (past_due)', () => {+ it('changes the plan on the subscription, and never opens a second Checkout', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () =>+ Response.json({+ planId: 'growth',+ status: 'past_due',+ interval: 'month',+ priceAmount: 249,+ }),+ ),+ );+ await render('starter', { status: 'past_due' });+ expect(button('Choose Starter')).toBeUndefined();+ expect(button('Choose Growth')).toBeUndefined();+ expect(container.textContent).not.toContain("Your plan isn't active.");+ await click('Upgrade to Growth');+ await click('Confirm Change');+ expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual(['/api/stripe/subscription']);+ });+});+describe('cancelling', () => {it('asks what went wrong first, then cancels at the end of the period and tells the team', async () => {vi.stubGlobal(diff --git a/web/src/components/settings/plan-switcher.tsx b/web/src/components/settings/plan-switcher.tsxindex df2f2162a..aabd9745e 100644--- a/web/src/components/settings/plan-switcher.tsx+++ b/web/src/components/settings/plan-switcher.tsx@@ -27,9 +27,11 @@ import {FIRST_MONTH_CODE,annualSaving,periodPrice,+ subscriptionEnded,type BillingInterval,} from '@/lib/billing/plan-purchase';import { useUserRole } from '@/hooks/use-user-role';+import { useRouter } from '@/i18n/navigation';import { formatNumber } from '@/lib/format';import { cn } from '@/lib/utils';import { CancelSubscriptionDialog } from './cancel-subscription-dialog';@@ -46,26 +48,36 @@ interface SubscriptionData {interface PlanSwitcherProps {subscription: SubscriptionData;onUpdate: (data: SubscriptionData) => void;+ /** The organization a new subscription is for, once the old one has ended. */+ organizationId?: string | null;}-export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {+export function PlanSwitcher({ subscription, onUpdate, organizationId = null }: PlanSwitcherProps) {const t = useTranslations('settings');const tCards = useTranslations('settings.planCards');// Buying or changing the plan charges the organization's card: admins only,// as the subscription route checks.const { canAdmin } = useUserRole();+ // A change can unlock a read-only workspace: the layout reads the plan again.+ const router = useRouter();const [loading, setLoading] = useState(false);const [portalLoading, setPortalLoading] = useState(false);const [cancelOpen, setCancelOpen] = useState(false);// The plan a card's button asked for: bought now during a trial, or changed to.const [pending, setPending] = useState<{ planId: PlanId; buy: boolean } | null>(null);const [promoCode, setPromoCode] = useState(FIRST_MONTH_CODE);+ // The plan whose Checkout is opening, once the subscription has ended.+ const [checkoutPlan, setCheckoutPlan] = useState<PlanId | null>(null);const currentPlanId = subscription.planId as PlanId;const currentInterval: BillingInterval = subscription.interval === 'year' ? 'year' : 'month';const [period, setPeriod] = useState<BillingInterval>(currentInterval);// A trial is bought outright: any plan, either period, paid today.const trialing = subscription.status === 'trialing';+ // A canceled or never-started plan: no subscription to change, so a card+ // starts a new one through Stripe Checkout (the workspace is read-only+ // until then).+ const ended = subscriptionEnded(subscription.status);const saving = Math.max(0, ...SUBSCRIBABLE_PLANS.map((id) => annualSaving(id) ?? 0));async function handleConfirm() {@@ -98,6 +110,7 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {}const data = await res.json();onUpdate(data);+ router.refresh();toast.success(pending.buy ? t('planBought', { plan: PLANS[pending.planId].name }) : t('planChanged'),);@@ -109,6 +122,25 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {}}+ async function handleCheckout(planId: PlanId) {+ if (!organizationId) return;+ setCheckoutPlan(planId);+ try {+ const res = await fetch('/api/stripe/checkout', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ planId, organizationId, interval: period, returnTo: 'billing' }),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok || !data.url) throw new Error(data.error || t('checkoutFailed'));+ window.location.href = data.url;+ // No loading reset — we're navigating away to Stripe.+ } catch (err) {+ toast.error(err instanceof Error ? err.message : t('checkoutFailed'));+ setCheckoutPlan(null);+ }+ }+async function handleCancel() {try {const res = await fetch('/api/stripe/subscription', { method: 'DELETE' });@@ -149,6 +181,7 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {status: data.status,currentPeriodEnd: data.currentPeriodEnd,});+ router.refresh();toast.success(t('subscriptionReactivated'));} catch (err) {toast.error(err instanceof Error ? err.message : 'Failed to reactivate');@@ -231,6 +264,7 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {return (<div className="space-y-4">{!canAdmin && <p className="text-sm text-muted-foreground">{t('planAdminOnly')}</p>}+ {ended && canAdmin && <p className="text-sm text-muted-foreground">{t('planEnded')}</p>}{/* Billing period: a year up front saves 20% */}<div className="flex flex-wrap items-center justify-between gap-3"><div@@ -271,20 +305,24 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">{SUBSCRIBABLE_PLANS.map((planId) => {const plan = PLANS[planId];- const isCurrent = planId === currentPlanId;+ // An ended plan is no one's current plan any more.+ const isCurrent = !ended && planId === currentPlanId;const upgrade = isUpgrade(planId);const price = periodPrice(planId, period);const fullYear = plan.pricing ? plan.pricing.monthly * 12 : null;const planSaving = annualSaving(planId);- // What its button does: buy it now during a trial; otherwise switch- // the period of the current plan, or change to this one.- const action = trialing- ? 'buy'- : isCurrent- ? period === currentInterval- ? null- : 'period'- : 'change';+ // What its button does: start a new subscription once the old one+ // has ended; buy it now during a trial; otherwise switch the period+ // of the current plan, or change to this one.+ const action = ended+ ? 'subscribe'+ : trialing+ ? 'buy'+ : isCurrent+ ? period === currentInterval+ ? null+ : 'period'+ : 'change';return (<Card key={planId} className={isCurrent ? 'border-primary' : undefined}>@@ -350,21 +388,41 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {<ButtonclassName="w-full"variant={- action === 'buy'- ? isCurrent- ? 'default'- : 'outline'- : upgrade+ action === 'subscribe'+ ? plan.highlighted? 'default': 'outline'+ : action === 'buy'+ ? isCurrent+ ? 'default'+ : 'outline'+ : upgrade+ ? 'default'+ : 'outline'+ }+ disabled={+ price == null ||+ (action === 'subscribe' && (!organizationId || checkoutPlan != null))}- disabled={price == null}onClick={() => {+ if (action === 'subscribe') {+ void handleCheckout(planId);+ return;+ }setPromoCode(FIRST_MONTH_CODE);setPending({ planId, buy: action === 'buy' });}}>- {action === 'buy' ? (+ {action === 'subscribe' ? (+ checkoutPlan === planId ? (+ t('processing')+ ) : (+ <>+ <ShoppingCart className="mr-1 h-4 w-4" />+ {t('choosePlanFor', { plan: plan.name })}+ </>+ )+ ) : action === 'buy' ? (<><ShoppingCart className="mr-1 h-4 w-4" />{t('buyPlanNow', { plan: plan.name })}@@ -523,8 +581,9 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {</ul></div>- {/* Cancel / Reactivate + Stripe billing portal */}- {subscription.cancelAtPeriodEnd && (+ {/* Cancel / Reactivate + Stripe billing portal. An ended plan has+ neither: a card above starts a new one. */}+ {subscription.cancelAtPeriodEnd && !ended && (<div className="flex items-center justify-between rounded-lg border border-destructive/20 bg-destructive/5 p-4"><div><p className="text-sm font-medium">@@ -548,7 +607,7 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {)}<div className="flex items-center justify-between gap-4">{/* Cancelling is the admins', as changing the plan is. */}- {subscription.cancelAtPeriodEnd || !canAdmin ? (+ {subscription.cancelAtPeriodEnd || !canAdmin || ended ? (<span />) : (<Buttondiff --git a/web/src/components/settings/webflow-card.test.tsx b/web/src/components/settings/webflow-card.test.tsxindex f4ee4593b..10ceace98 100644--- a/web/src/components/settings/webflow-card.test.tsx+++ b/web/src/components/settings/webflow-card.test.tsx@@ -24,6 +24,11 @@ vi.mock('@/stores/use-brand-store', () => ({}));const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));vi.mock('sonner', () => ({ toast }));+// The read-only workspace's upgrade dialog.+const openUpgrade = vi.hoisted(() => vi.fn());+vi.mock('@/components/providers/upgrade-gate', () => ({+ useUpgradeGate: () => ({ isLocked: false, openUpgrade, guard: (fn: () => unknown) => fn }),+}));const { WebflowCard } = await import('./webflow-card');@@ -421,6 +426,24 @@ describe('WebflowCard', () => {expect(container.querySelector('input[type="password"]')).not.toBeNull();});+ it('opens the upgrade dialog, not an error, for a read-only workspace', async () => {+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });+ client.disconnectWebflow.mockResolvedValue({ ok: false, code: 'subscription' });+ openUpgrade.mockClear();+ await render();+ await act(async () => {+ button('Disconnect')!.click();+ });+ const confirm = [...document.body.querySelectorAll('button')].filter(+ (b) => b.textContent === 'Disconnect',+ );+ await act(async () => {+ confirm[confirm.length - 1].click();+ });+ expect(openUpgrade).toHaveBeenCalledTimes(1);+ expect(toast.error).not.toHaveBeenCalled();+ });+it('gives another collection its own suggested map, not the saved one', async () => {client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });client.listWebflowCollections.mockResolvedValue({diff --git a/web/src/components/settings/webflow-card.tsx b/web/src/components/settings/webflow-card.tsxindex ab4bf7600..eb135167a 100644--- a/web/src/components/settings/webflow-card.tsx+++ b/web/src/components/settings/webflow-card.tsx@@ -27,6 +27,7 @@ import {SelectValue,} from '@/components/ui/select';import { useUserRole } from '@/hooks/use-user-role';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';import {WEBFLOW_PARTS,WEBFLOW_PART_TYPES,@@ -75,6 +76,8 @@ export function WebflowCard() {const t = useTranslations('settings.webflow');const { activeBrandId, brands } = useBrandStore();const { canManage } = useUserRole();+ // A read-only workspace's refusal opens the upgrade dialog, not a toast.+ const { openUpgrade } = useUpgradeGate();const brand = brands.find((b) => b.id === activeBrandId) ?? null;// The connection as read for a brand: another brand's never shows.@@ -125,7 +128,8 @@ export function WebflowCard() {const result = await disconnectWebflow(activeBrandId);setDisconnecting(false);if (!result.ok) {- toast.error(t(`errors.${result.code}`));+ if (result.code === 'subscription') openUpgrade();+ else toast.error(t(`errors.${result.code}`));return;}setConnection(null);@@ -283,6 +287,7 @@ function TokenForm({onCancel?: () => void;}) {const t = useTranslations('settings.webflow');+ const { openUpgrade } = useUpgradeGate();const [token, setToken] = useState('');const [connecting, setConnecting] = useState(false);@@ -291,7 +296,9 @@ function TokenForm({const result = await connectWebflow(brandId, token.trim());setConnecting(false);if (!result.ok) {- toast.error(t(result.code === 'invalid' ? 'errors.invalidToken' : `errors.${result.code}`));+ if (result.code === 'subscription') openUpgrade();+ else+ toast.error(t(result.code === 'invalid' ? 'errors.invalidToken' : `errors.${result.code}`));return;}setToken('');@@ -379,6 +386,7 @@ function WebflowMapping({onStale: () => void;}) {const t = useTranslations('settings.webflow');+ const { openUpgrade } = useUpgradeGate();// The saved settings, for the fields read: a save doesn't read them again.const saved = useRef(connection);useEffect(() => {@@ -390,6 +398,10 @@ function WebflowMapping({}, [onStale]);/** Says what went wrong, and reads the connection again when it changed. */const report = (code: WebflowError) => {+ if (code === 'subscription') {+ openUpgrade();+ return;+ }toast.error(t(`errors.${code}`));if (STALE.includes(code)) stale.current();};diff --git a/web/src/config/plans.test.ts b/web/src/config/plans.test.tsnew file mode 100644index 000000000..55a1e6d1b--- /dev/null+++ b/web/src/config/plans.test.ts@@ -0,0 +1,17 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { isSubscriptionActive } from './plans';++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('isSubscriptionActive', () => {+ it('counts an active plan and a trial, nothing else', () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ expect(isSubscriptionActive('active')).toBe(true);+ expect(isSubscriptionActive('trialing')).toBe(true);+ for (const status of ['canceled', 'past_due', 'incomplete', null, undefined]) {+ expect(isSubscriptionActive(status)).toBe(false);+ }+ });+});diff --git a/web/src/hooks/use-failure-toast.test.tsx b/web/src/hooks/use-failure-toast.test.tsxindex 3569c5053..b1c34379b 100644--- a/web/src/hooks/use-failure-toast.test.tsx+++ b/web/src/hooks/use-failure-toast.test.tsx@@ -6,10 +6,16 @@ import messages from '../../messages/en.json';import type { ApiFailure } from '@/lib/api-failure';import { useFailureToast } from './use-failure-toast';-const toast = vi.hoisted(() => ({ error: vi.fn() }));+const toast = vi.hoisted(() => ({ error: vi.fn(), dismiss: vi.fn() }));vi.mock('sonner', () => ({ toast }));const push = vi.fn();vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push }) }));+// The dashboard's read-only state: none outside its provider.+const openUpgrade = vi.fn();+let upgrade: { isLocked: boolean; openUpgrade: () => void } | null = null;+vi.mock('@/components/providers/upgrade-gate', () => ({+ useUpgradeDialog: () => upgrade,+}));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =true;@@ -17,7 +23,9 @@ vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push }) }));/** Shows the failure's toast once, and returns what toast.error got. */function show(failure: ApiFailure, options?: { id?: string; description?: string }) {toast.error.mockReset();+ toast.dismiss.mockReset();push.mockReset();+ openUpgrade.mockReset();function Probe() {const failureToast = useFailureToast();failureToast(failure, options);@@ -62,4 +70,53 @@ describe('useFailureToast (BUG-001)', () => {expect(message).toBe('Something went wrong. Try again.');expect(options.action).toBeUndefined();});++ it('keeps the toast for a feature the plan lacks or a used-up allowance', () => {+ upgrade = { isLocked: false, openUpgrade };+ const [message, options] = show('plan');+ expect(message).toBe("Your plan doesn't include this. Upgrade to use it.");+ expect(options.action?.label).toBe('Upgrade');+ expect(show('limit')[1].action?.label).toBe('Upgrade');+ expect(openUpgrade).not.toHaveBeenCalled();+ upgrade = null;+ });++ describe('a workspace whose plan is not active', () => {+ it('opens the upgrade dialog instead of a toast, and clears the loading toast', () => {+ upgrade = { isLocked: true, openUpgrade };+ expect(show('subscription', { id: 't1' })).toBeUndefined();+ expect(openUpgrade).toHaveBeenCalledTimes(1);+ expect(toast.dismiss).toHaveBeenCalledWith('t1');+ upgrade = null;+ });++ it('opens it for the server’s subscription_inactive even before the page knows', () => {+ upgrade = { isLocked: false, openUpgrade };+ expect(show('subscription')).toBeUndefined();+ expect(openUpgrade).toHaveBeenCalledTimes(1);+ expect(toast.dismiss).not.toHaveBeenCalled();+ upgrade = null;+ });++ it('opens it for any plan refusal while the dashboard is read-only, not for a limit', () => {+ upgrade = { isLocked: true, openUpgrade };+ expect(show('plan')).toBeUndefined();+ expect(openUpgrade).toHaveBeenCalledTimes(1);+ expect(show('limit')[0]).toBe(+ "You've used this month's allowance. Upgrade, or wait until it resets.",+ );+ upgrade = null;+ });++ it('falls back to a toast with Choose a plan outside the dashboard', () => {+ upgrade = null;+ const [message, options] = show('subscription');+ expect(message).toBe(+ "Your workspace's plan isn't active, so changes are paused. Choose a plan to use Ansvisor again.",+ );+ expect(options.action?.label).toBe('Choose a plan');+ options.action?.onClick();+ expect(push).toHaveBeenCalledWith('/dashboard/settings/billing');+ });+ });});diff --git a/web/src/hooks/use-failure-toast.ts b/web/src/hooks/use-failure-toast.tsindex 17108459a..c9f9f913b 100644--- a/web/src/hooks/use-failure-toast.ts+++ b/web/src/hooks/use-failure-toast.ts@@ -4,17 +4,29 @@ import { useCallback } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';import { useRouter } from '@/i18n/navigation';+import { useUpgradeDialog } from '@/components/providers/upgrade-gate';import type { ApiFailure } from '@/lib/api-failure';/*** A failed call as a toast (BUG-001): the reason in plain words and the one* thing to do about it — sign in again, switch brand, reload, or upgrade.+ * A workspace whose plan isn't active gets the upgrade dialog instead, as its+ * guarded buttons do: for the server's subscription_inactive, and for any+ * other plan refusal while the dashboard already knows it is read-only.+ * Other plan limits (a feature the plan lacks, a used-up allowance) keep the+ * toast.*/export function useFailureToast() {const t = useTranslations('apiFailure');const router = useRouter();+ const upgrade = useUpgradeDialog();return useCallback((failure: ApiFailure, options: { id?: string | number; description?: string } = {}) => {+ if (upgrade && (failure === 'subscription' || (failure === 'plan' && upgrade.isLocked))) {+ if (options.id !== undefined) toast.dismiss(options.id);+ upgrade.openUpgrade();+ return;+ }const action = (() => {switch (failure) {case 'session':@@ -23,6 +35,11 @@ export function useFailureToast() {return { label: t('yourBrands'), onClick: () => router.push('/dashboard/brands') };case 'not_found':return { label: t('reload'), onClick: () => window.location.reload() };+ case 'subscription':+ return {+ label: t('choosePlan'),+ onClick: () => router.push('/dashboard/settings/billing'),+ };case 'plan':case 'limit':return {@@ -36,6 +53,6 @@ export function useFailureToast() {})();toast.error(t(failure), { ...options, ...(action ? { action } : {}) });},- [t, router],+ [t, router, upgrade],);}diff --git a/web/src/lib/agent/unanswered-turn.test.ts b/web/src/lib/agent/unanswered-turn.test.tsnew file mode 100644index 000000000..0c71ea1c0--- /dev/null+++ b/web/src/lib/agent/unanswered-turn.test.ts@@ -0,0 +1,37 @@+import type { UIMessage } from 'ai';+import { describe, expect, it } from 'vitest';+import { takeBackUnansweredTurn } from './unanswered-turn';++const user = (id: string, text: string): UIMessage => ({+ id,+ role: 'user',+ parts: [{ type: 'text', text }],+});+const answer = (id: string, text: string): UIMessage => ({+ id,+ role: 'assistant',+ parts: [{ type: 'text', text }],+});++describe('takeBackUnansweredTurn', () => {+ it('takes the refused message off the thread, with its text for the input', () => {+ const thread = [user('u1', 'Hi'), answer('a1', 'Hello'), user('u2', 'How is my brand doing?')];+ expect(takeBackUnansweredTurn(thread)).toEqual({+ messages: [user('u1', 'Hi'), answer('a1', 'Hello')],+ text: 'How is my brand doing?',+ });+ });++ it('drops an empty answer begun after it too', () => {+ const begun: UIMessage = { id: 'a2', role: 'assistant', parts: [] };+ expect(takeBackUnansweredTurn([user('u1', 'Hi'), begun])).toEqual({+ messages: [],+ text: 'Hi',+ });+ });++ it('leaves a thread that was answered alone', () => {+ expect(takeBackUnansweredTurn([user('u1', 'Hi'), answer('a1', 'Hello')])).toBeNull();+ expect(takeBackUnansweredTurn([])).toBeNull();+ });+});diff --git a/web/src/lib/agent/unanswered-turn.ts b/web/src/lib/agent/unanswered-turn.tsnew file mode 100644index 000000000..2a3623eba--- /dev/null+++ b/web/src/lib/agent/unanswered-turn.ts@@ -0,0 +1,23 @@+import type { UIMessage } from 'ai';++/**+ * A turn the API refused before answering it (a read-only workspace's 402):+ * the thread without the person's last message (and any empty answer begun+ * after it), and that message's text, to put back in the input. Null when the+ * thread doesn't end with their message.+ */+export function takeBackUnansweredTurn(+ messages: UIMessage[],+): { messages: UIMessage[]; text: string } | null {+ let end = messages.length;+ while (end > 0 && messages[end - 1].role === 'assistant' && !messages[end - 1].parts?.length) {+ end -= 1;+ }+ const last = messages[end - 1];+ if (!last || last.role !== 'user') return null;+ const text = (last.parts ?? [])+ .filter((part): part is { type: 'text'; text: string } => part.type === 'text')+ .map((part) => part.text)+ .join('');+ return { messages: messages.slice(0, end - 1), text };+}diff --git a/web/src/lib/api-failure.test.ts b/web/src/lib/api-failure.test.tsindex 93ea38c93..8680ff2f1 100644--- a/web/src/lib/api-failure.test.ts+++ b/web/src/lib/api-failure.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { apiFailure } from './api-failure';+import { apiFailure, isSubscriptionInactive } from './api-failure';describe('apiFailure', () => {it('reads a bad or expired session from 401 only', () => {@@ -15,6 +15,17 @@ describe('apiFailure', () => {expect(apiFailure(402, { error: 'no_subscription' })).toBe('plan');});+ it("tells a workspace whose plan isn't active from a plan without the feature", () => {+ // The server's 402 for any change while the workspace is read-only.+ expect(apiFailure(402, { error: 'plan_limit', code: 'subscription_inactive' })).toBe(+ 'subscription',+ );+ // Any other 402 is still the plan.+ expect(apiFailure(402, { error: 'plan_limit' })).toBe('plan');+ // A session that expired is still a session first.+ expect(apiFailure(401, { code: 'subscription_inactive' })).toBe('session');+ });+it('reads a rate limit as busy, never as an allowance to upgrade', () => {// server/src/middleware/rate-limiter.js: a message, no error.const limiter = { success: false, message: 'Too many requests, please try again later.' };@@ -46,3 +57,20 @@ describe('apiFailure', () => {expect(apiFailure(502)).toBe('failed');});});++describe('isSubscriptionInactive', () => {+ const body = { error: 'plan_limit', code: 'subscription_inactive', message: 'Read-only' };++ it('reads the code from a body, or from the text an error carries', () => {+ expect(isSubscriptionInactive(body)).toBe(true);+ // The AI SDK's chat transport: new Error(await response.text()).+ expect(isSubscriptionInactive(new Error(JSON.stringify(body)).message)).toBe(true);+ });++ it('is false for anything else', () => {+ expect(isSubscriptionInactive({ error: 'plan_limit' })).toBe(false);+ expect(isSubscriptionInactive('Failed to fetch the chat response.')).toBe(false);+ expect(isSubscriptionInactive(null)).toBe(false);+ expect(isSubscriptionInactive(undefined)).toBe(false);+ });+});diff --git a/web/src/lib/api-failure.ts b/web/src/lib/api-failure.tsindex 0c5428a14..1ecef5535 100644--- a/web/src/lib/api-failure.ts+++ b/web/src/lib/api-failure.ts@@ -9,6 +9,7 @@ export const API_FAILURES = ['workspace','not_found','plan',+ 'subscription','limit','busy','failed',@@ -24,6 +25,10 @@ export type ApiFailure = (typeof API_FAILURES)[number];*/export function apiFailure(status: number, body: Record<string, unknown> = {}): ApiFailure {if (status === 401) return 'session';+ // The workspace's plan isn't active (a trial that ended, a canceled plan):+ // the server's 402 for any change while it is read-only. The upgrade+ // dialog, not a toast.+ if (body.code === 'subscription_inactive') return 'subscription';if (body.error === 'quota_exhausted') return 'limit';// A monthly budget used up: plan-guard's PlanLimitError answers 429 with plan_limit.if (status === 429 && body.error === 'plan_limit') return 'limit';@@ -39,3 +44,24 @@ export function apiFailure(status: number, body: Record<string, unknown> = {}):if (status === 404) return 'not_found';return 'failed';}++/**+ * Whether a response body is the server's subscription_inactive (a read-only+ * workspace), also when it comes as text: the AI SDK's chat transport throws+ * an error whose message is the response body.+ */+export function isSubscriptionInactive(body: unknown): boolean {+ let value = body;+ if (typeof value === 'string') {+ try {+ value = JSON.parse(value);+ } catch {+ return false;+ }+ }+ return (+ typeof value === 'object' &&+ value !== null &&+ (value as { code?: unknown }).code === 'subscription_inactive'+ );+}diff --git a/web/src/lib/billing/plan-purchase.test.ts b/web/src/lib/billing/plan-purchase.test.tsindex fad548142..ca4f95436 100644--- a/web/src/lib/billing/plan-purchase.test.ts+++ b/web/src/lib/billing/plan-purchase.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from 'vitest';-import { annualSaving, periodPrice, planChange, planRequestSchema } from './plan-purchase';+import {+ annualSaving,+ periodPrice,+ planChange,+ planRequestSchema,+ subscriptionEnded,+} from './plan-purchase';describe('plan prices', () => {it('reads a month or a year up front from the config', () => {@@ -77,3 +83,18 @@ describe('planChange', () => {expect(planRequestSchema.safeParse({ interval: 'week' }).success).toBe(false);});});++describe('subscriptionEnded', () => {+ it('keeps a subscription that is billing, trialing or retrying a payment', () => {+ for (const status of ['active', 'trialing', 'past_due', 'unpaid', 'paused']) {+ expect(subscriptionEnded(status)).toBe(false);+ }+ });++ it('starts a new one after a cancel, an expired first payment, or none ever', () => {+ for (const status of ['canceled', 'incomplete_expired', 'incomplete', 'inactive', null]) {+ expect(subscriptionEnded(status)).toBe(true);+ }+ expect(subscriptionEnded(undefined)).toBe(true);+ });+});diff --git a/web/src/lib/billing/plan-purchase.ts b/web/src/lib/billing/plan-purchase.tsindex 77c63a83d..97c8af989 100644--- a/web/src/lib/billing/plan-purchase.ts+++ b/web/src/lib/billing/plan-purchase.ts@@ -74,3 +74,20 @@ export function planChange(}return { kind: 'change', planId, interval };}++/**+ * Stripe statuses with a subscription still there to change or fix: billing+ * on it, a payment being retried (`past_due`, `unpaid`; the card is updated+ * in Stripe's billing page), or a trial paused for a card.+ */+const LIVE_STATUSES = new Set(['active', 'trialing', 'past_due', 'unpaid', 'paused']);++/**+ * Whether the organization has no subscription left to change — a canceled+ * plan, an expired first payment, or none ever — so choosing a plan starts a+ * new one through Checkout instead of changing the old one, which Stripe+ * refuses once it has ended.+ */+export function subscriptionEnded(status: string | null | undefined): boolean {+ return !status || !LIVE_STATUSES.has(status);+}diff --git a/web/src/lib/billing/portal-client.ts b/web/src/lib/billing/portal-client.tsnew file mode 100644index 000000000..82c986658--- /dev/null+++ b/web/src/lib/billing/portal-client.ts@@ -0,0 +1,12 @@+/**+ * Opens Stripe's billing page for the organization (POST /api/stripe/portal),+ * where the card is updated: Billing's Manage billing, and the read-only+ * notices for a payment that didn't go through. Navigates away on success;+ * throws with the route's error otherwise.+ */+export async function openBillingPortal(): Promise<void> {+ const res = await fetch('/api/stripe/portal', { method: 'POST' });+ const body = (await res.json().catch(() => ({}))) as { url?: string; error?: string };+ if (!res.ok || !body.url) throw new Error(body.error || 'Failed to open billing portal');+ window.location.href = body.url;+}diff --git a/web/src/lib/billing/subscription-access.test.ts b/web/src/lib/billing/subscription-access.test.tsindex e5dae285f..b9b0649a9 100644--- a/web/src/lib/billing/subscription-access.test.ts+++ b/web/src/lib/billing/subscription-access.test.ts@@ -1,9 +1,9 @@import { describe, expect, it, vi } from 'vitest';-import { evaluateSubscriptionAccess } from './subscription-access';+import { evaluateSubscriptionAccess, readOnlyReason } from './subscription-access';// Minimal Supabase stub: the chained query builder resolves to `ownerRow` at-// `.maybeSingle()`. Only the blocked (non-admin, inactive) path touches it.+// `.maybeSingle()`. Only the read-only path for non-admins touches it.function fakeSupabase(ownerRow: { full_name: string | null } | null) {const builder = {select: () => builder,@@ -20,39 +20,71 @@ function fakeSupabase(ownerRow: { full_name: string | null } | null) {describe('evaluateSubscriptionAccess', () => {it('returns ok for active/trialing regardless of role (no owner lookup)', async () => {const { client, from } = fakeSupabase(null);- expect(await evaluateSubscriptionAccess(client, 'org', 'analyst', 'active')).toEqual({+ expect(await evaluateSubscriptionAccess(client, 'org', 'analyst', 'active', true)).toEqual({state: 'ok',});- expect(await evaluateSubscriptionAccess(client, 'org', 'admin', 'trialing')).toEqual({+ expect(await evaluateSubscriptionAccess(client, 'org', 'admin', 'trialing', true)).toEqual({state: 'ok',});expect(from).not.toHaveBeenCalled();});- it('routes admins to the payment flow when the subscription is inactive', async () => {+ it("sends an admin who never subscribed back to onboarding's plan step", async () => {const { client, from } = fakeSupabase(null);- expect(await evaluateSubscriptionAccess(client, 'org', 'admin', 'past_due')).toEqual({- state: 'needs_payment',+ expect(await evaluateSubscriptionAccess(client, 'org', 'admin', 'incomplete', false)).toEqual({+ state: 'choose_plan',});- expect(await evaluateSubscriptionAccess(client, 'org', 'admin', null)).toEqual({- state: 'needs_payment',+ expect(await evaluateSubscriptionAccess(client, 'org', 'admin', null, false)).toEqual({+ state: 'choose_plan',});expect(from).not.toHaveBeenCalled();});- it('blocks non-admins when inactive and surfaces the owner name', async () => {+ it('lets an admin whose plan ended into the dashboard, read-only', async () => {+ const { client, from } = fakeSupabase(null);+ expect(await evaluateSubscriptionAccess(client, 'org', 'admin', 'canceled', true)).toEqual({+ state: 'read_only',+ adminName: null,+ });+ expect(await evaluateSubscriptionAccess(client, 'org', 'admin', 'past_due', true)).toEqual({+ state: 'read_only',+ adminName: null,+ });+ expect(from).not.toHaveBeenCalled();+ });++ it('lets other members in read-only and names the admin to ask', async () => {const { client } = fakeSupabase({ full_name: 'Jane Owner' });- expect(await evaluateSubscriptionAccess(client, 'org', 'manager', 'canceled')).toEqual({- state: 'blocked',- ownerName: 'Jane Owner',+ expect(await evaluateSubscriptionAccess(client, 'org', 'manager', 'canceled', true)).toEqual({+ state: 'read_only',+ adminName: 'Jane Owner',+ });+ // Never subscribed: only an admin can take the plan step.+ expect(await evaluateSubscriptionAccess(client, 'org', 'analyst', null, false)).toEqual({+ state: 'read_only',+ adminName: 'Jane Owner',});});- it('falls back to a null owner name when the lookup returns nothing', async () => {+ it('falls back to no admin name when the lookup returns nothing', async () => {const { client } = fakeSupabase(null);- expect(await evaluateSubscriptionAccess(client, 'org', 'analyst', null)).toEqual({- state: 'blocked',- ownerName: null,+ expect(await evaluateSubscriptionAccess(client, 'org', 'analyst', null, true)).toEqual({+ state: 'read_only',+ adminName: null,});});});++describe('readOnlyReason', () => {+ it('reads a payment being retried as one to fix with the card', () => {+ expect(readOnlyReason('past_due')).toBe('payment_failed');+ expect(readOnlyReason('unpaid')).toBe('payment_failed');+ });++ it('reads anything else as ended, with no claim about a trial', () => {+ for (const status of ['canceled', 'paused', 'incomplete', 'incomplete_expired', null]) {+ expect(readOnlyReason(status)).toBe('ended');+ }+ expect(readOnlyReason(undefined)).toBe('ended');+ });+});diff --git a/web/src/lib/billing/subscription-access.ts b/web/src/lib/billing/subscription-access.tsindex 0f83a280b..04084e9e2 100644--- a/web/src/lib/billing/subscription-access.ts+++ b/web/src/lib/billing/subscription-access.ts@@ -6,8 +6,8 @@ type ServerSupabase = Awaited<ReturnType<typeof import('@/lib/supabase/server').export type SubscriptionAccess =| { state: 'ok' }- | { state: 'needs_payment' }- | { state: 'blocked'; ownerName: string | null };+ | { state: 'choose_plan' }+ | { state: 'read_only'; adminName: string | null };const ACTIVE_STATUSES = new Set(['active', 'trialing']);@@ -15,33 +15,38 @@ const ACTIVE_STATUSES = new Set(['active', 'trialing']);* Decide what an authenticated, onboarded org member may do when their org's* subscription is not active.*- * - active / trialing → 'ok' (full access)- * - inactive + admin → 'needs_payment' (admins, incl. the owner, can renew)- * - inactive + non-admin → 'blocked' (manager / analyst / agency_partner- * can't pay or re-onboard — they get a- * "contact your account owner" notice)+ * - active / trialing → 'ok' (full access)+ * - never subscribed + admin → 'choose_plan' (a new account that left+ * onboarding before its plan+ * step: back to that step)+ * - anything else → 'read_only' (a trial that ended, a+ * canceled or unpaid plan:+ * every page opens, no+ * action runs until a plan+ * is chosen in Billing)*- * This is the fix for the trial-ended invited-member case: previously *every*- * member was redirected into the onboarding wizard when the subscription- * lapsed, so a non-owner saw the payment screen and could walk back to step 1- * and re-create the brand / competitors on an already-set-up org.+ * "Never subscribed" is an org without a Stripe subscription id: onboarding+ * marks itself complete before its plan step, so a new account that stops at+ * the plan cards is onboarded but has never had a subscription. Once Stripe+ * has given one, the id stays, even after the subscription is deleted.*- * "Owner" is the org's first admin; we surface their name in the blocked- * message so a member knows who to contact. The lookup uses the caller's RLS- * client, so if it can't read the owner's row the message simply falls back to- * a generic wording (never throws).+ * Members other than admins can't buy a plan, so the read-only notices ask+ * them to turn to an admin: the org's first admin is named when the caller's+ * RLS client can read their row, and the wording falls back to a generic one+ * otherwise (never throws).*/export async function evaluateSubscriptionAccess(supabase: ServerSupabase,organizationId: string,role: TeamRole,subscriptionStatus: string | null,+ everSubscribed: boolean,): Promise<SubscriptionAccess> {if (subscriptionStatus && ACTIVE_STATUSES.has(subscriptionStatus)) {return { state: 'ok' };}if (role === 'admin') {- return { state: 'needs_payment' };+ return everSubscribed ? { state: 'read_only', adminName: null } : { state: 'choose_plan' };}const { data: owner } = await supabase@@ -53,5 +58,19 @@ export async function evaluateSubscriptionAccess(.limit(1).maybeSingle();- return { state: 'blocked', ownerName: (owner?.full_name as string | null) ?? null };+ return { state: 'read_only', adminName: (owner?.full_name as string | null) ?? null };+}++/** Why a workspace is read-only, as the upgrade notices say it. */+export type ReadOnlyReason = 'ended' | 'payment_failed';++/**+ * The reason, from Stripe's subscription status. A payment being retried+ * (`past_due`, `unpaid`) is fixed by updating the card in Stripe's billing+ * page. Anything else — a trial or a plan canceled, a first payment that+ * expired — reads the same: the row keeps no trace of whether it was a trial,+ * so the notices don't claim either.+ */+export function readOnlyReason(status: string | null | undefined): ReadOnlyReason {+ return status === 'past_due' || status === 'unpaid' ? 'payment_failed' : 'ended';}diff --git a/web/src/lib/catalog-client.test.ts b/web/src/lib/catalog-client.test.tsindex 939d452fe..e7e79d2fc 100644--- a/web/src/lib/catalog-client.test.ts+++ b/web/src/lib/catalog-client.test.ts@@ -54,6 +54,9 @@ describe('syncCatalogSource', () => {expect(await syncCatalogSource('s1')).toEqual({ ok: false, code: 'workspace' });answer(429, { message: 'Too many requests' });expect(await syncCatalogSource('s1')).toEqual({ ok: false, code: 'busy' });+ // A read-only workspace (plan not active): the upgrade dialog's.+ answer(402, { error: 'plan_limit', code: 'subscription_inactive' });+ expect(await syncCatalogSource('s1')).toEqual({ ok: false, code: 'subscription' });answer(500, { code: 'failed' });expect(await syncCatalogSource('s1')).toEqual({ ok: false, code: 'failed' });});@@ -132,6 +135,12 @@ describe('stores (00282)', () => {});answer(429, { message: 'Too many requests' });expect(await updateStoreSignIn('st1', {})).toEqual({ ok: false, code: 'busy', message: null });+ answer(402, { error: 'plan_limit', code: 'subscription_inactive' });+ expect(await updateStoreSignIn('st1', {})).toEqual({+ ok: false,+ code: 'subscription',+ message: null,+ });});});@@ -222,7 +231,8 @@ describe('sign-in platforms (#1270)', () => {});describe('StoreError', () => {- // Every code, so a new one fails the typecheck here until it has its words.+ // Every code, so a new one fails the typecheck here until it has its words;+ // but 'subscription', which opens the upgrade dialog instead of saying one.const CODES = {connect_failed: true,not_connected: true,@@ -239,7 +249,7 @@ describe('StoreError', () => {workspace: true,busy: true,failed: true,- } satisfies Record<StoreError, true>;+ } satisfies Record<Exclude<StoreError, 'subscription'>, true>;it('has words for every reason a store call fails', () => {for (const code of Object.keys(CODES)) {diff --git a/web/src/lib/catalog-client.ts b/web/src/lib/catalog-client.tsindex 3e5869a50..d4b0fe908 100644--- a/web/src/lib/catalog-client.ts+++ b/web/src/lib/catalog-client.ts@@ -27,6 +27,8 @@ export type CatalogSyncError =| 'session'| 'workspace'| 'busy'+ /** A read-only workspace (plan not active): the upgrade dialog, not a message. */+ | 'subscription'| 'failed';export type CatalogSyncResult =@@ -72,7 +74,10 @@ async function call(path: string, init: RequestInit): Promise<CatalogSyncResult>return {ok: false,code:- general === 'session' || general === 'workspace' || general === 'busy'+ general === 'session' ||+ general === 'workspace' ||+ general === 'busy' ||+ general === 'subscription'? general: 'failed',};@@ -141,6 +146,8 @@ export type StoreError =| 'session'| 'workspace'| 'busy'+ /** A read-only workspace (plan not active): the upgrade dialog, not a message. */+ | 'subscription'| 'failed';/** `message`: the store's own words for what to fix, when it has them. */@@ -189,7 +196,12 @@ async function storeCall(path: string, init: RequestInit): Promise<StoreResult>return {ok: false,code:- general === 'session' || general === 'workspace' || general === 'busy' ? general : 'failed',+ general === 'session' ||+ general === 'workspace' ||+ general === 'busy' ||+ general === 'subscription'+ ? general+ : 'failed',message: null,};} catch (err) {diff --git a/web/src/lib/content/cms-send-client.test.ts b/web/src/lib/content/cms-send-client.test.tsindex a744bf856..2d3c0d7f8 100644--- a/web/src/lib/content/cms-send-client.test.ts+++ b/web/src/lib/content/cms-send-client.test.ts@@ -150,6 +150,10 @@ describe('sendPagesToCms', () => {session = null;expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ code: 'session' });expect(fetchMock).toHaveBeenCalledTimes(4);+ // A read-only workspace (plan not active): the upgrade dialog's.+ session = { access_token: 'tok' };+ answer(402, { error: 'plan_limit', code: 'subscription_inactive' });+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ code: 'subscription' });});it('reads an unknown code, a body that isn’t JSON or no answer as failed', async () => {diff --git a/web/src/lib/content/cms-send-client.ts b/web/src/lib/content/cms-send-client.tsindex c18f6e451..ef6e3fba7 100644--- a/web/src/lib/content/cms-send-client.ts+++ b/web/src/lib/content/cms-send-client.ts@@ -30,10 +30,12 @@ export type CmsSendError =| 'failed'// More than the API's proxy takes in one request (413).| 'too_large'- // Not a send's own: the session, another workspace's brand, the rate limiter.+ // Not a send's own: the session, another workspace's brand, the rate limiter,+ // a read-only workspace (the upgrade dialog, not a message).| 'session'| 'workspace'- | 'busy';+ | 'busy'+ | 'subscription';export interface CmsDelivery {id: string;@@ -69,7 +71,7 @@ const KNOWN: readonly CmsSendError[] = [];/** The reasons any call can fail for, as the other calls read them (BUG-001). */-const GENERAL: readonly CmsSendError[] = ['session', 'workspace', 'busy'];+const GENERAL: readonly CmsSendError[] = ['session', 'workspace', 'busy', 'subscription'];/*** Sends pages of one brand to its webhook, or its Webflow collection: one isdiff --git a/web/src/lib/content/publish-client.test.ts b/web/src/lib/content/publish-client.test.tsindex 0aa55d3e8..5a1356d10 100644--- a/web/src/lib/content/publish-client.test.ts+++ b/web/src/lib/content/publish-client.test.ts@@ -70,6 +70,9 @@ describe('publishPage', () => {expect(await publishPage('d1', 'x')).toEqual({ ok: false, code: 'no_route' });answer(403, { code: 'not_in_workspace' });expect(await publishPage('d1', 'x')).toEqual({ ok: false, code: 'workspace' });+ // A read-only workspace (plan not active): the upgrade dialog's.+ answer(402, { error: 'plan_limit', code: 'subscription_inactive' });+ expect(await publishPage('d1', 'x')).toEqual({ ok: false, code: 'subscription' });answer(500, { code: 'failed' });expect(await publishPage('d1', 'x')).toEqual({ ok: false, code: 'failed' });});diff --git a/web/src/lib/content/publish-client.ts b/web/src/lib/content/publish-client.tsindex 7f8bc365f..68b17bdb8 100644--- a/web/src/lib/content/publish-client.ts+++ b/web/src/lib/content/publish-client.ts@@ -17,6 +17,8 @@ export type PublishError =| 'session'| 'workspace'| 'busy'+ /** A read-only workspace (plan not active): the upgrade dialog, not a message. */+ | 'subscription'| 'failed';export type PublishResult =@@ -73,6 +75,7 @@ export async function publishPage(draftId: string, url: string): Promise<Publishgeneral === 'session' ||general === 'workspace' ||general === 'busy' ||+ general === 'subscription' ||general === 'not_found'? general: 'failed',diff --git a/web/src/lib/mcp-auth.test.ts b/web/src/lib/mcp-auth.test.tsnew file mode 100644index 000000000..327ed3bf9--- /dev/null+++ b/web/src/lib/mcp-auth.test.ts@@ -0,0 +1,81 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * authenticateMcpRequest on a read-only workspace (Ansvisor Cloud, plan not+ * active): the REST routes' reads go through, their writes answer 402+ * subscription_inactive; the MCP endpoint gates its tools instead.+ */++let status: string | null;+vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: (table: string) => {+ const row =+ table === 'api_keys'+ ? { id: 'key-1', user_id: 'user-1', revoked_at: null }+ : table === 'profiles'+ ? { organization_id: 'org-1' }+ : { subscription_status: status };+ const query = {+ select: () => query,+ eq: () => query,+ update: () => query,+ then: (resolve: (value: unknown) => void) => resolve({ data: null }),+ maybeSingle: async () => ({ data: row, error: null }),+ };+ return query;+ },+ auth: { admin: { getUserById: async () => ({ data: { user: { email: '[email protected]' } } }) } },+ },+}));++const { authenticateMcpRequest } = await import('./mcp-auth');++const request = (method: string) =>+ new Request('http://localhost/api/mcp/content-drafts', {+ method,+ headers: { authorization: 'Bearer ans_test' },+ });++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ status = 'canceled';+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('authenticateMcpRequest on a read-only workspace', () => {+ it('lets a read through', async () => {+ const auth = await authenticateMcpRequest(request('GET'));+ expect(auth).toMatchObject({ userId: 'user-1', organizationId: 'org-1' });+ });++ it('answers a write with 402 subscription_inactive', async () => {+ for (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) {+ const res = (await authenticateMcpRequest(request(method))) as Response;+ expect(res.status).toBe(402);+ expect(await res.json()).toMatchObject({+ error: 'plan_limit',+ code: 'subscription_inactive',+ });+ }+ });++ it('leaves the MCP endpoint to gate its tools', async () => {+ const auth = await authenticateMcpRequest(request('POST'), { gateWrites: false });+ expect(auth).toMatchObject({ organizationId: 'org-1' });+ });++ it('lets a write through once the plan is active', async () => {+ status = 'active';+ expect(await authenticateMcpRequest(request('POST'))).toMatchObject({ apiKeyId: 'key-1' });+ });++ it('never gates self-hosted', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ expect(await authenticateMcpRequest(request('POST'))).toMatchObject({ apiKeyId: 'key-1' });+ });+});diff --git a/web/src/lib/mcp-auth.ts b/web/src/lib/mcp-auth.tsindex 5cd97b4c5..cd19f85fe 100644--- a/web/src/lib/mcp-auth.ts+++ b/web/src/lib/mcp-auth.ts@@ -1,6 +1,7 @@import { createHash, randomBytes } from 'node:crypto';import { NextResponse } from 'next/server';import { supabaseAdmin } from '@/lib/supabase/admin';+import { subscriptionActiveFor, subscriptionInactiveResponse } from '@/lib/mcp/subscription-gate';export const API_KEY_PREFIX = 'ans_';export const API_KEY_DISPLAY_PREFIX_LEN = 12;@@ -23,14 +24,25 @@ export interface McpAuthContext {apiKeyId: string;}+/** The methods that change something: a read-only workspace's REST routes refuse them. */+const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);+/*** Resolve the bearer token on a request into a user/org context.** Accepts only Ansvisor API keys (prefix `ans_`) — not Supabase session JWTs.* MCP endpoints are intended to be hit by long-lived external clients, so we* intentionally don't fall back to the dashboard's session cookie.+ *+ * On Ansvisor Cloud, a write (POST, PUT, PATCH, DELETE) for an organization+ * whose plan isn't active answers 402 subscription_inactive, so a new write+ * route is gated without asking. The MCP endpoint, where every call is a+ * POST, passes `gateWrites: false` and gates its tools instead.*/-export async function authenticateMcpRequest(req: Request): Promise<McpAuthContext | NextResponse> {+export async function authenticateMcpRequest(+ req: Request,+ { gateWrites = true }: { gateWrites?: boolean } = {},+): Promise<McpAuthContext | NextResponse> {const auth = req.headers.get('authorization') ?? '';const token = auth.startsWith('Bearer ') ? auth.slice(7).trim() : '';@@ -57,6 +69,15 @@ export async function authenticateMcpRequest(req: Request): Promise<McpAuthConte.eq('id', key.user_id).maybeSingle();+ const organizationId = (profile?.organization_id as string | null | undefined) ?? null;+ if (+ gateWrites &&+ WRITE_METHODS.has(req.method.toUpperCase()) &&+ !(await subscriptionActiveFor(organizationId))+ ) {+ return subscriptionInactiveResponse();+ }+// Best-effort touch — failing here shouldn't block the request.supabaseAdmin.from('api_keys')@@ -71,7 +92,7 @@ export async function authenticateMcpRequest(req: Request): Promise<McpAuthContereturn {userId: key.user_id,email: user?.email ?? null,- organizationId: profile?.organization_id ?? null,+ organizationId,apiKeyId: key.id,};}diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex e83262084..f63e9ec54 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -16,6 +16,7 @@ import { countTrafficLogs, scanTrafficLogs } from '@/lib/traffic-scan';import { computeAiVisibilityScore } from '@/lib/visibility-score';import { API_BASE_URL } from '@/config/api';import { ORG_PLAN_COLUMNS, planFromOrgRow, usagePlanFromOrgRow } from '@/lib/guards/plan-guard';+import { assertSubscriptionActive } from '@/lib/mcp/subscription-gate';import {fetchPromptUsageRow,toPromptUsageSummary,@@ -1023,6 +1024,8 @@ export async function generateBriefFor(.eq('brands.organization_id', auth.organizationId).maybeSingle();if (!ownership) return null;+ // No brief (an LLM call) for a read-only workspace, whoever asks.+ await assertSubscriptionActive(auth.organizationId);const apiUrl = API_BASE_URL;const cronSecret = process.env.CRON_SECRET;@@ -1207,6 +1210,8 @@ export async function runSiteAuditFor(.eq('organization_id', auth.organizationId).maybeSingle();if (!brand) return null;+ // No audit (quota and crawling) for a read-only workspace, whoever asks.+ await assertSubscriptionActive(auth.organizationId);const cronSecret = process.env.CRON_SECRET;if (!cronSecret) {@@ -3459,6 +3464,8 @@ export async function createImproveActionFor(.eq('prompt_sets.brands.organization_id', auth.organizationId).maybeSingle();if (!ownership) return null;+ // No Improve action (an LLM call) for a read-only workspace, whoever asks.+ await assertSubscriptionActive(auth.organizationId);const cronSecret = process.env.CRON_SECRET;if (!cronSecret) {diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex af892a766..6500d555f 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -75,6 +75,7 @@ import {type MentionsFilterParams,} from './mentions';import { MENTION_SENTIMENTS, MENTION_SORTS } from '@/lib/mentions-list';+import { gateWriteTools } from './subscription-gate';/*** Build a fresh MCP server bound to a single authenticated request.@@ -137,10 +138,15 @@ const MENTIONS_BASIS ='read no change into it. Sentiment is measured for the brand only, not competitors.';export function createMcpServer(auth: McpAuthContext): McpServer {- const server = new McpServer({- name: 'ansvisor',- version: '0.1.0',- });+ // A read-only workspace (Cloud, plan not active) keeps its list_/get_ tools;+ // every other tool answers subscription_inactive until a plan is chosen.+ const server = gateWriteTools(+ new McpServer({+ name: 'ansvisor',+ version: '0.1.0',+ }),+ auth.organizationId,+ );server.registerTool('list_brands',diff --git a/web/src/lib/mcp/subscription-gate.test.ts b/web/src/lib/mcp/subscription-gate.test.tsnew file mode 100644index 000000000..92f5c955b--- /dev/null+++ b/web/src/lib/mcp/subscription-gate.test.ts@@ -0,0 +1,235 @@+// @vitest-environment node+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The MCP server on a read-only workspace (Ansvisor Cloud, plan not active):+ * list_/get_ tools answer, every other tool answers subscription_inactive.+ */++let status: string | null;+let dbError: { message: string } | null;+vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: () => {+ const query = {+ select: () => query,+ eq: () => query,+ maybeSingle: async () =>+ dbError+ ? { data: null, error: dbError }+ : { data: { subscription_status: status }, error: null },+ };+ return query;+ },+ },+}));++const data = vi.hoisted(() => ({+ listBrandsFor: vi.fn(async () => [{ id: 'brand-1', name: 'Acme' }]),+ dismissTopicSuggestionFor: vi.fn(async () => ({ id: 'suggestion-1', status: 'dismissed' })),+}));+vi.mock('@/lib/mcp/data', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/mcp/data')>()),+ ...data,+}));++const { createMcpServer } = await import('./server');+const { isReadTool, SubscriptionInactiveError, subscriptionActiveFor, gateWriteTools } =+ await import('./subscription-gate');+const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js');+const { runSiteAuditFor, generateBriefFor } = await import('./data');++const SUGGESTION_ID = '11111111-2222-3333-4444-555555555555';++/** A client talking to a server built for one request, as the MCP route builds it. */+async function connect() {+ const server = createMcpServer({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ const client = new Client({ name: 'test', version: '1.0.0' });+ await client.connect(clientTransport);+ return client;+}++/** A tool result's text, read as the JSON it carries. */+const body = (result: Awaited<ReturnType<Client['callTool']>>) =>+ JSON.parse((result.content as { text: string }[])[0].text);++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ status = 'canceled';+ dbError = null;+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('the MCP tools on a read-only workspace', () => {+ it('keeps every list_/get_ tool open and gates the ones that write, run or spend', async () => {+ const client = await connect();+ const { tools } = await client.listTools();+ const names = tools.map((tool) => tool.name);+ expect(names.filter(isReadTool)).toHaveLength(36);+ expect(names.filter((name) => !isReadTool(name)).sort()).toEqual([+ 'accept_prompt_suggestion',+ 'accept_topic_suggestion',+ 'add_content_source',+ 'create_content_draft',+ 'create_improve_action',+ 'dismiss_prompt_suggestion',+ 'dismiss_topic_suggestion',+ 'generate_content_brief',+ 'override_mention_sentiment',+ 'run_site_audit',+ 'set_content_draft_ready',+ 'suggest_content_changes',+ 'update_opportunity_status',+ 'update_task_status',+ ]);+ });++ it('answers every gated tool, as registered, with subscription_inactive before it runs', async () => {+ const server = createMcpServer({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ });+ // The handlers the SDK calls once a call's arguments are checked.+ const registered = (+ server as unknown as {+ _registeredTools: Record<string, { handler: (...args: unknown[]) => unknown }>;+ }+ )._registeredTools;+ const gated = Object.keys(registered).filter((name) => !isReadTool(name));+ expect(gated).toHaveLength(14);+ for (const name of gated) {+ const result = (await registered[name].handler({}, {})) as {+ isError?: boolean;+ content: { text: string }[];+ };+ expect(result.isError, name).toBe(true);+ expect(JSON.parse(result.content[0].text), name).toMatchObject({+ code: 'subscription_inactive',+ });+ }+ expect(data.dismissTopicSuggestionFor).not.toHaveBeenCalled();+ });++ it('refuses a tool registered around the gate', () => {+ const server = gateWriteTools(new McpServer({ name: 'test', version: '0' }), 'org-1');+ expect(() => server.tool('update_anything', async () => ({ content: [] }))).toThrow(+ /registerTool/,+ );+ });++ it('keeps a gated tool closed when the plan cannot be read', async () => {+ dbError = { message: 'connection reset' };+ await expect(subscriptionActiveFor('org-1')).rejects.toThrow('connection reset');+ const client = await connect();+ const result = await client.callTool({+ name: 'dismiss_topic_suggestion',+ arguments: { suggestion_id: SUGGESTION_ID },+ });+ expect(result.isError).toBe(true);+ expect(data.dismissTopicSuggestionFor).not.toHaveBeenCalled();+ });++ it('answers a read tool', async () => {+ const client = await connect();+ const result = await client.callTool({ name: 'list_brands', arguments: {} });+ expect(result.isError).toBeFalsy();+ expect(body(result)).toEqual([{ id: 'brand-1', name: 'Acme' }]);+ });++ it('refuses a write tool with subscription_inactive, without running it', async () => {+ const client = await connect();+ const result = await client.callTool({+ name: 'dismiss_topic_suggestion',+ arguments: { suggestion_id: SUGGESTION_ID },+ });+ expect(result.isError).toBe(true);+ expect(body(result)).toMatchObject({ error: 'plan_limit', code: 'subscription_inactive' });+ expect(data.dismissTopicSuggestionFor).not.toHaveBeenCalled();+ });++ it('runs a write tool once the plan is active', async () => {+ status = 'trialing';+ const client = await connect();+ const result = await client.callTool({+ name: 'dismiss_topic_suggestion',+ arguments: { suggestion_id: SUGGESTION_ID },+ });+ expect(result.isError).toBeFalsy();+ expect(data.dismissTopicSuggestionFor).toHaveBeenCalledTimes(1);+ });++ it('never gates self-hosted', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ const client = await connect();+ const result = await client.callTool({+ name: 'dismiss_topic_suggestion',+ arguments: { suggestion_id: SUGGESTION_ID },+ });+ expect(result.isError).toBeFalsy();+ expect(data.dismissTopicSuggestionFor).toHaveBeenCalledTimes(1);+ });+});++describe('the costly internal calls on a read-only workspace', () => {+ const auth = {+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'agent-internal',+ };+ const fetchMock = vi.fn(async () =>+ Response.json({+ audit: { id: 'audit-1', brandId: 'brand-1', url: 'https://ansvisor.com', status: 'running' },+ }),+ );++ beforeEach(() => {+ vi.stubEnv('CRON_SECRET', 'secret');+ vi.stubGlobal('fetch', fetchMock);+ fetchMock.mockClear();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('refuses a Site Audit before the server is asked, whoever calls it', async () => {+ await expect(runSiteAuditFor(auth, 'brand-1', 'https://ansvisor.com')).rejects.toBeInstanceOf(+ SubscriptionInactiveError,+ );+ await expect(generateBriefFor(auth, 'opportunity-1')).rejects.toMatchObject({+ code: 'subscription_inactive',+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('starts one once the plan is active', async () => {+ status = 'active';+ await expect(runSiteAuditFor(auth, 'brand-1', 'https://ansvisor.com')).resolves.toMatchObject({+ id: 'audit-1',+ status: 'running',+ });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('never gates self-hosted', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ await runSiteAuditFor(auth, 'brand-1', 'https://ansvisor.com');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/src/lib/mcp/subscription-gate.ts b/web/src/lib/mcp/subscription-gate.tsnew file mode 100644index 000000000..fa8994317--- /dev/null+++ b/web/src/lib/mcp/subscription-gate.ts@@ -0,0 +1,117 @@+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { NextResponse } from 'next/server';+import { isCloud, isSubscriptionActive } from '@/config/plans';+import { supabaseAdmin } from '@/lib/supabase/admin';++/**+ * Ansvisor Cloud's read-only mode on the API key surface (MCP tools, the+ * /api/mcp REST routes): while a workspace's plan isn't active — its trial+ * ended, or it was canceled — reading stays open and anything that writes,+ * runs or spends answers with the server's 402 body, as the dashboard's+ * upgrade dialog reads it. Self-hosted is never gated.+ */+export const SUBSCRIPTION_INACTIVE = {+ error: 'plan_limit',+ code: 'subscription_inactive',+ message:+ "This workspace's plan isn't active (its free trial ended or it was canceled), so it is " ++ 'read-only: reading still works, but nothing can be changed, run or generated until an ' ++ 'admin chooses a plan in Settings › Billing.',+} as const;++/**+ * The tools that only read: open while read-only. Any other tool — a new one+ * too, until it is named as a read — needs an active plan.+ */+export function isReadTool(name: string): boolean {+ return name.startsWith('list_') || name.startsWith('get_');+}++/** Whether the organization may write: always self-hosted, and for a key without one. */+export async function subscriptionActiveFor(organizationId: string | null): Promise<boolean> {+ if (!isCloud() || !organizationId) return true;+ const { data, error } = await supabaseAdmin+ .from('organizations')+ .select('subscription_status')+ .eq('id', organizationId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ return isSubscriptionActive(data?.subscription_status as string | null | undefined);+}++/** A call that writes, runs or spends, refused while the workspace is read-only. */+export class SubscriptionInactiveError extends Error {+ readonly code = SUBSCRIPTION_INACTIVE.code;++ constructor() {+ super(SUBSCRIPTION_INACTIVE.message);+ this.name = 'SubscriptionInactiveError';+ }+}++/**+ * Refuse a costly call (the server's internal endpoints: a brief, a Site+ * Audit, an Improve action) while the workspace is read-only, whoever calls+ * it: an MCP tool, a REST route, the in-product agent, or one added later.+ */+export async function assertSubscriptionActive(organizationId: string | null): Promise<void> {+ if (!(await subscriptionActiveFor(organizationId))) throw new SubscriptionInactiveError();+}++/** The REST routes' answer to a write while read-only. */+export function subscriptionInactiveResponse(): NextResponse {+ return NextResponse.json(SUBSCRIPTION_INACTIVE, { status: 402 });+}++/**+ * A REST route's answer to a call that threw: 402 subscription_inactive when+ * a costly call was refused (assertSubscriptionActive), else 500 with the+ * error's message.+ */+export function failedCallResponse(err: unknown): NextResponse {+ if (err instanceof SubscriptionInactiveError) return subscriptionInactiveResponse();+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+}++/** A tool's answer to a call while read-only: a tool error carrying the same body. */+export function subscriptionInactiveToolResult() {+ return {+ content: [{ type: 'text' as const, text: JSON.stringify(SUBSCRIPTION_INACTIVE, null, 2) }],+ isError: true,+ };+}++type AnyToolCallback = (...args: unknown[]) => unknown;+type LooseRegisterTool = (name: string, config: unknown, cb: AnyToolCallback) => unknown;++/**+ * Have every tool registered on `server` from here on, other than a read+ * tool, check the organization's plan before it runs. The plan that can't be+ * read refuses the call too (subscriptionActiveFor throws). The plan is read once+ * per server, which the MCP route builds per request, and only when a gated+ * tool is called.+ */+export function gateWriteTools(server: McpServer, organizationId: string | null): McpServer {+ let active: Promise<boolean> | null = null;+ const register = server.registerTool.bind(server) as unknown as LooseRegisterTool;+ const gated: LooseRegisterTool = (name, config, cb) =>+ register(+ name,+ config,+ isReadTool(name)+ ? cb+ : async (...args: unknown[]) => {+ active ??= subscriptionActiveFor(organizationId);+ if (!(await active)) return subscriptionInactiveToolResult();+ return cb(...args);+ },+ );+ server.registerTool = gated as unknown as McpServer['registerTool'];+ // The SDK's older tool() would register around the gate: refused, so every+ // tool goes through registerTool above.+ server.tool = (() => {+ throw new Error('Register MCP tools with registerTool: the read-only gate wraps it');+ }) as McpServer['tool'];+ return server;+}diff --git a/web/src/lib/webflow-client.test.ts b/web/src/lib/webflow-client.test.tsindex 535f48c2f..1f570c7d8 100644--- a/web/src/lib/webflow-client.test.ts+++ b/web/src/lib/webflow-client.test.ts@@ -73,6 +73,9 @@ describe('webflow-client', () => {expect(await disconnectWebflow('b1')).toEqual({ ok: false, code: 'workspace' });answer(429, { message: 'Too many requests' });expect(await disconnectWebflow('b1')).toEqual({ ok: false, code: 'busy' });+ // A read-only workspace (plan not active): the upgrade dialog's.+ answer(402, { error: 'plan_limit', code: 'subscription_inactive' });+ expect(await disconnectWebflow('b1')).toEqual({ ok: false, code: 'subscription' });answer(500, { code: 'something_else' });expect(await disconnectWebflow('b1')).toEqual({ ok: false, code: 'failed' });fetchMock.mockRejectedValue(new TypeError('offline'));diff --git a/web/src/lib/webflow-client.ts b/web/src/lib/webflow-client.tsindex af55cb28c..84f309646 100644--- a/web/src/lib/webflow-client.ts+++ b/web/src/lib/webflow-client.ts@@ -63,6 +63,8 @@ export type WebflowError =| 'session'| 'workspace'| 'busy'+ /** A read-only workspace (plan not active): the upgrade dialog, not a message. */+ | 'subscription'| 'failed';const KNOWN: readonly WebflowError[] = [@@ -115,7 +117,10 @@ async function call<T>(return {ok: false,code:- general === 'session' || general === 'workspace' || general === 'busy'+ general === 'session' ||+ general === 'workspace' ||+ general === 'busy' ||+ general === 'subscription'? general: 'failed',};