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): show tracked prompt usage against the plan limit (#1009)

Cihan7f81622d892c
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 9ec6fd8e7..937067b4a 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -65,6 +65,7 @@ import {
X,
ListChecks,
Sparkles,
+ ExternalLink,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useBrandStore } from '@/stores/use-brand-store';
@@ -80,6 +81,7 @@ import {
deletePrompt,
getPromptsPageData,
updatePrompt,
+ type LocationQuota,
} from '@/lib/actions/prompt';
import { Checkbox } from '@/components/ui/checkbox';
import { useUserRole } from '@/hooks/use-user-role';
@@ -100,7 +102,8 @@ import { DateRangeFilter } from '@/components/filters/date-range-filter';
import { getBrandFilterOptions } from '@/lib/actions/tracking';
import { formatRegionDisplay } from '@/lib/region';
import { SuggestionsTab } from './_suggestions-tab';
-import { PLANS } from '@/config/plans';
+import { CONTACT_SALES_URL, PLANS } from '@/config/plans';
+import { getPromptUsage, isPromptLimitReached } from '@/lib/prompt-usage';
import { getTopics } from '@/lib/actions/topic';
import { analyzeNewPrompt, type PromptVisibilitySummary } from '@/lib/actions/tracking';
import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';
@@ -497,6 +500,100 @@ function PromptFormFields({
);
}
+// ─── 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.';
+
+/**
+ * "187 / 200 prompt locations · Growth plan" with a thin progress bar. The
+ * numbers are the ones the plan-limit guard enforces (getLocationQuota), so
+ * the counter can't promise a slot that a save would then reject.
+ */
+function PromptUsageMeter({ quota }: { quota: LocationQuota }) {
+ const usage = getPromptUsage(quota.used, quota.maxPrompts);
+
+ 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
+ <InfoTip content={PROMPT_USAGE_TOOLTIP} />
+ </span>
+ );
+ }
+
+ const tone =
+ usage.state === 'warning'
+ ? { text: 'text-amber-600 dark:text-amber-500', bar: 'bg-amber-500' }
+ : usage.state === 'full' || usage.state === 'over'
+ ? { text: 'text-red-600 dark:text-red-500', bar: 'bg-red-500' }
+ : { text: 'text-muted-foreground', bar: 'bg-primary' };
+ const status =
+ usage.state === 'full'
+ ? 'Limit reached'
+ : usage.state === 'over'
+ ? 'Over limit'
+ : `${usage.remaining} slot${usage.remaining === 1 ? '' : 's'} left`;
+
+ return (
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">
+ <span className="text-muted-foreground">
+ <span className={cn('font-medium tabular-nums', tone.text)}>
+ {quota.used} / {quota.maxPrompts}
+ </span>{' '}
+ 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-valuemin={0}
+ aria-valuemax={quota.maxPrompts}
+ aria-valuenow={Math.min(quota.used, quota.maxPrompts)}
+ >
+ <div
+ className={cn('h-full rounded-full', tone.bar)}
+ style={{ width: `${usage.percent}%` }}
+ />
+ </div>
+ <span className={cn('font-medium', tone.text)}>{status}</span>
+ <InfoTip content={PROMPT_USAGE_TOOLTIP} />
+ </div>
+ );
+}
+
+/**
+ * Where to go when the limit is reached. Starter can upgrade to Growth in
+ * billing; Growth and Enterprise (custom limits) are raised by Ansvisor.
+ */
+function PromptLimitActions({ planId }: { planId: LocationQuota['planId'] }) {
+ const contact = (
+ <a
+ href={CONTACT_SALES_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={buttonVariants({
+ variant: planId === 'starter' ? 'outline' : 'default',
+ size: 'sm',
+ })}
+ >
+ Contact us
+ <ExternalLink />
+ </a>
+ );
+ if (planId !== 'starter') return contact;
+ return (
+ <>
+ <Link href="/dashboard/settings?tab=billing" className={buttonVariants({ size: 'sm' })}>
+ Upgrade plan
+ </Link>
+ {contact}
+ </>
+ );
+}
+
/**
* Quick-add dialog for the active brand (#460). Same mechanism as the Add
* Prompt card on brands/[id]/prompts: topic select + the grouped
@@ -508,16 +605,22 @@ function PromptFormFields({
function AddPromptDialog({
brandId,
shoppingEnabled,
+ locationQuota,
open,
onClose,
onAdded,
}: {
brandId: string;
shoppingEnabled: boolean;
+ /** When the plan limit is already reached, the dialog explains it instead of the form. */
+ locationQuota: LocationQuota | null;
open: boolean;
onClose: () => void;
onAdded: () => void;
}) {
+ const limitReached =
+ !!locationQuota &&
+ isPromptLimitReached(getPromptUsage(locationQuota.used, locationQuota.maxPrompts));
const { allowedScraperIds, allowedModelIds, visibleScrapers, visibleModels } =
useAllowedEngines(shoppingEnabled);
@@ -603,51 +706,80 @@ function AddPromptDialog({
Track a new prompt for this brand across the selected platforms.
</DialogDescription>
</DialogHeader>
- <div className="space-y-3">
- <PromptFormFields
- autoFocus
- text={text}
- onTextChange={(value) => {
- setText(value);
- if (error) setError(null);
- }}
- onSubmit={handleAdd}
- category={category}
- onCategoryChange={setCategory}
- topics={topics}
- scrapers={scrapers}
- models={models}
- setScrapers={setScrapers}
- setModels={setModels}
- visibleScrapers={visibleScrapers}
- visibleModels={visibleModels}
- saving={saving}
- />
+ {limitReached && locationQuota ? (
+ <>
+ <div className="flex items-start gap-2.5 rounded-lg border border-red-200 bg-red-50 p-3 text-sm dark:border-red-900/50 dark:bg-red-950/30">
+ <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-red-600 dark:text-red-500" />
+ <div className="space-y-1">
+ <p className="font-medium text-red-900 dark:text-red-200">
+ 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{' '}
+ {locationQuota.planId === 'starter' ? 'upgrade your plan' : 'contact us'} to track
+ more.
+ </p>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={handleClose}>
+ Close
+ </Button>
+ <PromptLimitActions planId={locationQuota.planId} />
+ </DialogFooter>
+ </>
+ ) : (
+ <>
+ <div className="space-y-3">
+ <PromptFormFields
+ autoFocus
+ text={text}
+ onTextChange={(value) => {
+ setText(value);
+ if (error) setError(null);
+ }}
+ onSubmit={handleAdd}
+ category={category}
+ onCategoryChange={setCategory}
+ topics={topics}
+ scrapers={scrapers}
+ models={models}
+ setScrapers={setScrapers}
+ setModels={setModels}
+ visibleScrapers={visibleScrapers}
+ visibleModels={visibleModels}
+ saving={saving}
+ />
- {error && <p className="text-xs text-red-500">{error}</p>}
- </div>
- <DialogFooter>
- <Button type="button" variant="outline" onClick={handleClose} disabled={saving}>
- Cancel
- </Button>
- <Button
- type="button"
- onClick={handleAdd}
- disabled={saving || !text.trim() || (scrapers.length === 0 && models.length === 0)}
- >
- {saving ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- Adding…
- </>
- ) : (
- <>
- <Plus className="mr-2 h-4 w-4" />
- Add Prompt
- </>
- )}
- </Button>
- </DialogFooter>
+ {error && <p className="text-xs text-red-500">{error}</p>}
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={handleClose} disabled={saving}>
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ onClick={handleAdd}
+ disabled={saving || !text.trim() || (scrapers.length === 0 && models.length === 0)}
+ >
+ {saving ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Adding…
+ </>
+ ) : (
+ <>
+ <Plus className="mr-2 h-4 w-4" />
+ Add Prompt
+ </>
+ )}
+ </Button>
+ </DialogFooter>
+ </>
+ )}
</DialogContent>
</Dialog>
);
@@ -960,6 +1092,7 @@ export default function PromptsPage() {
const analysisGenRef = useRef(0);
const [refreshing, setRefreshing] = useState(false);
const [quota, setQuota] = useState<VolumeQuota | null>(null);
+ const [locationQuota, setLocationQuota] = useState<LocationQuota | null>(null);
const [addPromptOpen, setAddPromptOpen] = useState(false);
const [editingPrompt, setEditingPrompt] = useState<Prompt | null>(null);
const { canManage } = useUserRole();
@@ -1099,6 +1232,7 @@ export default function PromptsPage() {
if (isCancelled?.()) return;
setVolumes(page.volumes);
if (page.quota) setQuota(page.quota);
+ setLocationQuota(page.locationQuota);
const prompts = page.promptSets.flatMap((ps) => ps.prompts);
setAllPrompts(prompts);
setVisibility(page.visibility);
@@ -1635,6 +1769,7 @@ export default function PromptsPage() {
positionsWindow={positionsWindow}
positionsPreset={range ? rangePreset : '30d'}
regionFilter={regionFilter}
+ locationQuota={locationQuota}
onAddPrompt={canManage ? () => setAddPromptOpen(true) : undefined}
onEditPrompt={canManage ? setEditingPrompt : undefined}
/>
@@ -2002,6 +2137,7 @@ export default function PromptsPage() {
<AddPromptDialog
brandId={activeBrandId}
shoppingEnabled={!!activeBrand?.shoppingModeEnabled}
+ locationQuota={locationQuota}
open={addPromptOpen}
onClose={() => setAddPromptOpen(false)}
onAdded={loadData}
@@ -2041,6 +2177,7 @@ function AllPromptsTab({
positionsWindow,
positionsPreset,
regionFilter,
+ locationQuota,
onAddPrompt,
onEditPrompt,
}: {
@@ -2056,6 +2193,8 @@ function AllPromptsTab({
positionsPreset: PromptRangePreset;
/** Selected location; empty means every location. */
regionFilter: string;
+ /** Org-wide tracked-location usage for the header counter; null hides it. */
+ locationQuota: LocationQuota | null;
/** Opens the Add Prompt dialog; undefined when the user can't write (member role). */
onAddPrompt?: () => void;
/** Opens the Edit Prompt dialog for a row; undefined hides the pencil (member role). */
@@ -2205,6 +2344,11 @@ function AllPromptsTab({
<div className="flex items-center justify-between gap-4 flex-wrap">
<div>
<CardTitle className="text-sm font-medium">All Prompts ({prompts.length})</CardTitle>
+ {locationQuota && (
+ <div className="mt-1">
+ <PromptUsageMeter quota={locationQuota} />
+ </div>
+ )}
<p className="text-xs text-muted-foreground mt-0.5">
{onEditPrompt
? 'Every tracked prompt for this brand · edit or pause any row in place'
diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.ts
index 581779fd3..ec0f01992 100644
--- a/web/src/lib/actions/prompt.ts
+++ b/web/src/lib/actions/prompt.ts
@@ -12,7 +12,7 @@ import {
} from '@/lib/prompt-locations';
import { ALL_MODELS, ALL_SCRAPERS, DEFAULT_PROMPT_RANGE_DAYS } from '@/config/prompt-options';
import { isValidLocation, locationCode } from '@/lib/region';
-import type { Plan } from '@/config/plans';
+import type { Plan, PlanId } from '@/config/plans';
import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';
import { getPromptVisibilitySummaries, type PromptVisibilitySummary } from '@/lib/actions/tracking';
@@ -547,18 +547,30 @@ export async function bulkUpdatePromptLocations(
/**
* Org-wide tracked-location usage against the plan cap, for the prompts page
- * to bound its location pickers before a save can fail.
+ * to bound its location pickers before a save can fail, and for the Tracked
+ * Prompts usage counter. `maxPrompts` has Enterprise plan_overrides merged.
*/
-export async function getLocationQuota(
- brandId: string,
-): Promise<{ maxPrompts: number; used: number }> {
+export interface LocationQuota {
+ /** Tracked-location cap; -1 = unlimited. */
+ maxPrompts: number;
+ used: number;
+ planId: PlanId;
+ planName: string;
+}
+
+export async function getLocationQuota(brandId: string): Promise<LocationQuota> {
const supabase = await createClient();
const { organizationId: orgId } = await getBrandContext(supabase, brandId);
const [plan, usage] = await Promise.all([
getOrgPlan(orgId),
getOrgLocationUsage(supabase, orgId),
]);
- return { maxPrompts: plan.limits.maxPrompts, used: usage.total };
+ return {
+ maxPrompts: plan.limits.maxPrompts,
+ used: usage.total,
+ planId: plan.id,
+ planName: plan.name,
+ };
}
interface AddPromptInput {
@@ -726,6 +738,8 @@ export interface PromptsPageData {
quota: VolumeQuota | null;
/** True when the volumes upstream failed/timed out — the table still renders. */
volumesDegraded: boolean;
+ /** Org-wide tracked-location usage for the counter; null when it failed to load. */
+ locationQuota: LocationQuota | null;
}
/**
@@ -750,7 +764,7 @@ export async function getPromptsPageData(
// no date dimension, so neither changes with the selected range or the
// selected location.
const days = opts?.days ?? DEFAULT_PROMPT_RANGE_DAYS;
- const [promptSets, visibility, volumesResult] = await Promise.all([
+ const [promptSets, visibility, volumesResult, locationQuota] = await Promise.all([
getPromptSets(brandId),
getPromptVisibilitySummaries(brandId, {
days,
@@ -765,6 +779,12 @@ export async function getPromptsPageData(
return { volumes: [] as PromptVolume[], quota: null, degraded: true };
},
),
+ // The counter is informational — the limit is enforced on save either
+ // way — so a failure here hides it instead of failing the page.
+ getLocationQuota(brandId).catch((err) => {
+ console.error('[prompts] location quota fetch failed, hiding the counter:', err);
+ return null;
+ }),
]);
return {
@@ -773,5 +793,6 @@ export async function getPromptsPageData(
volumes: volumesResult.volumes,
quota: volumesResult.quota,
volumesDegraded: volumesResult.degraded,
+ locationQuota,
};
}
diff --git a/web/src/lib/prompt-usage.test.ts b/web/src/lib/prompt-usage.test.ts
new file mode 100644
index 000000000..3d1ab1cfb
--- /dev/null
+++ b/web/src/lib/prompt-usage.test.ts
@@ -0,0 +1,43 @@
+/**
+ * prompt-usage.test.ts (PROMPT-009)
+ *
+ * Tests the Tracked Prompts usage counter states.
+ */
+
+import { describe, expect, test } from 'vitest';
+import { getPromptUsage, isPromptLimitReached } from './prompt-usage';
+
+describe('getPromptUsage', () => {
+ test('-1 is unlimited and never blocks', () => {
+ const u = getPromptUsage(5000, -1);
+ expect(u.state).toBe('unlimited');
+ expect(isPromptLimitReached(u)).toBe(false);
+ });
+
+ test('below 80% is normal', () => {
+ expect(getPromptUsage(0, 200)).toEqual({ state: 'normal', remaining: 200, percent: 0 });
+ expect(getPromptUsage(159, 200).state).toBe('normal');
+ });
+
+ test('from 80% up to one below the limit is a warning with the slots left', () => {
+ expect(getPromptUsage(160, 200)).toEqual({ state: 'warning', remaining: 40, percent: 80 });
+ expect(getPromptUsage(187, 200)).toEqual({ state: 'warning', remaining: 13, percent: 94 });
+ expect(getPromptUsage(49, 50).state).toBe('warning');
+ });
+
+ test('exactly at the limit is full (the cap is inclusive)', () => {
+ const u = getPromptUsage(200, 200);
+ expect(u).toEqual({ state: 'full', remaining: 0, percent: 100 });
+ expect(isPromptLimitReached(u)).toBe(true);
+ });
+
+ test('above the limit (after a downgrade) is over, with the bar capped at 100', () => {
+ const u = getPromptUsage(187, 50);
+ expect(u).toEqual({ state: 'over', remaining: 0, percent: 100 });
+ expect(isPromptLimitReached(u)).toBe(true);
+ });
+
+ test('a zero limit is full at zero usage', () => {
+ expect(getPromptUsage(0, 0).state).toBe('full');
+ });
+});
diff --git a/web/src/lib/prompt-usage.ts b/web/src/lib/prompt-usage.ts
new file mode 100644
index 000000000..ebba1aa34
--- /dev/null
+++ b/web/src/lib/prompt-usage.ts
@@ -0,0 +1,41 @@
+/**
+ * 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).
+ */
+
+export type PromptUsageState = 'unlimited' | 'normal' | 'warning' | 'full' | 'over';
+
+export interface PromptUsage {
+ state: PromptUsageState;
+ /** Locations that can still be added; 0 when full or over. */
+ remaining: number;
+ /** Fill of the progress bar, 0–100 (capped at 100 when over). */
+ percent: number;
+}
+
+/** From this share of the limit on, the counter turns amber. */
+export const PROMPT_USAGE_WARNING_RATIO = 0.8;
+
+/**
+ * `limit === -1` is unlimited (self-host, enterprise without an override).
+ * The cap is inclusive (locationLimitMessage), so landing exactly on it is
+ * "full", not "over". "over" happens after a downgrade below current usage.
+ */
+export function getPromptUsage(used: number, limit: number): PromptUsage {
+ if (limit === -1) return { state: 'unlimited', remaining: Infinity, percent: 0 };
+ const remaining = Math.max(0, limit - used);
+ const percent = limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 100;
+ let state: PromptUsageState;
+ if (used > limit) state = 'over';
+ else if (used === limit) state = 'full';
+ else if (used >= limit * PROMPT_USAGE_WARNING_RATIO) state = 'warning';
+ else state = 'normal';
+ return { state, remaining, percent };
+}
+
+/** Whether adding a prompt is blocked: no location left under the cap. */
+export function isPromptLimitReached(usage: PromptUsage): boolean {
+ return usage.state === 'full' || usage.state === 'over';
+}