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(prompts): count only active prompt locations toward the plan limit (#1034)

Cihana8464458fab1
diff --git a/supabase/migrations/00128_count_active_prompt_locations.sql b/supabase/migrations/00128_count_active_prompt_locations.sql
new file mode 100644
index 000000000..9b92f4e52
--- /dev/null
+++ b/supabase/migrations/00128_count_active_prompt_locations.sql
@@ -0,0 +1,33 @@
+-- Only active prompts count toward the plan's prompt-location limit.
+--
+-- The tracking worker only runs active prompts, so a paused prompt costs
+-- nothing; counting it made users pay plan room for prompts that don't run.
+-- Paused prompts now free their locations. The other side of that rule lives
+-- in the app: resuming a paused prompt counts as adding its locations, so it
+-- needs free room like any new prompt (web/src/lib/prompt-locations.ts),
+-- which closes the "pause, add new ones, resume the old ones" way past the
+-- limit.
+--
+-- Same shape as 00070, plus `p.is_active`: one row per brand, a prompt's
+-- locations are `greatest(coalesce(array_length(regions,1),0),1)`, mirrored
+-- by promptLocationCount in web/src/lib/prompt-locations.ts.
+create or replace function public.org_prompt_location_usage(p_organization_id uuid)
+returns table (brand_id uuid, locations bigint)
+language sql
+stable
+set search_path to 'public'
+as $$
+ select b.id, sum(greatest(coalesce(array_length(p.regions, 1), 0), 1))::bigint
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ join public.brands b on b.id = ps.brand_id
+ where b.organization_id = p_organization_id
+ and p.is_active
+ group by b.id;
+$$;
+
+revoke all on function public.org_prompt_location_usage(uuid) from public;
+grant execute on function public.org_prompt_location_usage(uuid) to authenticated, service_role;
+
+comment on function public.org_prompt_location_usage(uuid) is
+ 'Active prompt locations per brand for one org (#691, 00128) — the plan-quota unit, one per region entry per active prompt, minimum one; paused prompts don''t count. Security invoker: RLS scopes it to the caller''s org.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 145f8d92f..60d8822c6 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -14700,3 +14700,40 @@ grant execute on function public.content_opportunity_aggregates(
timestamptz
) to authenticated;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00128_count_active_prompt_locations.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Only active prompts count toward the plan's prompt-location limit.
+--
+-- The tracking worker only runs active prompts, so a paused prompt costs
+-- nothing; counting it made users pay plan room for prompts that don't run.
+-- Paused prompts now free their locations. The other side of that rule lives
+-- in the app: resuming a paused prompt counts as adding its locations, so it
+-- needs free room like any new prompt (web/src/lib/prompt-locations.ts),
+-- which closes the "pause, add new ones, resume the old ones" way past the
+-- limit.
+--
+-- Same shape as 00070, plus `p.is_active`: one row per brand, a prompt's
+-- locations are `greatest(coalesce(array_length(regions,1),0),1)`, mirrored
+-- by promptLocationCount in web/src/lib/prompt-locations.ts.
+create or replace function public.org_prompt_location_usage(p_organization_id uuid)
+returns table (brand_id uuid, locations bigint)
+language sql
+stable
+set search_path to 'public'
+as $$
+ select b.id, sum(greatest(coalesce(array_length(p.regions, 1), 0), 1))::bigint
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ join public.brands b on b.id = ps.brand_id
+ where b.organization_id = p_organization_id
+ and p.is_active
+ group by b.id;
+$$;
+
+revoke all on function public.org_prompt_location_usage(uuid) from public;
+grant execute on function public.org_prompt_location_usage(uuid) to authenticated, service_role;
+
+comment on function public.org_prompt_location_usage(uuid) is
+ 'Active prompt locations per brand for one org (#691, 00128) — the plan-quota unit, one per region entry per active prompt, minimum one; paused prompts don''t count. Security invoker: RLS scopes it to the caller''s org.';
+
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 29c21da47..690326c7c 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
@@ -7,6 +7,7 @@ import {
getPromptSets,
savePromptSet,
addPromptToSet,
+ setPromptActive,
updatePrompt,
updatePromptLocations,
bulkUpdatePromptLocations,
@@ -375,13 +376,27 @@ export default function PromptsPage() {
async (prompt: Prompt) => {
updatePromptLocal(prompt.id, { isActive: !prompt.isActive });
try {
- await updatePrompt(prompt.id, { isActive: !prompt.isActive });
+ const result = await setPromptActive(prompt.id, !prompt.isActive);
+ if ('error' in result) {
+ updatePromptLocal(prompt.id, { isActive: prompt.isActive });
+ // Resuming needs a free slot on the plan; the message says how many.
+ toast.error(
+ result.code === 'plan_limit' ? 'Not enough room to resume' : 'Failed to update prompt',
+ result.code === 'plan_limit' ? { description: result.error } : undefined,
+ );
+ return;
+ }
+ // Pausing frees room and resuming takes it, so the location pickers
+ // need the new usage figure. A failed refresh keeps the last one
+ // rather than leaving the pickers uncapped.
+ const quota = await getLocationQuota(brandId).catch(() => null);
+ if (quota) setLocationQuota(quota);
} catch {
updatePromptLocal(prompt.id, { isActive: prompt.isActive });
toast.error('Failed to update prompt');
}
},
- [updatePromptLocal],
+ [brandId, updatePromptLocal],
);
const handleEditPrompt = useCallback(
@@ -993,10 +1008,14 @@ export default function PromptsPage() {
onPlatformsChange={(platforms) => handlePlatformsChange(prompt.id, platforms)}
onRegionsChange={(regions) => handleRegionsChange(prompt.id, regions)}
maxLocations={
+ // A paused prompt's locations aren't in `used`; its cap is
+ // what it could take back when resumed.
locationQuota && locationQuota.maxPrompts !== -1
? Math.max(
prompt.regions.length,
- locationQuota.maxPrompts - locationQuota.used + prompt.regions.length,
+ locationQuota.maxPrompts -
+ locationQuota.used +
+ (prompt.isActive ? prompt.regions.length : 0),
)
: null
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 566456ea9..6bbb3dbcf 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -1572,14 +1572,14 @@ export default function InsightsPage() {
/>
<KpiCard
title="Tracked Prompts"
- tooltip="Distinct prompts that produced tracked results in the selected period and filters. The quota below is current usage across your organization, counting one per location each prompt targets — it does not change with the date range."
+ tooltip="Distinct prompts that produced tracked results in the selected period and filters. The quota below is current usage across your organization, counting one per location each active prompt targets (paused prompts don't count) — it does not change with the date range."
icon={Layers}
value={trackedPrompts?.activeInPeriod ?? 0}
sub={
trackedPrompts && trackedPrompts.quotaLimit !== -1 ? (
<>
<span className="tabular-nums">
- {trackedPrompts.quotaUsed} / {trackedPrompts.quotaLimit} prompt locations
+ {trackedPrompts.quotaUsed} / {trackedPrompts.quotaLimit} active locations
</span>
{trackedPrompts.quotaUsed >= trackedPrompts.quotaLimit * 0.9 && (
<button
@@ -1595,7 +1595,7 @@ export default function InsightsPage() {
)}
</>
) : (
- `${trackedPrompts?.quotaUsed ?? 0} prompt locations tracked`
+ `${trackedPrompts?.quotaUsed ?? 0} active prompt locations`
)
}
onClick={() => router.push('/dashboard/prompts')}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 6834f2f1c..30ea2c884 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -94,6 +94,7 @@ import {
deletePrompt,
getPromptsPageData,
importPrompts,
+ setPromptActive,
updatePrompt,
type LocationQuota,
} from '@/lib/actions/prompt';
@@ -536,9 +537,9 @@ function brandLocation(region: string | undefined, state: string | undefined): s
// ─── Tracked prompt limit (PROMPT-009) ────────────────────────────────────────
const PROMPT_USAGE_TOOLTIP =
- 'Your plan limits tracked prompt locations across every brand in your organization. ' +
- 'Each prompt counts once per location it targets, and paused prompts count too. ' +
- 'Remove prompts or locations to free slots.';
+ 'Your plan limits active prompt locations across every brand in your organization. ' +
+ "Each prompt counts once per location it targets; paused prompts don't count, and " +
+ 'resuming one needs a free slot. Pause or remove prompts or locations to free slots.';
/**
* "187 / 200 prompt locations · Growth plan" with a thin progress bar. The
@@ -551,7 +552,7 @@ function PromptUsageMeter({ quota }: { quota: LocationQuota }) {
if (usage.state === 'unlimited') {
return (
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
- <span className="tabular-nums">{quota.used}</span> prompt locations tracked · Unlimited
+ <span className="tabular-nums">{quota.used}</span> active prompt locations · Unlimited
<InfoTip content={PROMPT_USAGE_TOOLTIP} />
</span>
);
@@ -576,12 +577,12 @@ function PromptUsageMeter({ quota }: { quota: LocationQuota }) {
<span className={cn('font-medium tabular-nums', tone.text)}>
{quota.used} / {quota.maxPrompts}
</span>{' '}
- prompt locations · {quota.planName} plan
+ active prompt locations · {quota.planName} plan
</span>
<div
className="h-1.5 w-24 overflow-hidden rounded-full bg-muted"
role="progressbar"
- aria-label="Tracked prompt locations used"
+ aria-label="Active prompt locations used"
aria-valuemin={0}
aria-valuemax={quota.maxPrompts}
aria-valuenow={Math.min(quota.used, quota.maxPrompts)}
@@ -815,10 +816,10 @@ function AddPromptDialog({
You&apos;ve reached your prompt limit
</p>
<p className="text-red-800/80 dark:text-red-300/80">
- Your {locationQuota.planName} plan tracks up to {locationQuota.maxPrompts} prompt
- locations and {locationQuota.used} are in use. Each prompt counts once per
- location it targets, and paused prompts count too. Remove prompts or locations to
- free a slot, or{' '}
+ Your {locationQuota.planName} plan tracks up to {locationQuota.maxPrompts} active
+ prompt locations and {locationQuota.used} are in use. Each prompt counts once per
+ location it targets; paused prompts don&apos;t count. Pause or remove prompts or
+ locations to free a slot, or{' '}
{locationQuota.planId === 'starter' ? 'upgrade your plan' : 'contact us'} to track
more.
</p>
@@ -1033,19 +1034,35 @@ function EditPromptDialog({
if (!prompt || !text.trim() || (scrapers.length === 0 && models.length === 0) || busy) return;
setSaving(true);
setError(null);
+ let activeChanged = false;
try {
+ // Pausing or resuming goes first and on its own: resuming needs a free
+ // slot on the plan, and a refusal has to reach the dialog as a message.
+ if (isActive !== prompt.isActive) {
+ const result = await setPromptActive(prompt.id, isActive);
+ if ('error' in result) {
+ setError(
+ result.code === 'plan_limit'
+ ? result.error
+ : 'Failed to update prompt. Please try again.',
+ );
+ return;
+ }
+ activeChanged = true;
+ }
await updatePrompt(prompt.id, {
text: text.trim(),
category: category || undefined,
platforms: scrapers,
models,
- isActive,
});
onClose();
toast.success('Prompt updated.');
onChanged();
} catch {
setError('Failed to update prompt. Please try again.');
+ // The pause or resume already went through; show it in the table.
+ if (activeChanged) onChanged();
} finally {
setSaving(false);
}
@@ -2551,7 +2568,17 @@ function AllPromptsTab({
const toggleActive = useCallback(
async (prompt: Prompt) => {
try {
- await updatePrompt(prompt.id, { isActive: !prompt.isActive });
+ const result = await setPromptActive(prompt.id, !prompt.isActive);
+ if ('error' in result) {
+ // Resuming needs a free slot on the plan; the message says how many.
+ toast.error(
+ result.code === 'plan_limit'
+ ? 'Not enough room to resume'
+ : 'Failed to update the prompt.',
+ { description: result.code === 'plan_limit' ? result.error : prompt.text },
+ );
+ return;
+ }
toast.success(prompt.isActive ? 'Tracking paused' : 'Tracking resumed', {
description: prompt.text,
});
diff --git a/web/src/lib/actions/prompt.test.ts b/web/src/lib/actions/prompt.test.ts
new file mode 100644
index 000000000..0a49273e6
--- /dev/null
+++ b/web/src/lib/actions/prompt.test.ts
@@ -0,0 +1,170 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { PLANS, type Plan } from '@/config/plans';
+
+/**
+ * setPromptActive meters resuming like adding (00128): only active prompts
+ * count toward the plan, so a paused prompt's locations come back when it is
+ * resumed. A refusal comes back as a value and nothing is written; pausing is
+ * always allowed. Location edits on a paused prompt aren't metered until then.
+ */
+
+let promptRow: { regions: string[]; is_active: boolean } | null;
+let usedLocations = 0;
+let usageFails = false;
+let plan: Plan;
+let writes: unknown[] = [];
+
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));
+vi.mock('@/lib/actions/volumes', () => ({ getPromptVolumes: vi.fn() }));
+vi.mock('@/lib/actions/tracking', () => ({ getPromptVisibilitySummaries: vi.fn() }));
+
+vi.mock('@/lib/guards/plan-guard', () => ({
+ getOrgPlan: vi.fn(async () => plan),
+}));
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ rpc: async () =>
+ usageFails
+ ? { data: null, error: { message: 'rpc failed' } }
+ : { data: [{ brand_id: 'b1', locations: usedLocations }], error: null },
+ from: () => ({
+ select: () => ({
+ eq: () => ({
+ single: async () =>
+ promptRow
+ ? {
+ data: { ...promptRow, prompt_sets: { brands: { organization_id: 'org-1' } } },
+ error: null,
+ }
+ : { data: null, error: { message: 'no rows' } },
+ }),
+ }),
+ update: (payload: Record<string, unknown>) => {
+ writes.push(payload);
+ return {
+ eq: () => ({
+ select: () => ({
+ single: async () => ({
+ data: { id: 'p1', ...promptRow, ...payload },
+ error: null,
+ }),
+ }),
+ }),
+ };
+ },
+ }),
+ })),
+}));
+
+const { setPromptActive, updatePromptLocations } = await import('./prompt');
+
+const capped = (maxPrompts: number): Plan => ({
+ ...PLANS.starter,
+ limits: { ...PLANS.starter.limits, maxPrompts },
+});
+
+describe('setPromptActive', () => {
+ beforeEach(() => {
+ writes = [];
+ usageFails = false;
+ plan = capped(50);
+ });
+
+ it('refuses to resume a prompt whose locations no longer fit, and writes nothing', async () => {
+ // Paused 3-location prompt, and its room was filled while it was paused.
+ promptRow = { regions: ['US', 'DE', 'TR'], is_active: false };
+ usedLocations = 49;
+
+ const result = await setPromptActive('p1', true);
+
+ expect(result).toMatchObject({ code: 'plan_limit' });
+ expect('error' in result && result.error).toContain('49 in place + 3 added');
+ expect(writes).toEqual([]);
+ });
+
+ it('resumes when the plan has room for every location', async () => {
+ promptRow = { regions: ['US', 'DE', 'TR'], is_active: false };
+ usedLocations = 47;
+
+ const result = await setPromptActive('p1', true);
+
+ expect(result).toMatchObject({ prompt: { id: 'p1', isActive: true } });
+ expect(writes).toEqual([{ is_active: true }]);
+ });
+
+ it('always lets a prompt be paused, even over the limit', async () => {
+ promptRow = { regions: ['US'], is_active: true };
+ usedLocations = 60;
+
+ const result = await setPromptActive('p1', false);
+
+ expect(result).toMatchObject({ prompt: { isActive: false } });
+ expect(writes).toEqual([{ is_active: false }]);
+ });
+
+ it('lets a prompt that is already active be "resumed" at the limit', async () => {
+ promptRow = { regions: ['US'], is_active: true };
+ usedLocations = 50;
+
+ const result = await setPromptActive('p1', true);
+
+ expect(result).toMatchObject({ prompt: { isActive: true } });
+ });
+
+ it('never limits unlimited plans', async () => {
+ plan = capped(-1);
+ promptRow = { regions: ['US', 'DE'], is_active: false };
+ usedLocations = 5000;
+
+ const result = await setPromptActive('p1', true);
+
+ expect(result).toMatchObject({ prompt: { isActive: true } });
+ });
+
+ it('returns an error and writes nothing for a prompt it cannot see', async () => {
+ promptRow = null;
+
+ const result = await setPromptActive('p1', true);
+
+ expect(result).toEqual({ error: 'Prompt not found' });
+ expect(writes).toEqual([]);
+ });
+
+ it('returns a failed limit check as a value instead of throwing', async () => {
+ promptRow = { regions: ['US'], is_active: false };
+ usageFails = true;
+
+ const result = await setPromptActive('p1', true);
+
+ expect(result).toEqual({ error: "Couldn't check your plan's prompt limit. Please try again." });
+ expect(writes).toEqual([]);
+ });
+});
+
+describe('updatePromptLocations on paused prompts', () => {
+ beforeEach(() => {
+ writes = [];
+ usageFails = false;
+ plan = capped(50);
+ usedLocations = 50;
+ });
+
+ it('lets a paused prompt gain locations at the limit; they count when it is resumed', async () => {
+ promptRow = { regions: ['US'], is_active: false };
+
+ const result = await updatePromptLocations('p1', ['US', 'DE', 'TR']);
+
+ expect(result).toMatchObject({ prompt: { regions: ['US', 'DE', 'TR'] } });
+ expect(writes).toEqual([{ regions: ['US', 'DE', 'TR'] }]);
+ });
+
+ it('still meters an active prompt gaining locations', async () => {
+ promptRow = { regions: ['US'], is_active: true };
+
+ const result = await updatePromptLocations('p1', ['US', 'DE']);
+
+ expect(result).toMatchObject({ code: 'plan_limit' });
+ expect(writes).toEqual([]);
+ });
+});
diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.ts
index e7220245b..56daaa51b 100644
--- a/web/src/lib/actions/prompt.ts
+++ b/web/src/lib/actions/prompt.ts
@@ -5,6 +5,7 @@ import { revalidatePath } from 'next/cache';
import type { PromptSet, Prompt, AIPlatform, PromptVolume } from '@/types';
import { getOrgPlan } from '@/lib/guards/plan-guard';
import {
+ activationDelta,
getOrgLocationUsage,
locationLimitMessage,
planBulkLocationChange,
@@ -197,15 +198,17 @@ export async function savePromptSet(input: SavePromptSetInput): Promise<SaveProm
);
const plan = await getOrgPlan(orgId);
- // Count existing tracked locations for this org, excluding this brand's own
+ // Count existing active locations for this org, excluding this brand's own
// (its whole set is replaced below, so a re-save doesn't compete with
// itself). Every prompt saved here targets exactly one location — the
- // brand's region — so the request adds one location per prompt. The cap is
- // inclusive: landing exactly on maxPrompts is allowed (onboarding generates
- // 5 per topic, so hitting the cap there is a normal, recoverable state).
+ // brand's region — so the request adds one location per active prompt;
+ // paused ones take no room (00128). The cap is inclusive: landing exactly
+ // on maxPrompts is allowed (onboarding generates 5 per topic, so hitting
+ // the cap there is a normal, recoverable state).
const usage = await getOrgLocationUsage(supabase, orgId);
const otherLocations = usage.total - (usage.byBrand.get(input.brandId) ?? 0);
- const limitError = locationLimitMessage(plan, otherLocations, input.prompts.length);
+ const adding = input.prompts.filter((p) => p.isActive ?? true).length;
+ const limitError = locationLimitMessage(plan, otherLocations, adding);
if (limitError) {
return { code: 'plan_limit', error: limitError };
}
@@ -299,7 +302,6 @@ export async function updatePrompt(
category?: string;
platforms?: string[];
models?: string[];
- isActive?: boolean;
},
): Promise<Prompt> {
const supabase = await createClient();
@@ -307,7 +309,6 @@ export async function updatePrompt(
const payload: Record<string, unknown> = {};
if (updates.text !== undefined) payload.text = updates.text;
if (updates.category !== undefined) payload.category = updates.category || null;
- if (updates.isActive !== undefined) payload.is_active = updates.isActive;
// Both the category and the platform/model branch need context from the
// prompt's row (its brand, org and shopping pref) — one fetch serves them.
@@ -374,9 +375,9 @@ export type UpdatePromptLocationsResult =
/**
* Retarget a prompt's tracking locations (#691).
*
- * Its own action rather than a field on `updatePrompt` because locations are
- * the only prompt edit that meters against the plan, so this is the one that
- * can be REFUSED — and a refusal has to reach the user as a value: every
+ * Its own action rather than a field on `updatePrompt` because locations meter
+ * against the plan (as does resuming, see setPromptActive), so this edit can
+ * be REFUSED — and a refusal has to reach the user as a value: every
* error thrown from a server action reaches production as a meaningless
* digest string (#427).
*
@@ -406,7 +407,7 @@ export async function updatePromptLocations(
const { data: promptRow } = await supabase
.from('prompts')
- .select('regions, prompt_sets!inner(brands!inner(organization_id))')
+ .select('regions, is_active, prompt_sets!inner(brands!inner(organization_id))')
.eq('id', id)
.single();
const orgId = (
@@ -414,8 +415,9 @@ export async function updatePromptLocations(
)?.brands?.organization_id;
if (!orgId) return { error: 'Prompt not found' };
+ // A paused prompt takes no room; its locations are counted when resumed.
const delta = regions.length - promptLocationCount(promptRow?.regions as string[] | null);
- if (delta > 0) {
+ if (delta > 0 && promptRow?.is_active !== false) {
const plan = await getOrgPlan(orgId);
const usage = await getOrgLocationUsage(supabase, orgId);
const limitError = locationLimitMessage(plan, usage.total, delta);
@@ -497,11 +499,11 @@ export async function bulkUpdatePromptLocations(
};
}
- const rows: { id: string; regions: string[]; organizationId: string }[] = [];
+ const rows: { id: string; regions: string[]; isActive: boolean; organizationId: string }[] = [];
for (let i = 0; i < ids.length; i += BULK_LOCATION_READ_CHUNK) {
const { data, error } = await supabase
.from('prompts')
- .select('id, regions, prompt_sets!inner(brands!inner(organization_id))')
+ .select('id, regions, is_active, prompt_sets!inner(brands!inner(organization_id))')
.in('id', ids.slice(i, i + BULK_LOCATION_READ_CHUNK));
if (error) return { error: error.message };
for (const row of data ?? []) {
@@ -511,6 +513,7 @@ export async function bulkUpdatePromptLocations(
rows.push({
id: row.id as string,
regions: (row.regions as string[] | null) ?? [],
+ isActive: row.is_active !== false,
organizationId: orgId,
});
}
@@ -719,6 +722,60 @@ export async function addPromptToBrand(
return { prompt: result.prompt };
}
+export type SetPromptActiveResult = { prompt: Prompt } | { error: string; code?: 'plan_limit' };
+
+/**
+ * Pause or resume one prompt — the only way a prompt's active state changes
+ * after it is created. Pausing frees its locations on the plan (00128).
+ * Resuming brings them all back (activationDelta), so it is measured like
+ * adding them and refused when the plan has no room: pausing prompts,
+ * filling their room with new ones and resuming the old ones can't get past
+ * the limit. Errors come back as values (#427).
+ */
+export async function setPromptActive(
+ id: string,
+ isActive: boolean,
+): Promise<SetPromptActiveResult> {
+ const supabase = await createClient();
+
+ if (isActive) {
+ const { data: row, error } = await supabase
+ .from('prompts')
+ .select('regions, is_active, prompt_sets!inner(brands!inner(organization_id))')
+ .eq('id', id)
+ .single();
+ if (error || !row) return { error: 'Prompt not found' };
+ const adding = activationDelta([
+ { isActive: row.is_active !== false, regions: row.regions as string[] | null },
+ ]);
+ const orgId = (row.prompt_sets as unknown as { brands: { organization_id: string } } | null)
+ ?.brands?.organization_id;
+ if (adding > 0) {
+ if (!orgId) return { error: 'Prompt not found' };
+ let limitError: string | null;
+ try {
+ const [plan, usage] = await Promise.all([
+ getOrgPlan(orgId),
+ getOrgLocationUsage(supabase, orgId),
+ ]);
+ limitError = locationLimitMessage(plan, usage.total, adding);
+ } catch {
+ return { error: "Couldn't check your plan's prompt limit. Please try again." };
+ }
+ if (limitError) return { code: 'plan_limit', error: limitError };
+ }
+ }
+
+ const { data, error } = await supabase
+ .from('prompts')
+ .update({ is_active: isActive })
+ .eq('id', id)
+ .select()
+ .single();
+ if (error || !data) return { error: error?.message ?? 'Failed to update the prompt' };
+ return { prompt: mapPromptRow(data as Record<string, unknown>) };
+}
+
export interface ImportPromptRow {
/** Index in the preview's importable list, echoed back for the imported ones. */
idx: number;
diff --git a/web/src/lib/prompt-locations.test.ts b/web/src/lib/prompt-locations.test.ts
index da17b553b..106998b25 100644
--- a/web/src/lib/prompt-locations.test.ts
+++ b/web/src/lib/prompt-locations.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import {
+ activationDelta,
promptLocationCount,
summarizeLocationRows,
locationLimitMessage,
@@ -74,14 +75,39 @@ describe('locationLimitMessage', () => {
it('spells out the location math in the message', () => {
const msg = locationLimitMessage(starter, 48, 5);
- expect(msg).toContain('50 tracked prompt locations');
+ expect(msg).toContain('50 active prompt locations');
+ expect(msg).toContain("paused prompts don't count");
expect(msg).toContain('53');
expect(msg).toContain('48 in place + 5 added');
- expect(msg).toContain('Remove 3 locations');
+ expect(msg).toContain('Remove or pause 3 locations');
});
it('uses singular grammar for a single excess location', () => {
- expect(locationLimitMessage(starter, 50, 1)).toContain('Remove 1 location ');
+ expect(locationLimitMessage(starter, 50, 1)).toContain('Remove or pause 1 location ');
+ });
+});
+
+describe('activationDelta', () => {
+ it('counts every location of each paused prompt being resumed', () => {
+ expect(
+ activationDelta([
+ { isActive: false, regions: ['US', 'DE'] },
+ { isActive: false, regions: [] },
+ { isActive: true, regions: ['TR'] },
+ ]),
+ ).toBe(3);
+ });
+
+ it('costs nothing to "resume" prompts that are already active', () => {
+ expect(activationDelta([{ isActive: true, regions: ['US', 'DE'] }])).toBe(0);
+ expect(activationDelta([])).toBe(0);
+ });
+
+ it('closes the pause-and-refill loophole', () => {
+ // 50 of 50 active after pausing 10 and adding 10 new ones: resuming
+ // the old ten would need 10 more, which the plan doesn't have.
+ const resuming = Array.from({ length: 10 }, () => ({ isActive: false, regions: ['US'] }));
+ expect(locationLimitMessage(starter, 50, activationDelta(resuming))).not.toBeNull();
});
});
@@ -157,3 +183,18 @@ describe('planBulkLocationChange', () => {
expect(plan.delta).toBe(0);
});
});
+
+describe('planBulkLocationChange on paused prompts', () => {
+ it("writes the change but doesn't count it until the prompt is resumed", () => {
+ const plan = planBulkLocationChange(
+ [
+ { id: 'a', regions: ['US'], isActive: true },
+ { id: 'b', regions: ['US'], isActive: false },
+ ],
+ 'add',
+ ['DE'],
+ );
+ expect(plan.changes.map((c) => c.promptId)).toEqual(['a', 'b']);
+ expect(plan.delta).toBe(1);
+ });
+});
diff --git a/web/src/lib/prompt-locations.ts b/web/src/lib/prompt-locations.ts
index 33d0f4c75..3916b6aa6 100644
--- a/web/src/lib/prompt-locations.ts
+++ b/web/src/lib/prompt-locations.ts
@@ -23,16 +23,16 @@ type ServerSupabase = Awaited<ReturnType<typeof createClient>>;
* or missing region list still runs once (the worker falls back to a single
* untargeted pass), so it costs one.
*
- * Mirrored in SQL by `org_prompt_location_usage` (00070) as
- * `greatest(coalesce(array_length(regions,1),0),1)` — the two definitions
- * must not drift.
+ * Mirrored in SQL by `org_prompt_location_usage` (00070, active prompts only
+ * since 00128) as `greatest(coalesce(array_length(regions,1),0),1)` — the
+ * two definitions must not drift.
*/
export function promptLocationCount(regions: readonly unknown[] | null | undefined): number {
return Array.isArray(regions) && regions.length > 0 ? regions.length : 1;
}
export interface OrgLocationUsage {
- /** Tracked locations across every prompt in the org. */
+ /** Active locations across every prompt in the org; paused prompts don't count (00128). */
total: number;
/**
* Tracked locations per brand — for replace-style saves (savePromptSet
@@ -76,9 +76,21 @@ export async function getOrgLocationUsage(
}
/**
- * The one quota decision: may a change that adds `adding` locations proceed
- * when `used` are already tracked? Returns null to allow, or the user-facing
- * rejection message.
+ * Locations that making these prompts active adds to the plan's count: each
+ * one that is paused now brings all its locations back. Resuming is metered
+ * like adding, so pausing prompts, filling their room with new ones and
+ * resuming the old ones can't get past the limit.
+ */
+export function activationDelta(
+ prompts: readonly { isActive: boolean; regions?: readonly unknown[] | null }[],
+): number {
+ return prompts.reduce((sum, p) => (p.isActive ? sum : sum + promptLocationCount(p.regions)), 0);
+}
+
+/**
+ * The one quota decision: may a change that adds `adding` active locations
+ * proceed when `used` are already active? Returns null to allow, or the
+ * user-facing rejection message.
*
* The rules every caller relies on:
* - `maxPrompts === -1` (self-host, enterprise) is unlimited — always null.
@@ -94,10 +106,10 @@ export function locationLimitMessage(plan: Plan, used: number, adding: number):
if (total <= max) return null;
const over = total - max;
return (
- `Your ${plan.name} plan allows up to ${max} tracked prompt locations — each prompt ` +
- `counts once per location it targets. This change would use ${total} ` +
- `(${used} in place + ${adding} added). Remove ${over} location${over === 1 ? '' : 's'} ` +
- `to continue, or upgrade your plan.`
+ `Your ${plan.name} plan allows up to ${max} active prompt locations — each prompt ` +
+ `counts once per location it targets, and paused prompts don't count. This change ` +
+ `would use ${total} (${used} in place + ${adding} added). Remove or pause ${over} ` +
+ `location${over === 1 ? '' : 's'} to continue, or upgrade your plan.`
);
}
@@ -106,6 +118,8 @@ export function locationLimitMessage(plan: Plan, used: number, adding: number):
export interface PromptLocations {
id: string;
regions: string[];
+ /** Paused prompts take no room on the plan, so their changes cost nothing. */
+ isActive?: boolean;
}
export interface BulkLocationChange {
@@ -123,7 +137,7 @@ export interface BulkLocationPlan {
unchanged: number;
/** Would have been left with no location at all, so they were left alone. */
blocked: number;
- /** Locations the whole batch adds — what the plan cap is measured against. */
+ /** Active locations the whole batch adds — what the plan cap is measured against. */
delta: number;
}
@@ -173,7 +187,8 @@ export function planBulkLocationChange(
const delta = promptLocationCount(next) - promptLocationCount(current);
plan.changes.push({ promptId: prompt.id, regions: next, delta });
- plan.delta += delta;
+ // A paused prompt's locations count only once it is resumed.
+ if (prompt.isActive !== false) plan.delta += delta;
}
return plan;
diff --git a/web/src/lib/prompt-usage.ts b/web/src/lib/prompt-usage.ts
index ebba1aa34..e0a4e1d7e 100644
--- a/web/src/lib/prompt-usage.ts
+++ b/web/src/lib/prompt-usage.ts
@@ -1,8 +1,8 @@
/**
* Tracked Prompts usage counter (PROMPT-009): which state the "used / limit"
* counter is in. The numbers come from getLocationQuota, so the counter shows
- * exactly what the plan-limit guard enforces (tracked prompt locations,
- * org-wide, paused prompts included — see prompt-locations.ts).
+ * exactly what the plan-limit guard enforces (active prompt locations,
+ * org-wide; paused prompts don't count — see prompt-locations.ts).
*/
export type PromptUsageState = 'unlimited' | 'normal' | 'warning' | 'full' | 'over';