Skip to content

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

feat(web): show "No active plan" instead of a used-up quota while the plan has ended, and keep the buttons opening the plan dialog (#1614)

Cihan0e3dff19654a
diff --git a/web/messages/en.json b/web/messages/en.json
index 1b21f96de..7b26500a6 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -110,6 +110,7 @@
"failed": "Couldn't check the code. Try again."
}
},
+ "noPlan": "No active plan",
"actions": {
"addPrompts": "Adding prompts needs a plan",
"editPrompts": "Editing prompts needs a plan",
@@ -6217,7 +6218,8 @@
"plan": "{plan} plan",
"resets": "Resets {date}",
"upgrade": "Upgrade plan",
- "tooltip": "Every new opportunity counts once, whether Ansvisor suggested it or you asked for it; dismissed and deleted ones still count, merged duplicates don't. Generating a brief counts separately. Unused allowance doesn't carry over. Both reset on {date}, when your subscription renews."
+ "tooltip": "Every new opportunity counts once, whether Ansvisor suggested it or you asked for it; dismissed and deleted ones still count, merged duplicates don't. Generating a brief counts separately. Unused allowance doesn't carry over.",
+ "tooltipResets": "Both reset on {date}, when your subscription renews."
},
"kpi": {
"total": "Total Opportunities",
@@ -8957,7 +8959,9 @@
"back": "Back",
"next": "Next",
"finish": "Finish Setup",
- "ecommerceDetected": "{brand} looks like an online store, so we turned on Product Visibility: ChatGPT Shopping is tracked for your prompts on plans that include it. You can turn it off in brand settings."
+ "ecommerceDetected": "{brand} looks like an online store, so we turned on Product Visibility: ChatGPT Shopping is tracked for your prompts on plans that include it. You can turn it off in brand settings.",
+ "suggestionsUsedUp": "Setup suggestions are used up for today. Try again tomorrow, or add your own.",
+ "promptSuggestionsUsedUp": "Setup suggestions are used up for today. Add your own prompts to each topic below to continue."
},
"settings": {
"facts": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx
index 614985a7e..cfd562e42 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx
@@ -78,6 +78,15 @@ describe('AuditBulkBar', () => {
expect(button('Re-audit').disabled).toBe(true);
});
+ it('keeps Re-audit clickable without an active plan, with no "none left" (0 of 0 is no plan)', () => {
+ render(2, { used: 40, limit: 0, remaining: 0, noPlan: true });
+ expect(container.textContent).not.toContain('No audits left this month');
+ expect(container.querySelector('.text-destructive')).toBeNull();
+ expect(button('Re-audit').disabled).toBe(false);
+ act(() => button('Re-audit').click());
+ expect(onReaudit).toHaveBeenCalledOnce();
+ });
+
it("says the runs' share is still scheduled when the user's is used up (SA-019)", () => {
// The spec's example: 100 auto and 375 of the user's used, day 28's 25 to come.
render(1, {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx
index 65a07db57..198b2272e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx
@@ -12,6 +12,8 @@ import {
} from '@/components/ui/dropdown-menu';
import type { AuditQuota } from '@/lib/actions/audits';
import { cn } from '@/lib/utils';
+import { isNoPlan } from '@/lib/billing/no-plan';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { EmptyPoolMessage } from './_quota-meter';
export type ExportFormat = 'csv' | 'xlsx';
@@ -88,7 +90,10 @@ export function AuditBulkBar({
children?: ReactNode;
}) {
const t = useTranslations('audit.bulk');
- const limited = quota !== null && quota.limit !== -1;
+ const { isLocked } = useUpgradeGate();
+ // Without an active plan the quota reads 0 of 0: not "none left". The audit
+ // stays clickable, and opens the plan dialog.
+ const limited = quota !== null && quota.limit !== -1 && !isNoPlan(quota, isLocked);
const remaining = quota?.remaining ?? 0;
const uses = audits ?? count;
const over = limited && uses > remaining;
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx
index 99390bd81..21048dcfe 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx
@@ -126,6 +126,25 @@ describe('AuditOverviewCards', () => {
expect(audits).toContain('Auto-audit off · How it works');
});
+ it('says "No active plan" for 0 of 0 without one, with no count, bar or runs', () => {
+ render(overview(), {
+ used: 245,
+ running: 0,
+ limit: 0,
+ remaining: 0,
+ noPlan: true,
+ auto: auto({ enabled: false, reserved: 0 }),
+ });
+ const audits = cards()[3];
+ expect(audits).toContain('Audits this month');
+ expect(audits).toContain('—');
+ expect(audits).toContain('No active plan');
+ expect(audits).not.toContain('of 0 left');
+ expect(audits).not.toContain('How it works');
+ expect(container.querySelector('[role=img][aria-label]')).toBeNull();
+ expect(container.querySelector('.text-destructive')).toBeNull();
+ });
+
it('counts the pages on other sites apart, and says when there are no gaps or pages', () => {
render(overview({ otherPages: 3, gaps: [] }));
expect(cards()[1]).toContain('+ 3 on other sites');
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx
index 7df4be48a..dc6ba0dbe 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx
@@ -8,6 +8,8 @@ import { Skeleton } from '@/components/ui/skeleton';
import { pct } from '@/components/audit/audit-report';
import type { AuditOverview, AuditQuota } from '@/lib/actions/audits';
import { formatNumber } from '@/lib/format';
+import { isNoPlan } from '@/lib/billing/no-plan';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { MetricCard } from '../insights/_kpi-cards';
import { upIsGood } from '../insights/kpi-format';
import { autoSharePct, quotaShares, QuotaSegments, RunDots } from './_quota-meter';
@@ -99,6 +101,8 @@ export function AuditOverviewCards({
}) {
const t = useTranslations('audit.overview');
const tq = useTranslations('audit.quota');
+ const tReadOnly = useTranslations('readOnly');
+ const { isLocked } = useUpgradeGate();
const [howOpen, setHowOpen] = useState(false);
if (!overview) {
@@ -116,7 +120,10 @@ export function AuditOverviewCards({
}
const domain = overview.primaryHost ?? t('yourDomain');
- const shares = quota ? quotaShares(quota) : null;
+ // Without an active plan the quota reads 0 of 0: the card says so, with no
+ // count, bar or runs, rather than "0 of 0 left".
+ const noPlan = isNoPlan(quota, isLocked);
+ const shares = quota && !noPlan ? quotaShares(quota) : null;
const auto = quota?.auto;
const gapsSub =
overview.pages === 0 ? t('noPages') : overview.gaps.length > 0 ? t('gapsSub') : t('noGaps');
@@ -145,7 +152,7 @@ export function AuditOverviewCards({
{howToggle}
</div>
</div>
- ) : auto?.enabled ? (
+ ) : auto?.enabled && !noPlan ? (
<div className="space-y-2 pb-0.5">
<RunDots auto={auto} now={now} />
<div className="truncate text-xs text-muted-foreground">
@@ -188,13 +195,13 @@ export function AuditOverviewCards({
label={t('auditsThisMonth')}
tooltip={t('auditsTip')}
icon={CalendarDays}
- value={shares ? formatNumber(shares.left) : t('unlimited')}
+ value={noPlan ? '—' : shares ? formatNumber(shares.left) : t('unlimited')}
delta={
shares && quota
? { text: t('ofLeft', { limit: formatNumber(quota.limit) }), tone: 'neutral' }
: null
}
- sub={quota && !shares ? t('unlimitedSub') : undefined}
+ sub={noPlan ? tReadOnly('noPlan') : quota && !shares ? t('unlimitedSub') : undefined}
footer={quotaFooter}
/>
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.test.tsx
new file mode 100644
index 000000000..8c4fd6c81
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.test.tsx
@@ -0,0 +1,77 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import type { AuditAutoStatus, AuditQuota } from '@/lib/actions/audits';
+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
+import { EmptyPoolMessage } from './_quota-meter';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/**
+ * "You've used your N audits" while auto-audit's runs still keep some (spec
+ * §4.4); never without an active plan, whose 0 left isn't used up.
+ */
+
+const auto = (reserved: number): AuditAutoStatus => ({
+ enabled: true,
+ setting: null,
+ emailAfterRun: false,
+ perRun: 5,
+ reserved,
+ used: 5,
+ running: 0,
+ periodStart: '2026-10-01T00:00:00.000Z',
+ periodEnd: '2026-11-01T00:00:00.000Z',
+ runs: [],
+ nextRun: { day: 7, at: '2026-10-07T00:00:00.000Z' },
+});
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function render(quota: AuditQuota, isLocked = false) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade: vi.fn() }}
+ >
+ <EmptyPoolMessage quota={quota} />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+describe('EmptyPoolMessage', () => {
+ it("says the user's share is used up while auto-audit's runs still keep some", async () => {
+ await render({ used: 80, limit: 100, remaining: 0, auto: auto(20) });
+ expect(container.textContent).toBe(
+ "You've used your 75 audits. 20 auto audits are still scheduled. Turn off auto-audit to use them now, or upgrade.",
+ );
+ });
+
+ it('says nothing without an active plan, though its runs read as still scheduled', async () => {
+ await render({ used: 80, limit: 0, remaining: 0, noPlan: true, auto: auto(20) });
+ expect(container.textContent).toBe('');
+ });
+
+ it('says nothing on a read-only workspace, marked or not', async () => {
+ await render({ used: 80, limit: 100, remaining: 0, auto: auto(20) }, true);
+ expect(container.textContent).toBe('');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.tsx
index 0ab44a2d7..c708eb9f9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.tsx
@@ -3,6 +3,8 @@
import { useTranslations } from 'next-intl';
import type { AuditAutoStatus, AuditQuota } from '@/lib/actions/audits';
import { autoRunStates } from '@/lib/audit-auto-runs';
+import { isNoPlan } from '@/lib/billing/no-plan';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { formatMonthDay, formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
@@ -121,7 +123,9 @@ export function EmptyPoolMessage({
className?: string;
}) {
const t = useTranslations('audit.quota');
- const shares = quota ? quotaShares(quota) : null;
+ const { isLocked } = useUpgradeGate();
+ // Without an active plan nothing is used up (and no run is scheduled).
+ const shares = quota && !isNoPlan(quota, isLocked) ? quotaShares(quota) : null;
if (!quota || !shares || quota.remaining > 0 || shares.autoScheduled === 0) return null;
return (
<p className={cn('text-xs text-destructive', className)}>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsx
index 42568acf6..b4d7f7f65 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsx
@@ -175,6 +175,16 @@ describe('AuditSettingsDialog', () => {
expect(actions.setOpportunityPrefs).not.toHaveBeenCalled();
});
+ // The server reads the month's audits as 0 once the plan has ended.
+ it('says "No active plan" on a read-only workspace, not "all 0 audits a month are yours"', async () => {
+ actions.getAuditSettings.mockResolvedValue(
+ settings({ autoAudit: { enabled: false, setting: null, perRun: 5, limit: 0 } }),
+ );
+ await render(true, undefined, true);
+ expect(dialog().textContent).toContain('No active plan');
+ expect(dialog().textContent).not.toContain('audits a month are yours');
+ });
+
it("shows the server's message when a pattern is refused", async () => {
actions.saveAuditSettings.mockRejectedValue(
new Error('"careers" isn\'t a page path. Start it with /, as in /legal/*.'),
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsx
index 56524a0ec..24a344735 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsx
@@ -86,8 +86,9 @@ export function AuditSettingsDialog({
const t = useTranslations('audit.settings');
// A read-only workspace (plan not active): the settings open to read; Save
// and Unpin open the upgrade dialog instead.
- const { guard } = useUpgradeGate();
+ const { guard, isLocked } = useUpgradeGate();
const tActions = useTranslations('readOnly.actions');
+ const tReadOnly = useTranslations('readOnly');
const [settings, setSettings] = useState<AuditSettings | null>(null);
const [autoAudit, setAutoAudit] = useState(false);
const [emailAfterRun, setEmailAfterRun] = useState(false);
@@ -165,17 +166,21 @@ export function AuditSettingsDialog({
};
const auto = settings?.autoAudit;
+ // Read-only (no active plan): the month's audits read 0, so it says there's
+ // no plan, not "all 0 audits a month are yours".
const autoLine = !auto
? null
- : auto.limit === -1
- ? t('autoAuditUnlimited', { perRun: auto.perRun })
- : autoAudit
- ? t('autoAuditOn', {
- perRun: auto.perRun,
- total: formatNumber(auto.perRun * 5),
- limit: formatNumber(auto.limit),
- })
- : t('autoAuditOff', { limit: formatNumber(auto.limit) });
+ : isLocked
+ ? tReadOnly('noPlan')
+ : auto.limit === -1
+ ? t('autoAuditUnlimited', { perRun: auto.perRun })
+ : autoAudit
+ ? t('autoAuditOn', {
+ perRun: auto.perRun,
+ total: formatNumber(auto.perRun * 5),
+ limit: formatNumber(auto.limit),
+ })
+ : t('autoAuditOff', { limit: formatNumber(auto.limit) });
const timing: string[] = [];
if (auto && autoAudit && schedule && now) {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.test.tsx
index d079d7cd6..b56614cef 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.test.tsx
@@ -127,6 +127,35 @@ describe('SiteAuditPage Run audit', () => {
expect(push).not.toHaveBeenCalled();
});
+ // The server reads 0 of 0 without an active plan (noPlan): not "used up".
+ it('keeps Run Audit clickable without an active plan, with no red 0/0: it opens the upgrade dialog', async () => {
+ audits.getAuditHub.mockResolvedValue({
+ pages: { pages: [], total: 0, primaryHost: 'acme.com' },
+ quota: { used: 12, limit: 0, remaining: 0, noPlan: true },
+ trend: null,
+ overview: null,
+ });
+ await render(true);
+ expect(runButton().disabled).toBe(false);
+ expect(container.textContent).not.toContain('0/0');
+ expect(container.querySelector('.text-destructive')).toBeNull();
+ await act(async () => runButton().click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Running an audit needs a plan');
+ expect(audits.runAudit).not.toHaveBeenCalled();
+ });
+
+ it('still keeps Run Audit off with the red count once an active plan is used up', async () => {
+ audits.getAuditHub.mockResolvedValue({
+ pages: { pages: [], total: 0, primaryHost: 'acme.com' },
+ quota: { used: 10, limit: 10, remaining: 0 },
+ trend: null,
+ overview: null,
+ });
+ await render(false);
+ expect(runButton().disabled).toBe(true);
+ expect(container.querySelector('.text-destructive')?.textContent).toContain('0/10');
+ });
+
it('starts an audit on the button on an active plan, and opens it', async () => {
await render(false);
await act(async () => runButton().click());
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
index cf31e9407..1ed5fc30b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
@@ -27,6 +27,7 @@ import { qualityPhase } from '@/lib/content/quality';
import { useBrandStore } from '@/stores/use-brand-store';
import { useUserRole } from '@/hooks/use-user-role';
import { useUpgradeGate } from '@/components/providers/upgrade-gate';
+import { isNoPlan } from '@/lib/billing/no-plan';
import {
runAudit,
runAuditsBulk,
@@ -97,7 +98,7 @@ export default function SiteAuditPage() {
// A read-only workspace (plan not active): Run audit, the bulk bars' Audit,
// Pin, Exclude and Restore, and deleting a run open the upgrade dialog
// instead; the settings open to read, and their Save asks too.
- const { guard } = useUpgradeGate();
+ const { guard, isLocked } = useUpgradeGate();
const tActions = useTranslations('readOnly.actions');
// Prefill the URL with the active brand's primary domain (read once at init).
@@ -234,7 +235,10 @@ export default function SiteAuditPage() {
};
}, [groupByTemplate, activeBrandId, refreshKey, t]);
- const quotaExhausted = quota !== null && quota.limit !== -1 && quota.remaining <= 0;
+ // Without an active plan the quota reads 0 of 0: not used up. Run audit
+ // stays clickable, and opens the plan dialog.
+ const quotaExhausted =
+ quota !== null && !isNoPlan(quota, isLocked) && quota.limit !== -1 && quota.remaining <= 0;
// Trend points within the selected range (oldest → newest).
const rangePoints = useMemo(() => {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx
index fe03a948d..f8dfde8fb 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx
@@ -219,6 +219,61 @@ describe('Content Opportunities on a read-only workspace', () => {
});
});
+describe('the usage card and New without an active plan', () => {
+ // The server reads limits of 0 and `noPlan` once the plan has ended.
+ const usage = (over: Record<string, unknown> = {}) => ({
+ plan: 'growth',
+ planName: 'Growth',
+ periodStart: '2026-10-01T00:00:00.000Z',
+ periodEnd: '2026-11-01T00:00:00.000Z',
+ opportunities: { used: 2, limit: 0, remaining: 0, perRequest: 0, noPlan: true },
+ briefs: { used: 4, limit: 0, remaining: 0, noPlan: true },
+ noPlan: true,
+ ...over,
+ });
+
+ it('says "No active plan", not "Limit reached" or the old plan, and New opens the plan dialog', async () => {
+ content.getContentUsage.mockResolvedValue(usage());
+ await render(true);
+ expect(container.textContent).toContain('No active plan');
+ expect(container.textContent).not.toContain('Limit reached');
+ expect(container.textContent).not.toContain('Growth plan');
+ // The usage card: the counts used, no red bar or line.
+ const card = [...container.querySelectorAll('[data-slot="card"]')].find((el) =>
+ el.textContent?.includes('This billing period'),
+ )!;
+ expect(card.textContent).toContain('New opportunities2');
+ expect(card.querySelector('.text-red-600, .bg-red-500')).toBeNull();
+ // Nothing renews without a plan: the hint says what counts, not when it resets.
+ const hint = card.querySelector('[title]')!.getAttribute('title');
+ expect(hint).toContain('Every new opportunity counts once');
+ expect(hint).not.toContain('when your subscription renews');
+ expect(buttonNamed('New').disabled).toBe(false);
+ await act(async () => buttonNamed('New').click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Generating opportunities needs a plan');
+ });
+
+ it('still says "Limit reached" with the plan, and keeps New off, once an active plan is used up', async () => {
+ content.getContentUsage.mockResolvedValue({
+ ...usage(),
+ noPlan: undefined,
+ opportunities: { used: 50, limit: 50, remaining: 0, perRequest: 5 },
+ briefs: { used: 4, limit: 50, remaining: 46 },
+ });
+ await render(false);
+ expect(container.textContent).toContain('Limit reached');
+ expect(container.textContent).toContain('Growth plan');
+ expect(container.textContent).not.toContain('No active plan');
+ const card = [...container.querySelectorAll('[data-slot="card"]')].find((el) =>
+ el.textContent?.includes('This billing period'),
+ )!;
+ expect(card.querySelector('[title]')!.getAttribute('title')).toContain(
+ "Unused allowance doesn't carry over. Both reset on Nov 1, when your subscription renews.",
+ );
+ expect(buttonNamed('New').disabled).toBe(true);
+ });
+});
+
describe('Content Opportunities on an active plan', () => {
it('runs the actions', async () => {
await render(false);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index 91c4f37c5..2ad4fac7a 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -104,6 +104,7 @@ import {
import { OpportunityDetail } from '@/components/content/opportunity-detail';
import { ContentUsageCard } from '@/components/content/content-usage-card';
import { hasContentQuota, onDemandMax, type ContentUsage } from '@/lib/content-usage';
+import { isNoPlan } from '@/lib/billing/no-plan';
import { suggestedBounds, suggestedDate, type SuggestedRange } from '@/lib/suggested-date';
import {
DEFAULT_OPPORTUNITY_SORT,
@@ -870,7 +871,10 @@ export default function ContentPage() {
});
const requestMax = contentUsage ? onDemandMax(contentUsage) : FALLBACK_REQUEST_MAX;
- const limitReached = hasContentQuota(contentUsage) && requestMax === 0;
+ // Without an active plan the quota reads 0 of 0: New stays clickable, and
+ // opens the plan dialog.
+ const limitReached =
+ hasContentQuota(contentUsage) && !isNoPlan(contentUsage, isLocked) && requestMax === 0;
const resetsOn = contentUsage?.periodEnd
? new Date(contentUsage.periodEnd).toLocaleDateString(locale, {
month: 'short',
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx
index 2f14ef5d7..d1f083559 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx
@@ -33,10 +33,14 @@ vi.mock('@/lib/actions/tracking', () => ({
getBrandFilterOptions: vi.fn(async () => ({ regions: [] })),
}));
vi.mock('@/lib/actions/topic', () => ({ getTopics: vi.fn(async () => []) }));
+const contentUsage = vi.hoisted(() => ({ value: null as object | null }));
+const getOpenSuggestionForPrompt = vi.hoisted(() =>
+ vi.fn(async (): Promise<string | null> => null),
+);
vi.mock('@/lib/actions/content', () => ({
- getContentUsage: vi.fn(async () => null),
+ getContentUsage: vi.fn(async () => contentUsage.value),
getGenerationJobStatus: vi.fn(),
- getOpenSuggestionForPrompt: vi.fn(async () => null),
+ getOpenSuggestionForPrompt,
suggestContentForPrompt: vi.fn(),
}));
vi.mock('@/lib/actions/content-drafts', () => ({ getDraftForPrompt: vi.fn(async () => null) }));
@@ -55,14 +59,16 @@ vi.mock('@/stores/use-brand-store', () => ({
select({ activeBrandId: 'b1', brands: [{ id: 'b1', slug: 'acme', name: 'Acme' }] }),
}));
vi.mock('next/navigation', () => ({ useSearchParams: () => new URLSearchParams() }));
+// The route names the tab: Tracked unless a test opens Insights.
+const nav = vi.hoisted(() => ({ pathname: '/dashboard/prompts/tracked', push: vi.fn() }));
vi.mock('@/i18n/navigation', () => ({
Link: ({ href, children, ...props }: { href: string; children: ReactNode }) => (
<a href={href} {...props}>
{children}
</a>
),
- usePathname: () => '/dashboard/prompts/tracked',
- useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+ usePathname: () => nav.pathname,
+ useRouter: () => ({ push: nav.push, replace: vi.fn() }),
}));
const toast = vi.hoisted(() =>
Object.assign(vi.fn(), {
@@ -122,6 +128,9 @@ const dialog = () => document.querySelector('[role="dialog"]');
beforeEach(() => {
vi.clearAllMocks();
+ nav.pathname = '/dashboard/prompts/tracked';
+ contentUsage.value = null;
+ getOpenSuggestionForPrompt.mockResolvedValue(null);
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, json: async () => ({}) })),
@@ -237,3 +246,103 @@ describe('volumes on a read-only workspace', () => {
);
});
});
+
+describe('the volume quota without an active plan', () => {
+ // The server reads 0 of 0 with `noPlan` once the plan has ended.
+ const noPlan = { used: 3, limit: 0, remaining: 0, noPlan: true };
+ const pageData = (quota: object | null) => ({
+ volumes: [],
+ quota,
+ promptSets: [{ prompts: [prompt] }],
+ visibility: {},
+ positions: {},
+ });
+ const reds = () => container.querySelectorAll('.text-red-500');
+
+ it('offers Analyze on Tracked, not "limit is reached", and it opens the upgrade dialog', async () => {
+ actions.getPromptsPageData.mockResolvedValue(pageData(noPlan));
+ await render(true);
+ expect(container.textContent).toContain('Run volume analysis to fill in');
+ expect(container.textContent).not.toContain('limit is reached');
+ const analyze = button('Analyze 1 prompt')!;
+ expect(analyze.disabled).toBe(false);
+ await act(async () => analyze.click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Analyzing prompts needs a plan');
+ expect(volumes.startPromptVolumeAnalysis).not.toHaveBeenCalled();
+ });
+
+ it("keeps the row menu's Suggest content clickable at a content quota of 0 of 0: it opens the upgrade dialog", async () => {
+ contentUsage.value = {
+ plan: 'growth',
+ planName: 'Growth',
+ periodStart: '2026-10-01T00:00:00.000Z',
+ periodEnd: '2026-11-01T00:00:00.000Z',
+ opportunities: { used: 2, limit: 0, remaining: 0, perRequest: 0, noPlan: true },
+ briefs: { used: 0, limit: 0, remaining: 0, noPlan: true },
+ noPlan: true,
+ };
+ await render(true);
+ const trigger = container.querySelector<HTMLElement>(
+ `[aria-label="Actions for ${prompt.text}"]`,
+ )!;
+ await act(async () => trigger.click());
+ const suggest = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((el) =>
+ el.textContent?.startsWith('Suggest content'),
+ )!;
+ expect(suggest.textContent).toBe('Suggest content');
+ expect(suggest.hasAttribute('data-disabled')).toBe(false);
+ await act(async () => suggest.click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Suggesting content needs a plan');
+ });
+
+ it("opens the prompt's content suggestion from the row menu, which costs nothing", async () => {
+ contentUsage.value = {
+ plan: 'growth',
+ planName: 'Growth',
+ periodStart: '2026-10-01T00:00:00.000Z',
+ periodEnd: '2026-11-01T00:00:00.000Z',
+ opportunities: { used: 2, limit: 0, remaining: 0, perRequest: 0, noPlan: true },
+ briefs: { used: 0, limit: 0, remaining: 0, noPlan: true },
+ noPlan: true,
+ };
+ getOpenSuggestionForPrompt.mockResolvedValue('opp-1');
+ await render(true);
+ const trigger = container.querySelector<HTMLElement>(
+ `[aria-label="Actions for ${prompt.text}"]`,
+ )!;
+ await act(async () => trigger.click());
+ expect(getOpenSuggestionForPrompt).toHaveBeenCalledWith('p1');
+ const items = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ const open = items.find((el) => el.textContent === 'Open content suggestion')!;
+ expect(open).toBeDefined();
+ expect(items.some((el) => el.textContent?.startsWith('Suggest content'))).toBe(false);
+ await act(async () => open.click());
+ expect(nav.push).toHaveBeenCalledWith('/dashboard/content?opportunity=opp-1');
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+
+ it('says "No active plan" on Insights, not a red 0/0 or "limit reached"', async () => {
+ nav.pathname = '/dashboard/prompts/insights';
+ actions.getPromptsPageData.mockResolvedValue(pageData(noPlan));
+ await render(true);
+ expect(container.textContent).toContain('No active plan');
+ expect(container.textContent).not.toContain('0/0');
+ expect(container.textContent).not.toContain('Monthly analysis limit reached');
+ expect(reds()).toHaveLength(0);
+ const analyze = button('Analyze Volumes')!;
+ expect(analyze.disabled).toBe(false);
+ await act(async () => analyze.click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Analyzing prompts needs a plan');
+ });
+
+ it('still says the limit is reached, in red, once an active plan is used up', async () => {
+ nav.pathname = '/dashboard/prompts/insights';
+ actions.getPromptsPageData.mockResolvedValue(pageData({ used: 10, limit: 10, remaining: 0 }));
+ await render(false);
+ expect(container.textContent).toContain('0/10 analyses left');
+ expect(container.textContent).toContain('Monthly analysis limit reached');
+ expect(container.textContent).not.toContain('No active plan');
+ expect(reds().length).toBeGreaterThan(0);
+ expect(button('Analyze Volumes')!.disabled).toBe(true);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index f75504b22..0991f30e8 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -142,6 +142,7 @@ import { Checkbox } from '@/components/ui/checkbox';
import { useUserRole } from '@/hooks/use-user-role';
import { usePlanContext } from '@/components/providers/plan-provider';
import { useUpgradeGate } from '@/components/providers/upgrade-gate';
+import { isNoPlan } from '@/lib/billing/no-plan';
import {
MODEL_GROUPS,
ALL_MODELS,
@@ -1309,6 +1310,7 @@ export default function PromptsPage() {
// runs open the upgrade dialog instead.
const { guard, isLocked } = useUpgradeGate();
const tActions = useTranslations('readOnly.actions');
+ const tReadOnly = useTranslations('readOnly');
const failureToast = useFailureToast();
const openAddPrompt = guard(() => setAddPromptOpen(true), { action: tActions('addPrompts') });
@@ -1819,7 +1821,10 @@ export default function PromptsPage() {
v.intent.toLowerCase().includes(search.toLowerCase()),
);
- const quotaExhausted = quota !== null && quota.limit !== -1 && quota.remaining <= 0;
+ // Without an active plan the quota reads 0 of 0: not used up. The analyses
+ // stay clickable, and open the plan dialog.
+ const noPlan = isNoPlan(quota, isLocked);
+ const quotaExhausted = !noPlan && quota !== null && quota.limit !== -1 && quota.remaining <= 0;
// Reads "Analyzing 32/100..." once the first poll lands, so a run measured in
// minutes shows movement instead of an indefinite spinner. A count is only
@@ -2189,7 +2194,7 @@ export default function PromptsPage() {
quotaExhausted ? 'text-red-500' : 'text-muted-foreground',
)}
>
- {quota.remaining}/{quota.limit} analyses left
+ {noPlan ? tReadOnly('noPlan') : `${quota.remaining}/${quota.limit} analyses left`}
</span>
)}
{volumes.length > 0 && (
@@ -2281,7 +2286,9 @@ export default function PromptsPage() {
)}
{quota && quota.limit !== -1 && !quotaExhausted && (
<p className="text-xs text-muted-foreground">
- {quota.remaining}/{quota.limit} analyses remaining this month
+ {noPlan
+ ? tReadOnly('noPlan')
+ : `${quota.remaining}/${quota.limit} analyses remaining this month`}
</p>
)}
</>
@@ -2657,6 +2664,7 @@ function RowActionsMenu({
onSuggestContent,
onOpenSuggestion,
suggesting,
+ noPlan,
suggestDisabledReason,
onCreateContent,
onDelete,
@@ -2672,6 +2680,8 @@ function RowActionsMenu({
onOpenSuggestion: (opportunityId: string) => void;
/** A suggestion for this prompt is being written. */
suggesting: boolean;
+ /** No active plan (read-only): Suggest content opens the plan dialog; a written suggestion still opens. */
+ noPlan: boolean;
/** Why Suggest content can't run now (the month's quota is used up, or a bulk run is going). */
suggestDisabledReason: string | null;
/** Opens New content › Start for a new page for this prompt. */
@@ -2680,9 +2690,11 @@ function RowActionsMenu({
}) {
const t = useTranslations('prompts.content');
const router = useRouter();
- // With the month's quota used up, a prompt that already has a suggestion
- // can still open it, which costs nothing; the menu asks as it opens.
+ // With the month's quota used up, or without an active plan, a prompt that
+ // already has a suggestion can still open it, which costs nothing; the menu
+ // asks as it opens.
const [openSuggestionId, setOpenSuggestionId] = useState<string | null>(null);
+ const canOpenSuggestion = suggestDisabledReason !== null || noPlan;
// A draft already being written for the prompt opens instead of a second
// one; undefined while the menu asks.
const [draftId, setDraftId] = useState<string | null | undefined>(undefined);
@@ -2690,7 +2702,7 @@ function RowActionsMenu({
if (!open) return;
setDraftId(undefined);
getDraftForPrompt(brandId, prompt.id).then(setDraftId, () => setDraftId(null));
- if (suggestDisabledReason === null) return;
+ if (!canOpenSuggestion) return;
getOpenSuggestionForPrompt(prompt.id).then(setOpenSuggestionId, () =>
setOpenSuggestionId(null),
);
@@ -2717,7 +2729,7 @@ function RowActionsMenu({
<TrendingUp className="h-3.5 w-3.5" />
Improve position…
</DropdownMenuItem>
- {suggestDisabledReason !== null && openSuggestionId ? (
+ {canOpenSuggestion && openSuggestionId ? (
<DropdownMenuItem className="gap-2" onClick={() => onOpenSuggestion(openSuggestionId)}>
<Lightbulb className="h-3.5 w-3.5" />
Open content suggestion
@@ -2867,7 +2879,7 @@ function AllPromptsTab({
const now = useNow({ updateInterval: 60_000 }).getTime();
// A read-only workspace (plan not active): the row menu's and the bulk
// bar's actions open the upgrade dialog instead.
- const { guard } = useUpgradeGate();
+ const { guard, isLocked } = useUpgradeGate();
const tActions = useTranslations('readOnly.actions');
// Rows deleted from the row menu or the bulk bar, hidden at once and
// deleted for real after the Undo window (PROMPT-006). There is no soft
@@ -3089,8 +3101,11 @@ function AllPromptsTab({
}, [activeBrandId, usageVersion]);
const hasOpportunityLimit =
hasContentQuota(contentUsage) && contentUsage.opportunities.limit !== -1;
+ // Without an active plan the quota reads 0 of 0: Suggest content stays
+ // clickable, and opens the plan dialog.
+ const contentNoPlan = isNoPlan(contentUsage, isLocked);
const suggestDisabledReason =
- hasOpportunityLimit && contentUsage.opportunities.remaining <= 0
+ hasOpportunityLimit && !contentNoPlan && contentUsage.opportunities.remaining <= 0
? contentUsage.periodEnd
? `Limit reached · resets ${new Date(contentUsage.periodEnd).toLocaleDateString('en-US', {
month: 'short',
@@ -3667,6 +3682,7 @@ function AllPromptsTab({
? 'Wait for the suggestion being written'
: bulkSuggestBlock(selectedPrompts.length, contentUsage, {
unavailable: contentUsageFailed,
+ isLocked,
}))
}
deleting={showDeleteProgress ? deleteProgress : null}
@@ -4006,6 +4022,7 @@ function AllPromptsTab({
})}
onOpenSuggestion={openOpportunity}
suggesting={suggestingIds.has(p.id)}
+ noPlan={contentNoPlan}
suggestDisabledReason={
suggestDisabledReason ??
(bulkSuggesting ? 'Wait for the selected prompts' : null)
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.test.tsx
index ab70b1228..97329a7a1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.test.tsx
@@ -4,6 +4,8 @@ import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../messages/en.json';
import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
+import { PlanProvider } from '@/components/providers/plan-provider';
+import type { PlanId } from '@/config/plans';
import type { BotConnections, NewBotConnection } from '@/lib/actions/ai-bots';
/**
@@ -67,17 +69,27 @@ afterEach(() => {
act(() => root.unmount());
container.remove();
document.body.innerHTML = '';
+ vi.unstubAllEnvs();
});
const openUpgrade = vi.fn();
-async function render(canConnect = true, isLocked = false) {
+/** `planId`: on Ansvisor Cloud, the plan the workspace is (or was) on. */
+async function render(canConnect = true, isLocked = false, planId?: PlanId) {
+ const source = <BotsSource brandId="b1" canConnect={canConnect} />;
+ if (planId) vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
<UpgradeDialogContext.Provider
value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
>
- <BotsSource brandId="b1" canConnect={canConnect} />
+ {planId ? (
+ <PlanProvider planId={planId} subscriptionActive={!isLocked}>
+ {source}
+ </PlanProvider>
+ ) : (
+ source
+ )}
</UpgradeDialogContext.Provider>
</NextIntlClientProvider>,
);
@@ -134,6 +146,40 @@ describe('BotsSource', () => {
expect(getBotConnections).toHaveBeenCalledTimes(2);
});
+ // The server reads caps of 0 without an active plan (noPlan): the plan it was on decides.
+ it('shows a workspace whose Growth plan ended its own connections and use, not Upgrade', async () => {
+ openUpgrade.mockReset();
+ getBotConnections.mockResolvedValue(
+ info({
+ connections: [
+ { id: 'c1', kind: 'cloudflare_worker', createdAt: 't', lastEventAt: hoursAgo(1) },
+ ],
+ usage: { ...info().usage, stored: 1_200, cap: 0, rawCap: 0, noPlan: true },
+ }),
+ );
+ await render(true, true, 'growth');
+ expect(card()).toContain('Cloudflare / Vercel · last event 1h ago');
+ expect(card()).not.toContain('Growth+');
+ expect(container.querySelector('a[href="/dashboard/settings?tab=billing"]')).toBeNull();
+ await act(async () => button('Manage')!.click());
+ expect(page()).toContain('This month: 1,200 detailed rows. · No active plan');
+ expect(page()).not.toContain('of 0');
+ await act(async () => button('Create connection')!.click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Connecting bot logs needs a plan');
+ expect(createBotConnection).not.toHaveBeenCalled();
+ });
+
+ it('keeps Upgrade for a workspace whose Starter plan ended', async () => {
+ getBotConnections.mockResolvedValue(
+ info({ usage: { ...info().usage, cap: 0, rawCap: 0, noPlan: true } }),
+ );
+ await render(true, true, 'starter');
+ expect(card()).toContain('Cloudflare / Vercel · Growth+');
+ expect(container.querySelector('a')?.getAttribute('href')).toBe(
+ '/dashboard/settings?tab=billing',
+ );
+ });
+
it('makes no connection on a read-only workspace: Create connection opens the upgrade dialog', async () => {
openUpgrade.mockReset();
await render(true, true);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.tsx
index f284621b7..d28bf18b2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.tsx
@@ -34,6 +34,7 @@ import {
import { SourceCard } from './_source-card';
import { getBotConnections } from '@/lib/traffic-reads';
import { useUpgradeGate } from '@/components/providers/upgrade-gate';
+import { usePlanContext } from '@/components/providers/plan-provider';
const KINDS: BotConnectionKind[] = ['cloudflare_worker', 'cloudflare_logpush', 'vercel_drain'];
@@ -163,6 +164,7 @@ export function BotsDialog({
// upgrade dialog instead; revoking one stays open (it ends an access).
const { guard } = useUpgradeGate();
const tActions = useTranslations('readOnly.actions');
+ const tReadOnly = useTranslations('readOnly');
const close = (next: boolean) => {
if (!next) {
@@ -280,12 +282,14 @@ export function BotsDialog({
))}
</ul>
<p className="text-xs text-muted-foreground">
- {usage.cap < 0
+ {/* Without an active plan the cap reads 0: the month's rows, not "of 0". */}
+ {usage.cap < 0 || usage.noPlan
? t('usageNoCap', { stored: formatNumber(usage.stored), count: usage.stored })
: t('usage', {
stored: formatNumber(usage.stored),
cap: formatNumber(usage.cap),
})}
+ {usage.noPlan && ` · ${tReadOnly('noPlan')}`}
{pausedUntil && ` ${t('paused', { day: shortDay(pausedUntil) })}`}
</p>
{/* Log senders' records count against their own cap (§6.3). */}
@@ -382,6 +386,9 @@ export function BotsSource({
failed: boolean;
} | null>(null);
const [open, setOpen] = useState(false);
+ // Without an active plan the caps read 0: the plan it was on decides the lock.
+ const { isLocked } = useUpgradeGate();
+ const { planId } = usePlanContext();
const load = useCallback(() => {
const done = (next: BotConnections | null) =>
@@ -412,7 +419,7 @@ export function BotsSource({
);
}
- const state = botsCardState(info);
+ const state = botsCardState(info, { isLocked, planId });
const button = (label: string, primary: boolean) => (
<Button
size="sm"
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.test.tsx
index e040933ce..6a104e2b0 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.test.tsx
@@ -5,6 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../messages/en.json';
import type { BotConnections } from '@/lib/actions/ai-bots';
import type { TrafficBots, TrafficDateWindow } from '@/lib/actions/traffic';
+import { PlanProvider } from '@/components/providers/plan-provider';
+import type { PlanId } from '@/config/plans';
/**
* AI bots reading your site (AT-011, spec §3.7, §7): Starter locked with
@@ -92,6 +94,7 @@ afterEach(() => {
act(() => root.unmount());
container.remove();
document.body.innerHTML = '';
+ vi.unstubAllEnvs();
});
async function render(canConnect = true, revision = 0, onChanged?: () => void) {
@@ -111,6 +114,20 @@ async function render(canConnect = true, revision = 0, onChanged?: () => void) {
});
}
+/** On Ansvisor Cloud, on `planId`, whose subscription has ended. */
+async function renderOnEndedPlan(planId: PlanId) {
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <PlanProvider planId={planId} subscriptionActive={false}>
+ <BotsReportSection brandId="b1" dateWindow={WEEK} rangeLabel="last 7 days" canConnect />
+ </PlanProvider>
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
/** A fresh section: it reads again. */
async function remount(canConnect = true) {
act(() => root.unmount());
@@ -239,6 +256,32 @@ describe('BotsReportSection', () => {
);
});
+ // A plan that ended reads caps of 0 with noPlan: the plan it was on decides the lock.
+ it('shows a workspace whose Growth plan ended its own data, not the locked sample', async () => {
+ getBotConnections.mockResolvedValue(
+ info({ usage: { ...info().usage, cap: 0, rawCap: 0, noPlan: true } }),
+ );
+ await renderOnEndedPlan('growth');
+ expect(text()).not.toContain('The AI bot report comes with the Growth plan.');
+ expect(text()).not.toContain('8,420');
+ expect(container.querySelector('a[href="/dashboard/settings?tab=billing"]')).toBeNull();
+ expect(rows()).toEqual([
+ ['Training (GPTBot, ClaudeBot)', '1,200', '300', '2h ago'],
+ ['Search index (OAI-SearchBot)', '400', '120', '1h ago'],
+ ['/menu', '90', '2h ago', '—', '1h ago'],
+ ]);
+ });
+
+ it('keeps the locked sample and Upgrade for a workspace whose Starter plan ended', async () => {
+ getBotConnections.mockResolvedValue(
+ info({ usage: { ...info().usage, cap: 0, rawCap: 0, noPlan: true } }),
+ );
+ await renderOnEndedPlan('starter');
+ expect(text()).toContain('The AI bot report comes with the Growth plan.');
+ expect(text()).toContain('8,420');
+ expect(container.querySelector('a[href="/dashboard/settings?tab=billing"]')).not.toBeNull();
+ });
+
it('offers Connect over sample data, and a preview of it', async () => {
getBotConnections.mockResolvedValue(info({ connections: [] }));
getTrafficBots.mockResolvedValue(report({ lastSeen: null, types: [], pages: [] }));
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.tsx
index 6b90e31cb..1edfbe8da 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.tsx
@@ -28,6 +28,8 @@ import { formatTrafficBucketDate } from './_charts';
import { BotsDialog } from './_bots-connect';
import { getBotConnections, getTrafficBots } from '@/lib/traffic-reads';
import { useRangeReady } from './_range-ready';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
+import { usePlanContext } from '@/components/providers/plan-provider';
/** Where Upgrade goes, as on the Prompts page's usage cards. */
const PLAN_PAGE = '/dashboard/settings?tab=billing';
@@ -231,6 +233,10 @@ export function BotsReportSection({
} | null>(null);
const [preview, setPreview] = useState(false);
const [connectOpen, setConnectOpen] = useState(false);
+ // Without an active plan the caps read 0: the plan it was on decides the lock.
+ const { isLocked } = useUpgradeGate();
+ const { planId } = usePlanContext();
+ const plan = { isLocked, planId };
useEffect(() => {
let cancelled = false;
@@ -275,7 +281,7 @@ export function BotsReportSection({
// that read fails: taken down, it would lose the new connection's secret
// and settings.
const dialogInfo = info ?? connections?.lastInfo ?? null;
- const state = info ? botReportState(info, report) : null;
+ const state = info ? botReportState(info, report, plan) : null;
const pausedUntil = info ? rowsPausedUntil(info.usage) : null;
// Past the raw cap log files aren't read: the report stops mid-month.
const logsPaused = info ? logsPausedUntil(info) : null;
@@ -402,7 +408,7 @@ export function BotsReportSection({
)}
</div>
- {dialogInfo && botReportState(dialogInfo, null) !== 'locked' && (
+ {dialogInfo && botReportState(dialogInfo, null, plan) !== 'locked' && (
<BotsDialog
brandId={brandId}
open={connectOpen}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx
index f0a3db820..3827c9f2f 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx
@@ -204,7 +204,7 @@ export function PagesCard({
const pageActions = usePageActions(brandId, dateWindow);
// A read-only workspace (plan not active): Audit page, and Add prompts (its
// dialog asks the AI as it opens), open the upgrade dialog instead.
- const { guard } = useUpgradeGate();
+ const { guard, isLocked } = useUpgradeGate();
const tActions = useTranslations('readOnly.actions');
// The page whose suggested prompts are open (part B2); each opening starts
// afresh, and tracking some reads the list again for its prompt counts.
@@ -364,7 +364,7 @@ export function PagesCard({
.slice(0, PAGE_ACTION_MAX)
.map((row) => pageUrl(domain, row.page))
: [];
- const block = auditBlock(pageActions.quota, auditUrls.length);
+ const block = auditBlock(pageActions.quota, auditUrls.length, isLocked);
return (
<Card aria-busy={stale} className={cn('transition-opacity', stale && 'opacity-60')}>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.test.ts
index 958c7ce88..cd2cfc52b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.test.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.test.ts
@@ -13,6 +13,13 @@ describe('auditBlock', () => {
expect(auditBlock({ used: 900, limit: -1, remaining: -1 }, 50)).toBeNull();
});
+ it('never blocks without an active plan: 0 of 0 is no plan, not spent', () => {
+ expect(auditBlock({ used: 40, limit: 0, remaining: 0, noPlan: true }, 3)).toBeNull();
+ // A read-only workspace reads the same, marked or not.
+ expect(auditBlock({ used: 40, limit: 0, remaining: 0 }, 3, true)).toBeNull();
+ expect(auditBlock({ used: 40, limit: 0, remaining: 0 }, 3)).toEqual({ reason: 'noneLeft' });
+ });
+
it('blocks when the month is spent, or fewer are left than pages', () => {
expect(auditBlock({ used: 100, limit: 100, remaining: 0 }, 1)).toEqual({ reason: 'noneLeft' });
// Running audits and the auto-audit share can take it below zero.
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts
index 5b4c5a910..1d15d541b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts
@@ -7,6 +7,7 @@ import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { toast } from 'sonner';
import { useRouter } from '@/i18n/navigation';
import { getAuditQuota, runAuditsBulk, type AuditQuota } from '@/lib/actions/audits';
+import { isNoPlan } from '@/lib/billing/no-plan';
import { generateOpportunitiesOnDemand, getGenerationJobStatus } from '@/lib/actions/content';
import { suggestForPage } from '@/lib/content-job';
import {
@@ -205,13 +206,16 @@ export function usePageActions(brandId: string, dateWindow: TrafficDateWindow) {
/**
* Why a bulk audit of `count` pages can't start, or null when it can: the
* month's audits are spent, or fewer are left than pages (the server starts
- * all of them or none). An unknown or unlimited quota never blocks.
+ * all of them or none). An unknown or unlimited quota never blocks, nor one
+ * read without an active plan (0 of 0, or a read-only workspace: `isLocked`):
+ * Audit opens the plan dialog.
*/
export function auditBlock(
quota: AuditQuota | null,
count: number,
+ isLocked = false,
): { reason: 'noneLeft' } | { reason: 'overQuota'; remaining: number } | null {
- if (!quota || quota.limit === -1) return null;
+ if (!quota || quota.limit === -1 || isNoPlan(quota, isLocked)) return null;
const remaining = Math.max(0, quota.remaining);
if (remaining === 0) return { reason: 'noneLeft' };
if (count > remaining) return { reason: 'overQuota', remaining };
diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.test.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.test.tsx
new file mode 100644
index 000000000..17536c71a
--- /dev/null
+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.test.tsx
@@ -0,0 +1,156 @@
+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';
+
+/**
+ * Onboarding's suggestions once the day's setup suggestions are used up
+ * (429 onboarding_daily_limit): each step says so, and says how to go on,
+ * with no Try again; any other failure keeps Try again. The wizard resumes on
+ * a brand already created, so the steps are reached without walking them.
+ */
+
+/** The brand's rows the resume reads; prompt sets decide step 3 or step 5. */
+const db = vi.hoisted(() => ({ promptSets: [] as { id: string }[] }));
+vi.mock('@/lib/supabase/client', () => {
+ /** A query that answers `data` however it ends (single, limit, or awaited). */
+ const query = (data: unknown) => {
+ const q: Record<string, unknown> = {};
+ for (const m of ['select', 'eq', 'limit', 'order', 'update']) q[m] = () => q;
+ q.single = async () => ({ data });
+ q.then = (resolve: (v: unknown) => unknown) => resolve({ data });
+ return q;
+ };
+ const rows: Record<string, () => unknown> = {
+ profiles: () => ({ organization_id: 'org-1', onboarding_completed: false }),
+ brands: () => [
+ {
+ id: 'b1',
+ organization_id: 'org-1',
+ name: 'Acme',
+ slug: 'acme',
+ brand_domains: [{ id: 'd1', brand_id: 'b1', domain: 'acme.com', is_primary: true }],
+ },
+ ],
+ prompt_sets: () => db.promptSets,
+ };
+ return {
+ createClient: () => ({
+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },
+ from: (table: string) => query(rows[table]?.() ?? null),
+ }),
+ };
+});
+vi.mock('@/lib/actions/topic', () => ({
+ getTopics: vi.fn(async () => [{ id: 't1', name: 'Coffee' }]),
+ createTopics: vi.fn(async () => undefined),
+}));
+vi.mock('@/lib/actions/competitor', () => ({
+ getCompetitors: vi.fn(async () => []),
+ addCompetitor: vi.fn(),
+}));
+vi.mock('@/lib/actions/brand', () => ({ createBrand: vi.fn(), markBrandAsEcommerce: vi.fn() }));
+vi.mock('@/lib/actions/prompt', () => ({
+ getPromptCapacity: vi.fn(async () => ({ maxPrompts: 50, used: 0 })),
+ savePromptSet: vi.fn(),
+}));
+vi.mock('@/lib/actions/tracking', () => ({ triggerTrackingCheck: vi.fn() }));
+vi.mock('@/lib/actions/volumes', () => ({ bootstrapBrandVolumes: vi.fn() }));
+vi.mock('@/lib/actions/menu-access', () => ({ setMyWorkAreas: vi.fn() }));
+const setup = vi.hoisted(() => ({
+ suggestTopics: vi.fn(),
+ generatePromptsFromTopics: vi.fn(),
+ suggestCompetitors: vi.fn(),
+}));
+vi.mock('@/lib/ai-brand-setup', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/ai-brand-setup')>()),
+ ...setup,
+}));
+vi.mock('@/lib/analytics', () => ({ track: vi.fn(), setPersonProperties: vi.fn() }));
+// The effects depend on these: the same ones every render.
+const stable = vi.hoisted(() => ({
+ router: { push: () => {}, replace: () => {}, refresh: () => {} },
+ store: { addBrand: () => {}, setActiveBrand: () => {}, updateBrand: () => {} },
+}));
+vi.mock('@/i18n/navigation', () => ({ useRouter: () => stable.router }));
+vi.mock('@/stores/use-brand-store', () => ({ useBrandStore: () => stable.store }));
+vi.mock('@/components/onboarding/onboarding-frame', () => ({
+ OnboardingFrame: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.mock('@/components/onboarding/dashboard-preview', () => ({ DashboardPreview: () => null }));
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+const { default: OnboardingPage } = await import('./page');
+const { SetupDailyLimitError } = await import('@/lib/ai-brand-setup');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ db.promptSets = [];
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.restoreAllMocks();
+});
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <OnboardingPage />
+ </NextIntlClientProvider>,
+ );
+ });
+ // The resume reads, then the step's own suggestions.
+ await act(async () => {});
+ await act(async () => {});
+}
+
+const text = () => container.textContent ?? '';
+const button = (name: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent?.trim() === name);
+
+describe('setup suggestions used up for the day', () => {
+ it('says so on the competitors step, with no Try again', async () => {
+ db.promptSets = [{ id: 's1' }];
+ setup.suggestCompetitors.mockRejectedValue(new SetupDailyLimitError('limit'));
+ await render();
+ expect(setup.suggestCompetitors).toHaveBeenCalledOnce();
+ expect(text()).toContain(
+ 'Setup suggestions are used up for today. Try again tomorrow, or add your own.',
+ );
+ expect(text()).not.toContain("Couldn't fetch competitor suggestions");
+ expect(button('Try again')).toBeUndefined();
+ });
+
+ it('keeps Try again for any other failure', async () => {
+ db.promptSets = [{ id: 's1' }];
+ setup.suggestCompetitors.mockRejectedValue(new Error('Server error: 500'));
+ await render();
+ expect(text()).toContain("Couldn't fetch competitor suggestions right now");
+ expect(button('Try again')).toBeDefined();
+ });
+
+ it('says on the prompts step to add your own to each topic to continue', async () => {
+ setup.generatePromptsFromTopics.mockRejectedValue(new SetupDailyLimitError('limit'));
+ await render();
+ await act(async () => button('Looks good')!.click());
+ expect(setup.generatePromptsFromTopics).toHaveBeenCalledOnce();
+ expect(text()).toContain(
+ 'Setup suggestions are used up for today. Add your own prompts to each topic below to continue.',
+ );
+ expect(text()).not.toContain("Couldn't generate prompt suggestions");
+ });
+});
diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
index d982e32de..80fa5c5e2 100644
--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
@@ -80,6 +80,8 @@ import {
suggestTopics,
generatePromptsFromTopics,
suggestCompetitors,
+ suggestFailure,
+ type SuggestFailure,
} from '@/lib/ai-brand-setup';
import { DashboardPreview } from '@/components/onboarding/dashboard-preview';
import { OnboardingFrame } from '@/components/onboarding/onboarding-frame';
@@ -282,6 +284,7 @@ const COMPETITOR_LOADING_MESSAGES = [
export default function OnboardingPage() {
const router = useRouter();
+ const tWizard = useTranslations('brands.wizard');
const tWelcome = useTranslations('welcome');
const { addBrand, setActiveBrand, updateBrand: updateBrandInStore } = useBrandStore();
@@ -309,7 +312,9 @@ export default function OnboardingPage() {
const [loadingTopics, setLoadingTopics] = useState(false);
// #379 — suggestions can fail even after the server's retries; each step
// then shows an inline "add your own" fallback instead of a bare toast.
- const [topicSuggestError, setTopicSuggestError] = useState(false);
+ // 'dailyLimit': the day's setup suggestions are used up (429), so it says
+ // to try tomorrow, and offers no Try again.
+ const [topicSuggestError, setTopicSuggestError] = useState<SuggestFailure | null>(null);
const [topicLoadingMsg, setTopicLoadingMsg] = useState('');
const topicMsgIdx = useRef(0);
@@ -332,7 +337,7 @@ export default function OnboardingPage() {
// Step 4
const [topicPrompts, setTopicPrompts] = useState<TopicPromptsData[]>([]);
const [loadingPrompts, setLoadingPrompts] = useState(false);
- const [promptGenError, setPromptGenError] = useState(false);
+ const [promptGenError, setPromptGenError] = useState<SuggestFailure | null>(null);
const [topicSaveError, setTopicSaveError] = useState(false);
const [promptCapacity, setPromptCapacity] = useState<{
maxPrompts: number;
@@ -348,7 +353,7 @@ export default function OnboardingPage() {
}
const [suggestedCompetitors, setSuggestedCompetitors] = useState<CompetitorItem[]>([]);
const [loadingCompetitors, setLoadingCompetitors] = useState(false);
- const [competitorSuggestError, setCompetitorSuggestError] = useState(false);
+ const [competitorSuggestError, setCompetitorSuggestError] = useState<SuggestFailure | null>(null);
const [ecommerceDetected, setEcommerceDetected] = useState(false);
const ecommerceSetup = useRef<Promise<void> | null>(null);
const [competitorName, setCompetitorName] = useState('');
@@ -691,7 +696,7 @@ export default function OnboardingPage() {
const fetchTopicSuggestions = async () => {
setLoadingTopics(true);
- setTopicSuggestError(false);
+ setTopicSuggestError(null);
try {
const { topics } = await suggestTopics({
brandName: brandName.trim(),
@@ -703,7 +708,7 @@ export default function OnboardingPage() {
setSelectedTopics(new Set(topics.slice(0, 7)));
} catch (err) {
console.error('Topic suggestion error:', err);
- setTopicSuggestError(true);
+ setTopicSuggestError(suggestFailure(err));
} finally {
setLoadingTopics(false);
}
@@ -743,7 +748,7 @@ export default function OnboardingPage() {
if (!createdBrand) return;
setLoadingPrompts(true);
setTopicSaveError(false);
- setPromptGenError(false);
+ setPromptGenError(null);
const topicNames = Array.from(selectedTopics);
// Save topics to DB first, with its own error handling. createTopics
@@ -784,7 +789,7 @@ export default function OnboardingPage() {
// advance with empty per-topic groups so the manual add inputs are
// usable, and explain inline. Continue stays disabled until they add
// at least one prompt.
- setPromptGenError(true);
+ setPromptGenError(suggestFailure(err));
setTopicPrompts(topicNames.map((topic) => ({ topic, prompts: [] })));
setStep(4);
} finally {
@@ -851,7 +856,7 @@ export default function OnboardingPage() {
const fetchCompetitorSuggestions = async () => {
setLoadingCompetitors(true);
- setCompetitorSuggestError(false);
+ setCompetitorSuggestError(null);
try {
const { competitors, isEcommerce } = await suggestCompetitors({
brandName: brandName.trim(),
@@ -865,7 +870,7 @@ export default function OnboardingPage() {
if (isEcommerce) ecommerceSetup.current = turnOnProductVisibility();
} catch (err) {
console.error('Competitor suggestion error:', err);
- setCompetitorSuggestError(true);
+ setCompetitorSuggestError(suggestFailure(err));
} finally {
setLoadingCompetitors(false);
}
@@ -1342,11 +1347,19 @@ export default function OnboardingPage() {
{topicSuggestError && (
<div className="flex items-center justify-between gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm">
<span>
- Couldn&apos;t fetch topic suggestions right now — add your own above.
+ {topicSuggestError === 'dailyLimit' ? (
+ tWizard('suggestionsUsedUp')
+ ) : (
+ <>
+ Couldn&apos;t fetch topic suggestions right now — add your own above.
+ </>
+ )}
</span>
- <Button variant="outline" size="sm" onClick={fetchTopicSuggestions}>
- Try again
- </Button>
+ {topicSuggestError !== 'dailyLimit' && (
+ <Button variant="outline" size="sm" onClick={fetchTopicSuggestions}>
+ Try again
+ </Button>
+ )}
</div>
)}
{suggestedTopics.map((topic) => {
@@ -1493,8 +1506,14 @@ export default function OnboardingPage() {
{promptGenError && (
<div className="mb-4 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm">
- Couldn&apos;t generate prompt suggestions right now — add your own to each topic
- below to continue.
+ {promptGenError === 'dailyLimit' ? (
+ tWizard('promptSuggestionsUsedUp')
+ ) : (
+ <>
+ Couldn&apos;t generate prompt suggestions right now — add your own to each topic
+ below to continue.
+ </>
+ )}
</div>
)}
@@ -1639,11 +1658,19 @@ export default function OnboardingPage() {
{competitorSuggestError && (
<div className="flex items-center justify-between gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm">
<span>
- Couldn&apos;t fetch competitor suggestions right now — add your own above.
+ {competitorSuggestError === 'dailyLimit' ? (
+ tWizard('suggestionsUsedUp')
+ ) : (
+ <>
+ Couldn&apos;t fetch competitor suggestions right now — add your own above.
+ </>
+ )}
</span>
- <Button variant="outline" size="sm" onClick={fetchCompetitorSuggestions}>
- Try again
- </Button>
+ {competitorSuggestError !== 'dailyLimit' && (
+ <Button variant="outline" size="sm" onClick={fetchCompetitorSuggestions}>
+ Try again
+ </Button>
+ )}
</div>
)}
{suggestedCompetitors.length > 0 && (
diff --git a/web/src/components/content/content-usage-card.tsx b/web/src/components/content/content-usage-card.tsx
index 1f0af6fac..7ec2d57cc 100644
--- a/web/src/components/content/content-usage-card.tsx
+++ b/web/src/components/content/content-usage-card.tsx
@@ -5,7 +5,10 @@ import { Gauge, Info } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Link } from '@/i18n/navigation';
import { cn } from '@/lib/utils';
+import { isNoPlan } from '@/lib/billing/no-plan';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import {
+ counterTone,
hasContentQuota,
usagePercent,
usageTone,
@@ -41,17 +44,28 @@ export function ContentUsageCard({
className?: string;
}) {
const t = useTranslations('content.usage');
+ const tReadOnly = useTranslations('readOnly');
const locale = useLocale();
+ const { isLocked } = useUpgradeGate();
if (!hasContentQuota(usage)) return null;
+ // Without an active plan the limits read 0: what was used, and that there's
+ // no plan, rather than "limit reached" and the old plan's name.
+ const noPlan = isNoPlan(usage, isLocked);
+
const resets = usage.periodEnd
? new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', timeZone: 'UTC' }).format(
new Date(usage.periodEnd),
)
: null;
const exhausted =
- usageTone(usage.opportunities) === 'exhausted' || usageTone(usage.briefs) === 'exhausted';
+ !noPlan &&
+ (usageTone(usage.opportunities) === 'exhausted' || usageTone(usage.briefs) === 'exhausted');
+ // Without an active plan there's no renewal to reset them on.
+ const tooltip = noPlan
+ ? t('tooltip')
+ : `${t('tooltip')} ${t('tooltipResets', { date: resets ?? '' })}`;
return (
<Card className={className}>
@@ -60,26 +74,24 @@ export function ContentUsageCard({
{t('title')}
</CardTitle>
<span className="inline-flex items-center gap-1.5 text-muted-foreground">
- <span
- className="inline-flex cursor-help"
- title={t('tooltip', { date: resets ?? '' })}
- aria-label={t('tooltip', { date: resets ?? '' })}
- >
+ <span className="inline-flex cursor-help" title={tooltip} aria-label={tooltip}>
<Info className="h-3.5 w-3.5" />
</span>
<Gauge className="h-3.5 w-3.5" />
</span>
</CardHeader>
<CardContent className="space-y-2">
- <Counter label={t('opportunities')} counter={usage.opportunities} />
- <Counter label={t('briefs')} counter={usage.briefs} />
+ <Counter label={t('opportunities')} counter={usage.opportunities} noPlan={noPlan} />
+ <Counter label={t('briefs')} counter={usage.briefs} noPlan={noPlan} />
<p className="text-xs text-muted-foreground">
- {[
- usage.planName && t('plan', { plan: usage.planName }),
- resets && t('resets', { date: resets }),
- ]
- .filter(Boolean)
- .join(' · ')}
+ {noPlan
+ ? tReadOnly('noPlan')
+ : [
+ usage.planName && t('plan', { plan: usage.planName }),
+ resets && t('resets', { date: resets }),
+ ]
+ .filter(Boolean)
+ .join(' · ')}
{exhausted && usage.plan === 'starter' && (
<>
{' · '}
@@ -97,15 +109,26 @@ export function ContentUsageCard({
);
}
-function Counter({ label, counter }: { label: string; counter: UsageCounter }) {
+function Counter({
+ label,
+ counter,
+ noPlan,
+}: {
+ label: string;
+ counter: UsageCounter;
+ noPlan: boolean;
+}) {
const t = useTranslations('content.usage');
- const tone = usageTone(counter);
+ const tone = counterTone(counter, noPlan);
return (
<div>
<div className="flex items-baseline justify-between gap-2 text-xs">
<span className="font-medium">{label}</span>
{tone === 'unlimited' ? (
<span className="text-muted-foreground">{t('unlimited')}</span>
+ ) : tone === 'noPlan' ? (
+ // What was used; there's no limit to count it against.
+ <span className="text-sm font-semibold tabular-nums">{counter.used}</span>
) : (
<span className="tabular-nums">
<span className="text-sm font-semibold">{counter.used}</span>
@@ -113,7 +136,7 @@ function Counter({ label, counter }: { label: string; counter: UsageCounter }) {
</span>
)}
</div>
- {tone !== 'unlimited' && (
+ {tone !== 'unlimited' && tone !== 'noPlan' && (
<>
<div className="mt-1 h-1.5 overflow-hidden rounded-full bg-muted">
<div
diff --git a/web/src/components/content/opportunity-detail.test.tsx b/web/src/components/content/opportunity-detail.test.tsx
index c58e706c6..78945e886 100644
--- a/web/src/components/content/opportunity-detail.test.tsx
+++ b/web/src/components/content/opportunity-detail.test.tsx
@@ -172,3 +172,28 @@ describe('the opportunity panel on a read-only workspace', () => {
expect(openUpgrade).not.toHaveBeenCalled();
});
});
+
+describe('the brief quota without an active plan', () => {
+ it('says "No active plan", not the limit, and Generate opens the upgrade dialog', async () => {
+ // The server reads 0 of 0 with `noPlan` once the plan has ended.
+ content.getBriefQuota.mockResolvedValue({ used: 4, limit: 0, remaining: 0, noPlan: true });
+ await render(true);
+ expect(container.textContent).toContain('No active plan');
+ expect(container.textContent).not.toContain('Monthly Brief Limit Reached');
+ expect(container.textContent).not.toContain('0/0');
+ const generate = buttonNamed('Generate Content Brief');
+ expect(generate.disabled).toBe(false);
+ expect(buttonNamed('Generate Brief').disabled).toBe(false);
+ await act(async () => generate.click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Generating a brief needs a plan');
+ expect(content.generateBrief).not.toHaveBeenCalled();
+ });
+
+ it('still says the limit is reached once an active plan is used up', async () => {
+ content.getBriefQuota.mockResolvedValue({ used: 10, limit: 10, remaining: 0 });
+ await render(false);
+ expect(container.textContent).toContain('Monthly Brief Limit Reached');
+ expect(container.textContent).not.toContain('No active plan');
+ expect(buttonNamed('Generate Brief').disabled).toBe(true);
+ });
+});
diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsx
index 12dfbfa5f..65e117b0c 100644
--- a/web/src/components/content/opportunity-detail.tsx
+++ b/web/src/components/content/opportunity-detail.tsx
@@ -71,6 +71,7 @@ import { getOpportunityDrafts } from '@/lib/actions/content-drafts';
import { getPlanPriorities, setPlanRowPriority } from '@/lib/actions/content-plan';
import { useUserRole } from '@/hooks/use-user-role';
import { useUpgradeGate } from '@/components/providers/upgrade-gate';
+import { isNoPlan } from '@/lib/billing/no-plan';
import { useBrandStore } from '@/stores/use-brand-store';
import { OpportunityActions } from '@/components/content/opportunity-actions';
import { NewContentDialog, type DialogPreset } from '@/components/content/new-content-dialog';
@@ -159,8 +160,9 @@ export function OpportunityDetail({
const locale = useLocale();
// A read-only workspace (plan not active): every action here opens the
// upgrade dialog instead; Copy, Export and Open draft stay open.
- const { guard } = useUpgradeGate();
+ const { guard, isLocked } = useUpgradeGate();
const tActions = useTranslations('readOnly.actions');
+ const tReadOnly = useTranslations('readOnly');
const [opportunity, setOpportunity] = useState<ContentOpportunity | null>(null);
const [loading, setLoading] = useState(true);
@@ -444,7 +446,10 @@ export function OpportunityDetail({
const primaryType = assetTypeLabel(sd.assets?.[0]?.type);
const canSendToActionCenter = !['dismissed', 'archived', 'done'].includes(opportunity.status);
const quotaLimited = quota !== null && quota.limit !== -1;
- const quotaExhausted = quotaLimited && quota.remaining <= 0;
+ // Without an active plan the quota reads 0 of 0: not used up. Generate
+ // stays clickable, and opens the plan dialog.
+ const noPlan = isNoPlan(quota, isLocked);
+ const quotaExhausted = quotaLimited && !noPlan && quota.remaining <= 0;
const actionId = sd.actions?.all ?? Object.values(sd.actions ?? {})[0];
const canSendToWorkflow = !['dismissed', 'archived'].includes(opportunity.status);
@@ -908,7 +913,9 @@ export function OpportunityDetail({
</Button>
{quotaLimited && (
<p className="text-xs text-muted-foreground mt-3 tabular-nums">
- {quota.remaining}/{quota.limit} briefs remaining this billing period
+ {noPlan
+ ? tReadOnly('noPlan')
+ : `${quota.remaining}/${quota.limit} briefs remaining this billing period`}
</p>
)}
</>
diff --git a/web/src/lib/actions/ai-bots.ts b/web/src/lib/actions/ai-bots.ts
index 382e48f91..a8eb28695 100644
--- a/web/src/lib/actions/ai-bots.ts
+++ b/web/src/lib/actions/ai-bots.ts
@@ -40,6 +40,11 @@ export interface BotUsage {
rawCappedAt: string | null;
/** Log records a month: -1 no cap, 0 the report is locked. */
rawCap: number;
+ /**
+ * No active plan (read-only): both caps read 0, yet the report isn't
+ * locked; its connections and stored data still show. Never sent on a plan.
+ */
+ noPlan?: boolean;
}
export interface BotConnections {
@@ -114,6 +119,7 @@ export async function getBotConnections(brandId: string): Promise<BotConnections
raw: n(usage.raw),
rawCappedAt: typeof usage.rawCappedAt === 'string' ? usage.rawCappedAt : null,
rawCap: Number(usage.rawCap ?? 0),
+ ...(usage.noPlan === true ? { noPlan: true } : {}),
},
};
}
diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.ts
index f43fb56b9..0c59d2f23 100644
--- a/web/src/lib/actions/audits.ts
+++ b/web/src/lib/actions/audits.ts
@@ -3,6 +3,7 @@
import { createClient } from '@/lib/supabase/server';
import { API_BASE_URL } from '@/config/api';
import type { SiteTrust } from '@/lib/content/site-trust';
+import type { NoPlanMark } from '@/lib/billing/no-plan';
const AEO_SERVER_URL = API_BASE_URL;
@@ -59,7 +60,7 @@ export interface AuditResult {
recommendations: AuditRecommendation[];
}
-export interface AuditQuota {
+export interface AuditQuota extends NoPlanMark {
used: number;
limit: number;
/**
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index 55ff924ce..439fef462 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -6,6 +6,7 @@ import { API_BASE_URL } from '@/config/api';
import { apiFailure, type ApiFailure } from '@/lib/api-failure';
import type { ContentUsage } from '@/lib/content-usage';
import { assertWritable } from '@/lib/subscription-guard';
+import type { NoPlanMark } from '@/lib/billing/no-plan';
const AEO_SERVER_URL = API_BASE_URL;
@@ -339,7 +340,7 @@ export async function getOpportunityBasket(id: string): Promise<OpportunityBaske
return res.json();
}
-export interface BriefQuota {
+export interface BriefQuota extends NoPlanMark {
used: number;
limit: number;
remaining: number;
diff --git a/web/src/lib/actions/volumes.ts b/web/src/lib/actions/volumes.ts
index 78a23f284..01afd8daa 100644
--- a/web/src/lib/actions/volumes.ts
+++ b/web/src/lib/actions/volumes.ts
@@ -3,8 +3,9 @@
import { createClient } from '@/lib/supabase/server';
import type { PromptVolume } from '@/types';
import { API_BASE_URL } from '@/config/api';
+import type { NoPlanMark } from '@/lib/billing/no-plan';
-export interface VolumeQuota {
+export interface VolumeQuota extends NoPlanMark {
used: number;
limit: number;
remaining: number;
diff --git a/web/src/lib/ai-bots.test.ts b/web/src/lib/ai-bots.test.ts
index 8859efd80..1af5aa6cf 100644
--- a/web/src/lib/ai-bots.test.ts
+++ b/web/src/lib/ai-bots.test.ts
@@ -41,6 +41,34 @@ describe('botsCardState', () => {
state({ connections: [conn(null), conn('2026-10-19T09:00:00Z', 'c2')], usage: usage() }),
).toBe('on');
});
+
+ it('without an active plan, is locked only if the plan it was on had no report (Starter)', () => {
+ // The caps read 0 whatever the plan was.
+ const noPlan = usage({ cap: 0, rawCap: 0, noPlan: true });
+ const growth = { planId: 'growth' as const };
+ expect(
+ botsCardState({ connections: [conn('2026-10-19T09:00:00Z')], usage: noPlan }, growth),
+ ).toBe('on');
+ expect(botsCardState({ connections: [conn(null)], usage: noPlan }, growth)).toBe('waiting');
+ expect(botsCardState({ connections: [], usage: noPlan }, growth)).toBe('off');
+ expect(
+ botsCardState(
+ { connections: [conn('2026-10-19T09:00:00Z')], usage: noPlan },
+ { planId: 'starter' },
+ ),
+ ).toBe('locked');
+ // A read-only workspace (isLocked) reads the same, marked or not.
+ const zero = usage({ cap: 0, rawCap: 0 });
+ expect(
+ botsCardState({ connections: [conn(null)], usage: zero }, { ...growth, isLocked: true }),
+ ).toBe('waiting');
+ expect(
+ botsCardState(
+ { connections: [conn(null)], usage: zero },
+ { planId: 'starter', isLocked: true },
+ ),
+ ).toBe('locked');
+ });
});
describe('lastBotEvent and rowsPausedUntil', () => {
@@ -119,6 +147,45 @@ describe('botReportState and sampleBotTypes (AT-011)', () => {
).toBe('data');
});
+ it('shows a workspace whose Growth plan ended its own data, not the locked sample', () => {
+ const noPlan = usage({ cap: 0, rawCap: 0, noPlan: true });
+ const growth = { planId: 'growth' as const };
+ expect(
+ botReportState(
+ { connections: [conn(null)], usage: noPlan },
+ report('2026-10-19T09:00:00Z'),
+ growth,
+ ),
+ ).toBe('data');
+ expect(botReportState({ connections: [conn(null)], usage: noPlan }, report(null), growth)).toBe(
+ 'waiting',
+ );
+ expect(botReportState({ connections: [], usage: noPlan }, report(null), growth)).toBe('off');
+ // Read-only (isLocked) without the server's mark reads the same.
+ expect(
+ botReportState(
+ { connections: [conn(null)], usage: usage({ cap: 0, rawCap: 0 }) },
+ report('2026-10-19T09:00:00Z'),
+ { ...growth, isLocked: true },
+ ),
+ ).toBe('data');
+ });
+
+ it('keeps the locked sample and Upgrade for a workspace whose Starter plan ended', () => {
+ const noPlan = usage({ cap: 0, rawCap: 0, noPlan: true });
+ expect(
+ botReportState({ connections: [conn(null)], usage: noPlan }, report('2026-10-19T09:00:00Z'), {
+ planId: 'starter',
+ }),
+ ).toBe('locked');
+ expect(
+ botReportState({ connections: [], usage: usage({ cap: 0, rawCap: 0 }) }, report(null), {
+ planId: 'starter',
+ isLocked: true,
+ }),
+ ).toBe('locked');
+ });
+
it("samples the mockup's numbers, last seen 2h, 40m and 5m ago", () => {
const now = Date.parse('2026-10-19T12:00:00.000Z');
expect(sampleBotTypes(now).map((t) => [t.type, t.hits, t.pages, t.lastSeen])).toEqual([
diff --git a/web/src/lib/ai-bots.ts b/web/src/lib/ai-bots.ts
index e3b38f772..bb9844c8a 100644
--- a/web/src/lib/ai-bots.ts
+++ b/web/src/lib/ai-bots.ts
@@ -5,9 +5,12 @@
import type { BotConnection, BotConnections, BotUsage } from '@/lib/actions/ai-bots';
import type { TrafficBots } from '@/lib/actions/traffic';
+import { isNoPlan } from '@/lib/billing/no-plan';
+import { PLANS, type PlanId } from '@/config/plans';
/**
- * locked — the plan has no bot report (Starter: Upgrade);
+ * locked — the plan has no bot report (Starter: Upgrade); without an active
+ * plan, the plan it was on decides (reportLocked);
* off — nothing connected yet;
* waiting — connected, no request has arrived yet;
* on — requests arrive.
@@ -22,8 +25,33 @@ export function lastBotEvent(connections: BotConnection[]): string | null {
);
}
-export function botsCardState({ connections, usage }: BotConnections): BotsCardState {
- if (usage.cap === 0) return 'locked';
+/**
+ * Read-only once the plan has ended: the workspace is locked (`isLocked`,
+ * useUpgradeGate) and the plan it was on (`planId`, usePlanContext).
+ */
+export interface BotPlan {
+ isLocked?: boolean;
+ planId?: PlanId;
+}
+
+/**
+ * The report is locked on a plan without it (cap 0). Without an active plan
+ * (isNoPlan) the caps read 0 whatever the plan was, so the plan it was on
+ * decides: one without the report (Starter) keeps its Upgrade; one with it
+ * shows its connections and stored data, and connecting opens the plan dialog.
+ */
+function reportLocked(usage: BotUsage, { isLocked = false, planId }: BotPlan): boolean {
+ if (isNoPlan(usage, isLocked)) {
+ return planId !== undefined && PLANS[planId]?.limits.maxBotEventsPerMonth === 0;
+ }
+ return usage.cap === 0;
+}
+
+export function botsCardState(
+ { connections, usage }: BotConnections,
+ plan: BotPlan = {},
+): BotsCardState {
+ if (reportLocked(usage, plan)) return 'locked';
if (connections.length === 0) return 'off';
return lastBotEvent(connections) ? 'on' : 'waiting';
}
@@ -73,8 +101,12 @@ export function logsPausedUntil(info: BotConnections): string | null {
*/
export type BotReportState = 'locked' | 'off' | 'waiting' | 'data';
-export function botReportState(info: BotConnections, report: TrafficBots | null): BotReportState {
- if (info.usage.cap === 0) return 'locked';
+export function botReportState(
+ info: BotConnections,
+ report: TrafficBots | null,
+ plan: BotPlan = {},
+): BotReportState {
+ if (reportLocked(info.usage, plan)) return 'locked';
// Bots counted before a connection was revoked still show.
if (report?.lastSeen) return 'data';
return info.connections.length === 0 ? 'off' : 'waiting';
diff --git a/web/src/lib/ai-brand-setup.test.ts b/web/src/lib/ai-brand-setup.test.ts
index 7c21504d9..8dd802923 100644
--- a/web/src/lib/ai-brand-setup.test.ts
+++ b/web/src/lib/ai-brand-setup.test.ts
@@ -6,8 +6,14 @@ vi.mock('@/lib/supabase/client', () => ({
}),
}));
-const { BRAND_SETUP_LIMITS, generatePromptsFromTopics, suggestCompetitors, suggestTopics } =
- await import('./ai-brand-setup');
+const {
+ BRAND_SETUP_LIMITS,
+ SetupDailyLimitError,
+ generatePromptsFromTopics,
+ suggestCompetitors,
+ suggestFailure,
+ suggestTopics,
+} = await import('./ai-brand-setup');
/** Setup's suggestion calls send no more than the API takes (#1611 follow-up). */
@@ -125,3 +131,56 @@ describe('prompts for many topics', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
});
+
+/**
+ * Setup suggestions for a workspace that never subscribed are bounded a day
+ * (429 `onboarding_daily_limit`): the onboarding steps say so, apart from any
+ * other failure, which reads as before.
+ */
+
+const params = { brandName: 'Acme', description: '', website: 'acme.com', language: 'en' };
+const answer = (status: number, body: unknown) =>
+ vi.fn(async () => ({ ok: status < 400, status, json: async () => body }));
+
+describe('setup suggestions past the daily limit', () => {
+ const limit = { success: false, error: 'rate_limited', code: 'onboarding_daily_limit' };
+
+ it('throws SetupDailyLimitError, read as "dailyLimit", from each of the three calls', async () => {
+ vi.stubGlobal('fetch', answer(429, limit));
+ const calls = [
+ suggestTopics(params),
+ generatePromptsFromTopics(params, ['Coffee']),
+ suggestCompetitors(params),
+ ];
+ for (const call of calls) {
+ const err = await call.catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(SetupDailyLimitError);
+ expect(suggestFailure(err)).toBe('dailyLimit');
+ }
+ });
+
+ it('keeps the usual message, so a caller that only shows it says what it said before', async () => {
+ vi.stubGlobal('fetch', answer(429, limit));
+ await expect(suggestTopics(params)).rejects.toThrow('Failed to suggest topics');
+ });
+
+ it('reads any other failure as before: a plain Error, "failed"', async () => {
+ for (const [status, body] of [
+ [500, { error: 'boom' }],
+ [429, { error: 'rate_limited' }],
+ [402, { code: 'onboarding_daily_limit' }],
+ ] as const) {
+ vi.stubGlobal('fetch', answer(status, body));
+ const err = await suggestCompetitors(params).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(Error);
+ expect(err).not.toBeInstanceOf(SetupDailyLimitError);
+ expect((err as Error).message).toBe('Failed to suggest competitors');
+ expect(suggestFailure(err)).toBe('failed');
+ }
+ });
+
+ it('returns the suggestions on success', async () => {
+ vi.stubGlobal('fetch', answer(200, { topics: [{ name: 'Coffee' }] }));
+ await expect(suggestTopics(params)).resolves.toEqual({ topics: ['Coffee'] });
+ });
+});
diff --git a/web/src/lib/ai-brand-setup.ts b/web/src/lib/ai-brand-setup.ts
index fbab57e41..7a3533c01 100644
--- a/web/src/lib/ai-brand-setup.ts
+++ b/web/src/lib/ai-brand-setup.ts
@@ -4,7 +4,9 @@
*
* Each function owns session lookup, Authorization header construction, and
* the POST itself. On success it returns typed data; on failure it throws so
- * the caller can decide what to show the user.
+ * the caller can decide what to show the user: a SetupDailyLimitError once a
+ * workspace that never subscribed has used the day's setup suggestions (429),
+ * a plain Error otherwise.
*
* These are plain async functions, not server actions — they run in the browser
* and reach the API via the proxy at BROWSER_API_BASE_URL.
@@ -24,6 +26,35 @@ async function getAuthHeader(): Promise<string> {
return `Bearer ${session?.access_token}`;
}
+/**
+ * The day's setup suggestions are used up: a workspace that never subscribed
+ * gets a few a day (429 `onboarding_daily_limit`), and adds its own until
+ * tomorrow. Its message is the call's usual one, so a caller that only shows
+ * the message says what it said before.
+ */
+export class SetupDailyLimitError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'SetupDailyLimitError';
+ }
+}
+
+/** How a suggestion call failed, as the onboarding steps tell it. */
+export type SuggestFailure = 'failed' | 'dailyLimit';
+
+export function suggestFailure(err: unknown): SuggestFailure {
+ return err instanceof SetupDailyLimitError ? 'dailyLimit' : 'failed';
+}
+
+/** The error a failed call throws: SetupDailyLimitError past the day's limit, else an Error. */
+async function failure(res: Response, message: string): Promise<Error> {
+ if (res.status === 429) {
+ const body = (await res.json().catch(() => null)) as { code?: unknown } | null;
+ if (body?.code === 'onboarding_daily_limit') return new SetupDailyLimitError(message);
+ }
+ return new Error(message);
+}
+
// ── Shared request body shape ──────────────────────────────────────────────────
export interface BrandSetupParams {
@@ -88,7 +119,7 @@ export async function suggestTopics(params: BrandSetupParams): Promise<SuggestTo
}),
});
- if (!res.ok) throw new Error('Failed to suggest topics');
+ if (!res.ok) throw await failure(res, 'Failed to suggest topics');
const data = await res.json();
const topics = (data.topics || []).map((t: { name: string }) => t.name);
return { topics };
@@ -139,7 +170,7 @@ export async function generatePromptsFromTopics(
}),
});
- if (!res.ok) throw new Error('Failed to generate prompts');
+ if (!res.ok) throw await failure(res, 'Failed to generate prompts');
const data = await res.json();
return (data.topicPrompts || []).map((tp: { topic: string; prompts: string[] }) => ({
topic: tp.topic,
@@ -191,7 +222,7 @@ export async function suggestCompetitors(
}),
});
- if (!res.ok) throw new Error('Failed to suggest competitors');
+ if (!res.ok) throw await failure(res, 'Failed to suggest competitors');
const data = await res.json();
const competitors = (data.competitors || []).map((c: { name: string; domain: string }) => ({
name: c.name,
diff --git a/web/src/lib/billing/no-plan.test.ts b/web/src/lib/billing/no-plan.test.ts
new file mode 100644
index 000000000..a0f1b2af1
--- /dev/null
+++ b/web/src/lib/billing/no-plan.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+import { isNoPlan } from './no-plan';
+
+/** A quota's 0 read without an active plan isn't "used up". */
+describe('isNoPlan', () => {
+ it('is true when the server marks the quota, or the workspace is read-only', () => {
+ expect(isNoPlan({ noPlan: true })).toBe(true);
+ expect(isNoPlan({ noPlan: true }, false)).toBe(true);
+ expect(isNoPlan(null, true)).toBe(true);
+ expect(isNoPlan({}, true)).toBe(true);
+ });
+
+ it('is false on an active plan, which never sends the field', () => {
+ expect(isNoPlan({})).toBe(false);
+ expect(isNoPlan({ noPlan: false })).toBe(false);
+ expect(isNoPlan(null)).toBe(false);
+ expect(isNoPlan(undefined, false)).toBe(false);
+ });
+});
diff --git a/web/src/lib/billing/no-plan.ts b/web/src/lib/billing/no-plan.ts
new file mode 100644
index 000000000..87308c738
--- /dev/null
+++ b/web/src/lib/billing/no-plan.ts
@@ -0,0 +1,20 @@
+/**
+ * A quota read while the workspace has no active plan (read-only once the
+ * plan has ended): the server answers the reads that cost nothing with what
+ * is stored, every limit 0 and `noPlan: true`. An active plan, and
+ * self-hosted, never send the field.
+ */
+export interface NoPlanMark {
+ /** No active plan: the limits read 0, but nothing was used up. */
+ noPlan?: boolean;
+}
+
+/**
+ * Whether a quota's 0 means "no active plan" rather than "used up": the
+ * server marked it so, or the workspace is read-only. Such a quota isn't
+ * shown as spent (no red, no "limit reached"), and its actions stay
+ * clickable: the upgrade gate opens the plan dialog instead of running them.
+ */
+export function isNoPlan(quota: NoPlanMark | null | undefined, isLocked = false): boolean {
+ return isLocked || quota?.noPlan === true;
+}
diff --git a/web/src/lib/content-usage.test.ts b/web/src/lib/content-usage.test.ts
index b51cc46fa..3623880f3 100644
--- a/web/src/lib/content-usage.test.ts
+++ b/web/src/lib/content-usage.test.ts
@@ -6,6 +6,7 @@
import { describe, expect, test } from 'vitest';
import {
+ counterTone,
hasContentQuota,
onDemandMax,
usagePercent,
@@ -29,6 +30,15 @@ describe('usageTone', () => {
});
});
+describe('counterTone', () => {
+ test('is "noPlan", not exhausted, when the limit reads 0 without an active plan', () => {
+ expect(counterTone(c(4, 0), true)).toBe('noPlan');
+ expect(counterTone(c(4, 0))).toBe('exhausted');
+ expect(counterTone(c(7, 10))).toBe('normal');
+ expect(counterTone(c(0, -1))).toBe('unlimited');
+ });
+});
+
describe('usagePercent', () => {
test('is capped at 100 and empty when unlimited', () => {
expect(usagePercent(c(32, 50))).toBe(64);
diff --git a/web/src/lib/content-usage.ts b/web/src/lib/content-usage.ts
index bd3499c7c..424767ac4 100644
--- a/web/src/lib/content-usage.ts
+++ b/web/src/lib/content-usage.ts
@@ -5,14 +5,16 @@
* decides how they read.
*/
-export interface UsageCounter {
+import type { NoPlanMark } from '@/lib/billing/no-plan';
+
+export interface UsageCounter extends NoPlanMark {
used: number;
/** -1 means unlimited. */
limit: number;
remaining: number;
}
-export interface ContentUsage {
+export interface ContentUsage extends NoPlanMark {
plan: string;
planName: string | null;
periodStart: string | null;
@@ -45,6 +47,14 @@ export function usageTone(counter: UsageCounter): UsageTone {
return counter.used / counter.limit >= USAGE_WARNING_RATIO ? 'warning' : 'normal';
}
+/**
+ * A counter's tone on the usage card. Without an active plan (`noPlan`) its
+ * limit reads 0, yet nothing was used up: 'noPlan', never 'exhausted'.
+ */
+export function counterTone(counter: UsageCounter, noPlan = false): UsageTone | 'noPlan' {
+ return noPlan ? 'noPlan' : usageTone(counter);
+}
+
/** Bar width, 0–100. */
export function usagePercent(counter: UsageCounter): number {
if (counter.limit <= 0) return counter.limit === -1 ? 0 : 100;
diff --git a/web/src/lib/prompt-bulk-actions.test.ts b/web/src/lib/prompt-bulk-actions.test.ts
index 7870833a2..f1bf2149a 100644
--- a/web/src/lib/prompt-bulk-actions.test.ts
+++ b/web/src/lib/prompt-bulk-actions.test.ts
@@ -61,6 +61,13 @@ describe('bulkSuggestBlock', () => {
expect(bulkSuggestBlock(6, usage(-1, 5, -1))).toBe('Select up to 5 to suggest content');
});
+ test('never blocks without an active plan: 0 of 0 is no plan, and the click opens its dialog', () => {
+ expect(bulkSuggestBlock(1, { ...usage(0, 0, 0), noPlan: true })).toBeNull();
+ // A read-only workspace reads the same, marked or not.
+ expect(bulkSuggestBlock(1, usage(0, 0, 0), { isLocked: true })).toBeNull();
+ expect(bulkSuggestBlock(1, usage(0, 0, 0))).toBe('Monthly limit reached');
+ });
+
test('waits for the quota before asking for anything', () => {
expect(bulkSuggestBlock(1, null)).toBe('Checking your content quota…');
});
diff --git a/web/src/lib/prompt-bulk-actions.ts b/web/src/lib/prompt-bulk-actions.ts
index 8bbd7b784..1eaefe7c0 100644
--- a/web/src/lib/prompt-bulk-actions.ts
+++ b/web/src/lib/prompt-bulk-actions.ts
@@ -6,6 +6,7 @@
*/
import { onDemandMax, type ContentUsage } from '@/lib/content-usage';
+import { isNoPlan } from '@/lib/billing/no-plan';
import type { PromptSuggestionOutcome } from '@/lib/content-job';
/** Every row on the page is selected (and there is at least one). */
@@ -30,13 +31,16 @@ export const FALLBACK_PER_REQUEST = 3;
* when it can. It may ask for what one "+ New" request may (CONTENT-003):
* Starter 3, Growth 5, never more than is left of the month. Nothing is asked
* for while the quota is loading; if it can't be read, the smallest cap holds
- * and the server still keeps the month's limit.
+ * and the server still keeps the month's limit. Without an active plan
+ * (`noPlan`, 0 of 0, or a read-only workspace: `isLocked`) nothing blocks:
+ * the click opens the plan dialog.
*/
export function bulkSuggestBlock(
count: number,
usage: ContentUsage | null,
- { unavailable = false }: { unavailable?: boolean } = {},
+ { unavailable = false, isLocked = false }: { unavailable?: boolean; isLocked?: boolean } = {},
): string | null {
+ if (isNoPlan(usage, isLocked)) return null;
if (!usage && !unavailable) return 'Checking your content quota…';
const max = usage ? onDemandMax(usage) : FALLBACK_PER_REQUEST;
if (max === 0) return 'Monthly limit reached';
diff --git a/web/src/lib/prompt-improve.ts b/web/src/lib/prompt-improve.ts
index 84eb87a59..2c6ae12c7 100644
--- a/web/src/lib/prompt-improve.ts
+++ b/web/src/lib/prompt-improve.ts
@@ -5,6 +5,8 @@
* be a server action.
*/
+import type { NoPlanMark } from '@/lib/billing/no-plan';
+
export type ImproveState =
| 'no_runs'
| 'not_mentioned'
@@ -76,7 +78,7 @@ export interface ImproveSet {
* or more) and stays on the server; the panel gets an estimate of the
* generations it still buys.
*/
-export interface ImproveQuota {
+export interface ImproveQuota extends NoPlanMark {
unlimited: boolean;
exhausted: boolean;
generationsLeft: number | null;