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): open the plan dialog from the Prompts area's actions while the plan has ended (#1606)

Cihan5d438f66f669
diff --git a/web/messages/en.json b/web/messages/en.json
index fa4a66ca2..bc600bd78 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -109,6 +109,36 @@
"invalid": "“{code}” isn’t a valid code.",
"failed": "Couldn't check the code. Try again."
}
+ },
+ "actions": {
+ "addPrompts": "Adding prompts needs a plan",
+ "editPrompts": "Editing prompts needs a plan",
+ "deletePrompts": "Deleting prompts needs a plan",
+ "pausePrompts": "Pausing prompts needs a plan",
+ "resumePrompts": "Resuming prompts needs a plan",
+ "trackPrompts": "Tracking prompts needs a plan",
+ "generatePrompts": "Generating prompts needs a plan",
+ "analyzePrompts": "Analyzing prompts needs a plan",
+ "runPrompts": "Running prompts needs a plan",
+ "testPrompt": "Testing a prompt needs a plan",
+ "improvePrompt": "Improving a prompt needs a plan",
+ "changeLocations": "Changing locations needs a plan",
+ "setWorkStatus": "Setting a work status needs a plan",
+ "refreshVolumes": "Refreshing volumes needs a plan",
+ "suggestPrompts": "Suggesting prompts needs a plan",
+ "dismissSuggestions": "Dismissing suggestions needs a plan",
+ "suggestContent": "Suggesting content needs a plan",
+ "createContent": "Creating content needs a plan",
+ "optimizeContent": "Optimizing content needs a plan",
+ "sendAction": "Sending actions needs a plan",
+ "addTopics": "Adding topics needs a plan",
+ "editTopics": "Editing topics needs a plan",
+ "deleteTopics": "Deleting topics needs a plan",
+ "suggestTopics": "Suggesting topics needs a plan",
+ "addCompetitors": "Adding competitors needs a plan",
+ "deleteCompetitors": "Deleting competitors needs a plan",
+ "suggestCompetitors": "Suggesting competitors needs a plan",
+ "pinCompetitors": "Pinning competitors needs a plan"
}
},
"common": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.test.tsx
index 5ca3e1e11..06591e8f1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.test.tsx
@@ -1,6 +1,9 @@
import { act } from 'react';
-import { createRoot } from 'react-dom/client';
+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 { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
import type { Brand, Topic } from '@/types';
(
@@ -32,34 +35,38 @@ const topics: Topic[] = Array.from({ length: 21 }, (_, i) => ({
createdAt: '2026-01-01T00:00:00.000Z',
}));
-vi.mock('next/navigation', () => ({ useParams: () => ({ id: 'brand-id' }) }));
-vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));
-vi.mock('@/lib/supabase/client', () => ({
- createClient: () => ({
- auth: { getSession: async () => ({ data: { session: { access_token: 'token' } } }) },
- }),
+/** What the page loads: each describe sets its own topics and session. */
+const loaded = vi.hoisted(() => ({
+ topics: [] as unknown[],
+ session: null as { access_token: string } | null,
}));
-vi.mock('@/lib/actions/prompt', () => ({
- getPromptSets: async () => [],
+
+const actions = vi.hoisted(() => ({
+ getPromptSets: vi.fn(),
savePromptSet: vi.fn(),
addPromptToSet: vi.fn(),
setPromptActive: vi.fn(),
updatePrompt: vi.fn(),
updatePromptLocations: vi.fn(),
bulkUpdatePromptLocations: vi.fn(),
- getLocationQuota: async () => null,
+ getLocationQuota: vi.fn(async () => null),
deletePrompt: vi.fn(),
}));
+vi.mock('@/lib/actions/prompt', () => actions);
vi.mock('@/lib/actions/brand', () => ({ getBrandById: async () => brand }));
-vi.mock('@/lib/actions/topic', () => ({ getTopics: async () => topics }));
+vi.mock('@/lib/actions/topic', () => ({ getTopics: async () => loaded.topics }));
+vi.mock('next/navigation', () => ({ useParams: () => ({ id: 'brand-id' }) }));
+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));
+vi.mock('@/lib/supabase/client', () => ({
+ createClient: () => ({
+ auth: { getSession: async () => ({ data: { session: loaded.session } }) },
+ }),
+}));
vi.mock('@/components/providers/plan-provider', () => ({
usePlanContext: () => ({ planId: 'growth', allowedModelIds: null }),
}));
vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => ({ canManage: true }) }));
vi.mock('@/lib/tracking-job-store', () => ({ saveTrackingJob: vi.fn() }));
-vi.mock('@/components/dashboard/prompt-suggestion-card', () => ({
- PromptSuggestionCard: ({ text }: { text: string }) => <p>{text}</p>,
-}));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
vi.mock('sonner', () => ({ toast }));
@@ -92,12 +99,35 @@ const fetchMock = vi.fn(async (url: string, init?: { body?: string }) => {
});
let container: HTMLDivElement;
-let root: ReturnType<typeof createRoot>;
+let root: Root;
+const openUpgrade = vi.fn();
+
+async function render(isLocked: boolean) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <PromptsPage />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+}
+
+const button = (name: string) =>
+ [...container.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === name,
+ )!;
+const include = () =>
+ container.querySelector<HTMLButtonElement>(
+ '[role="checkbox"][aria-label="Include this prompt"]',
+ )!;
beforeEach(() => {
- fetchMock.mockClear();
- toast.success.mockClear();
- toast.error.mockClear();
+ vi.clearAllMocks();
vi.stubGlobal('fetch', fetchMock);
container = document.createElement('div');
document.body.appendChild(container);
@@ -111,8 +141,14 @@ afterEach(() => {
});
describe("a brand's Prompts page", () => {
+ beforeEach(() => {
+ loaded.topics = topics;
+ loaded.session = { access_token: 'token' };
+ actions.getPromptSets.mockResolvedValue([]);
+ });
+
it('generates prompts for every topic of a brand with more than one call takes', async () => {
- await act(async () => root.render(<PromptsPage />));
+ await render(false);
expect(container.textContent).toContain('21 topics selected');
const generate = [...container.querySelectorAll('button')].find(
@@ -134,3 +170,57 @@ describe("a brand's Prompts page", () => {
expect(container.textContent).toContain('best topic 21');
});
});
+
+/**
+ * Manage prompts on a read-only workspace (plan not active): AI Generate and
+ * a prompt's Include toggle open the upgrade dialog instead of running.
+ */
+describe('Manage prompts on a read-only workspace', () => {
+ beforeEach(() => {
+ loaded.topics = [
+ { id: 't1', brandId: 'brand-id', name: 'Coffee', isActive: true, createdAt: '2026-10-01' },
+ ];
+ loaded.session = null;
+ actions.getPromptSets.mockResolvedValue([
+ {
+ id: 'set-1',
+ prompts: [
+ {
+ id: 'p1',
+ promptSetId: 'set-1',
+ text: 'Best coffee subscription?',
+ category: 'Coffee',
+ platforms: ['chatgpt'],
+ regions: ['US'],
+ models: [],
+ isActive: true,
+ workStatus: null,
+ targetUrlCount: 0,
+ citedUrlCount: 0,
+ createdAt: '2026-10-01T00:00:00.000Z',
+ },
+ ],
+ },
+ ]);
+ actions.setPromptActive.mockResolvedValue({ success: true });
+ });
+
+ it('generates nothing and pauses nothing, and says why', async () => {
+ await render(true);
+ await act(async () => button('Generate Prompts').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Generating prompts needs a plan');
+ expect(fetchMock).not.toHaveBeenCalled();
+
+ await act(async () => include().click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Pausing prompts needs a plan');
+ expect(openUpgrade).toHaveBeenCalledTimes(2);
+ expect(actions.setPromptActive).not.toHaveBeenCalled();
+ });
+
+ it('pauses a prompt on an active plan', async () => {
+ await render(false);
+ await act(async () => include().click());
+ expect(actions.setPromptActive).toHaveBeenCalledWith('p1', false);
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
index 35e1672c3..2811cd9b8 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
@@ -2,6 +2,7 @@
import { useEffect, useState, useCallback, useMemo } from 'react';
import { useParams } from 'next/navigation';
+import { useTranslations } from 'next-intl';
import { createClient } from '@/lib/supabase/client';
import {
getPromptSets,
@@ -39,6 +40,7 @@ import { cn } from '@/lib/utils';
import { MODEL_GROUPS, ALL_MODELS, SCRAPER_GROUPS, ALL_SCRAPERS } from '@/config/prompt-options';
import { usePlanContext } from '@/components/providers/plan-provider';
import { useUserRole } from '@/hooks/use-user-role';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { PLANS } from '@/config/plans';
import { saveTrackingJob } from '@/lib/tracking-job-store';
import { useRouter } from '@/i18n/navigation';
@@ -91,6 +93,10 @@ export default function PromptsPage() {
const [generateTopics, setGenerateTopics] = useState<string[] | null>(null);
const { planId, allowedModelIds: planAllowedModelIds } = usePlanContext();
const { canManage } = useUserRole();
+ // A read-only workspace (plan not active): every write and run below opens
+ // the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const allowedScraperIds = useMemo(() => {
const allowed = PLANS[planId].limits.allowedScrapers;
const ids = allowed ? [...allowed] : ALL_SCRAPERS.map((s) => s.id);
@@ -801,7 +807,7 @@ export default function PromptsPage() {
</div>
<Button
- onClick={handleAddManualPrompt}
+ onClick={guard(handleAddManualPrompt, { action: tActions('addPrompts') })}
disabled={
isAddingManual ||
!manualText.trim() ||
@@ -872,7 +878,7 @@ export default function PromptsPage() {
</p>
)}
<Button
- onClick={handleGenerate}
+ onClick={guard(handleGenerate, { action: tActions('generatePrompts') })}
disabled={isGenerating || !generateTopics || generateTopics.length === 0}
className="w-full"
>
@@ -925,7 +931,10 @@ export default function PromptsPage() {
</div>
<div className="flex items-center gap-3 pt-4">
- <Button onClick={handleSaveSuggestions} disabled={isSaving}>
+ <Button
+ onClick={guard(handleSaveSuggestions, { action: tActions('addPrompts') })}
+ disabled={isSaving}
+ >
{isSaving ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
@@ -933,7 +942,11 @@ export default function PromptsPage() {
)}
Save Selected ({suggestions.filter((s) => s.isActive).length})
</Button>
- <Button variant="outline" onClick={handleGenerate} disabled={isGenerating}>
+ <Button
+ variant="outline"
+ onClick={guard(handleGenerate, { action: tActions('generatePrompts') })}
+ disabled={isGenerating}
+ >
{isGenerating ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
@@ -955,14 +968,18 @@ export default function PromptsPage() {
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold">All Prompts ({allPrompts.length})</h2>
<div className="flex items-center gap-2">
- <Button size="sm" variant="outline" onClick={openBulkDialog}>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={guard(openBulkDialog, { action: tActions('changeLocations') })}
+ >
<Globe className="mr-2 h-3.5 w-3.5" />
Locations
</Button>
<Button
size="sm"
variant={unanalyzedPrompts.length > 0 ? 'default' : 'outline'}
- onClick={openAnalyzeDialog}
+ onClick={guard(openAnalyzeDialog, { action: tActions('analyzePrompts') })}
>
<Search className="mr-2 h-3.5 w-3.5" />
Analyze Prompts
@@ -987,12 +1004,27 @@ export default function PromptsPage() {
topics={topics}
allowedScraperIds={allowedScraperIds}
allowedModelIds={allowedModelIds}
- onToggle={() => handleTogglePrompt(prompt)}
- onTextChange={(text) => handleEditPrompt(prompt.id, text)}
- onCategoryChange={(category) => handleCategoryChange(prompt.id, category)}
- onModelsChange={(models) => handleModelsChange(prompt.id, models)}
- onPlatformsChange={(platforms) => handlePlatformsChange(prompt.id, platforms)}
- onRegionsChange={(regions) => handleRegionsChange(prompt.id, regions)}
+ onToggle={guard(() => handleTogglePrompt(prompt), {
+ action: tActions(prompt.isActive ? 'pausePrompts' : 'resumePrompts'),
+ })}
+ onTextChange={guard((text: string) => handleEditPrompt(prompt.id, text), {
+ action: tActions('editPrompts'),
+ })}
+ onCategoryChange={guard(
+ (category: string) => handleCategoryChange(prompt.id, category),
+ { action: tActions('editPrompts') },
+ )}
+ onModelsChange={guard((models: string[]) => handleModelsChange(prompt.id, models), {
+ action: tActions('editPrompts'),
+ })}
+ onPlatformsChange={guard(
+ (platforms: string[]) => handlePlatformsChange(prompt.id, platforms),
+ { action: tActions('editPrompts') },
+ )}
+ onRegionsChange={guard(
+ (regions: string[]) => handleRegionsChange(prompt.id, regions),
+ { action: tActions('editPrompts') },
+ )}
maxLocations={
// A paused prompt's locations aren't in `used`; its cap is
// what it could take back when resumed.
@@ -1005,7 +1037,9 @@ export default function PromptsPage() {
)
: null
}
- onDelete={() => handleDeletePrompt(prompt.id)}
+ onDelete={guard(() => handleDeletePrompt(prompt.id), {
+ action: tActions('deletePrompts'),
+ })}
mode="manage"
/>
))}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.test.tsx
new file mode 100644
index 000000000..24e7fc17d
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.test.tsx
@@ -0,0 +1,105 @@
+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 { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
+
+/**
+ * Manage topics on a read-only workspace (plan not active): Add and a topic's
+ * Edit open the upgrade dialog instead of writing.
+ */
+
+const actions = vi.hoisted(() => ({
+ getTopics: vi.fn(),
+ getPromptCountByTopic: vi.fn(async () => 0),
+ createTopic: vi.fn(),
+ updateTopic: vi.fn(),
+ deleteTopic: vi.fn(),
+}));
+vi.mock('@/lib/actions/topic', () => actions);
+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => ({ canManage: true }) }));
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+const { default: BrandTopicsPage } = await import('./page');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+// Already settled, so `use(params)` reads it without suspending.
+const params = Object.assign(Promise.resolve({ id: 'b1' }), {
+ status: 'fulfilled',
+ value: { id: 'b1' },
+});
+
+let container: HTMLDivElement;
+let root: Root;
+const openUpgrade = vi.fn();
+
+async function render(isLocked: boolean) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <BrandTopicsPage params={params} />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+}
+
+const typeName = async (name: string) => {
+ const input = container.querySelector<HTMLInputElement>('#add-topic input')!;
+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setValue.call(input, name);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+};
+const add = () =>
+ [...container.querySelectorAll<HTMLButtonElement>('#add-topic button')].find(
+ (b) => b.textContent?.trim() === 'Add',
+ )!;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ actions.getTopics.mockResolvedValue([
+ { id: 't1', brandId: 'b1', name: 'Coffee', isActive: true, createdAt: '2026-10-01' },
+ ]);
+ actions.createTopic.mockResolvedValue({ id: 't2', name: 'Tea' });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('Manage topics on a read-only workspace', () => {
+ it('adds nothing and opens no rename, and says why', async () => {
+ await render(true);
+ await typeName('Tea');
+ await act(async () => add().click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Adding topics needs a plan');
+ expect(actions.createTopic).not.toHaveBeenCalled();
+
+ const edit = container.querySelector<HTMLButtonElement>('[aria-label="Edit topic"]')!;
+ await act(async () => edit.click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Editing topics needs a plan');
+ expect(openUpgrade).toHaveBeenCalledTimes(2);
+ expect(container.querySelector('[aria-label="Save topic changes"]')).toBeNull();
+ });
+
+ it('adds a topic on an active plan', async () => {
+ await render(false);
+ await typeName('Tea');
+ await act(async () => add().click());
+ expect(actions.createTopic).toHaveBeenCalledWith('b1', 'Tea');
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx
index 2d7939bd0..2e2e496e5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx
@@ -1,6 +1,7 @@
'use client';
import { use, useCallback, useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
import {
createTopic,
deleteTopic,
@@ -18,6 +19,7 @@ import { Separator } from '@/components/ui/separator';
import { toast } from 'sonner';
import { Check, Loader2, Lock, Pencil, Plus, Tag, Trash2, X } from 'lucide-react';
import { useUserRole } from '@/hooks/use-user-role';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import {
Dialog,
DialogClose,
@@ -44,6 +46,10 @@ export default function BrandTopicsPage({ params }: PageProps) {
const [editingId, setEditingId] = useState<string | null>(null);
const [editName, setEditName] = useState('');
const { canManage } = useUserRole();
+ // A read-only workspace (plan not active): adding, renaming and deleting
+ // open the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const load = useCallback(
async (isCancelled?: () => boolean) => {
@@ -194,10 +200,13 @@ export default function BrandTopicsPage({ params }: PageProps) {
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
- onClick={() => {
- setEditingId(topic.id);
- setEditName(topic.name);
- }}
+ onClick={guard(
+ () => {
+ setEditingId(topic.id);
+ setEditName(topic.name);
+ },
+ { action: tActions('editTopics') },
+ )}
aria-label="Edit topic"
>
<Pencil className="h-3.5 w-3.5" />
@@ -233,7 +242,9 @@ export default function BrandTopicsPage({ params }: PageProps) {
render={
<Button
variant="destructive"
- onClick={() => handleDelete(topic.id)}
+ onClick={guard(() => handleDelete(topic.id), {
+ action: tActions('deleteTopics'),
+ })}
/>
}
>
@@ -271,12 +282,16 @@ export default function BrandTopicsPage({ params }: PageProps) {
maxLength={TOPIC_NAME_CHARS}
value={newName}
onChange={(e) => setNewName(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && newName.trim() && handleAdd()}
+ onKeyDown={(e) =>
+ e.key === 'Enter' &&
+ newName.trim() &&
+ guard(handleAdd, { action: tActions('addTopics') })()
+ }
className="flex-1"
/>
<Button
variant="outline"
- onClick={handleAdd}
+ onClick={guard(handleAdd, { action: tActions('addTopics') })}
disabled={isAdding || !newName.trim()}
className="gap-1.5 shrink-0"
>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.test.tsx
new file mode 100644
index 000000000..fac231f01
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.test.tsx
@@ -0,0 +1,120 @@
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
+
+/**
+ * Competitors on a read-only workspace (plan not active): Add, Suggest (it
+ * asks the AI as its dialog opens) and Delete open the upgrade dialog instead.
+ */
+
+const competitorActions = vi.hoisted(() => ({
+ getCompetitors: vi.fn(),
+ addCompetitor: vi.fn(),
+ deleteCompetitor: vi.fn(),
+}));
+vi.mock('@/lib/actions/competitor', () => competitorActions);
+vi.mock('@/lib/actions/tracking', () => ({
+ getCompetitorComparison: vi.fn(async () => ({ brands: [] })),
+ getHeadToHeadComparison: vi.fn(),
+ getHeadToHeadRuns: vi.fn(),
+}));
+const suggestCompetitors = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/ai-brand-setup', () => ({ suggestCompetitors }));
+vi.mock('@/hooks/use-feature-gate', () => ({
+ useFeatureGate: () => ({ canUse: () => true, isCloud: true }),
+}));
+const brand = {
+ id: 'b1',
+ name: 'Acme',
+ slug: 'acme',
+ domains: [{ domain: 'acme.com', isPrimary: true }],
+};
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: (select: (state: unknown) => unknown) => select({ getActiveBrand: () => brand }),
+}));
+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({
+ HeaderWithAiUsage: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.mock('@/components/filters/date-range-filter', () => ({ DateRangeFilter: () => null }));
+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+const { default: CompetitorsPage } = await import('./page');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+const openUpgrade = vi.fn();
+
+async function render(isLocked: boolean) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <CompetitorsPage />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+}
+
+// The header's buttons: the empty state below repeats Add and Suggest.
+const headerButton = (name: string) =>
+ [...container.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === name,
+ )!;
+const dialog = () => document.querySelector('[role="dialog"]');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ competitorActions.getCompetitors.mockResolvedValue([
+ { id: 'c1', brandId: 'b1', name: 'Rival', domain: 'rival.com', createdAt: '2026-10-01' },
+ ]);
+ suggestCompetitors.mockResolvedValue({ competitors: [] });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('Competitors on a read-only workspace', () => {
+ it('asks the AI for nothing: Suggest opens the upgrade dialog, not its own', async () => {
+ await render(true);
+ await act(async () => headerButton('Suggest competitors').click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Suggesting competitors needs a plan');
+ expect(suggestCompetitors).not.toHaveBeenCalled();
+ expect(dialog()).toBeNull();
+ });
+
+ it('adds and deletes nothing', async () => {
+ await render(true);
+ await act(async () => headerButton('Add Competitor').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Adding competitors needs a plan');
+ const remove = container.querySelector<HTMLButtonElement>('button[aria-label="Delete"]')!;
+ await act(async () => remove.click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Deleting competitors needs a plan');
+ expect(openUpgrade).toHaveBeenCalledTimes(2);
+ expect(dialog()).toBeNull();
+ expect(competitorActions.deleteCompetitor).not.toHaveBeenCalled();
+ });
+
+ it('opens Suggest, which asks the AI, on an active plan', async () => {
+ await render(false);
+ await act(async () => headerButton('Suggest competitors').click());
+ expect(openUpgrade).not.toHaveBeenCalled();
+ expect(dialog()).not.toBeNull();
+ expect(suggestCompetitors).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
index 754c60e05..9f6c8e8a4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
@@ -5,6 +5,7 @@ import { useRouter } from '@/i18n/navigation';
import { useTranslations } from 'next-intl';
import { useBrandStore } from '@/stores/use-brand-store';
import { useFeatureGate } from '@/hooks/use-feature-gate';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { getCompetitors, addCompetitor, deleteCompetitor } from '@/lib/actions/competitor';
import type { SuggestedCompetitor } from '@/lib/ai-brand-setup';
import { SuggestCompetitorsDialog } from './_suggest-competitors-dialog';
@@ -1241,6 +1242,14 @@ export default function CompetitorsPage() {
const [suggestDialogOpen, setSuggestDialogOpen] = useState(false);
const [deleting, setDeleting] = useState<string | null>(null);
const [confirmDelete, setConfirmDelete] = useState<Competitor | null>(null);
+ // A read-only workspace (plan not active): Add, Suggest (it asks the AI as
+ // it opens) and Delete open the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
+ const openAdd = guard(() => setDialogOpen(true), { action: tActions('addCompetitors') });
+ const openSuggest = guard(() => setSuggestDialogOpen(true), {
+ action: tActions('suggestCompetitors'),
+ });
// Head-to-head
const [selectedCompetitorId, setSelectedCompetitorId] = useState<string | null>(null);
@@ -1558,11 +1567,11 @@ export default function CompetitorsPage() {
/>
)}
</div>
- <Button variant="outline" className="gap-2" onClick={() => setSuggestDialogOpen(true)}>
+ <Button variant="outline" className="gap-2" onClick={openSuggest}>
<Sparkles className="h-4 w-4" />
{t('suggestCompetitors')}
</Button>
- <Button className="gap-2" onClick={() => setDialogOpen(true)}>
+ <Button className="gap-2" onClick={openAdd}>
<Plus className="h-4 w-4" />
{t('addCompetitor')}
</Button>
@@ -1571,10 +1580,7 @@ export default function CompetitorsPage() {
</HeaderWithAiUsage>
{competitors.length === 0 ? (
- <EmptyState
- onAdd={() => setDialogOpen(true)}
- onSuggest={() => setSuggestDialogOpen(true)}
- />
+ <EmptyState onAdd={openAdd} onSuggest={openSuggest} />
) : (
<>
{/* Competitor List */}
@@ -1619,7 +1625,9 @@ export default function CompetitorsPage() {
onSelect={() =>
selectCompetitor(selectedCompetitorId === comp.id ? null : comp.id)
}
- onDelete={() => setConfirmDelete(comp)}
+ onDelete={guard(() => setConfirmDelete(comp), {
+ action: tActions('deleteCompetitors'),
+ })}
deleting={deleting === comp.id}
/>
))}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsx
index 9b64ce389..28f4b6be9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsx
@@ -3,6 +3,9 @@ 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 { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
+import { trackSuggestions } from '@/lib/actions/prompt-suggestions';
+import { sendTopicOpportunityToActionCenter } from '@/lib/actions/topic';
import { Opportunities } from './_opportunities';
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
@@ -74,3 +77,65 @@ describe('Opportunities — estimated volume (PROMPT-013)', () => {
expect(container.textContent).not.toContain('~');
});
});
+
+describe('Opportunities on a read-only workspace (plan not active)', () => {
+ const openUpgrade = vi.fn();
+ const render = (isLocked: boolean) =>
+ act(() =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <Opportunities
+ brandId="b1"
+ suggestions={[suggestion('s1', 'Espresso', 800), suggestion('s2', 'Espresso', 400)]}
+ trackedTopicIds={[]}
+ topics={null}
+ entities={null}
+ slotsLeft={null}
+ contentUsage={null}
+ onTracked={() => {}}
+ />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ ),
+ );
+ const button = (name: string) =>
+ [...container.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent === name,
+ )!;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal(
+ 'open',
+ vi.fn(() => null),
+ );
+ vi.mocked(trackSuggestions).mockResolvedValue({ trackedIds: ['s1', 's2'], skippedIds: [] });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('opens the upgrade dialog from a topic’s Track and Send action, and runs neither', async () => {
+ render(true);
+ await act(async () => button('Track 2').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Tracking prompts needs a plan');
+ await act(async () => button('Send action').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Sending actions needs a plan');
+ expect(openUpgrade).toHaveBeenCalledTimes(2);
+ expect(trackSuggestions).not.toHaveBeenCalled();
+ expect(sendTopicOpportunityToActionCenter).not.toHaveBeenCalled();
+ // No tab is opened for a Track that doesn't run.
+ expect(window.open).not.toHaveBeenCalled();
+ });
+
+ it('tracks on an active plan', async () => {
+ render(false);
+ await act(async () => button('Track 2').click());
+ expect(trackSuggestions).toHaveBeenCalledWith(['s1', 's2']);
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx
index 149fc1ed7..27933ba81 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx
@@ -26,6 +26,7 @@ import {
import type { TopicCompetitors } from '@/lib/insights-topics';
import { guessedVolumeEstimate } from '@/lib/volume-estimate';
import { EstimateRange } from '@/components/prompts/volume-estimate';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
/** Items shown, as in the mockup; "See all" opens the rest. */
const VISIBLE_ITEMS = 4;
@@ -68,6 +69,10 @@ export function Opportunities({
className?: string;
}) {
const t = useTranslations('insights.opportunities');
+ // A read-only workspace (plan not active): Track, Send action and Suggest
+ // content open the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const failureToast = useFailureToast();
const format = useFormatter();
const f = numberFormat(useLocale());
@@ -355,7 +360,7 @@ export function Opportunities({
size="sm"
className="h-7 gap-1.5 px-2.5 text-xs"
disabled={planFull || busy !== null}
- onClick={() => track(item)}
+ onClick={guard(() => track(item), { action: tActions('trackPrompts') })}
>
{/* Track N adds one prompt at a time, so a big topic takes a moment. */}
{busy === item.key && (
@@ -375,7 +380,9 @@ export function Opportunities({
size="sm"
className="h-7 gap-1.5 px-2.5 text-xs"
disabled={blocked !== null || working.has(item.key)}
- onClick={() => (isTopic ? sendAction(item) : suggestContent(item))}
+ onClick={guard(() => (isTopic ? sendAction(item) : suggestContent(item)), {
+ action: tActions(isTopic ? 'sendAction' : 'suggestContent'),
+ })}
>
{working.has(item.key) && (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsx
index 440640840..5238284b0 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsx
@@ -21,6 +21,7 @@ import { numberFormat } from '@/lib/number-format';
import { LOW_SAMPLE_ANSWERS } from '@/lib/insights-summary';
import { dayLabel } from './kpi-format';
import { useUserRole } from '@/hooks/use-user-role';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { setPinnedCompetitors } from '@/lib/actions/brand';
import type { VisibilityRateTrendData } from '@/lib/actions/tracking';
import {
@@ -66,6 +67,9 @@ export function TrendCard({
const locale = useLocale();
const f = numberFormat(locale);
const { canManage } = useUserRole();
+ // A read-only workspace (plan not active): pinning opens the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const [hoveredKey, setHoveredKey] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
@@ -178,7 +182,9 @@ export function TrendCard({
? onChart.length === 1
: onChart.length >= MAX_PINNED_COMPETITORS)
}
- onCheckedChange={() => togglePin(c.key)}
+ onCheckedChange={guard(() => togglePin(c.key), {
+ action: tActions('pinCompetitors'),
+ })}
>
{c.name}
</DropdownMenuCheckboxItem>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 9aed94b52..b6d8c1bca 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -66,6 +66,7 @@ import {
import { cn } from '@/lib/utils';
import { getAIProviderDisplayName, resolveAIProvider } from '@/components/ai-provider-avatar';
import { usePlanContext } from '@/components/providers/plan-provider';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { toast } from 'sonner';
import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';
import type { PromptComparison } from '@/lib/insights-same-prompts';
@@ -629,6 +630,10 @@ export default function InsightsPage() {
const tCommon = useTranslations('common');
const router = useRouter();
const { isCloud } = usePlanContext();
+ // A read-only workspace (plan not active): Run All and Test Single Prompt
+ // open the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const locale = useLocale();
const brand = useBrandStore((s) => s.getActiveBrand());
const [summary, setSummary] = useState<InsightsSummary | null>(null);
@@ -979,6 +984,11 @@ export default function InsightsPage() {
}
};
+ const runAll = guard(handleRunPrompts, { action: tActions('runPrompts') });
+ const openSinglePrompt = guard(() => setShowSinglePrompt(true), {
+ action: tActions('testPrompt'),
+ });
+
const handleStopTracking = async () => {
if (!activeJobId) return;
try {
@@ -1104,10 +1114,10 @@ export default function InsightsPage() {
</HeaderWithAiUsage>
<TrackingProgressBanner jobStatus={jobStatus} onStop={handleStopTracking} />
{!localJobActive && <ServerRunBanner run={cronRun} />}
- <EmptyState onRunPrompts={handleRunPrompts} isRunning={isRunning} isCloud={isCloud} />
+ <EmptyState onRunPrompts={runAll} isRunning={isRunning} isCloud={isCloud} />
{!isCloud && (
<div className="flex justify-center">
- <Button variant="outline" onClick={() => setShowSinglePrompt(true)} className="gap-2">
+ <Button variant="outline" onClick={openSinglePrompt} className="gap-2">
<FlaskConical className="h-4 w-4" />
Or test a single prompt
</Button>
@@ -1182,16 +1192,12 @@ export default function InsightsPage() {
{/* Self-host only */}
{!isCloud && (
<>
- <Button
- variant="outline"
- onClick={() => setShowSinglePrompt(true)}
- className="gap-2"
- >
+ <Button variant="outline" onClick={openSinglePrompt} className="gap-2">
<FlaskConical className="h-4 w-4" />
Test Single Prompt
</Button>
- <Button onClick={handleRunPrompts} disabled={isRunning} className="gap-2">
+ <Button onClick={runAll} disabled={isRunning} className="gap-2">
{isRunning ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.test.tsx
new file mode 100644
index 000000000..87d22d524
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.test.tsx
@@ -0,0 +1,117 @@
+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 { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
+import type { QueryFanoutData } from '@/lib/actions/fanout';
+
+/**
+ * Track on the Query Fan-out tab adds the sub-query as a tracked prompt; on
+ * a read-only workspace (plan not active) it opens the upgrade dialog
+ * instead, and the intents aren't asked for.
+ */
+
+const actions = vi.hoisted(() => ({
+ getQueryFanout: vi.fn(),
+ trackFanoutQuery: vi.fn(),
+ classifyFanoutIntents: vi.fn(async () => ({})),
+}));
+vi.mock('@/lib/actions/fanout', () => actions);
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children }: { href: string; children: React.ReactNode }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+const { QueryFanoutTab } = await import('./_fanout-tab');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const data: QueryFanoutData = {
+ subQueries: [
+ {
+ query: 'best coffee beans',
+ engines: ['chatgpt-web'],
+ timesSearched: 3,
+ sourcedPrompts: [{ id: 'p1', text: 'Best coffee subscription?' }],
+ tracked: false,
+ trackedPromptId: null,
+ },
+ ],
+ totalObserved: 1,
+ promptCoverage: [
+ {
+ id: 'p1',
+ text: 'Best coffee subscription?',
+ totalRuns: 3,
+ runsWithFanout: 3,
+ platforms: ['chatgpt-web'],
+ fanoutPlatforms: ['chatgpt-web'],
+ },
+ ],
+ engines: [],
+ truncated: false,
+};
+
+let container: HTMLDivElement;
+let root: Root;
+const openUpgrade = vi.fn();
+
+async function render(isLocked: boolean) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <QueryFanoutTab brandId="b1" range={null} rangeLabel="last 7 days" />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ );
+ });
+ // The High frequency view lists each sub-query with its Track button.
+ const view = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'High frequency',
+ )!;
+ await act(async () => view.click());
+}
+
+const track = () =>
+ container.querySelector<HTMLButtonElement>(
+ '[aria-label=\'Track "best coffee beans" as a prompt\']',
+ )!;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ actions.getQueryFanout.mockResolvedValue(data);
+ actions.trackFanoutQuery.mockResolvedValue({ promptId: 'p2' });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('Track on the Query Fan-out tab', () => {
+ it('opens the upgrade dialog, tracking nothing, on a read-only workspace', async () => {
+ await render(true);
+ await act(async () => track().click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Tracking prompts needs a plan');
+ expect(actions.trackFanoutQuery).not.toHaveBeenCalled();
+ expect(actions.classifyFanoutIntents).not.toHaveBeenCalled();
+ });
+
+ it('tracks the sub-query on an active plan', async () => {
+ await render(false);
+ await act(async () => track().click());
+ expect(actions.trackFanoutQuery).toHaveBeenCalledWith('b1', 'best coffee beans');
+ expect(openUpgrade).not.toHaveBeenCalled();
+ expect(actions.classifyFanoutIntents).toHaveBeenCalledWith(['best coffee beans']);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx
index 79b7be7b2..e1df4ead2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx
@@ -30,6 +30,7 @@ import {
} from '@/components/ui/table';
import { Check, ChevronRight, Plus, Loader2, Search } from 'lucide-react';
import { usePagination, TablePager } from '@/components/table-pager';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import {
FanoutEngineNotices,
FanoutEngineStrip,
@@ -97,6 +98,10 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryF
const [searchText, setSearchText] = useState('');
// The engine chip picked above the lists; null shows every engine.
const [engine, setEngine] = useState<string | null>(null);
+ // A read-only workspace (plan not active): Track opens the upgrade dialog
+ // instead, and the intents (an AI call the API refuses then) aren't asked.
+ const { guard, isLocked } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
// Mirror of `intents` for the async classification chain (avoids stale
// closures), plus a run counter so a reload/brand switch/unmount cancels
@@ -165,7 +170,7 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryF
to: range?.to,
});
setData(result);
- void classifyProgressively(result.subQueries.map((s) => s.query));
+ if (!isLocked) void classifyProgressively(result.subQueries.map((s) => s.query));
} catch (err) {
console.error('[fanout] load failed', err);
toast.error(userErrorMessage(err, 'Failed to load query fan-out — please retry.'));
@@ -182,7 +187,7 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryF
}
}
},
- [brandId, range, classifyProgressively],
+ [brandId, range, classifyProgressively, isLocked],
);
useEffect(() => {
@@ -377,7 +382,7 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryF
pager={pager}
rangeLabel={rangeLabel}
engine={engine}
- onTrack={handleTrack}
+ onTrack={guard(handleTrack, { action: tActions('trackPrompts') })}
searchText={searchText}
onSearchChange={setSearchText}
/>
@@ -389,7 +394,7 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryF
pager={byPromptPager}
rangeLabel={rangeLabel}
engine={engine}
- onTrack={handleTrack}
+ onTrack={guard(handleTrack, { action: tActions('trackPrompts') })}
searchText={searchText}
onSearchChange={setSearchText}
/>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx
index 422001b02..168db5584 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx
@@ -4,6 +4,7 @@ import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../messages/en.json';
import type { PromptSuggestion, TrackSuggestionsResult } from '@/lib/actions/prompt-suggestions';
+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
import { SuggestionsCard } from './_suggestions-card';
(
@@ -50,6 +51,9 @@ const ids = (from: number, to: number) =>
let container: HTMLDivElement;
let root: Root;
const onAccepted = vi.fn();
+// The workspace's plan: active unless a test says it's read-only.
+let isLocked = false;
+const openUpgrade = vi.fn();
async function render(count: number, planId: 'starter' | 'growth' = 'starter') {
actions.getPromptSuggestions.mockResolvedValue({
@@ -58,13 +62,17 @@ async function render(count: number, planId: 'starter' | 'growth' = 'starter') {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <SuggestionsCard
- brandId="b1"
- onAccepted={onAccepted}
- sourceStates={null}
- planId={planId}
- limitActions={<button type="button">Upgrade plan</button>}
- />
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <SuggestionsCard
+ brandId="b1"
+ onAccepted={onAccepted}
+ sourceStates={null}
+ planId={planId}
+ limitActions={<button type="button">Upgrade plan</button>}
+ />
+ </UpgradeDialogContext.Provider>
</NextIntlClientProvider>,
);
});
@@ -85,6 +93,7 @@ beforeEach(() => {
document.body.appendChild(container);
root = createRoot(container);
vi.clearAllMocks();
+ isLocked = false;
});
afterEach(() => {
@@ -246,3 +255,39 @@ describe('SuggestionsCard — estimated volume', () => {
expect(container.textContent).not.toContain('~1,200');
});
});
+
+describe('SuggestionsCard on a read-only workspace (plan not active)', () => {
+ const button = (name: string) =>
+ [...container.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent === name || b.getAttribute('aria-label') === name,
+ )!;
+
+ it('adds, accepts, dismisses and generates nothing, and says why', async () => {
+ isLocked = true;
+ await render(2);
+
+ await clickAddAll();
+ expect(openUpgrade).toHaveBeenLastCalledWith('Adding prompts needs a plan');
+ await act(async () => button('Add to tracked prompts').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Adding prompts needs a plan');
+ await act(async () => button('Dismiss suggestion').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Dismissing suggestions needs a plan');
+ await act(async () => button('New').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Suggesting prompts needs a plan');
+
+ expect(openUpgrade).toHaveBeenCalledTimes(4);
+ expect(actions.trackSuggestions).not.toHaveBeenCalled();
+ expect(actions.acceptSuggestion).not.toHaveBeenCalled();
+ expect(actions.dismissSuggestion).not.toHaveBeenCalled();
+ expect(actions.refreshPromptSuggestions).not.toHaveBeenCalled();
+ expect(rows()).toHaveLength(2);
+ });
+
+ it('accepts on an active plan', async () => {
+ await render(1);
+ actions.acceptSuggestion.mockResolvedValue({ success: true });
+ await act(async () => button('Add to tracked prompts').click());
+ expect(actions.acceptSuggestion).toHaveBeenCalledWith('s1');
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
index 1a9ba19f1..98f65904e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
@@ -61,6 +61,7 @@ import {
type GscSuggestionBadge,
} from '@/lib/prompt-suggestion-source';
import type { SuggestionSourceStates } from '@/lib/actions/integrations';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
/**
* Analytics evidence, in the customer's own numbers (#705). A blind spot is
@@ -286,6 +287,10 @@ export function SuggestionsCard({
limitActions,
}: Props) {
const t = useTranslations('prompts.suggestions');
+ // A read-only workspace (plan not active): generating, adding and
+ // dismissing open the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
// One method note for the list's volume ranges (PROMPT-013).
const volumeNote = useMemo(() => createEstimateNoteHandle(), []);
const [suggestions, setSuggestions] = useState<PromptSuggestion[]>([]);
@@ -536,7 +541,7 @@ export function SuggestionsCard({
</div>
<Button
- onClick={handleRefresh}
+ onClick={guard(handleRefresh, { action: tActions('suggestPrompts') })}
disabled={refreshing}
size="sm"
variant="outline"
@@ -551,7 +556,7 @@ export function SuggestionsCard({
</Button>
<Button
- onClick={handleAddAll}
+ onClick={guard(handleAddAll, { action: tActions('addPrompts') })}
disabled={adding || clearing || visible.length === 0}
size="sm"
variant="outline"
@@ -567,7 +572,7 @@ export function SuggestionsCard({
</Button>
<Button
- onClick={handleClearAll}
+ onClick={guard(handleClearAll, { action: tActions('dismissSuggestions') })}
disabled={clearing || adding || visible.length === 0}
size="sm"
variant="outline"
@@ -648,7 +653,7 @@ export function SuggestionsCard({
</div>
{notice.kind === 'ready' && (
<Button
- onClick={handleRefresh}
+ onClick={guard(handleRefresh, { action: tActions('suggestPrompts') })}
disabled={refreshing}
size="sm"
className="shrink-0 gap-2"
@@ -685,7 +690,12 @@ export function SuggestionsCard({
Click refresh to generate new prompt ideas tailored to your brand and competitor
activity.
</p>
- <Button onClick={handleRefresh} disabled={refreshing} size="sm" className="gap-2">
+ <Button
+ onClick={guard(handleRefresh, { action: tActions('suggestPrompts') })}
+ disabled={refreshing}
+ size="sm"
+ className="gap-2"
+ >
{refreshing ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
@@ -793,7 +803,9 @@ export function SuggestionsCard({
size="icon"
variant="outline"
className="h-8 w-8"
- onClick={() => handleAccept(s)}
+ onClick={guard(() => handleAccept(s), {
+ action: tActions('addPrompts'),
+ })}
disabled={busy}
title="Add to tracked prompts"
aria-label="Add to tracked prompts"
@@ -808,7 +820,9 @@ export function SuggestionsCard({
size="icon"
variant="ghost"
className="h-8 w-8 text-muted-foreground"
- onClick={() => handleDismiss(s)}
+ onClick={guard(() => handleDismiss(s), {
+ action: tActions('dismissSuggestions'),
+ })}
disabled={busy}
title="Dismiss suggestion"
aria-label="Dismiss suggestion"
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx
index aadf7beeb..f346dccd9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx
@@ -1,6 +1,7 @@
'use client';
import { useEffect, useState, useCallback, useTransition } from 'react';
+import { useTranslations } from 'next-intl';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -23,6 +24,7 @@ import {
dismissTopicSuggestion,
type TopicSuggestion,
} from '@/lib/actions/topic-suggestions';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
interface Props {
brandId: string;
@@ -47,6 +49,10 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)
// restores the stored preference.
const [expanded, setExpanded] = useState(false);
const [, startTransition] = useTransition();
+ // A read-only workspace (plan not active): generating, adding and
+ // dismissing open the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
useEffect(() => {
try {
@@ -195,7 +201,7 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)
</button>
{expanded && canManage && (
<Button
- onClick={handleRefresh}
+ onClick={guard(handleRefresh, { action: tActions('suggestTopics') })}
disabled={refreshing}
size="sm"
variant="outline"
@@ -243,7 +249,12 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)
: 'No topic suggestions have been generated for this brand yet.'}
</p>
{canManage && (
- <Button onClick={handleRefresh} disabled={refreshing} size="sm" className="gap-2">
+ <Button
+ onClick={guard(handleRefresh, { action: tActions('suggestTopics') })}
+ disabled={refreshing}
+ size="sm"
+ className="gap-2"
+ >
{refreshing ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
@@ -274,7 +285,9 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)
size="icon"
variant="outline"
className="h-8 w-8"
- onClick={() => handleAccept(s)}
+ onClick={guard(() => handleAccept(s), {
+ action: tActions('addTopics'),
+ })}
disabled={busy}
title="Add to tracked topics"
aria-label="Add to tracked topics"
@@ -289,7 +302,9 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)
size="icon"
variant="ghost"
className="h-8 w-8 text-muted-foreground"
- onClick={() => handleDismiss(s)}
+ onClick={guard(() => handleDismiss(s), {
+ action: tActions('dismissSuggestions'),
+ })}
disabled={busy}
title="Dismiss suggestion"
aria-label="Dismiss suggestion"
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.test.tsx
index 52b95bb8e..8613a3bef 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.test.tsx
@@ -3,6 +3,7 @@ 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 { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
/**
* The Topics tab's buttons sit where the Prompts tab's do: beside the tabs,
@@ -10,6 +11,9 @@ import messages from '../../../../../../messages/en.json';
*/
let canManage = true;
+// The workspace's plan: active unless a test says it's read-only.
+let isLocked = false;
+const openUpgrade = vi.fn();
vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => ({ canManage }) }));
vi.mock('@/stores/use-brand-store', () => ({
useBrandStore: (select: (state: unknown) => unknown) =>
@@ -35,6 +39,8 @@ let root: Root;
beforeEach(() => {
canManage = true;
+ isLocked = false;
+ openUpgrade.mockClear();
container = document.createElement('div');
slot = document.createElement('div');
document.body.append(slot, container);
@@ -51,13 +57,17 @@ async function render() {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <TopicsTab
- actionsSlot={slot}
- range={{ from: '2026-10-11T00:00:00.000Z', days: 7 }}
- rangePreset="7d"
- customFrom=""
- customTo=""
- />
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <TopicsTab
+ actionsSlot={slot}
+ range={{ from: '2026-10-11T00:00:00.000Z', days: 7 }}
+ rangePreset="7d"
+ customFrom=""
+ customTo=""
+ />
+ </UpgradeDialogContext.Provider>
</NextIntlClientProvider>,
);
});
@@ -81,3 +91,26 @@ describe('TopicsTab buttons', () => {
expect(labels(slot)).toEqual(['Export CSV', 'Manage topics']);
});
});
+
+describe('Add Topic on a read-only workspace (plan not active)', () => {
+ const addTopic = () =>
+ [...slot.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === 'Add Topic',
+ )!;
+ const dialog = () => document.querySelector('[role="dialog"]');
+
+ it('opens the upgrade dialog instead of the Add Topic form', async () => {
+ isLocked = true;
+ await render();
+ await act(async () => addTopic().click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Adding topics needs a plan');
+ expect(dialog()).toBeNull();
+ });
+
+ it('opens the Add Topic form on an active plan', async () => {
+ await render();
+ await act(async () => addTopic().click());
+ expect(openUpgrade).not.toHaveBeenCalled();
+ expect(dialog()?.textContent).toContain('Add Topic');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx
index 68209aaf5..f07c94e31 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx
@@ -6,6 +6,7 @@ import { useTranslations } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { useBrandStore } from '@/stores/use-brand-store';
import { useUserRole } from '@/hooks/use-user-role';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { getTopicsOverview, type TopicOverviewRow } from '@/lib/actions/topic';
import { TOPIC_NAME_CHARS } from '@/lib/topic-names';
import { customUtcWindow } from '@/lib/topic-trend';
@@ -245,6 +246,9 @@ export function TopicsTab({
(s) => s.brands.find((brand) => brand.id === s.activeBrandId) ?? null,
);
const { canManage } = useUserRole();
+ // A read-only workspace (plan not active): Add Topic opens the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const [topics, setTopics] = useState<TopicOverviewRow[]>([]);
const [unassignedPromptCount, setUnassignedPromptCount] = useState(0);
const [loading, setLoading] = useState(true);
@@ -252,6 +256,7 @@ export function TopicsTab({
const [isAdding, setIsAdding] = useState(false);
const [newName, setNewName] = useState('');
const [open, setOpen] = useState(false);
+ const openAddTopic = guard(() => setOpen(true), { action: tActions('addTopics') });
// Default matches the previous hard-coded order (#597): visibility descending.
const [sortKey, setSortKey] = useState<TopicSortKey>('visibility');
const [sortDir, setSortDir] = useState<SortDir>('desc');
@@ -427,7 +432,7 @@ export function TopicsTab({
createPortal(
<>
{canManage && (
- <Button type="button" size="sm" className="gap-2" onClick={() => setOpen(true)}>
+ <Button type="button" size="sm" className="gap-2" onClick={openAddTopic}>
<Plus className="h-4 w-4" />
{t('addTopic')}
</Button>
@@ -590,7 +595,7 @@ export function TopicsTab({
<p className="mt-2">{t('emptyTitle')}</p>
<p className="text-xs">{t('emptyBody')}</p>
{canManage && (
- <Button className="mt-4" onClick={() => setOpen(true)}>
+ <Button className="mt-4" onClick={openAddTopic}>
<Plus className="mr-2 h-4 w-4" />
{t('addTopic')}
</Button>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx
new file mode 100644
index 000000000..2f14ef5d7
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.test.tsx
@@ -0,0 +1,239 @@
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
+import type { Prompt } from '@/types';
+
+/**
+ * Tracked Prompts on a read-only workspace (plan not active): Add prompt,
+ * the row menu, the bulk bar and Analyze open the upgrade dialog, labelled
+ * with what was clicked, and write nothing; on an active plan they work as
+ * before. The volumes the server refuses it don't read as an outage.
+ */
+
+const actions = vi.hoisted(() => ({
+ getPromptsPageData: vi.fn(),
+ setPromptActive: vi.fn(),
+ setPromptsActive: vi.fn(),
+ deletePrompt: vi.fn(),
+ deletePrompts: vi.fn(),
+ importPrompts: vi.fn(),
+ updatePrompt: vi.fn(),
+}));
+vi.mock('@/lib/actions/prompt', () => actions);
+const volumes = vi.hoisted(() => ({
+ startPromptVolumeAnalysis: vi.fn(),
+ getVolumeAnalysisStatus: vi.fn(async () => null),
+ refreshVolumes: vi.fn(),
+}));
+vi.mock('@/lib/actions/volumes', () => volumes);
+vi.mock('@/lib/actions/tracking', () => ({
+ getBrandFilterOptions: vi.fn(async () => ({ regions: [] })),
+}));
+vi.mock('@/lib/actions/topic', () => ({ getTopics: vi.fn(async () => []) }));
+vi.mock('@/lib/actions/content', () => ({
+ getContentUsage: vi.fn(async () => null),
+ getGenerationJobStatus: vi.fn(),
+ getOpenSuggestionForPrompt: vi.fn(async () => null),
+ suggestContentForPrompt: vi.fn(),
+}));
+vi.mock('@/lib/actions/content-drafts', () => ({ getDraftForPrompt: vi.fn(async () => null) }));
+vi.mock('@/lib/actions/prompt-workflow', () => ({ setPromptWorkStatus: vi.fn() }));
+// Start (New content) and the Positions panel have tests of their own.
+vi.mock('@/components/content/new-content-dialog', () => ({ NewContentDialog: () => null }));
+vi.mock('@/components/prompts/prompt-positions-sheet', () => ({
+ PromptPositionsSheet: () => null,
+}));
+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({
+ HeaderWithAiUsage: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => ({ canManage: true }) }));
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: (select: (state: unknown) => unknown) =>
+ select({ activeBrandId: 'b1', brands: [{ id: 'b1', slug: 'acme', name: 'Acme' }] }),
+}));
+vi.mock('next/navigation', () => ({ useSearchParams: () => new URLSearchParams() }));
+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() }),
+}));
+const toast = vi.hoisted(() =>
+ Object.assign(vi.fn(), {
+ success: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+ loading: vi.fn(),
+ dismiss: vi.fn(),
+ }),
+);
+vi.mock('sonner', () => ({ toast }));
+
+const { default: PromptsPage } = await import('./page');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const prompt: Prompt = {
+ id: 'p1',
+ promptSetId: 'set-1',
+ text: 'Best coffee subscription?',
+ platforms: ['chatgpt'],
+ regions: ['US'],
+ models: [],
+ isActive: true,
+ workStatus: null,
+ targetUrlCount: 0,
+ citedUrlCount: 0,
+ createdAt: '2026-09-01T00:00:00.000Z',
+};
+
+let container: HTMLDivElement;
+let root: Root;
+const openUpgrade = vi.fn();
+
+async function render(isLocked: boolean) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <PromptsPage />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+}
+
+const button = (name: string) =>
+ [...document.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === name,
+ );
+const dialog = () => document.querySelector('[role="dialog"]');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => ({ ok: false, json: async () => ({}) })),
+ );
+ actions.getPromptsPageData.mockResolvedValue({
+ volumes: [],
+ quota: null,
+ promptSets: [{ prompts: [prompt] }],
+ visibility: {},
+ positions: {},
+ });
+ actions.setPromptsActive.mockResolvedValue({ updated: 1 });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+describe('Tracked Prompts on a read-only workspace', () => {
+ it('opens the upgrade dialog from Add prompt, not the Add Prompt dialog', async () => {
+ await render(true);
+ await act(async () => button('Add prompt')!.click());
+ expect(openUpgrade).toHaveBeenCalledWith('Adding prompts needs a plan');
+ expect(dialog()).toBeNull();
+ });
+
+ it('opens Add Prompt on an active plan', async () => {
+ await render(false);
+ await act(async () => button('Add prompt')!.click());
+ expect(openUpgrade).not.toHaveBeenCalled();
+ expect(dialog()).not.toBeNull();
+ });
+
+ it('pauses nothing from the row menu or the bulk bar', async () => {
+ await render(true);
+ const trigger = container.querySelector<HTMLElement>(
+ `[aria-label="Actions for ${prompt.text}"]`,
+ )!;
+ await act(async () => trigger.click());
+ const pause = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (el) => el.textContent === 'Pause tracking',
+ )!;
+ await act(async () => pause.click());
+ expect(openUpgrade).toHaveBeenCalledTimes(1);
+ expect(openUpgrade).toHaveBeenLastCalledWith('Pausing prompts needs a plan');
+ expect(actions.setPromptActive).not.toHaveBeenCalled();
+
+ const box = container.querySelector<HTMLElement>(`[aria-label="Select ${prompt.text}"]`)!;
+ await act(async () => box.click());
+ await act(async () => button('Pause')!.click());
+ expect(openUpgrade).toHaveBeenCalledTimes(2);
+ expect(openUpgrade).toHaveBeenLastCalledWith('Pausing prompts needs a plan');
+ expect(actions.setPromptsActive).not.toHaveBeenCalled();
+ });
+
+ it('pauses from the bulk bar on an active plan', async () => {
+ await render(false);
+ const box = container.querySelector<HTMLElement>(`[aria-label="Select ${prompt.text}"]`)!;
+ await act(async () => box.click());
+ await act(async () => button('Pause')!.click());
+ expect(actions.setPromptsActive).toHaveBeenCalledWith(['p1'], false);
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+});
+
+describe('volumes on a read-only workspace', () => {
+ // The prompt has no volume yet: the banner offers "Analyze 1 prompt".
+ const pageData = (volumesDegraded: boolean) => ({
+ volumes: [],
+ quota: null,
+ promptSets: [{ prompts: [prompt] }],
+ visibility: {},
+ positions: {},
+ volumesDegraded,
+ visibilityDegraded: false,
+ });
+
+ it('starts no analysis: Analyze opens the upgrade dialog', async () => {
+ await render(true);
+ await act(async () => button('Analyze 1 prompt')!.click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Analyzing prompts needs a plan');
+ expect(volumes.startPromptVolumeAnalysis).not.toHaveBeenCalled();
+ });
+
+ it('opens the upgrade dialog, not "not part of your plan", when the server says the plan ended', async () => {
+ volumes.startPromptVolumeAnalysis.mockResolvedValue({
+ ok: false,
+ code: 'subscription_inactive',
+ });
+ await render(false);
+ await act(async () => button('Analyze 1 prompt')!.click());
+ expect(volumes.startPromptVolumeAnalysis).toHaveBeenCalledWith('b1', false);
+ expect(openUpgrade).toHaveBeenCalledTimes(1);
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('says nothing broke when the refused volumes leave their columns empty', async () => {
+ actions.getPromptsPageData.mockResolvedValue(pageData(true));
+ await render(true);
+ expect(toast.warning).not.toHaveBeenCalled();
+ });
+
+ it('still warns of a volumes outage on an active plan', async () => {
+ actions.getPromptsPageData.mockResolvedValue(pageData(true));
+ await render(false);
+ expect(toast.warning).toHaveBeenCalledWith(
+ 'Volume data is temporarily unavailable — showing prompts without it.',
+ );
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 148101045..f75504b22 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -141,6 +141,7 @@ import {
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 {
MODEL_GROUPS,
ALL_MODELS,
@@ -1304,6 +1305,12 @@ export default function PromptsPage() {
const [headerActions, setHeaderActions] = useState<HTMLDivElement | null>(null);
const [editingPrompt, setEditingPrompt] = useState<Prompt | null>(null);
const { canManage } = useUserRole();
+ // A read-only workspace (plan not active): adding, editing and the volume
+ // runs open the upgrade dialog instead.
+ const { guard, isLocked } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
+ const failureToast = useFailureToast();
+ const openAddPrompt = guard(() => setAddPromptOpen(true), { action: tActions('addPrompts') });
const activeBrandId = useBrandStore((s) => s.activeBrandId);
const tCommon = useTranslations('common');
@@ -1516,7 +1523,9 @@ export default function PromptsPage() {
setAllPrompts(prompts);
setVisibility(page.visibility);
setPositions(page.positions);
- if (page.volumesDegraded) {
+ // A read-only workspace's volumes are refused (402): their columns
+ // stay empty, without a warning that something broke.
+ if (page.volumesDegraded && !isLocked) {
toast.warning('Volume data is temporarily unavailable — showing prompts without it.');
}
if (page.visibilityDegraded) toast.warning(tPrompts('visibilityDegraded'));
@@ -1529,7 +1538,7 @@ export default function PromptsPage() {
if (!isCancelled?.()) setLoading(false);
}
},
- [activeBrandId, range, regionFilter, tPrompts],
+ [activeBrandId, range, regionFilter, tPrompts, isLocked],
);
useEffect(() => {
@@ -1688,12 +1697,17 @@ export default function PromptsPage() {
const started = await startPromptVolumeAnalysis(activeBrandId, force);
if (!started.ok) {
- toast.error(
- volumeErrorMessage(
- started.code,
- 'Volume analysis could not be started. Please try again.',
- ),
- );
+ // The plan ended meanwhile: the upgrade dialog, not "not in your plan".
+ if (started.code === 'subscription_inactive') {
+ failureToast('subscription');
+ } else {
+ toast.error(
+ volumeErrorMessage(
+ started.code,
+ 'Volume analysis could not be started. Please try again.',
+ ),
+ );
+ }
return;
}
@@ -1738,7 +1752,9 @@ export default function PromptsPage() {
}
};
- const handleAnalyzeNew = () => runVolumeAnalysis(false);
+ const handleAnalyzeNew = guard(() => runVolumeAnalysis(false), {
+ action: tActions('analyzePrompts'),
+ });
const handleRefreshVolumes = async () => {
if (!activeBrandId || volumes.length === 0) return;
@@ -1747,9 +1763,13 @@ export default function PromptsPage() {
try {
const result = await refreshVolumes(activeBrandId);
if (!result.ok) {
- toast.error(
- volumeErrorMessage(result.code, 'Volumes could not be refreshed. Please try again.'),
- );
+ if (result.code === 'subscription_inactive') {
+ failureToast('subscription');
+ } else {
+ toast.error(
+ volumeErrorMessage(result.code, 'Volumes could not be refreshed. Please try again.'),
+ );
+ }
return;
}
if (result.remaining !== undefined && quota) {
@@ -1769,7 +1789,9 @@ export default function PromptsPage() {
}
};
- const handleReanalyzeAll = () => runVolumeAnalysis(true);
+ const handleReanalyzeAll = guard(() => runVolumeAnalysis(true), {
+ action: tActions('analyzePrompts'),
+ });
// Each volume as an estimate: a range and how sure it is (PROMPT-013).
const estimateByPromptId = useMemo(() => {
@@ -1912,12 +1934,7 @@ export default function PromptsPage() {
them in this row's flex and gap. */}
<div ref={setHeaderActions} className="contents" />
{tab === 'all' && canManage && (
- <Button
- type="button"
- size="sm"
- className="gap-2"
- onClick={() => setAddPromptOpen(true)}
- >
+ <Button type="button" size="sm" className="gap-2" onClick={openAddPrompt}>
<Plus className="h-4 w-4" />
Add prompt
</Button>
@@ -2121,8 +2138,14 @@ export default function PromptsPage() {
regionFilter={regionFilter}
statusFilter={statusFilter}
onStatusFilterChange={setStatusFilter}
- onAddPrompt={canManage ? () => setAddPromptOpen(true) : undefined}
- onEditPrompt={canManage ? setEditingPrompt : undefined}
+ onAddPrompt={canManage ? openAddPrompt : undefined}
+ onEditPrompt={
+ canManage
+ ? guard((prompt: Prompt) => setEditingPrompt(prompt), {
+ action: tActions('editPrompts'),
+ })
+ : undefined
+ }
onChanged={reloadAfterChange}
/>
</>
@@ -2172,7 +2195,7 @@ export default function PromptsPage() {
{volumes.length > 0 && (
<>
<Button
- onClick={handleRefreshVolumes}
+ onClick={guard(handleRefreshVolumes, { action: tActions('refreshVolumes') })}
disabled={refreshing || analyzing || loading || quotaExhausted}
size="sm"
variant="outline"
@@ -2842,6 +2865,10 @@ function AllPromptsTab({
const tColumns = useTranslations('prompts.columns');
const tTips = useTranslations('prompts.columns.tips');
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 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
// delete for prompts — a delete drops their history — so the delay is the
@@ -3643,10 +3670,18 @@ function AllPromptsTab({
}))
}
deleting={showDeleteProgress ? deleteProgress : null}
- onPause={() => void setActiveFor(selectedPrompts, false)}
- onResume={() => void setActiveFor(selectedPrompts, true)}
- onSuggestContent={() => void suggestFor(selectedPrompts)}
- onDelete={() => setConfirmDelete(selectedPrompts)}
+ onPause={guard(() => void setActiveFor(selectedPrompts, false), {
+ action: tActions('pausePrompts'),
+ })}
+ onResume={guard(() => void setActiveFor(selectedPrompts, true), {
+ action: tActions('resumePrompts'),
+ })}
+ onSuggestContent={guard(() => void suggestFor(selectedPrompts), {
+ action: tActions('suggestContent'),
+ })}
+ onDelete={guard(() => setConfirmDelete(selectedPrompts), {
+ action: tActions('deletePrompts'),
+ })}
onClear={() => setSelectedIds(new Set())}
/>
)}
@@ -3824,7 +3859,13 @@ function AllPromptsTab({
<div className="inline-flex flex-col items-center gap-0.5">
<WorkStatusBadge
status={statusOf(p)}
- onChange={onEditPrompt ? (s) => handleStatusChange(p, s) : undefined}
+ onChange={
+ onEditPrompt
+ ? guard((s: PromptWorkStatus | null) => handleStatusChange(p, s), {
+ action: tActions('setWorkStatus'),
+ })
+ : undefined
+ }
/>
{p.targetUrlCount > 0 && (
<span
@@ -3956,24 +3997,32 @@ function AllPromptsTab({
prompt={p}
brandId={activeBrandId}
onEdit={() => onEditPrompt(p)}
- onToggleActive={() => void toggleActive(p)}
+ onToggleActive={guard(() => void toggleActive(p), {
+ action: tActions(p.isActive ? 'pausePrompts' : 'resumePrompts'),
+ })}
onImprove={() => openPositionsPanel(p.id, 'improve')}
- onSuggestContent={() => void suggestContent(p)}
+ onSuggestContent={guard(() => void suggestContent(p), {
+ action: tActions('suggestContent'),
+ })}
onOpenSuggestion={openOpportunity}
suggesting={suggestingIds.has(p.id)}
suggestDisabledReason={
suggestDisabledReason ??
(bulkSuggesting ? 'Wait for the selected prompts' : null)
}
- onCreateContent={() =>
- setContentPreset({
- kind: 'prompt',
- id: p.id,
- text: p.text,
- method: 'create',
- })
- }
- onDelete={() => setConfirmDelete([p])}
+ onCreateContent={guard(
+ () =>
+ setContentPreset({
+ kind: 'prompt',
+ id: p.id,
+ text: p.text,
+ method: 'create',
+ }),
+ { action: tActions('createContent') },
+ )}
+ onDelete={guard(() => setConfirmDelete([p]), {
+ action: tActions('deletePrompts'),
+ })}
/>
</TableCell>
)}
diff --git a/web/src/components/prompts/prompt-content-step.tsx b/web/src/components/prompts/prompt-content-step.tsx
index 00dd92562..01264d13f 100644
--- a/web/src/components/prompts/prompt-content-step.tsx
+++ b/web/src/components/prompts/prompt-content-step.tsx
@@ -6,6 +6,7 @@ import { FilePen, FilePlus, FileText, Loader2 } from 'lucide-react';
import { useRouter } from '@/i18n/navigation';
import { Button } from '@/components/ui/button';
import type { DialogPreset } from '@/components/content/new-content-dialog';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { getDraftForPrompt } from '@/lib/actions/content-drafts';
import { contentEditorPath } from '@/lib/content/drafts';
import { contentStep } from '@/lib/prompt-content';
@@ -39,6 +40,10 @@ export function PromptContentStep({
}) {
const t = useTranslations('prompts.content');
const router = useRouter();
+ // A read-only workspace (plan not active): Create or Optimize content opens
+ // the upgrade dialog instead; Open draft stays open.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const step = contentStep(summary);
const wanted = step !== null;
// The draft lookup for this prompt: undefined while it runs.
@@ -106,7 +111,9 @@ export function PromptContentStep({
size="sm"
className="shrink-0 gap-1.5"
disabled={draftId === undefined}
- onClick={start}
+ onClick={guard(start, {
+ action: tActions(step.kind === 'create' ? 'createContent' : 'optimizeContent'),
+ })}
>
{draftId === undefined ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
diff --git a/web/src/components/prompts/prompt-improve-tab.test.tsx b/web/src/components/prompts/prompt-improve-tab.test.tsx
index 7930b40bb..7ed7ae167 100644
--- a/web/src/components/prompts/prompt-improve-tab.test.tsx
+++ b/web/src/components/prompts/prompt-improve-tab.test.tsx
@@ -11,6 +11,7 @@ import { ImproveTab, useImprove, type ImproveController } from './prompt-improve
const actions = vi.hoisted(() => ({
getImproveSuggestions: vi.fn(),
generateImproveSuggestions: vi.fn(),
+ sendImproveToActionCenter: vi.fn(),
}));
vi.mock('@/lib/actions/prompt-improve', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/actions/prompt-improve')>()),
@@ -195,7 +196,11 @@ describe('useImprove on a read-only workspace (plan not active)', () => {
}
const mount = () =>
act(async () => {
- root.render(<Probe onImprove={keep} />);
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <Probe onImprove={keep} />
+ </NextIntlClientProvider>,
+ );
});
beforeEach(() => {
@@ -221,6 +226,11 @@ describe('useImprove on a read-only workspace (plan not active)', () => {
expect(improve.set).toBeNull();
await act(async () => improve.generate());
expect(gate.openUpgrade).toHaveBeenCalledTimes(1);
+ expect(gate.openUpgrade).toHaveBeenCalledWith('Improving a prompt needs a plan');
expect(actions.generateImproveSuggestions).not.toHaveBeenCalled();
+ // Send Actions writes to the Action Center: the dialog too, and nothing sent.
+ await act(async () => improve.send());
+ expect(gate.openUpgrade).toHaveBeenLastCalledWith('Sending actions needs a plan');
+ expect(actions.sendImproveToActionCenter).not.toHaveBeenCalled();
});
});
diff --git a/web/src/components/prompts/prompt-improve-tab.tsx b/web/src/components/prompts/prompt-improve-tab.tsx
index d4c584654..ca68551f8 100644
--- a/web/src/components/prompts/prompt-improve-tab.tsx
+++ b/web/src/components/prompts/prompt-improve-tab.tsx
@@ -104,8 +104,10 @@ export function useImprove({
}): ImproveController {
const locked = planId !== null && !hasFeature(PLANS[planId], 'prompt_improve');
// A read-only workspace (plan not active): the set isn't read (the API
- // refuses it), the tab opens empty, and Generate opens the upgrade dialog.
+ // refuses it), the tab opens empty, and Generate (Regenerate) and Send
+ // Actions open the upgrade dialog.
const { isLocked: readOnly, openUpgrade } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const key = promptId ? `${promptId}|${JSON.stringify(range)}` : '';
const [state, setState] = useState<{
key: string;
@@ -184,19 +186,23 @@ export function useImprove({
const generate = useCallback(() => {
if (!promptId) return;
if (readOnly) {
- openUpgrade();
+ openUpgrade(tActions('improvePrompt'));
return;
}
const forKey = keyRef.current;
setState((s) => ({ ...s, key: forKey, status: 'generating', error: null }));
generateImproveSuggestions(promptId, range).then((r) => apply(forKey, 'generate', r));
- }, [promptId, range, apply, readOnly, openUpgrade]);
+ }, [promptId, range, apply, readOnly, openUpgrade, tActions]);
const current = state.key === key ? state : null;
const status: Status = locked ? 'locked' : readOnly ? 'ready' : (current?.status ?? 'idle');
const set = readOnly ? null : (current?.set ?? null);
const send = useCallback(() => {
+ if (readOnly) {
+ openUpgrade(tActions('sendAction'));
+ return;
+ }
if (!promptId || !state.set || sending) return;
const selected = drafts.filter((d) => d.checked && !d.removed && d.title.trim());
if (selected.length === 0) return;
@@ -233,7 +239,7 @@ export function useImprove({
);
})
.finally(() => setSending(false));
- }, [promptId, range, drafts, sending, state.set]);
+ }, [promptId, range, drafts, sending, state.set, readOnly, openUpgrade, tActions]);
const dirty = useMemo(() => !!set && hasUnsentEdits(drafts, set.suggestions), [drafts, set]);
diff --git a/web/src/components/prompts/prompt-positions-sheet.test.tsx b/web/src/components/prompts/prompt-positions-sheet.test.tsx
index cd8fa88ac..b37781d08 100644
--- a/web/src/components/prompts/prompt-positions-sheet.test.tsx
+++ b/web/src/components/prompts/prompt-positions-sheet.test.tsx
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../messages/en.json';
import { summarizePositions, type PositionAnswer } from '@/lib/prompt-positions';
import type { PromptPositionsData } from '@/lib/actions/prompt-positions';
+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
/**
* The positions panel over a week: its cards carry the table's answer,
@@ -112,6 +113,9 @@ function unnamed(): PromptPositionsData {
let container: HTMLDivElement;
let root: Root;
+// The workspace's plan: active unless a test says it's read-only.
+let isLocked = false;
+const openUpgrade = vi.fn();
async function open(
preset: '7d' | '24h' = '7d',
@@ -120,21 +124,27 @@ async function open(
await act(async () =>
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <PromptPositionsSheet
- prompt={{ id: 'p1', text: 'Best coffee subscription?' }}
- range={{ preset, from: '', to: '' }}
- window={WEEK}
- onRangeChange={() => {}}
- region=""
- onClose={() => {}}
- {...more}
- />
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <PromptPositionsSheet
+ prompt={{ id: 'p1', text: 'Best coffee subscription?' }}
+ range={{ preset, from: '', to: '' }}
+ window={WEEK}
+ onRangeChange={() => {}}
+ region=""
+ onClose={() => {}}
+ {...more}
+ />
+ </UpgradeDialogContext.Provider>
</NextIntlClientProvider>,
),
);
}
beforeEach(() => {
+ isLocked = false;
+ openUpgrade.mockClear();
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
@@ -165,6 +175,20 @@ describe('PromptPositionsSheet', () => {
});
});
+ it('opens the upgrade dialog from Create content on a read-only workspace', async () => {
+ isLocked = true;
+ getPromptPositions.mockResolvedValue(unnamed());
+ const onStartContent = vi.fn();
+ await open('7d', { initialTab: 'improve', brandId: 'b1', onStartContent });
+ await act(async () => {});
+ const create = [...document.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Create content',
+ )!;
+ await act(async () => create.click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Creating content needs a plan');
+ expect(onStartContent).not.toHaveBeenCalled();
+ });
+
it('offers no content step where the page gives no way to start', async () => {
getPromptPositions.mockResolvedValue(unnamed());
await open('7d', { initialTab: 'improve' });
diff --git a/web/src/lib/actions/volumes.test.ts b/web/src/lib/actions/volumes.test.ts
new file mode 100644
index 000000000..19aa4c156
--- /dev/null
+++ b/web/src/lib/actions/volumes.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The volume runs' failure codes: a workspace whose plan isn't active is told
+ * apart from a plan without volume analysis, so the page can open the
+ * upgrade dialog rather than say the plan lacks it.
+ */
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({
+ auth: { getSession: async () => ({ data: { session: { access_token: 'token' } } }) },
+ }),
+}));
+
+const { startPromptVolumeAnalysis, refreshVolumes } = await import('./volumes');
+
+const answer = (status: number, body: Record<string, unknown>) =>
+ vi.fn(async () => new Response(JSON.stringify(body), { status }));
+
+beforeEach(() => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('the volume runs’ failure codes', () => {
+ it('reads the server’s 402 subscription_inactive as subscription_inactive, not plan_limit', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ answer(402, { success: false, error: 'plan_limit', code: 'subscription_inactive' }),
+ );
+ expect(await startPromptVolumeAnalysis('b1')).toEqual({
+ ok: false,
+ code: 'subscription_inactive',
+ });
+ expect(await refreshVolumes('b1')).toEqual({ ok: false, code: 'subscription_inactive' });
+ });
+
+ it('reads plan-guard’s 402 for no active subscription the same way', async () => {
+ vi.stubGlobal('fetch', answer(402, { success: false, error: 'plan_limit', message: '…' }));
+ expect(await startPromptVolumeAnalysis('b1')).toEqual({
+ ok: false,
+ code: 'subscription_inactive',
+ });
+ });
+
+ it('keeps plan_limit for a plan without the feature, and quota_exceeded', async () => {
+ vi.stubGlobal('fetch', answer(403, { success: false, error: 'plan_limit' }));
+ expect(await startPromptVolumeAnalysis('b1')).toEqual({ ok: false, code: 'plan_limit' });
+ vi.stubGlobal('fetch', answer(429, { error: 'quota_exceeded' }));
+ expect(await refreshVolumes('b1')).toEqual({ ok: false, code: 'quota_exceeded' });
+ });
+});
diff --git a/web/src/lib/actions/volumes.ts b/web/src/lib/actions/volumes.ts
index 954eedfa6..78a23f284 100644
--- a/web/src/lib/actions/volumes.ts
+++ b/web/src/lib/actions/volumes.ts
@@ -58,7 +58,7 @@ export async function analyzePromptVolume(
* rather than the reason. A small closed set of codes survives both, and the
* wording stays in the UI where it can be written for a person.
*/
-export type VolumeErrorCode = 'quota_exceeded' | 'plan_limit' | 'failed';
+export type VolumeErrorCode = 'quota_exceeded' | 'plan_limit' | 'subscription_inactive' | 'failed';
export type StartVolumeAnalysisResult =
| { ok: true; started: number; running: boolean; remaining?: number }
@@ -81,7 +81,12 @@ export interface VolumeAnalysisStatus {
}
async function toErrorCode(res: Response): Promise<VolumeErrorCode> {
- const body: { error?: string } = await res.json().catch(() => ({}));
+ const body: { error?: string; code?: string } = await res.json().catch(() => ({}));
+ // The workspace's plan isn't active (an ended trial, a canceled plan): the
+ // server's 402 subscription_inactive, or plan-guard's 402 for no active
+ // subscription. Its body says plan_limit too, but nothing is missing from
+ // the plan: there is no plan.
+ if (body.code === 'subscription_inactive' || res.status === 402) return 'subscription_inactive';
if (body.error === 'quota_exceeded') return 'quota_exceeded';
if (body.error === 'plan_limit') return 'plan_limit';
console.error('Volume analysis request failed', res.status, body.error);