Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(prompts): show usage cards above the tracked prompts table (#1054)
Cihana6bb4bdcb299
diff --git a/web/messages/en.json b/web/messages/en.jsonindex dfed8437f..a0fbb79b6 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2347,6 +2347,54 @@"selectPlatformsAndModels": "Select platform & models","selectedCount": "{count} selected"},+ "usage": {+ "title": "Tracked Prompts",+ "subtitle": "Every tracked prompt for this brand · edit or pause any row in place",+ "subtitleReadOnly": "Read-only overview of every tracked prompt for this brand",+ "planAndUsage": "Plan & usage",+ "planPill": "{plan} plan",+ "planLabel": {+ "self_hosted": "Self-Hosted",+ "starter": "Starter",+ "growth": "Growth",+ "enterprise": "Enterprise"+ },+ "thisBrand": "This brand",+ "account": "Account",+ "activePrompts": "Active prompts",+ "totalPrompts": "Total prompts",+ "promptLocations": "Prompt locations",+ "slotsLeft": "Slots left",+ "paused": "{count} paused",+ "beingTracked": "being tracked now",+ "activePlusPaused": "active + paused",+ "acrossBrands": "across {count, plural, one {# brand} other {# brands}}",+ "locationPairs": "prompt × location pairs",+ "overLimit": "over limit",+ "ofLimit": "of {limit} on {plan}",+ "onPlan": "on {plan}",+ "unlimited": "Unlimited",+ "cta": {+ "upgrade_growth": "Upgrade to Growth",+ "upgrade": "Upgrade plan",+ "contact": "Contact us"+ },+ "footer": "Click a card to filter the table (Active · Paused · All).",+ "updated": "Counts updated {when}",+ "updatedJustNow": "Counts updated just now",+ "loadFailed": "Couldn't load the counts",+ "retry": "Retry",+ "showPaused": "Show paused prompts",+ "table": {+ "active": "Active prompts ({count})",+ "paused": "Paused prompts ({count})",+ "all": "All prompts ({count})",+ "filtered": "Filtered by the card above",+ "showAll": "Show all {count}",+ "noneActive": "No active prompts match.",+ "nonePaused": "No paused prompts match."+ }+ },"bulkDelete": {"progress": "Deleting {done} of {total} prompts…","failed": "{count, plural, one {Failed to delete the prompt.} other {Failed to delete the prompts.}}",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.test.tsxnew file mode 100644index 000000000..3b5d191c6--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.test.tsx@@ -0,0 +1,200 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { PromptUsageSummary } from '@/lib/prompt-usage-summary';+import {+ PromptUsageCards,+ countByStatus,+ locationQuotaFromUsage,+ matchesStatusFilter,+ type PromptUsageState,+} from './_usage-cards';++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++vi.mock('@/i18n/navigation', () => ({+ Link: ({ children, ...props }: React.ComponentProps<'a'>) => <a {...props}>{children}</a>,+}));++const summary = (over: Partial<PromptUsageSummary> = {}): PromptUsageSummary => ({+ plan: { key: 'starter', name: 'Starter plan', locationLimit: 50, cta: 'upgrade_growth' },+ brand: { active: 44, paused: 2, total: 46 },+ account: { activePrompts: 44, brands: 1, locationsUsed: 46 },+ updatedAt: '2026-10-15T09:00:00.000Z',+ ...over,+});++let container: HTMLDivElement;+let root: Root;+const onFilter = vi.fn();+const onRetry = vi.fn();++function render(state: PromptUsageState) {+ act(() => {+ root.render(+ <NextIntlClientProvider+ locale="en"+ messages={messages}+ timeZone="UTC"+ now={new Date('2026-10-15T09:00:10.000Z')}+ >+ <PromptUsageCards+ state={state}+ brandName="Acme Coffee"+ readOnly={false}+ filter="active"+ onFilter={onFilter}+ onRetry={onRetry}+ />+ </NextIntlClientProvider>,+ );+ });+}++const values = () =>+ [...container.querySelectorAll('.text-2xl')].map((el) => el.textContent?.trim());+const button = (text: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent?.trim() === text)!;++beforeEach(() => {+ vi.clearAllMocks();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('PromptUsageCards', () => {+ it('shows the five numbers with the plan, and turns amber from 90% of the limit', () => {+ render({ status: 'ready', usage: summary() });++ expect(values()).toEqual(['44', '46', '44', '46 / 50', '4']);+ expect(container.textContent).toContain('Starter plan');+ expect(container.textContent).toContain('of 50 on Starter');+ expect(container.textContent).toContain('Counts updated just now');+ expect(container.querySelectorAll('.text-2xl')[4].className).toContain('text-amber-600');+ const upgrade = [...container.querySelectorAll('a')].find(+ (a) => a.textContent === 'Upgrade to Growth',+ );+ expect(upgrade?.getAttribute('href')).toBe('/dashboard/settings?tab=billing');+ });++ it('marks an account over its limit after a downgrade, with no slots left', () => {+ render({+ status: 'ready',+ usage: summary({ account: { activePrompts: 60, brands: 1, locationsUsed: 64 } }),+ });++ expect(values().slice(3)).toEqual(['64 / 50', '0']);+ expect(container.textContent).toContain('over limit');+ });++ it('asks an Enterprise account to contact us, against the limit set for it', () => {+ render({+ status: 'ready',+ usage: summary({+ plan: { key: 'enterprise', name: 'Enterprise plan', locationLimit: 1000, cta: 'contact' },+ brand: { active: 702, paused: 7, total: 709 },+ account: { activePrompts: 1248, brands: 3, locationsUsed: 781 },+ }),+ });++ expect(values()).toEqual(['702', '709', '1,248', '781 / 1,000', '219']);+ expect(container.textContent).toContain('across 3 brands');+ const contact = [...container.querySelectorAll('a')].find(+ (a) => a.textContent === 'Contact us',+ );+ expect(contact?.getAttribute('target')).toBe('_blank');+ });++ it('says Unlimited on self-hosted, with no plan page to link to', () => {+ render({+ status: 'ready',+ usage: summary({+ plan: { key: 'self_hosted', name: 'Self-Hosted plan', locationLimit: null, cta: null },+ account: { activePrompts: 57, brands: 1, locationsUsed: 74 },+ }),+ });++ expect(values().slice(3)).toEqual(['74', 'Unlimited']);+ expect(container.querySelector('[role=progressbar]')).toBeNull();+ expect(container.textContent).not.toContain('Plan & usage');+ });++ it('filters the table from the brand cards', () => {+ render({ status: 'ready', usage: summary() });++ act(() => button('Total prompts').click());+ expect(onFilter).toHaveBeenLastCalledWith('all');+ act(() => button('2 paused').click());+ expect(onFilter).toHaveBeenLastCalledWith('paused');+ act(() => button('Active prompts').click());+ expect(onFilter).toHaveBeenLastCalledWith('active');+ });++ it('shows dashes and a retry when the counts fail to load', () => {+ render({ status: 'error' });++ expect(values()).toEqual(['–', '–', '–', '–', '–']);+ act(() => button("Couldn't load the counts · Retry").click());+ expect(onRetry).toHaveBeenCalledOnce();+ });++ it("falls back to the server's plan name for a plan this bundle doesn't know", () => {+ render({+ status: 'ready',+ usage: summary({+ plan: { key: 'team' as never, name: 'Team plan', locationLimit: 500, cta: 'contact' },+ }),+ });++ expect(container.textContent).toContain('Team plan');+ expect(container.textContent).toContain('of 500 on Team plan');+ });++ it('shows skeletons, not zeros, while loading', () => {+ render({ status: 'loading' });++ expect(values()).toEqual([]);+ expect(container.querySelectorAll('[data-slot=skeleton]').length).toBeGreaterThan(0);+ });+});++describe('locationQuotaFromUsage', () => {+ it('gives the Add Prompt dialog the same limit and usage as the cards', () => {+ expect(locationQuotaFromUsage(summary())).toEqual({+ maxPrompts: 50,+ used: 46,+ planId: 'starter',+ planName: 'Starter',+ });+ expect(+ locationQuotaFromUsage(+ summary({+ plan: { key: 'self_hosted', name: 'Self-Hosted plan', locationLimit: null, cta: null },+ }),+ ).maxPrompts,+ ).toBe(-1);+ });+});++describe('the table status filter', () => {+ const rows = [{ isActive: true }, { isActive: true }, { isActive: false }];++ it('opens on active rows and counts each filter for the title', () => {+ expect(rows.filter((r) => matchesStatusFilter(r, 'active'))).toHaveLength(2);+ expect(rows.filter((r) => matchesStatusFilter(r, 'paused'))).toHaveLength(1);+ expect(rows.filter((r) => matchesStatusFilter(r, 'all'))).toHaveLength(3);+ expect(countByStatus(rows)).toEqual({ active: 2, paused: 1, all: 3 });+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.tsxnew file mode 100644index 000000000..196a3cc40--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.tsx@@ -0,0 +1,420 @@+'use client';++import { useCallback, useEffect, useState, type ReactNode } from 'react';+import { useFormatter, useNow, useTranslations } from 'next-intl';+import { RotateCw } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { buttonVariants } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import { CONTACT_SALES_URL, PLANS, type PlanId } from '@/config/plans';+import type { LocationQuota } from '@/lib/actions/prompt';+import { getPromptUsage } from '@/lib/prompt-usage';+import type { PromptUsageSummary } from '@/lib/prompt-usage-summary';+import { cn } from '@/lib/utils';++/**+ * Tracked Prompts usage cards (PROMPT-012): the brand's active and total+ * prompts, and the account's active prompts, prompt locations and slots left,+ * above the table. The brand cards filter the table; the account cards lead+ * to Plan & usage. They load on their own (GET /api/prompts/usage), so the+ * table never waits for them.+ */++/** Which rows the table shows; set by the This brand cards. */+export type PromptStatusFilter = 'active' | 'paused' | 'all';++export function matchesStatusFilter(+ prompt: { isActive: boolean },+ filter: PromptStatusFilter,+): boolean {+ return filter === 'all' || prompt.isActive === (filter === 'active');+}++/** How many rows each filter shows, for the table's title. */+export function countByStatus(+ prompts: { isActive: boolean }[],+): Record<PromptStatusFilter, number> {+ const active = prompts.filter((p) => p.isActive).length;+ return { active, paused: prompts.length - active, all: prompts.length };+}++/** Plan keys this bundle has labels for; any other shows the server's name. */+function isKnownPlan(key: string): key is PlanId {+ return Object.hasOwn(PLANS, key);+}++type UsageLoad =+ | { brandId: string; status: 'ready'; usage: PromptUsageSummary }+ | { brandId: string; status: 'error' };++export type PromptUsageState =+ | { status: 'loading' }+ | { status: 'error' }+ | { status: 'ready'; usage: PromptUsageSummary };++const PLAN_PAGE = '/dashboard/settings?tab=billing';++/**+ * The cards' data for a brand. Bump `version` after a change to the brand's+ * prompts or locations to refetch; the cards keep their numbers meanwhile.+ */+export function usePromptUsage(+ brandId: string | null,+ version: number,+): { state: PromptUsageState; retry: () => void } {+ const [load, setLoad] = useState<UsageLoad | null>(null);+ const [attempt, setAttempt] = useState(0);++ useEffect(() => {+ if (!brandId) return;+ const controller = new AbortController();+ fetch(`/api/prompts/usage?brandId=${encodeURIComponent(brandId)}`, {+ signal: controller.signal,+ cache: 'no-store',+ })+ .then(async (res) => {+ if (!res.ok) throw new Error(`usage ${res.status}`);+ return (await res.json()) as PromptUsageSummary;+ })+ .then((usage) => setLoad({ brandId, status: 'ready', usage }))+ .catch(() => {+ if (!controller.signal.aborted) setLoad({ brandId, status: 'error' });+ });+ return () => controller.abort();+ }, [brandId, version, attempt]);++ // Back to the skeletons while retrying, so the click visibly does something.+ const retry = useCallback(() => {+ setLoad(null);+ setAttempt((a) => a + 1);+ }, []);+ // Another brand's numbers never show while the new brand's load.+ const state: PromptUsageState =+ !load || load.brandId !== brandId+ ? { status: 'loading' }+ : load.status === 'ready'+ ? { status: 'ready', usage: load.usage }+ : { status: 'error' };+ return { state, retry };+}++/** The plan-limit numbers the Add Prompt dialog and bulk import bound themselves by. */+export function locationQuotaFromUsage(usage: PromptUsageSummary): LocationQuota {+ return {+ maxPrompts: usage.plan.locationLimit ?? -1,+ used: usage.account.locationsUsed,+ planId: usage.plan.key,+ planName: isKnownPlan(usage.plan.key) ? PLANS[usage.plan.key].name : usage.plan.name,+ };+}++type Tone = 'normal' | 'warning' | 'full';++const TONE_TEXT: Record<Tone, string> = {+ normal: '',+ warning: 'text-amber-600 dark:text-amber-500',+ full: 'text-red-600 dark:text-red-500',+};++const TONE_BAR: Record<Tone, string> = {+ normal: 'bg-foreground',+ warning: 'bg-amber-500 dark:bg-amber-400',+ full: 'bg-red-500 dark:bg-red-400',+};++export function PromptUsageCards({+ state,+ brandName,+ readOnly,+ filter,+ onFilter,+ onRetry,+}: {+ state: PromptUsageState;+ brandName: string | undefined;+ /** Member role: the subtitle says the table is read-only. */+ readOnly: boolean;+ filter: PromptStatusFilter;+ onFilter: (filter: PromptStatusFilter) => void;+ onRetry: () => void;+}) {+ const t = useTranslations('prompts.usage');+ const format = useFormatter();+ const now = useNow({ updateInterval: 60_000 });+ const n = (value: number) => format.number(value);++ const usage = state.status === 'ready' ? state.usage : null;+ const plan = usage?.plan;+ const planShort = !plan ? '' : isKnownPlan(plan.key) ? t(`planLabel.${plan.key}`) : plan.name;+ const planPill =+ plan && isKnownPlan(plan.key) ? t('planPill', { plan: planShort }) : (plan?.name ?? '');+ // Self-hosted has no plan page to go to.+ const planHref = plan?.cta ? PLAN_PAGE : undefined;++ const limit = plan?.locationLimit ?? null;+ const used = usage?.account.locationsUsed ?? 0;+ const meter = usage && limit !== null ? getPromptUsage(used, limit) : null;+ const tone: Tone =+ meter?.state === 'warning'+ ? 'warning'+ : meter?.state === 'full' || meter?.state === 'over'+ ? 'full'+ : 'normal';++ const value = (content: ReactNode, className?: string) =>+ usage ? (+ <div className={cn('mt-1 text-2xl font-bold tabular-nums', className)}>{content}</div>+ ) : state.status === 'error' ? (+ <div className="mt-1 text-2xl font-bold text-muted-foreground">–</div>+ ) : (+ <Skeleton className="mt-1.5 mb-1 h-7 w-16" />+ );+ const sub = (content: ReactNode) =>+ // Sub-lines wrap rather than cut off, so the plan CTA stays reachable on+ // narrow cards; the labels above them stay on one line.+ usage ? (+ <div className="text-xs leading-snug text-muted-foreground">{content}</div>+ ) : state.status === 'error' ? null : (+ <Skeleton className="mt-1 h-3 w-24" />+ );++ const cta =+ plan?.cta === 'contact' ? (+ <a+ href={CONTACT_SALES_URL}+ target="_blank"+ rel="noopener noreferrer"+ className={cn(+ 'relative z-10 underline underline-offset-2',+ tone === 'full' ? 'font-semibold text-red-600 dark:text-red-500' : 'text-foreground',+ )}+ >+ {t('cta.contact')}+ </a>+ ) : plan?.cta ? (+ <Link+ href={PLAN_PAGE}+ className={cn(+ 'relative z-10 underline underline-offset-2',+ tone === 'full' ? 'font-semibold text-red-600 dark:text-red-500' : 'text-foreground',+ )}+ >+ {t(`cta.${plan.cta}`)}+ </Link>+ ) : null;++ const updatedAt = usage ? new Date(usage.updatedAt) : null;+ const updatedLabel =+ updatedAt && now.getTime() - updatedAt.getTime() >= 60_000+ ? t('updated', { when: format.relativeTime(updatedAt, now) })+ : t('updatedJustNow');++ return (+ <section className="overflow-hidden rounded-xl border bg-card">+ <div className="flex flex-wrap items-center gap-x-2.5 gap-y-1 border-b px-4 py-3">+ <h2 className="text-[15px] font-semibold">{t('title')}</h2>+ <span className="text-xs text-muted-foreground">+ {readOnly ? t('subtitleReadOnly') : t('subtitle')}+ </span>+ {planHref && (+ <Link+ href={planHref}+ className={cn(+ buttonVariants({ variant: 'outline', size: 'sm' }),+ 'ml-auto h-7 text-xs',+ )}+ >+ {t('planAndUsage')}+ </Link>+ )}+ </div>++ <div className="grid grid-cols-1 min-[900px]:grid-cols-[2fr_3fr]">+ <div className="min-w-0 border-b min-[900px]:border-r min-[900px]:border-b-0">+ <GroupHeader name={t('thisBrand')}>+ <span className="truncate text-xs text-muted-foreground">{brandName}</span>+ </GroupHeader>+ <div className="grid auto-cols-fr grid-flow-col">+ <UsageCard+ label={t('activePrompts')}+ selected={filter === 'active'}+ onSelect={() => onFilter('active')}+ >+ {value(usage && n(usage.brand.active))}+ {sub(+ usage && (+ <>+ <button+ type="button"+ onClick={() => onFilter('paused')}+ title={t('showPaused')}+ aria-pressed={filter === 'paused'}+ className={cn(+ 'relative z-10 underline-offset-2 hover:underline',+ filter === 'paused' && 'font-medium text-foreground underline',+ )}+ >+ {t('paused', { count: n(usage.brand.paused) })}+ </button>{' '}+ · {t('beingTracked')}+ </>+ ),+ )}+ </UsageCard>+ <UsageCard+ label={t('totalPrompts')}+ selected={filter === 'all'}+ onSelect={() => onFilter('all')}+ >+ {value(usage && n(usage.brand.total))}+ {sub(t('activePlusPaused'))}+ </UsageCard>+ </div>+ </div>++ <div className="min-w-0">+ <GroupHeader name={t('account')}>+ {plan ? (+ <span className="rounded-md border bg-background px-2 text-xs leading-5 font-medium">+ {planPill}+ </span>+ ) : state.status === 'loading' ? (+ <Skeleton className="h-5 w-24" />+ ) : null}+ </GroupHeader>+ <div className="grid auto-cols-fr grid-flow-col">+ <UsageCard label={t('activePrompts')} href={planHref}>+ {value(usage && n(usage.account.activePrompts))}+ {sub(usage && t('acrossBrands', { count: usage.account.brands }))}+ </UsageCard>+ <UsageCard label={t('promptLocations')} href={planHref}>+ {value(+ <>+ {n(used)}+ {limit !== null && (+ <span className="text-[15px] font-medium text-muted-foreground">+ {' '}+ / {n(limit)}+ </span>+ )}+ </>,+ TONE_TEXT[tone],+ )}+ {usage && limit !== null && (+ <div+ className="my-1.5 h-1.5 overflow-hidden rounded-full bg-muted"+ role="progressbar"+ aria-label={t('promptLocations')}+ aria-valuemin={0}+ aria-valuemax={limit}+ aria-valuenow={Math.min(used, limit)}+ >+ <div+ className={cn('h-full rounded-full', TONE_BAR[tone])}+ style={{ width: `${meter?.percent ?? 0}%` }}+ />+ </div>+ )}+ {sub(+ limit === null ? (+ `${t('unlimited')} · ${t('locationPairs')}`+ ) : meter?.state === 'over' ? (+ <>+ {t('locationPairs')} · <span className={TONE_TEXT.full}>{t('overLimit')}</span>+ </>+ ) : (+ t('locationPairs')+ ),+ )}+ </UsageCard>+ <UsageCard label={t('slotsLeft')} href={planHref}>+ {value(limit === null ? t('unlimited') : n(meter?.remaining ?? 0), TONE_TEXT[tone])}+ {sub(+ <>+ {limit === null+ ? t('onPlan', { plan: planShort })+ : t('ofLimit', { limit: n(limit), plan: planShort })}+ {cta && <> · {cta}</>}+ </>,+ )}+ </UsageCard>+ </div>+ </div>+ </div>++ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t px-4 py-2.5 text-xs text-muted-foreground">+ <span>{t('footer')}</span>+ {state.status === 'error' ? (+ <button+ type="button"+ onClick={onRetry}+ className="inline-flex items-center gap-1 text-foreground hover:underline"+ >+ <RotateCw className="h-3 w-3" />+ {t('loadFailed')} · {t('retry')}+ </button>+ ) : usage ? (+ <span>{updatedLabel}</span>+ ) : null}+ </div>+ </section>+ );+}++function GroupHeader({ name, children }: { name: string; children?: ReactNode }) {+ return (+ <div className="flex h-[38px] items-center gap-2 border-b bg-muted/40 px-4 whitespace-nowrap">+ <span className="text-[11px] font-semibold tracking-wider text-foreground/80 uppercase">+ {name}+ </span>+ {children}+ </div>+ );+}++/**+ * One card. Its label is the card's control — a button that filters the+ * table, or a link to Plan & usage — stretched over the whole card, so links+ * inside the card (the paused count, the plan CTA) sit above it.+ */+function UsageCard({+ label,+ selected = false,+ onSelect,+ href,+ children,+}: {+ label: string;+ selected?: boolean;+ onSelect?: () => void;+ href?: string;+ children: ReactNode;+}) {+ const labelClass =+ 'block h-4 truncate text-left text-[11px] tracking-wide text-muted-foreground uppercase ' ++ "after:absolute after:inset-0 after:content-[''] focus-visible:outline-none";+ return (+ <div+ className={cn(+ 'relative min-w-0 border-r px-4 py-3.5 last:border-r-0 has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring/50 has-[:focus-visible]:ring-inset',+ (onSelect || href) && 'hover:bg-muted/40',+ selected && 'shadow-[inset_0_-2px_0_var(--foreground)]',+ )}+ >+ {onSelect ? (+ <button type="button" onClick={onSelect} aria-pressed={selected} className={labelClass}>+ {label}+ </button>+ ) : href ? (+ <Link href={href} className={labelClass}>+ {label}+ </Link>+ ) : (+ <div className="block h-4 truncate text-[11px] tracking-wide text-muted-foreground uppercase">+ {label}+ </div>+ )}+ {children}+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex c138072a2..3a992a1fd 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -2,7 +2,7 @@import { useState, useRef, useEffect, useCallback, useMemo } from 'react';import { createPortal } from 'react-dom';-import { useTranslations } from 'next-intl';+import { useFormatter, useTranslations } from 'next-intl';import { useSearchParams } from 'next/navigation';import { Link, usePathname, useRouter } from '@/i18n/navigation';import { PROMPTS_BASE, sectionFor, sectionFromPath } from '@/lib/prompts-routes';@@ -14,6 +14,14 @@ const PlatformVolumeChart = dynamic(() => import('./_charts').then((m) => m.Platloading: () => <Skeleton className="h-64 w-full" />,});import { QueryFanoutTab } from './_fanout-tab';+import {+ PromptUsageCards,+ countByStatus,+ locationQuotaFromUsage,+ matchesStatusFilter,+ usePromptUsage,+ type PromptStatusFilter,+} from './_usage-cards';import { INTENT_LABELS, INTENT_COLORS } from '@/config/intent-labels';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';@@ -564,68 +572,6 @@ function brandLocation(region: string | undefined, state: string | undefined): s// ─── Tracked prompt limit (PROMPT-009) ────────────────────────────────────────-const PROMPT_USAGE_TOOLTIP =- '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- * 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> active prompt locations · 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>{' '}- active prompt locations · {quota.planName} plan- </span>- <div- className="h-1.5 w-24 overflow-hidden rounded-full bg-muted"- role="progressbar"- aria-label="Active 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.@@ -1311,7 +1257,6 @@ 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();@@ -1321,6 +1266,14 @@ export default function PromptsPage() {const activeBrand = useBrandStore((s) => s.brands.find((brand) => brand.id === s.activeBrandId) ?? null,);+ // The usage cards (PROMPT-012) load on their own; `usageVersion` refetches+ // them after a change to the brand's prompts or locations. The Add Prompt+ // dialog and bulk import bound themselves by the same numbers.+ const [usageVersion, setUsageVersion] = useState(0);+ const { state: usageState, retry: retryUsage } = usePromptUsage(activeBrandId, usageVersion);+ const usage = usageState.status === 'ready' ? usageState.usage : null;+ const locationQuota = useMemo(() => (usage ? locationQuotaFromUsage(usage) : null), [usage]);+ const [statusFilter, setStatusFilter] = useState<PromptStatusFilter>('active');const searchParams = useSearchParams();// On /dashboard/prompts/{tracked,suggestions,fan-outs,insights} the route// names the view (PROMPT-001); ?tab= / ?view= are the older links' shape.@@ -1458,7 +1411,6 @@ 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);@@ -1485,6 +1437,13 @@ export default function PromptsPage() {};}, [loadData]);+ // After prompts are added, paused, resumed, deleted or retargeted: reload+ // the table and the usage cards together.+ const reloadAfterChange = useCallback(() => {+ setUsageVersion((v) => v + 1);+ return loadData();+ }, [loadData]);+// Locations the brand has actually produced results in — the same// whole-brand list the Visibility page offers, so the two pages never// disagree about where this brand is tracked. A brand tracked in one place@@ -1945,11 +1904,21 @@ export default function PromptsPage() {{view === 'suggestions' ? (activeBrandId && (<>- <SuggestionsTab brandId={activeBrandId} onAccepted={loadData} />+ <SuggestionsTab brandId={activeBrandId} onAccepted={reloadAfterChange} /></>)) : (<>+ {activeBrandId && (+ <PromptUsageCards+ state={usageState}+ brandName={activeBrand?.name}+ readOnly={!canManage}+ filter={statusFilter}+ onFilter={setStatusFilter}+ onRetry={retryUsage}+ />+ )}{!loading && unanalyzedCount > 0 && (<div className="flex flex-col gap-3 rounded-lg border border-amber-200 bg-amber-50 p-3 sm:flex-row sm:items-center sm:justify-between dark:border-amber-900/50 dark:bg-amber-950/30"><div className="flex items-start gap-2.5">@@ -1997,10 +1966,11 @@ export default function PromptsPage() {positionsWindow={positionsWindow}positionsPreset={range ? rangePreset : '30d'}regionFilter={regionFilter}- locationQuota={locationQuota}+ statusFilter={statusFilter}+ onStatusFilterChange={setStatusFilter}onAddPrompt={canManage ? () => setAddPromptOpen(true) : undefined}onEditPrompt={canManage ? setEditingPrompt : undefined}- onChanged={loadData}+ onChanged={reloadAfterChange}/></>)}@@ -2013,7 +1983,7 @@ export default function PromptsPage() {brandId={activeBrandId}range={range}rangeLabel={rangeLabel}- onTracked={loadData}+ onTracked={reloadAfterChange}/>)}</TabsContent>@@ -2371,7 +2341,7 @@ export default function PromptsPage() {defaultRegion={brandLocation(activeBrand?.region, activeBrand?.state)}open={addPromptOpen}onClose={() => setAddPromptOpen(false)}- onAdded={loadData}+ onAdded={reloadAfterChange}/>)}@@ -2381,7 +2351,7 @@ export default function PromptsPage() {brandId={activeBrandId}shoppingEnabled={!!activeBrand?.shoppingModeEnabled}onClose={() => setEditingPrompt(null)}- onChanged={loadData}+ onChanged={reloadAfterChange}/>)}</div>@@ -2558,7 +2528,8 @@ function AllPromptsTab({positionsWindow,positionsPreset,regionFilter,- locationQuota,+ statusFilter,+ onStatusFilterChange,onAddPrompt,onEditPrompt,onChanged,@@ -2577,8 +2548,9 @@ 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;+ /** Which rows show, set by the usage cards above (PROMPT-012). */+ statusFilter: PromptStatusFilter;+ onStatusFilterChange: (filter: PromptStatusFilter) => void;/** 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 row menu (member role). */@@ -2587,6 +2559,8 @@ function AllPromptsTab({onChanged: () => void;}) {const tCommon = useTranslations('common');+ const tUsage = useTranslations('prompts.usage');+ const format = useFormatter();const tDelete = useTranslations('prompts.bulkDelete');// 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@@ -3064,6 +3038,7 @@ function AllPromptsTab({(p) => p.text.toLowerCase().includes(q) || (p.category ?? '').toLowerCase().includes(q),);}+ list = list.filter((p) => matchesStatusFilter(p, statusFilter));if (workFilter !== 'all') {list = list.filter((p) =>workFilter === 'none' ? statusOf(p) === null : statusOf(p) === workFilter,@@ -3096,6 +3071,7 @@ function AllPromptsTab({}, [prompts,search,+ statusFilter,workFilter,lateOnly,statusOf,@@ -3110,7 +3086,10 @@ function AllPromptsTab({// changes the visible row set (search text, sort column, sort direction, work// status filter) so usePagination jumps back to page 0 automatically when// any filter or sort changes — satisfying the issue's acceptance criteria.- const promptsResetKey = `${search}::${workFilter}::${lateOnly}::${activeSort}::${dir}`;+ const promptsResetKey = `${search}::${statusFilter}::${workFilter}::${lateOnly}::${activeSort}::${dir}`;+ // From every row, pending deletes included, so the title agrees with the+ // usage cards until a delete actually lands after its Undo window.+ const statusCounts = useMemo(() => countByStatus(allRows), [allRows]);const promptsPager = usePagination(filtered.length, promptsResetKey);// Rows ticked for the bulk action bar. Only rows on screen can be ticked,@@ -3186,18 +3165,24 @@ function AllPromptsTab({<Card><CardHeader className="pb-3"><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>+ <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-0.5">+ <CardTitle className="text-sm font-medium">+ {tUsage(`table.${statusFilter}`, {+ count: format.number(statusCounts[statusFilter]),+ })}+ </CardTitle>+ {statusFilter !== 'all' && (+ <span className="text-xs text-muted-foreground">+ {tUsage('table.filtered')} ·{' '}+ <button+ type="button"+ onClick={() => onStatusFilterChange('all')}+ className="underline underline-offset-2 hover:text-foreground"+ >+ {tUsage('table.showAll', { count: format.number(statusCounts.all) })}+ </button>+ </span>)}- <p className="text-xs text-muted-foreground mt-0.5">- {onEditPrompt- ? 'Every tracked prompt for this brand · edit or pause any row in place'- : 'Read-only overview of every tracked prompt for this brand'}- </p></div><div className="flex items-center gap-2"><Select@@ -3560,11 +3545,25 @@ function AllPromptsTab({end={promptsPager.end}onPage={promptsPager.setPage}/>- {filtered.length === 0 && (- <div className="py-10 text-center text-sm text-muted-foreground">- No prompts match your search.- </div>- )}+ {filtered.length === 0 &&+ (statusFilter === 'all' ? (+ <div className="py-10 text-center text-sm text-muted-foreground">+ No prompts match your search.+ </div>+ ) : (+ // The table opens on Active: a brand whose prompts are all paused+ // must not look empty with no way back.+ <div className="py-10 text-center text-sm text-muted-foreground">+ {tUsage(statusFilter === 'active' ? 'table.noneActive' : 'table.nonePaused')}{' '}+ <button+ type="button"+ onClick={() => onStatusFilterChange('all')}+ className="underline underline-offset-2 hover:text-foreground"+ >+ {tUsage('table.showAll', { count: format.number(statusCounts.all) })}+ </button>+ </div>+ ))}</CardContent><PromptPositionsSheetprompt={openPositions}diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 76baf0afc..967797269 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -561,9 +561,10 @@ 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, and for the Tracked- * Prompts usage counter. `maxPrompts` has Enterprise plan_overrides merged.+ * Org-wide tracked-location usage against the plan cap, for the brand prompts+ * page to bound its location pickers before a save can fail. `maxPrompts` has+ * Enterprise plan_overrides merged. (The Tracked Prompts page reads the same+ * numbers from its usage cards, GET /api/prompts/usage.)*/export interface LocationQuota {/** Tracked-location cap; -1 = unlimited. */@@ -1019,8 +1020,6 @@ 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;}/**@@ -1049,7 +1048,9 @@ export async function getPromptsPageData(from: opts?.from ?? new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString(),to: opts?.to,};- const [promptSets, visibility, positionRows, volumesResult, locationQuota] = await Promise.all([+ // The plan-limit numbers aren't here: the usage cards read them from+ // GET /api/prompts/usage, which reads counters instead of counting prompts.+ const [promptSets, visibility, positionRows, volumesResult] = await Promise.all([getPromptSets(brandId),getPromptVisibilitySummaries(brandId, {days,@@ -1071,12 +1072,6 @@ 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;- }),]);const positions: Record<string, PromptPositionCell> = {};@@ -1102,7 +1097,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.tsindex 3d1ab1cfb..76a846af2 100644--- a/web/src/lib/prompt-usage.test.ts+++ b/web/src/lib/prompt-usage.test.ts@@ -1,5 +1,5 @@/**- * prompt-usage.test.ts (PROMPT-009)+ * prompt-usage.test.ts (PROMPT-009, PROMPT-012)** Tests the Tracked Prompts usage counter states.*/@@ -14,14 +14,15 @@ describe('getPromptUsage', () => {expect(isPromptLimitReached(u)).toBe(false);});- test('below 80% is normal', () => {+ test('below 90% is normal', () => {expect(getPromptUsage(0, 200)).toEqual({ state: 'normal', remaining: 200, percent: 0 });- expect(getPromptUsage(159, 200).state).toBe('normal');+ expect(getPromptUsage(179, 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 });+ test('from 90% up to one below the limit is a warning with the slots left', () => {+ expect(getPromptUsage(180, 200)).toEqual({ state: 'warning', remaining: 20, percent: 90 });expect(getPromptUsage(187, 200)).toEqual({ state: 'warning', remaining: 13, percent: 94 });+ expect(getPromptUsage(45, 50).state).toBe('warning');expect(getPromptUsage(49, 50).state).toBe('warning');});diff --git a/web/src/lib/prompt-usage.ts b/web/src/lib/prompt-usage.tsindex e0a4e1d7e..36083bd3a 100644--- a/web/src/lib/prompt-usage.ts+++ b/web/src/lib/prompt-usage.ts@@ -1,7 +1,7 @@/**- * 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 (active prompt locations,+ * Tracked prompt usage (PROMPT-009, PROMPT-012): which state "used / limit"+ * is in, for the usage cards' colors and for blocking Add Prompt. The numbers+ * are the ones the plan-limit guard enforces (active prompt locations,* org-wide; paused prompts don't count — see prompt-locations.ts).*/@@ -15,8 +15,8 @@ export interface PromptUsage {percent: number;}-/** From this share of the limit on, the counter turns amber. */-export const PROMPT_USAGE_WARNING_RATIO = 0.8;+/** From this share of the limit on, the usage cards turn amber (PROMPT-012: 90%). */+export const PROMPT_USAGE_WARNING_RATIO = 0.9;/*** `limit === -1` is unlimited (self-host, enterprise without an override).