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(billing): show the month's AI usage at the top right of the main pages (AI usage display, part 1) (#1430)
Cihancb0eff9f24ff
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 3c1f697ce..409ebf8b2 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -12,6 +12,32 @@"reload": "Reload","upgrade": "Upgrade"},+ "aiUsage": {+ "meter": {+ "ai": "AI",+ "label": "AI {percent} used this month",+ "labelWarning": "AI {percent} used this month, close to the limit",+ "labelExhausted": "AI {percent} used this month, the limit is reached"+ },+ "popover": {+ "title": "AI usage this month · {plan} plan",+ "titleNoPlan": "AI usage this month",+ "shared": "Shared by every seat · resets {date}",+ "sharedNoDate": "Shared by every seat",+ "exhausted": "Used up. AI features stop until {date}; Agent Chat on your own AI key keeps working.",+ "exhaustedNoDate": "Used up. AI features stop until it resets; Agent Chat on your own AI key keeps working.",+ "ownKey": "Agent Chat, on your own AI key",+ "notCounted": "Not counted",+ "otherLimits": "Other limits this month",+ "auditPages": "Site Audit pages",+ "promptLocations": "Prompt locations",+ "ofLimit": "{used} of {limit}",+ "askAdmin": "To get more AI usage or use your own key, ask an admin of your workspace.",+ "getMore": "Get more AI usage",+ "useOwnKey": "Use your own key",+ "details": "See details"+ }+ },"common": {"loading": "Loading...","error": "Something went wrong.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.test.tsxindex fa9c7f7c7..32b52d00a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.test.tsx@@ -95,6 +95,9 @@ vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => role }));vi.mock('@/lib/actions/team', () => ({ listMembers: vi.fn(async () => []) }));vi.mock('@/lib/download', () => ({ saveBlob }));vi.mock('sonner', () => ({ toast }));+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({+ HeaderWithAiUsage: ({ children }: { children: React.ReactNode }) => children,+}));vi.mock('@/components/action-center/action-center-tabs', () => ({ ActionCenterTabs: () => null }));vi.mock('@/components/action-center/action-table', () => ({ ActionTable: () => null }));vi.mock('@/components/action-center/action-drawer', () => ({ ActionDrawer: () => null }));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsxindex 661348e00..e5cc59d76 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx@@ -87,6 +87,7 @@ import { Skeleton } from '@/components/ui/skeleton';import { cn } from '@/lib/utils';import { BYTE_ORDER_MARK, actionListCsv } from '@/lib/action-center/export';import { saveBlob } from '@/lib/download';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';const isOpen = (action: ActionItem) => OPEN_ACTION_STATUSES.includes(action.status);@@ -145,13 +146,15 @@ export default function ActionCenterActionsPage() {function ActionsHeader({ action }: { action?: React.ReactNode }) {const t = useTranslations('actionCenter.actionsPage');return (- <div className="flex flex-wrap items-start justify-between gap-4">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>+ <HeaderWithAiUsage>+ <div className="flex flex-wrap items-start justify-between gap-4">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>+ </div>+ {action}</div>- {action}- </div>+ </HeaderWithAiUsage>);}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsxindex 957b9630c..0334f4e0f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx@@ -38,6 +38,7 @@ import { ActionCenterTabs } from '@/components/action-center/action-center-tabs'import { HistoryTable } from '@/components/action-center/history-table';import { HistoryDrawer } from '@/components/action-center/history-drawer';import { cn } from '@/lib/utils';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';const RANGE_DAYS = { '7d': 7, '30d': 30, '90d': 90, all: null } as const;type RangePreset = keyof typeof RANGE_DAYS;@@ -181,10 +182,12 @@ export default function ActionCenterHistoryPage() {};const header = (- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>- </div>+ <HeaderWithAiUsage>+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>+ </div>+ </HeaderWithAiUsage>);if (!brandId) {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.test.tsxindex d61c6ec1b..5d3d0f163 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.test.tsx@@ -49,6 +49,9 @@ vi.mock('@/hooks/use-user-role', () => ({useUserRole: () => ({ role: canManage ? 'admin' : 'analyst', canManage, canAdmin: canManage }),}));+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({+ HeaderWithAiUsage: ({ children }: { children: React.ReactNode }) => children,+}));vi.mock('@/components/action-center/action-center-tabs', () => ({ActionCenterTabs: () => null,}));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsxindex 16d02a505..8aeb82fa6 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsx@@ -33,6 +33,7 @@ import { KpiTable } from '@/components/action-center/kpi-table';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';import { cn } from '@/lib/utils';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';type KpiDatePreset = '7d' | '30d' | '90d';const KPI_DATE_PRESETS: readonly KpiDatePreset[] = ['7d', '30d', '90d'];@@ -50,10 +51,12 @@ export default function ActionCenterKpisPage() {return (<div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>- </div>+ <HeaderWithAiUsage>+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>+ </div>+ </HeaderWithAiUsage><ActionCenterTabs />{brand ? (<KpisContent key={brand.id} brand={brand} />diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsxindex f681a792a..796361adb 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx@@ -57,6 +57,7 @@ import { toCsv } from '@/lib/csv';import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';import type { KpiTrendPoint } from '@/lib/actions/kpis';import { signalChangeTone, signedPercent, type SignalMetric } from '@/lib/signals/metrics';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';const SIGNAL_EXPORT_HEADERS = ['title',@@ -103,10 +104,12 @@ export default function ActionCenterSignalsPage() {return (<div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>- </div>+ <HeaderWithAiUsage>+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>+ </div>+ </HeaderWithAiUsage><ActionCenterTabs />{brand ? (<SignalsContent key={brand.id} brand={brand} />diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsxindex 36e878808..1dffa900b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx@@ -61,6 +61,7 @@ import { usePagesExport } from './_use-pages-export';import { nextAutoRun } from '@/lib/audit-auto-runs';import { cn } from '@/lib/utils';import { parseListTab, withListTab, type ListTab } from './_list-tab';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';type RangePreset = '7d' | '30d' | '90d' | 'all';const RANGE_DAYS: Record<RangePreset, number | null> = { '7d': 7, '30d': 30, '90d': 90, all: null };@@ -528,16 +529,18 @@ export default function SiteAuditPage() {return (<div className="space-y-6">- <div className="flex items-start justify-between gap-4">- <div>- <h1 className="text-2xl font-bold">{t('title')}</h1>- <p className="text-sm text-muted-foreground">{t('description')}</p>+ <HeaderWithAiUsage>+ <div className="flex items-start justify-between gap-4">+ <div>+ <h1 className="text-2xl font-bold">{t('title')}</h1>+ <p className="text-sm text-muted-foreground">{t('description')}</p>+ </div>+ <Button variant="outline" className="shrink-0" onClick={() => setSettingsOpen(true)}>+ <Settings className="h-4 w-4" />+ {t('settings.button')}+ </Button></div>- <Button variant="outline" className="shrink-0" onClick={() => setSettingsOpen(true)}>- <Settings className="h-4 w-4" />- {t('settings.button')}- </Button>- </div>+ </HeaderWithAiUsage><AuditSettingsDialogbrandId={activeBrandId}open={settingsOpen}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsxindex 154567e53..4dcf81a4b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx@@ -8,6 +8,7 @@ import { BrandsClient } from './_brands-client';import { WorkspaceSettingsMenu } from '@/components/layout/workspace-settings-menu';import { Button } from '@/components/ui/button';import { Crown, Plus } from 'lucide-react';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';function BrandsHeader({canManage,@@ -21,30 +22,32 @@ function BrandsHeader({}) {const t = useTranslations('brands');return (- <div className="flex flex-wrap items-center justify-between gap-4">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-muted-foreground text-sm">{t('description')}</p>+ <HeaderWithAiUsage>+ <div className="flex flex-wrap items-center justify-between gap-4">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-muted-foreground text-sm">{t('description')}</p>+ </div>+ <div className="flex items-center gap-2">+ <WorkspaceSettingsMenu />+ {!canManage ? null : canAddBrand ? (+ <Link href="/dashboard/brands/new">+ <Button className="gap-2">+ <Plus className="h-4 w-4" />+ {t('addBrand')}+ </Button>+ </Link>+ ) : needsUpgrade ? (+ <Link href="/dashboard/settings?tab=billing">+ <Button variant="outline" className="gap-2">+ <Crown className="h-4 w-4" />+ {t('addBrand')}+ </Button>+ </Link>+ ) : null}+ </div></div>- <div className="flex items-center gap-2">- <WorkspaceSettingsMenu />- {!canManage ? null : canAddBrand ? (- <Link href="/dashboard/brands/new">- <Button className="gap-2">- <Plus className="h-4 w-4" />- {t('addBrand')}- </Button>- </Link>- ) : needsUpgrade ? (- <Link href="/dashboard/settings?tab=billing">- <Button variant="outline" className="gap-2">- <Crown className="h-4 w-4" />- {t('addBrand')}- </Button>- </Link>- ) : null}- </div>- </div>+ </HeaderWithAiUsage>);}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsxindex f8fb22848..9bd0f8825 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx@@ -85,6 +85,7 @@ import {} from '@/components/ui/table';import { Skeleton } from '@/components/ui/skeleton';import { cn } from '@/lib/utils';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';// ─── Constants ───────────────────────────────────────────────────────────────@@ -1180,34 +1181,36 @@ export default function CitationsPage() {return (<div className="space-y-6">- <div className="flex items-start justify-between gap-4">- <div>- <h1 className="text-2xl font-bold">{t('title')}</h1>- <p className="mt-1 text-sm text-muted-foreground">{t('description')}</p>- </div>- <span- title={- sourceTab === 'types'- ? 'Source Types is a chart breakdown, not exportable — switch to Domains, URLs, or Competitor Gaps to export.'- : undefined- }- >- <Button- variant="outline"- className="gap-2"- onClick={handleExportCsv}- disabled={exportDisabled}+ <HeaderWithAiUsage>+ <div className="flex items-start justify-between gap-4">+ <div>+ <h1 className="text-2xl font-bold">{t('title')}</h1>+ <p className="mt-1 text-sm text-muted-foreground">{t('description')}</p>+ </div>+ <span+ title={+ sourceTab === 'types'+ ? 'Source Types is a chart breakdown, not exportable — switch to Domains, URLs, or Competitor Gaps to export.'+ : undefined+ }>- {isExporting ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Download className="h-4 w-4" />- )}-- {isExporting ? tCommon('exporting') : tCommon('exportCsv')}- </Button>- </span>- </div>+ <Button+ variant="outline"+ className="gap-2"+ onClick={handleExportCsv}+ disabled={exportDisabled}+ >+ {isExporting ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Download className="h-4 w-4" />+ )}++ {isExporting ? tCommon('exporting') : tCommon('exportCsv')}+ </Button>+ </span>+ </div>+ </HeaderWithAiUsage><CitationsFilterBarfilters={filters}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsxindex cb184a9e9..c05e0ccb8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx@@ -69,6 +69,7 @@ import {Eye,Download,} from 'lucide-react';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';// ─── Shared Visual Components (mirroring Insights) ───────────────────────────@@ -117,10 +118,12 @@ function PlanGateOverlay() {const t = useTranslations('competitors');return (<div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-muted-foreground">{t('description')}</p>- </div>+ <HeaderWithAiUsage>+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-muted-foreground">{t('description')}</p>+ </div>+ </HeaderWithAiUsage><Card><CardContent className="flex flex-col items-center justify-center py-16 text-center"><div className="flex h-14 w-14 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30 mb-4">@@ -144,10 +147,12 @@ function NoBrandSelected() {const t = useTranslations('competitors');return (<div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-muted-foreground">{t('description')}</p>- </div>+ <HeaderWithAiUsage>+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-muted-foreground">{t('description')}</p>+ </div>+ </HeaderWithAiUsage><Card><CardContent className="flex flex-col items-center justify-center py-16 text-center"><div className="flex h-14 w-14 items-center justify-center rounded-full bg-white mb-4">@@ -1513,10 +1518,12 @@ export default function CompetitorsPage() {if (loading) {return (<div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-muted-foreground">{t('description')}</p>- </div>+ <HeaderWithAiUsage>+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-muted-foreground">{t('description')}</p>+ </div>+ </HeaderWithAiUsage><div className="flex items-center justify-center py-20"><Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /></div>@@ -1527,39 +1534,41 @@ export default function CompetitorsPage() {return (<div className="space-y-6">{/* Header */}- <div className="flex flex-wrap items-start justify-between gap-3">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-muted-foreground">{t('description')}</p>- </div>- <div className="flex flex-wrap items-end gap-3">- <div className="flex items-center gap-2">- <DateRangeFilter- value={datePreset}- presets={COMPETITOR_DATE_PRESETS}- onChange={setDatePreset}- from={dateFrom}- to={dateTo}- onFromChange={setDateFrom}- onToChange={setDateTo}- />- {comparisonLoading && (- <Loader2- className="mb-2 h-4 w-4 animate-spin text-muted-foreground"- aria-hidden="true"+ <HeaderWithAiUsage>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-muted-foreground">{t('description')}</p>+ </div>+ <div className="flex flex-wrap items-end gap-3">+ <div className="flex items-center gap-2">+ <DateRangeFilter+ value={datePreset}+ presets={COMPETITOR_DATE_PRESETS}+ onChange={setDatePreset}+ from={dateFrom}+ to={dateTo}+ onFromChange={setDateFrom}+ onToChange={setDateTo}/>- )}+ {comparisonLoading && (+ <Loader2+ className="mb-2 h-4 w-4 animate-spin text-muted-foreground"+ aria-hidden="true"+ />+ )}+ </div>+ <Button variant="outline" className="gap-2" onClick={() => setSuggestDialogOpen(true)}>+ <Sparkles className="h-4 w-4" />+ {t('suggestCompetitors')}+ </Button>+ <Button className="gap-2" onClick={() => setDialogOpen(true)}>+ <Plus className="h-4 w-4" />+ {t('addCompetitor')}+ </Button></div>- <Button variant="outline" className="gap-2" onClick={() => setSuggestDialogOpen(true)}>- <Sparkles className="h-4 w-4" />- {t('suggestCompetitors')}- </Button>- <Button className="gap-2" onClick={() => setDialogOpen(true)}>- <Plus className="h-4 w-4" />- {t('addCompetitor')}- </Button></div>- </div>+ </HeaderWithAiUsage>{competitors.length === 0 ? (<EmptyStatediff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsxindex 9617fc323..0712e7585 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx@@ -49,6 +49,7 @@ import { readUrlChoice, writeUrlParams } from '@/lib/url-state';import { useBrandStore } from '@/stores/use-brand-store';import { LibraryExportMenu, useLibraryExport } from './_library-export';import { LibraryTable, type LibraryRowActions } from './_library-table';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';/** A read of the brand's drafts: null until it comes back. */interface LibraryRead {@@ -199,23 +200,25 @@ export default function ContentLibraryPage() {return (<div className="space-y-6">- <div className="flex flex-wrap items-start justify-between gap-3">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-sm text-muted-foreground">{t('description')}</p>- </div>- <div className="flex items-center gap-2">- <LibraryExportMenu- disabled={listed.length === 0}- exporting={exporting}- onExport={(format) => void exportList(listed, tab, format)}- />- <Button className="gap-2" onClick={() => setStarting(true)}>- <Plus className="h-4 w-4" />- {t('newContent')}- </Button>+ <HeaderWithAiUsage>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-sm text-muted-foreground">{t('description')}</p>+ </div>+ <div className="flex items-center gap-2">+ <LibraryExportMenu+ disabled={listed.length === 0}+ exporting={exporting}+ onExport={(format) => void exportList(listed, tab, format)}+ />+ <Button className="gap-2" onClick={() => setStarting(true)}>+ <Plus className="h-4 w-4" />+ {t('newContent')}+ </Button>+ </div></div>- </div>+ </HeaderWithAiUsage><NewContentDialogopen={starting}onOpenChange={setStarting}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex 62d69985f..f871085a9 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -118,6 +118,7 @@ import { LoadingDots } from '@/components/ui/loading-dots';import { PAGE_SIZE, TablePager, usePagination } from '@/components/table-pager';import { toCsv } from '@/lib/csv';import { readUrlChoice, writeUrlParams } from '@/lib/url-state';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';const GENERATION_STORAGE_KEY = 'aeo:content-generation';@@ -1049,34 +1050,36 @@ export default function ContentPage() {return (<div className="space-y-6">- <div className="flex items-center justify-between gap-4 flex-wrap">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-muted-foreground text-sm">{t('description')}</p>- </div>- <div className="flex items-center gap-2">- {newButton}- <Button- onClick={handleExportCsv}- disabled={exporting || loading || total === 0}- variant="outline"- size="sm"- className="gap-2"- >- {exporting ? <LoadingDots /> : <Download className="h-4 w-4" />}- {tCommon('exportCsv')}- </Button>- <Button- onClick={() => setWebhookOpen(true)}- variant="outline"- size="sm"- className="gap-2"- >- <Settings2 className="h-4 w-4" />- {t('webhook.title')}- </Button>+ <HeaderWithAiUsage>+ <div className="flex items-center justify-between gap-4 flex-wrap">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-muted-foreground text-sm">{t('description')}</p>+ </div>+ <div className="flex items-center gap-2">+ {newButton}+ <Button+ onClick={handleExportCsv}+ disabled={exporting || loading || total === 0}+ variant="outline"+ size="sm"+ className="gap-2"+ >+ {exporting ? <LoadingDots /> : <Download className="h-4 w-4" />}+ {tCommon('exportCsv')}+ </Button>+ <Button+ onClick={() => setWebhookOpen(true)}+ variant="outline"+ size="sm"+ className="gap-2"+ >+ <Settings2 className="h-4 w-4" />+ {t('webhook.title')}+ </Button>+ </div></div>- </div>+ </HeaderWithAiUsage>{loading && opportunities.length === 0 ? (<div className="flex items-center justify-center min-h-[300px]">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsxindex c2109a373..88f9f9346 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx@@ -39,6 +39,7 @@ import { useBrandStore } from '@/stores/use-brand-store';import { AssignDialog } from './_assign-dialog';import { AiResultsStrip, PageTypeMix } from './_plan-insights';import { PlanTable } from './_plan-table';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';type PlanRead = {brandId: string;@@ -287,46 +288,48 @@ export default function ContentPlanPage() {return (<div className="space-y-6">- <div className="flex flex-wrap items-start justify-between gap-3">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-sm text-muted-foreground">{t('description')}</p>- </div>- <div className="flex flex-wrap items-center gap-2">- <div- role="group"- aria-label={t('period')}- className="inline-flex rounded-lg border bg-muted/40 p-0.5"- >- {PLAN_PERIODS.map((value) => (- <button- key={value}- type="button"- aria-pressed={days === value}- onClick={() => changeDays(value)}- className={cn(- 'rounded-md px-3 py-1 text-sm transition-colors',- days === value- ? 'bg-background font-medium shadow-sm'- : 'text-muted-foreground hover:text-foreground',- )}- >- {t('periods', { days: value })}- </button>- ))}+ <HeaderWithAiUsage>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-sm text-muted-foreground">{t('description')}</p>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <div+ role="group"+ aria-label={t('period')}+ className="inline-flex rounded-lg border bg-muted/40 p-0.5"+ >+ {PLAN_PERIODS.map((value) => (+ <button+ key={value}+ type="button"+ aria-pressed={days === value}+ onClick={() => changeDays(value)}+ className={cn(+ 'rounded-md px-3 py-1 text-sm transition-colors',+ days === value+ ? 'bg-background font-medium shadow-sm'+ : 'text-muted-foreground hover:text-foreground',+ )}+ >+ {t('periods', { days: value })}+ </button>+ ))}+ </div>+ <Button+ className="gap-2"+ onClick={() => {+ setPreset(null);+ setStarting(true);+ }}+ >+ <Plus className="h-4 w-4" />+ {t('newContent')}+ </Button></div>- <Button- className="gap-2"- onClick={() => {- setPreset(null);- setStarting(true);- }}- >- <Plus className="h-4 w-4" />- {t('newContent')}- </Button></div>- </div>+ </HeaderWithAiUsage><NewContentDialogopen={starting}onOpenChange={(open) => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex c526bae6f..9aed94b52 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -491,6 +491,7 @@ function NoDataForPeriod({ datePreset, onReset }: { datePreset: DatePreset; onReimport { saveTrackingJob, loadTrackingJob, clearTrackingJob } from '@/lib/tracking-job-store';import { toCsv } from '@/lib/csv';import { RunLine } from './_run-line';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';function TrackingProgressBanner({jobStatus,@@ -1095,10 +1096,12 @@ export default function InsightsPage() {if (trulyEmpty) {return (<div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-muted-foreground text-sm">{brand.name}</p>- </div>+ <HeaderWithAiUsage>+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-muted-foreground text-sm">{brand.name}</p>+ </div>+ </HeaderWithAiUsage><TrackingProgressBanner jobStatus={jobStatus} onStop={handleStopTracking} />{!localJobActive && <ServerRunBanner run={cronRun} />}<EmptyState onRunPrompts={handleRunPrompts} isRunning={isRunning} isCloud={isCloud} />@@ -1138,63 +1141,69 @@ export default function InsightsPage() {return (<div className="space-y-6">{/* Header */}- <div className="flex items-start justify-between gap-4">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>-- {/* The brand's last full run from the ledger; before the ledger has- one, the newest answer in view. */}- <RunLine- brandName={brand.name}- lastRunAt={runTimes.lastRunAt ?? summary?.lastCheckedAt ?? null}- nextRunAt={runTimes.nextRunAt}- hasData={hasAnyData === true}- />- </div>+ <HeaderWithAiUsage>+ <div className="flex items-start justify-between gap-4">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>++ {/* The brand's last full run from the ledger; before the ledger has+ one, the newest answer in view. */}+ <RunLine+ brandName={brand.name}+ lastRunAt={runTimes.lastRunAt ?? summary?.lastCheckedAt ?? null}+ nextRunAt={runTimes.nextRunAt}+ hasData={hasAnyData === true}+ />+ </div>- <div className="flex items-center gap-2 shrink-0">- {/* Always visible */}- <FormulaDialog />+ <div className="flex items-center gap-2 shrink-0">+ {/* Always visible */}+ <FormulaDialog />++ <Button+ variant="outline"+ className="gap-2"+ onClick={handleExportCsv}+ disabled={isExporting}+ >+ {isExporting ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Download className="h-4 w-4" />+ )}+ {isExporting ? tCommon('exporting') : tCommon('exportCsv')}+ </Button>- <Button- variant="outline"- className="gap-2"- onClick={handleExportCsv}- disabled={isExporting}- >- {isExporting ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Download className="h-4 w-4" />- )}- {isExporting ? tCommon('exporting') : tCommon('exportCsv')}- </Button>+ <Link href="/dashboard/reports" className={cn(buttonVariants(), 'gap-2')}>+ <FileText className="h-4 w-4" />+ Reports+ </Link>- <Link href="/dashboard/reports" className={cn(buttonVariants(), 'gap-2')}>- <FileText className="h-4 w-4" />- Reports- </Link>+ {/* Self-host only */}+ {!isCloud && (+ <>+ <Button+ variant="outline"+ onClick={() => setShowSinglePrompt(true)}+ className="gap-2"+ >+ <FlaskConical className="h-4 w-4" />+ Test Single Prompt+ </Button>- {/* Self-host only */}- {!isCloud && (- <>- <Button variant="outline" onClick={() => setShowSinglePrompt(true)} className="gap-2">- <FlaskConical className="h-4 w-4" />- Test Single Prompt- </Button>-- <Button onClick={handleRunPrompts} disabled={isRunning} className="gap-2">- {isRunning ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Play className="h-4 w-4" />- )}- Run All- </Button>- </>- )}+ <Button onClick={handleRunPrompts} disabled={isRunning} className="gap-2">+ {isRunning ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Play className="h-4 w-4" />+ )}+ Run All+ </Button>+ </>+ )}+ </div></div>- </div>+ </HeaderWithAiUsage>{/* Filter Bar */}<FilterBardiff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsxindex 6805744d5..51686c6a0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx@@ -24,6 +24,7 @@ import { MentionsListTab } from './_mentions-tab';import { MentionsOverviewTab } from './_overview';import { MentionsPerceptionTab } from './_perception';import { useMentionsExport } from './_use-mentions-export';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';/*** Mentions & Sentiment (MS-05): where AI mentions the brand, how it describes@@ -105,13 +106,15 @@ export default function MentionsPage() {return (<div className="space-y-6">- <div className="flex flex-wrap items-start justify-between gap-3">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-sm text-muted-foreground">{t('description')}</p>+ <HeaderWithAiUsage>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-sm text-muted-foreground">{t('description')}</p>+ </div>+ {urlRead && <MentionsHeaderActions tab={tab} exporter={exporter} />}</div>- {urlRead && <MentionsHeaderActions tab={tab} exporter={exporter} />}- </div>+ </HeaderWithAiUsage><Tabs value={tab} onValueChange={(v) => setTab(v as MentionsTab)}><TabsList aria-label={t('tabs.label')}>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex 85aa9af10..761a76a1a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -224,6 +224,7 @@ import {type PositionsRange,} from '@/lib/positions-range';import { viewerTimeZone } from '@/lib/time-zone';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';// ─── Info Tooltip ─────────────────────────────────────────────────────────────@@ -1887,14 +1888,16 @@ export default function PromptsPage() {return (<div className="space-y-6">{/* Header */}- <div className="flex items-center justify-between gap-4 flex-wrap">- <div>- <h1 className="text-2xl font-bold tracking-tight">Prompts</h1>- <p className="text-muted-foreground text-sm">- Manage every tracked prompt and review estimated AI demand- </p>+ <HeaderWithAiUsage>+ <div className="flex items-center justify-between gap-4 flex-wrap">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">Prompts</h1>+ <p className="text-muted-foreground text-sm">+ Manage every tracked prompt and review estimated AI demand+ </p>+ </div></div>- </div>+ </HeaderWithAiUsage><Tabs value={tab} onValueChange={(v) => showSection(v as TabId, view)}><div className="flex items-center justify-between gap-4 flex-wrap">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsxindex 5bc0d1873..0375ee3bf 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx@@ -30,6 +30,7 @@ import { formatDate } from '@/lib/format';import { cn } from '@/lib/utils';import { PLATFORM_LABELS } from '@/config/platform-labels';import { REPORT_TEMPLATES } from '@/lib/reports/templates';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';const KNOWN_TEMPLATE_IDS = new Set<string>(REPORT_TEMPLATES.map((tpl) => tpl.id));@@ -203,34 +204,36 @@ export default function ReportDetailPage() {return (<div className="space-y-6">- <div className="flex items-center justify-between">- <div className="space-y-1">- <Link- href="/dashboard/reports"- className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"- >- <ArrowLeft className="h-4 w-4" />- {t('backToReports')}- </Link>- <h1 className="text-2xl font-bold tracking-tight">{report.title}</h1>- <p className="text-sm text-muted-foreground">- {KNOWN_TEMPLATE_IDS.has(report.template) &&- t.has(`templates.${report.template}.name`) && (- <>{t(`templates.${report.template}.name`)} · </>- )}- {formatDate(report.dateFrom)} — {formatDate(report.dateTo)} · {t('generatedOn')}{' '}- {formatDate(report.createdAt)}- </p>+ <HeaderWithAiUsage>+ <div className="flex items-center justify-between">+ <div className="space-y-1">+ <Link+ href="/dashboard/reports"+ className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"+ >+ <ArrowLeft className="h-4 w-4" />+ {t('backToReports')}+ </Link>+ <h1 className="text-2xl font-bold tracking-tight">{report.title}</h1>+ <p className="text-sm text-muted-foreground">+ {KNOWN_TEMPLATE_IDS.has(report.template) &&+ t.has(`templates.${report.template}.name`) && (+ <>{t(`templates.${report.template}.name`)} · </>+ )}+ {formatDate(report.dateFrom)} — {formatDate(report.dateTo)} · {t('generatedOn')}{' '}+ {formatDate(report.createdAt)}+ </p>+ </div>+ <Button onClick={handleDownloadPdf} disabled={downloading} className="gap-2">+ {downloading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <FileDown className="h-4 w-4" />+ )}+ {t('downloadPDF')}+ </Button></div>- <Button onClick={handleDownloadPdf} disabled={downloading} className="gap-2">- {downloading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <FileDown className="h-4 w-4" />- )}- {t('downloadPDF')}- </Button>- </div>+ </HeaderWithAiUsage>{/* Everything below renders from the immutable saved payload; thecontainer id is the future PDF capture root. */}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsxindex 9a3addd20..0189cbd95 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/page.tsx@@ -42,6 +42,7 @@ import {type ReportSection,type ReportTemplateId,} from '@/lib/reports/templates';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';type DatePreset = '7d' | '30d' | '90d' | 'custom';@@ -184,16 +185,18 @@ export default function ReportsPage() {return (<div className="space-y-6">- <div className="flex items-center justify-between">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-muted-foreground">{t('description')}</p>+ <HeaderWithAiUsage>+ <div className="flex items-center justify-between">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-muted-foreground">{t('description')}</p>+ </div>+ <Button className="gap-2" onClick={openDialog} disabled={!activeBrandId}>+ <Plus className="h-4 w-4" />+ {t('generateReport')}+ </Button></div>- <Button className="gap-2" onClick={openDialog} disabled={!activeBrandId}>- <Plus className="h-4 w-4" />- {t('generateReport')}- </Button>- </div>+ </HeaderWithAiUsage><Card><CardHeader>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsxindex 9d407affe..89abcffbd 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx@@ -28,6 +28,7 @@ import {settingsSectionPath,type SettingsSection,} from './_sections';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';/*** Settings, opened on `section`: from its own address (/dashboard/settings/@@ -95,10 +96,12 @@ export function SettingsView({ section }: { section: SettingsSection }) {return (<div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>- <p className="text-muted-foreground">{t('description')}</p>- </div>+ <HeaderWithAiUsage>+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-muted-foreground">{t('description')}</p>+ </div>+ </HeaderWithAiUsage><Separator />diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsxindex 2ac7b1e1d..109da1cf2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx@@ -91,6 +91,7 @@ import { toCsv } from '@/lib/csv';import { PLATFORM_LABELS } from '@/config/platform-labels';import { formatRegionDisplay } from '@/lib/region';import type { AmazonShareDropAlert } from '@/lib/shopping-amazon-share-alert';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';const DATE_PRESETS: ShoppingDatePreset[] = ['7d', '30d', '90d', 'all'];@@ -785,13 +786,15 @@ function PromptsTabContent({function PageHeader({ t }: { t: ReturnType<typeof useTranslations<'shopping'>> }) {return (- <div>- <h1 className="flex items-center gap-2 text-2xl font-bold tracking-tight">- <ShoppingBag className="h-6 w-6 text-primary" />- {t('title')}- </h1>- <p className="mt-1 text-sm text-muted-foreground">{t('description')}</p>- </div>+ <HeaderWithAiUsage>+ <div>+ <h1 className="flex items-center gap-2 text-2xl font-bold tracking-tight">+ <ShoppingBag className="h-6 w-6 text-primary" />+ {t('title')}+ </h1>+ <p className="mt-1 text-sm text-muted-foreground">{t('description')}</p>+ </div>+ </HeaderWithAiUsage>);}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex 68172aa21..1dd421fbf 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -89,6 +89,7 @@ import {getTrafficTrend,} from '@/lib/traffic-reads';import { RangeReadyProvider, rangeKeyOf, useRangeGate } from './_range-ready';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';const PAGE_SIZE = 10;@@ -693,29 +694,31 @@ function TrafficPageContent({ brand }: { brand: Brand }) {return (<div className="space-y-6">{/* Header */}- <div className="flex flex-wrap items-start justify-between gap-3">- <div>- <h1 className="text-2xl font-bold tracking-tight">AI Traffic Analytics</h1>- <p className="text-muted-foreground text-sm">- {primaryDomain ? `${primaryDomain} · ` : ''}AI-referred visits to your website- </p>- </div>- {/* items-end, not items-center: the range control is two rows tall- (its label sits above the buttons), so centring left the Export- button floating above the segmented control's baseline. */}- <div className="flex flex-wrap items-end gap-3">- <DateRangeFilter- value={datePreset}- presets={DATE_PRESETS}- onChange={handleDatePresetChange}- from={customFrom}- to={customTo}- onFromChange={handleCustomFromChange}- onToChange={handleCustomToChange}- />- <ExportMenu exporter={exporter} />+ <HeaderWithAiUsage>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">AI Traffic Analytics</h1>+ <p className="text-muted-foreground text-sm">+ {primaryDomain ? `${primaryDomain} · ` : ''}AI-referred visits to your website+ </p>+ </div>+ {/* items-end, not items-center: the range control is two rows tall+ (its label sits above the buttons), so centring left the Export+ button floating above the segmented control's baseline. */}+ <div className="flex flex-wrap items-end gap-3">+ <DateRangeFilter+ value={datePreset}+ presets={DATE_PRESETS}+ onChange={handleDatePresetChange}+ from={customFrom}+ to={customTo}+ onFromChange={handleCustomFromChange}+ onToChange={handleCustomToChange}+ />+ <ExportMenu exporter={exporter} />+ </div></div>- </div>+ </HeaderWithAiUsage>{!rangeGate.settled && rangeSpinner}<RangeReadyProvider value={rangeGate.value}>diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsxindex ee29d5ad0..94a28b6e7 100644--- a/web/src/app/[locale]/(dashboard)/layout.tsx+++ b/web/src/app/[locale]/(dashboard)/layout.tsx@@ -5,6 +5,7 @@ import { SidebarErrorBoundary } from '@/components/layout/sidebar-error-boundaryimport { MobileNav } from '@/components/layout/mobile-nav';import { AuthProvider } from '@/components/providers/auth-provider';import { PlanProvider } from '@/components/providers/plan-provider';+import { AiUsageProvider } from '@/components/providers/ai-usage-provider';import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';import { BrandLoader } from '@/components/providers/brand-loader';import { BrandGuard } from '@/components/providers/brand-guard';@@ -88,25 +89,27 @@ export default async function DashboardLayout({ children }: { children: React.Re<GettingStartedPageOpened /><PlanProvider planId={planId} allowedModelIds={allowedModelIds}><RoleProvider role={role}>- <div className="flex h-screen overflow-hidden">- {/* Desktop sidebar */}- <div className="relative hidden md:flex md:flex-shrink-0">- <SidebarErrorBoundary>- <Sidebar />- </SidebarErrorBoundary>- </div>+ <AiUsageProvider>+ <div className="flex h-screen overflow-hidden">+ {/* Desktop sidebar */}+ <div className="relative hidden md:flex md:flex-shrink-0">+ <SidebarErrorBoundary>+ <Sidebar />+ </SidebarErrorBoundary>+ </div>- {/* Main area */}- <div className="flex flex-1 flex-col overflow-hidden">- <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">- <MobileNav />+ {/* Main area */}+ <div className="flex flex-1 flex-col overflow-hidden">+ <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">+ <MobileNav />+ </div>+ <main className="flex-1 overflow-y-auto bg-background p-6">+ <BrandGuard>{children}</BrandGuard>+ </main>+ <TrackingJobHandoff /></div>- <main className="flex-1 overflow-y-auto bg-background p-6">- <BrandGuard>{children}</BrandGuard>- </main>- <TrackingJobHandoff /></div>- </div>+ </AiUsageProvider></RoleProvider></PlanProvider></>diff --git a/web/src/components/ai-usage/ai-usage-meter.test.tsx b/web/src/components/ai-usage/ai-usage-meter.test.tsxnew file mode 100644index 000000000..729af815c--- /dev/null+++ b/web/src/components/ai-usage/ai-usage-meter.test.tsx@@ -0,0 +1,341 @@+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 { RoleProvider, type TeamRole } from '@/components/providers/role-provider';+import type { AiUsage, UsageLimits } from '@/lib/billing/ai-usage';+import { readAiUsage, readUsageLimits } from '@/lib/billing/ai-usage-client';++/**+ * The header meter (AI usage spec §3.1, §4): the share of the month's AI+ * allowance on every page, read once for all of them, and its popover.+ */++const env = { cloud: true, pathname: '/dashboard/insights' };+vi.mock('@/config/plans', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/config/plans')>()),+ isCloud: () => env.cloud,+}));+vi.mock('next/navigation', () => ({ usePathname: () => env.pathname }));+vi.mock('@/i18n/navigation', () => ({+ Link: ({+ href,+ className,+ onClick,+ children,+ }: {+ href: string;+ className?: string;+ onClick?: () => void;+ children: ReactNode;+ }) => (+ <a+ href={href}+ className={className}+ onClick={(e) => {+ e.preventDefault();+ onClick?.();+ }}+ >+ {children}+ </a>+ ),+}));+vi.mock('@/stores/use-brand-store', () => ({+ useBrandStore: (selector: (state: { activeBrandId: string | null }) => unknown) =>+ selector({ activeBrandId: 'b1' }),+}));+vi.mock('@/lib/billing/ai-usage-client', () => ({+ readAiUsage: vi.fn(),+ readUsageLimits: vi.fn(),+}));++const { AiUsageProvider, AI_USAGE_STALE_MS } =+ await import('@/components/providers/ai-usage-provider');+const { AiUsageMeter, HeaderWithAiUsage } = await import('./ai-usage-meter');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const usage = (over: Partial<AiUsage> = {}): AiUsage => ({+ plan: 'growth',+ planName: 'Growth',+ periodStart: '2026-10-20T09:00:00.000Z',+ periodEnd: '2026-11-20T09:00:00.000Z',+ unlimited: false,+ percentUsed: 21.4,+ features: [+ { feature: 'improve', percent: 4 },+ { feature: 'content', percent: 17.2 },+ { feature: 'action_center', percent: 0.2 },+ ],+ ...over,+});+const limits: UsageLimits = {+ auditPages: { used: 42, limit: 500 },+ promptLocations: { used: 1148, limit: 2000 },+};++let container: HTMLDivElement;+let root: Root;++async function render(role: TeamRole = 'admin', children: ReactNode = <AiUsageMeter />) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <RoleProvider role={role}>+ <AiUsageProvider>{children}</AiUsageProvider>+ </RoleProvider>+ </NextIntlClientProvider>,+ );+ });+ await act(async () => {});+}+async function remount(role: TeamRole = 'admin') {+ act(() => root.unmount());+ root = createRoot(container);+ await render(role);+}++const trigger = () => container.querySelector<HTMLButtonElement>('button');+const popup = () => document.querySelector<HTMLElement>('[data-slot="popover-content"]');+const links = () =>+ [...popup()!.querySelectorAll('a')].map((a) => [a.textContent, a.getAttribute('href')]);+async function open() {+ await act(async () => trigger()!.click());+ await act(async () => {});+}++beforeEach(() => {+ env.cloud = true;+ env.pathname = '/dashboard/insights';+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ vi.mocked(readAiUsage).mockReset().mockResolvedValue(usage());+ vi.mocked(readUsageLimits).mockReset().mockResolvedValue(limits);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.restoreAllMocks();+});++describe('AiUsageMeter', () => {+ it('shows the month’s share with a bar, named with what it shows', async () => {+ await render();+ const button = trigger()!;+ expect(button.textContent).toBe('AI21%');+ expect(button.getAttribute('aria-label')).toBe('AI 21% used this month');+ expect(button.className).toContain('text-foreground');+ expect(button.querySelector<HTMLElement>('[style]')!.style.width).toBe('21.4%');+ });++ it('keeps its room while the first read runs, from a phone’s width up', async () => {+ vi.mocked(readAiUsage).mockReturnValue(new Promise(() => {}));+ await render();+ expect(trigger()).toBeNull();+ const box = container.querySelector('span[aria-hidden]')!;+ expect(box.className).toContain('hidden');+ expect(box.className).toContain('sm:inline-block');+ });++ it('shows nothing on a plan without an allowance, without an active plan, or self-hosted', async () => {+ vi.mocked(readAiUsage).mockResolvedValue(usage({ unlimited: true, percentUsed: null }));+ await render();+ expect(container.innerHTML).toBe('');++ vi.mocked(readAiUsage).mockResolvedValue(null);+ await remount();+ expect(container.innerHTML).toBe('');++ env.cloud = false;+ vi.mocked(readAiUsage).mockClear();+ await remount();+ expect(container.innerHTML).toBe('');+ expect(readAiUsage).not.toHaveBeenCalled();+ });++ it('turns amber from 80% and red once used up, and says so in its name', async () => {+ vi.mocked(readAiUsage).mockResolvedValue(usage({ percentUsed: 84 }));+ await render();+ expect(trigger()!.className).toContain('text-amber-700');+ expect(trigger()!.getAttribute('aria-label')).toBe(+ 'AI 84% used this month, close to the limit',+ );++ vi.mocked(readAiUsage).mockResolvedValue(usage({ percentUsed: 100 }));+ await remount();+ expect(trigger()!.className).toContain('text-red-700');+ expect(trigger()!.getAttribute('aria-label')).toBe(+ 'AI 100% used this month, the limit is reached',+ );+ await open();+ expect(popup()!.textContent).toContain(+ 'Used up. AI features stop until Nov 20; Agent Chat on your own AI key keeps working.',+ );+ });++ it('opens what used it, what isn’t counted, the other limits and where to get more', async () => {+ await render();+ await open();+ const text = popup()!.textContent;+ expect(text).toContain('Shared by every seat · resets Nov 20');+ expect(popup()!.getAttribute('aria-labelledby')).toBeTruthy();+ expect(document.getElementById(popup()!.getAttribute('aria-labelledby')!)!.textContent).toBe(+ 'AI usage this month · Growth plan',+ );+ const rows = [...popup()!.querySelectorAll('li')].map((li) => li.textContent);+ expect(rows).toEqual([+ 'Improve suggestions4%',+ 'Content Editor (briefs, Content Agent)17%',+ 'Action Center task writing<1%',+ 'Agent Chat, on your own AI keyNot counted',+ 'Site Audit pages42 of 500',+ 'Prompt locations1,148 of 2,000',+ ]);+ expect(readUsageLimits).toHaveBeenCalledWith('b1');+ // Opening reads the usage again.+ expect(readAiUsage).toHaveBeenCalledTimes(2);+ expect(links()).toEqual([+ ['Get more AI usage', '/dashboard/settings/billing'],+ ['Use your own key', '/dashboard/settings/ai-providers'],+ ['See details', '/dashboard/settings/billing#ai-usage'],+ ]);+ });++ it('closes when one of its links is followed', async () => {+ await render();+ await open();+ await act(async () => popup()!.querySelector('a')!.click());+ await act(async () => {});+ expect(trigger()!.getAttribute('aria-expanded')).toBe('false');+ });++ it('makes Get more the primary button from 80%, and leaves it out on Enterprise', async () => {+ await render();+ await open();+ expect(popup()!.querySelector('a')!.className).not.toContain('bg-primary');++ vi.mocked(readAiUsage).mockResolvedValue(usage({ percentUsed: 84 }));+ await remount();+ await open();+ const getMore = popup()!.querySelector('a')!;+ expect(getMore.textContent).toBe('Get more AI usage');+ expect(getMore.className).toContain('bg-primary');++ vi.mocked(readAiUsage).mockResolvedValue(usage({ plan: 'enterprise', planName: 'Enterprise' }));+ await remount();+ await open();+ expect(popup()!.textContent).not.toContain('Get more AI usage');+ });++ it('tells a member who isn’t an admin to ask one, instead of the admin’s links', async () => {+ await render('manager');+ await open();+ expect(popup()!.textContent).toContain(+ 'To get more AI usage or use your own key, ask an admin of your workspace.',+ );+ expect(links()).toEqual([['See details', '/dashboard/settings/billing#ai-usage']]);+ });++ it('leaves the other limits out when none has a cap', async () => {+ vi.mocked(readUsageLimits).mockResolvedValue({ auditPages: null, promptLocations: null });+ await render();+ await open();+ expect(popup()!.textContent).not.toContain('Other limits this month');+ });++ it('keeps the limits it shows while it reads them again, and only the latest read lands', async () => {+ const reads: ((value: UsageLimits) => void)[] = [];+ vi.mocked(readUsageLimits).mockImplementation(+ () => new Promise<UsageLimits>((resolve) => reads.push(resolve)),+ );+ await render();+ await open();+ expect(popup()!.textContent).toContain('Loading');+ await act(async () => reads[0](limits));+ expect(popup()!.textContent).toContain('42 of 500');++ // Closed and opened twice: the first of the two reads lands last.+ await act(async () => trigger()!.click());+ await open();+ await act(async () => trigger()!.click());+ await open();+ expect(popup()!.textContent).toContain('42 of 500');+ await act(async () => reads[2]({ ...limits, auditPages: { used: 44, limit: 500 } }));+ await act(async () => reads[1]({ ...limits, auditPages: { used: 43, limit: 500 } }));+ expect(popup()!.textContent).toContain('44 of 500');+ });+});++describe('HeaderWithAiUsage', () => {+ it('puts the meter after the page’s header row, under it on the right on a phone', async () => {+ await render(+ 'admin',+ <HeaderWithAiUsage>+ <h1>Mentions</h1>+ </HeaderWithAiUsage>,+ );+ const row = container.firstElementChild!;+ expect(row.firstElementChild!.textContent).toBe('Mentions');+ expect(row.lastElementChild).toBe(trigger());+ expect(trigger()!.className).toContain('self-end');+ expect(row.className).toContain('sm:flex-row');+ });+});++describe('AiUsageProvider', () => {+ it('reads once for every page, again on a page change once a minute old', async () => {+ let now = 1_000_000;+ vi.spyOn(Date, 'now').mockImplementation(() => now);+ await render();+ expect(readAiUsage).toHaveBeenCalledTimes(1);++ env.pathname = '/dashboard/prompts';+ await render();+ expect(readAiUsage).toHaveBeenCalledTimes(1);++ now += AI_USAGE_STALE_MS;+ env.pathname = '/dashboard/mentions';+ await render();+ expect(readAiUsage).toHaveBeenCalledTimes(2);+ });++ it('reads again on a return to the tab once a minute old, keeping the last read on a failure', async () => {+ let now = 1_000_000;+ vi.spyOn(Date, 'now').mockImplementation(() => now);+ await render();+ await act(async () => window.dispatchEvent(new Event('focus')));+ expect(readAiUsage).toHaveBeenCalledTimes(1);++ now += AI_USAGE_STALE_MS;+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(readAiUsage).mockRejectedValue(new Error('offline'));+ await act(async () => window.dispatchEvent(new Event('focus')));+ await act(async () => {});+ expect(readAiUsage).toHaveBeenCalledTimes(2);+ expect(trigger()!.textContent).toBe('AI21%');+ });++ it('reads again when the tab becomes visible, not while it is hidden', async () => {+ let now = 1_000_000;+ vi.spyOn(Date, 'now').mockImplementation(() => now);+ await render();+ now += AI_USAGE_STALE_MS;+ const visibility = vi.spyOn(document, 'visibilityState', 'get');++ visibility.mockReturnValue('hidden');+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));+ expect(readAiUsage).toHaveBeenCalledTimes(1);++ visibility.mockReturnValue('visible');+ vi.mocked(readAiUsage).mockResolvedValue(usage({ percentUsed: 30 }));+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));+ await act(async () => {});+ expect(readAiUsage).toHaveBeenCalledTimes(2);+ expect(trigger()!.textContent).toBe('AI30%');+ });+});diff --git a/web/src/components/ai-usage/ai-usage-meter.tsx b/web/src/components/ai-usage/ai-usage-meter.tsxnew file mode 100644index 000000000..90e3abe78--- /dev/null+++ b/web/src/components/ai-usage/ai-usage-meter.tsx@@ -0,0 +1,239 @@+'use client';++import { useRef, useState, type ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { Link } from '@/i18n/navigation';+import { useAiUsage } from '@/components/providers/ai-usage-provider';+import { buttonVariants } from '@/components/ui/button-variants';+import { LoadingDots } from '@/components/ui/loading-dots';+import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@/components/ui/popover';+import { useUserRole } from '@/hooks/use-user-role';+import {+ aiUsageTone,+ percentLabel,+ type UsageCount,+ type UsageLimits,+} from '@/lib/billing/ai-usage';+import { readUsageLimits } from '@/lib/billing/ai-usage-client';+import type { UsageTone } from '@/lib/content-usage';+import { formatMonthDay, formatNumber } from '@/lib/format';+import { cn } from '@/lib/utils';+import { useBrandStore } from '@/stores/use-brand-store';++/** Black under 80%, amber from 80%, red once used up (AI usage spec §4). */+const METER_CLASS: Record<UsageTone, string> = {+ normal: 'border-border text-foreground',+ warning: 'border-amber-500/70 text-amber-700 dark:border-amber-400/60 dark:text-amber-400',+ exhausted: 'border-red-500/70 text-red-700 dark:border-red-400/60 dark:text-red-400',+ unlimited: 'border-border text-muted-foreground',+};++const FILL_CLASS: Record<UsageTone, string> = {+ normal: 'bg-foreground',+ warning: 'bg-amber-500',+ exhausted: 'bg-red-500',+ unlimited: 'bg-muted-foreground/30',+};++const LABEL_KEY = {+ normal: 'meter.label',+ warning: 'meter.labelWarning',+ exhausted: 'meter.labelExhausted',+ unlimited: 'meter.label',+} as const satisfies Record<UsageTone, string>;++/**+ * A page's header row with the AI usage meter at its far right, on the+ * title's line (AI usage spec §3.1): the same place on every page, however+ * the row's own buttons wrap beside it. On a phone it goes under the row, on+ * the right, so the row keeps the whole width for its buttons.+ */+export function HeaderWithAiUsage({ children }: { children: ReactNode }) {+ return (+ <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:gap-3">+ <div className="min-w-0 sm:flex-1">{children}</div>+ <AiUsageMeter className="self-end sm:self-auto" />+ </div>+ );+}++/**+ * "AI 21%" at the far right of a page's header row (AI usage spec §3.1): the+ * share of the workspace's monthly AI allowance used, with a small bar. A+ * click opens what used it, what doesn't count, the limits that aren't AI,+ * and where to get more: getting more and an own key are an admin's to+ * change, so other members are told to ask one. Nothing on a plan without an+ * allowance; while the first read runs, an empty box of its size keeps the+ * header row from shifting.+ */+export function AiUsageMeter({ className }: { className?: string }) {+ const t = useTranslations('aiUsage');+ const tFeature = useTranslations('settings.aiUsageMeter.features');+ const tCommon = useTranslations('common');+ const { usage, refresh } = useAiUsage();+ const { canAdmin } = useUserRole();+ const brandId = useBrandStore((s) => s.activeBrandId);+ const [open, setOpen] = useState(false);+ // Undefined until the popover first opens, null while that first read runs;+ // a later opening keeps what it shows until the new read lands.+ const [limits, setLimits] = useState<UsageLimits | null | undefined>(undefined);+ // The latest read, so an earlier one landing late can't replace it.+ const limitsRead = useRef(0);++ if (usage === undefined) {+ return (+ <span+ aria-hidden+ className={cn('hidden h-8 w-[5.75rem] shrink-0 sm:inline-block', className)}+ />+ );+ }+ if (usage === null || usage.unlimited) return null;++ const tone = aiUsageTone(usage);+ const percent = usage.percentUsed ?? 0;+ const used = percentLabel(percent);+ const width = `${Math.min(100, percent)}%`;+ const resets = usage.periodEnd ? formatMonthDay(usage.periodEnd) : null;+ // A warning or a used-up allowance makes Get more the primary button (spec §4).+ const pressing = tone === 'warning' || tone === 'exhausted';++ const onOpenChange = (next: boolean) => {+ setOpen(next);+ if (!next) return;+ refresh();+ setLimits((shown) => shown ?? null);+ const id = ++limitsRead.current;+ void readUsageLimits(brandId).then((read) => {+ if (id === limitsRead.current) setLimits(read);+ });+ };+ const close = () => setOpen(false);++ const count = ({ used: n, limit }: UsageCount) =>+ t('popover.ofLimit', { used: formatNumber(n), limit: formatNumber(limit) });++ return (+ <Popover open={open} onOpenChange={onOpenChange}>+ <PopoverTrigger+ aria-label={t(LABEL_KEY[tone], { percent: used })}+ className={cn(+ 'inline-flex h-8 shrink-0 items-center gap-2 rounded-full border bg-background px-3 text-xs font-medium transition-colors outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50 aria-expanded:bg-muted',+ METER_CLASS[tone],+ className,+ )}+ >+ <span aria-hidden>{t('meter.ai')}</span>+ <span aria-hidden className="block h-1.5 w-11 overflow-hidden rounded-full bg-muted">+ <span className={cn('block h-full rounded-full', FILL_CLASS[tone])} style={{ width }} />+ </span>+ <span aria-hidden className="tabular-nums">+ {used}+ </span>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-80 max-w-[calc(100vw-2rem)] text-sm">+ <PopoverTitle className="text-xs font-normal text-muted-foreground">+ {usage.planName ? t('popover.title', { plan: usage.planName }) : t('popover.titleNoPlan')}+ </PopoverTitle>+ <p className="mt-0.5 text-2xl font-semibold tabular-nums">{used}</p>+ <div+ role="progressbar"+ aria-label={t('popover.titleNoPlan')}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.floor(percent)}+ aria-valuetext={used}+ className="mt-1.5 h-2 overflow-hidden rounded-full bg-muted"+ >+ <div className={cn('h-full rounded-full', FILL_CLASS[tone])} style={{ width }} />+ </div>+ <p className="mt-1.5 text-xs text-muted-foreground">+ {resets ? t('popover.shared', { date: resets }) : t('popover.sharedNoDate')}+ </p>+ {tone === 'exhausted' && (+ <p className="mt-2 text-xs text-red-700 dark:text-red-400">+ {resets ? t('popover.exhausted', { date: resets }) : t('popover.exhaustedNoDate')}+ </p>+ )}++ <ul className="mt-3 divide-y border-t text-[13px]">+ {usage.features.map(({ feature, percent: share }) => (+ <li key={feature} className="flex items-center justify-between gap-3 py-1.5">+ <span className="text-muted-foreground">{tFeature(feature)}</span>+ <span className="font-medium tabular-nums">{percentLabel(share)}</span>+ </li>+ ))}+ </ul>++ <ul className="mt-1 border-t text-[13px]">+ <li className="flex items-center justify-between gap-3 py-1.5">+ <span className="text-muted-foreground">{t('popover.ownKey')}</span>+ <span className="font-medium">{t('popover.notCounted')}</span>+ </li>+ </ul>++ {limits !== undefined &&+ (limits === null || limits.auditPages || limits.promptLocations) && (+ <>+ <p className="mt-3 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">+ {t('popover.otherLimits')}+ </p>+ {limits === null ? (+ <p className="mt-1 border-t py-1.5 text-muted-foreground">+ <LoadingDots />+ <span className="sr-only">{tCommon('loading')}</span>+ </p>+ ) : (+ <ul className="mt-1 divide-y border-t text-[13px]">+ {limits.auditPages && (+ <li className="flex items-center justify-between gap-3 py-1.5">+ <span className="text-muted-foreground">{t('popover.auditPages')}</span>+ <span className="font-medium tabular-nums">{count(limits.auditPages)}</span>+ </li>+ )}+ {limits.promptLocations && (+ <li className="flex items-center justify-between gap-3 py-1.5">+ <span className="text-muted-foreground">{t('popover.promptLocations')}</span>+ <span className="font-medium tabular-nums">+ {count(limits.promptLocations)}+ </span>+ </li>+ )}+ </ul>+ )}+ </>+ )}++ {!canAdmin && <p className="mt-3 text-xs text-muted-foreground">{t('popover.askAdmin')}</p>}+ <div className="mt-4 flex flex-wrap gap-1.5">+ {/* Enterprise has no bigger plan to move to. */}+ {canAdmin && usage.plan !== 'enterprise' && (+ <Link+ href="/dashboard/settings/billing"+ onClick={close}+ className={buttonVariants({ variant: pressing ? 'default' : 'outline', size: 'sm' })}+ >+ {t('popover.getMore')}+ </Link>+ )}+ {canAdmin && (+ <Link+ href="/dashboard/settings/ai-providers"+ onClick={close}+ className={buttonVariants({ variant: 'outline', size: 'sm' })}+ >+ {t('popover.useOwnKey')}+ </Link>+ )}+ <Link+ href="/dashboard/settings/billing#ai-usage"+ onClick={close}+ className={buttonVariants({ variant: 'ghost', size: 'sm' })}+ >+ {t('popover.details')}+ </Link>+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/web/src/components/providers/ai-usage-provider.tsx b/web/src/components/providers/ai-usage-provider.tsxnew file mode 100644index 000000000..3e2320d39--- /dev/null+++ b/web/src/components/providers/ai-usage-provider.tsx@@ -0,0 +1,87 @@+'use client';++import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from 'react';+import { usePathname } from 'next/navigation';+import { isCloud } from '@/config/plans';+import type { AiUsage } from '@/lib/billing/ai-usage';+import { readAiUsage } from '@/lib/billing/ai-usage-client';++/** A read this old is read again when the member opens another page or comes back to the tab. */+export const AI_USAGE_STALE_MS = 60_000;++interface AiUsageState {+ /**+ * Undefined while the first read runs; null when there is nothing to meter+ * (self-hosted, a workspace without an active plan) or it couldn't be read.+ */+ usage: AiUsage | null | undefined;+ /** Reads it again now: after a run, or when the popover opens. */+ refresh: () => void;+}++const AiUsageContext = createContext<AiUsageState>({ usage: null, refresh: () => {} });++/**+ * The workspace's AI usage this period, read once for every page's header+ * meter (AI usage spec §3.1), so moving between pages doesn't blink it. It+ * is read again on a page change or a return to the tab once the last read+ * is a minute old. Only Ansvisor Cloud meters AI: self-hosted reads nothing.+ */+export function AiUsageProvider({ children }: { children: ReactNode }) {+ const metered = isCloud();+ const pathname = usePathname();+ const [usage, setUsage] = useState<AiUsage | null | undefined>(metered ? undefined : null);+ const readAt = useRef(0);+ const reading = useRef(false);++ const read = useCallback(async () => {+ if (!metered || reading.current) return;+ reading.current = true;+ try {+ const next = await readAiUsage();+ readAt.current = Date.now();+ setUsage(next);+ } catch (err) {+ console.error('Failed to read AI usage:', err);+ // The last read stays; before any, there is nothing to show.+ setUsage((prev) => prev ?? null);+ } finally {+ reading.current = false;+ }+ }, [metered]);++ useEffect(() => {+ if (Date.now() - readAt.current >= AI_USAGE_STALE_MS) void read();+ }, [pathname, read]);++ useEffect(() => {+ const onReturn = () => {+ if (document.visibilityState !== 'visible') return;+ if (Date.now() - readAt.current >= AI_USAGE_STALE_MS) void read();+ };+ document.addEventListener('visibilitychange', onReturn);+ window.addEventListener('focus', onReturn);+ return () => {+ document.removeEventListener('visibilitychange', onReturn);+ window.removeEventListener('focus', onReturn);+ };+ }, [read]);++ const refresh = useCallback(() => void read(), [read]);+ const value = useMemo(() => ({ usage, refresh }), [usage, refresh]);+ return <AiUsageContext.Provider value={value}>{children}</AiUsageContext.Provider>;+}++/** The workspace's AI usage; outside the dashboard there is nothing to meter. */+export function useAiUsage(): AiUsageState {+ return useContext(AiUsageContext);+}diff --git a/web/src/components/settings/ai-usage-card.test.tsx b/web/src/components/settings/ai-usage-card.test.tsxindex a015e59ff..92401d43b 100644--- a/web/src/components/settings/ai-usage-card.test.tsx+++ b/web/src/components/settings/ai-usage-card.test.tsx@@ -110,6 +110,25 @@ describe('AiUsageCard', () => {expect(container.textContent).toBe('');});+ it('scrolls itself into view once read, for the header meter’s See details (#ai-usage)', async () => {+ const scroll = vi.fn();+ Element.prototype.scrollIntoView = scroll;+ vi.mocked(getAiUsage).mockResolvedValue(usage());++ await render();+ expect(scroll).not.toHaveBeenCalled();++ window.history.replaceState(null, '', '#ai-usage');+ act(() => root.unmount());+ root = createRoot(container);+ await render();+ expect(scroll).toHaveBeenCalledWith({ block: 'start' });+ expect(scroll.mock.contexts[0]).toBe(container.querySelector('#ai-usage'));+ window.history.replaceState(null, '', '#');+ // jsdom has no scrollIntoView of its own.+ delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView;+ });+it('says it couldn’t read the usage', async () => {const error = vi.spyOn(console, 'error').mockImplementation(() => {});vi.mocked(getAiUsage).mockRejectedValue(new Error('down'));diff --git a/web/src/components/settings/ai-usage-card.tsx b/web/src/components/settings/ai-usage-card.tsxindex 0db5aa40c..38e704a39 100644--- a/web/src/components/settings/ai-usage-card.tsx+++ b/web/src/components/settings/ai-usage-card.tsx@@ -1,6 +1,6 @@'use client';-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { useTranslations } from 'next-intl';import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';import { Skeleton } from '@/components/ui/skeleton';@@ -28,6 +28,7 @@ export function AiUsageCard() {// Undefined while it is read; null when there is no allowance to meter.const [usage, setUsage] = useState<AiUsage | null | undefined>(undefined);const [failed, setFailed] = useState(false);+ const card = useRef<HTMLDivElement>(null);useEffect(() => {let cancelled = false;@@ -44,6 +45,14 @@ export function AiUsageCard() {};}, []);+ // The header meter's "See details" (#ai-usage) lands here: the card shows+ // only once Billing has read the plan, after the browser looked for it.+ useEffect(() => {+ if (usage && window.location.hash === '#ai-usage') {+ card.current?.scrollIntoView({ block: 'start' });+ }+ }, [usage]);+if (usage === null || usage?.unlimited) return null;const tone = usage ? aiUsageTone(usage) : 'normal';@@ -58,7 +67,7 @@ export function AiUsageCard() {const used = t('used', { percent: percentLabel(usage?.percentUsed ?? 0) });return (- <Card>+ <Card id="ai-usage" ref={card} className="scroll-mt-6"><CardHeader><CardTitle>{t('title')}</CardTitle><CardDescription>{t('description')}</CardDescription>diff --git a/web/src/lib/billing/ai-usage-client.test.ts b/web/src/lib/billing/ai-usage-client.test.tsnew file mode 100644index 000000000..57f50625b--- /dev/null+++ b/web/src/lib/billing/ai-usage-client.test.ts@@ -0,0 +1,94 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { readAiUsage, readUsageLimits } from './ai-usage-client';++/**+ * The header meter's reads, from the browser through the API's proxy: the+ * period's AI usage, and the limits that aren't AI for its popover.+ */++let session: { access_token: string } | null;+vi.mock('@/lib/supabase/client', () => ({+ createClient: () => ({ auth: { getSession: async () => ({ data: { session } }) } }),+}));++const fetchMock = vi.fn();+const answer = (status: number, body: unknown) => ({+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+});++beforeEach(() => {+ session = { access_token: 'token-1' };+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+});++describe('readAiUsage', () => {+ it('reads the period’s usage through the proxy', async () => {+ fetchMock.mockResolvedValue(answer(200, { unlimited: false, percentUsed: 21 }));+ expect(await readAiUsage()).toEqual({ unlimited: false, percentUsed: 21 });+ expect(fetchMock).toHaveBeenCalledWith('/api/aeo/api/billing/ai-usage', {+ headers: { Authorization: 'Bearer token-1' },+ cache: 'no-store',+ // A read that hangs gives up, so the meter can read again.+ signal: expect.any(AbortSignal),+ });+ });++ it('is null without an active plan', async () => {+ fetchMock.mockResolvedValue(answer(402, { error: 'plan_limit' }));+ expect(await readAiUsage()).toBeNull();+ });++ it('throws when it can’t be read, or without a session', async () => {+ fetchMock.mockResolvedValue(answer(500, { error: 'Failed to read AI usage' }));+ await expect(readAiUsage()).rejects.toThrow('Failed to read AI usage');+ session = null;+ await expect(readAiUsage()).rejects.toThrow('Not authenticated');+ });+});++describe('readUsageLimits', () => {+ const prompts = (locationLimit: number | null) => ({+ plan: { key: 'growth', name: 'Growth plan', locationLimit, cta: 'upgrade' },+ brand: { active: 3, paused: 0, total: 3 },+ account: { activePrompts: 40, brands: 2, locationsUsed: 148 },+ updatedAt: '2026-10-23T10:00:00Z',+ });++ it('counts Site Audit pages with the running ones, and the account’s prompt locations', async () => {+ fetchMock.mockImplementation(async (url: string) =>+ url.startsWith('/api/aeo/api/audits/quota')+ ? answer(200, { success: true, quota: { used: 40, running: 2, limit: 500 } })+ : answer(200, prompts(200)),+ );+ expect(await readUsageLimits('b1')).toEqual({+ auditPages: { used: 42, limit: 500 },+ promptLocations: { used: 148, limit: 200 },+ });+ expect(fetchMock).toHaveBeenCalledWith('/api/aeo/api/audits/quota', {+ headers: { Authorization: 'Bearer token-1' },+ cache: 'no-store',+ signal: expect.any(AbortSignal),+ });+ expect(fetchMock).toHaveBeenCalledWith('/api/prompts/usage?brandId=b1', {+ cache: 'no-store',+ signal: expect.any(AbortSignal),+ });+ });++ it('leaves out a limit with no cap, one it can’t read, and prompts without a brand', async () => {+ fetchMock.mockImplementation(async (url: string) =>+ url.startsWith('/api/aeo/api/audits/quota')+ ? answer(200, { success: true, quota: { used: 0, running: 0, limit: -1 } })+ : answer(200, prompts(null)),+ );+ expect(await readUsageLimits('b1')).toEqual({ auditPages: null, promptLocations: null });++ fetchMock.mockReset();+ fetchMock.mockRejectedValueOnce(new Error('offline'));+ expect(await readUsageLimits(null)).toEqual({ auditPages: null, promptLocations: null });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/src/lib/billing/ai-usage-client.ts b/web/src/lib/billing/ai-usage-client.tsnew file mode 100644index 000000000..81faf8b1a--- /dev/null+++ b/web/src/lib/billing/ai-usage-client.ts@@ -0,0 +1,88 @@+import { BROWSER_API_BASE_URL } from '@/config/api';+import { createClient } from '@/lib/supabase/client';+import type { PromptUsageSummary } from '@/lib/prompt-usage-summary';+import type { AiUsage, UsageLimits } from './ai-usage';++/**+ * The header meter's reads (AI usage spec §3.1), from the browser through+ * the API's same-origin proxy: never through a server action, which Next+ * runs one at a time, so the meter would wait behind a page's own (the+ * Content Agent's last a whole run) and hold them up in turn.+ */++/** A read that hangs gives up after this, so the meter can read again. */+const READ_TIMEOUT_MS = 15_000;++async function accessToken(): Promise<string | null> {+ const {+ data: { session },+ } = await createClient().auth.getSession();+ return session?.access_token ?? null;+}++/**+ * This period's AI usage for the member's workspace (GET /api/billing/ai-usage,+ * the Billing page's figures). Null without an active plan (a new workspace,+ * past due, canceled): there is no allowance to meter. Throws when it can't+ * be read.+ */+export async function readAiUsage(): Promise<AiUsage | null> {+ const token = await accessToken();+ if (!token) throw new Error('Not authenticated');+ const res = await fetch(`${BROWSER_API_BASE_URL}/api/billing/ai-usage`, {+ headers: { Authorization: `Bearer ${token}` },+ cache: 'no-store',+ signal: AbortSignal.timeout(READ_TIMEOUT_MS),+ });+ if (!res.ok) {+ const body = (await res.json().catch(() => ({}))) as { error?: string; message?: string };+ if (body.error === 'plan_limit') return null;+ throw new Error(body.message || body.error || `Server error: ${res.status}`);+ }+ return (await res.json()) as AiUsage;+}++async function readJson<T>(url: string, init?: RequestInit): Promise<T | null> {+ try {+ const res = await fetch(url, {+ ...init,+ cache: 'no-store',+ signal: AbortSignal.timeout(READ_TIMEOUT_MS),+ });+ return res.ok ? ((await res.json()) as T) : null;+ } catch {+ return null;+ }+}++/**+ * The limits that aren't AI, for the meter's popover (spec §2: they stay+ * counts): the Site Audit pages audited this period (running ones included,+ * as the audit quota holds their slots) and the account's active prompt+ * locations, each of its plan's limit. One with no cap, or that can't be+ * read, is left out; without a brand there are no prompt counts to read.+ */+export async function readUsageLimits(brandId: string | null): Promise<UsageLimits> {+ const token = await accessToken();+ const [audit, prompts] = await Promise.all([+ token+ ? readJson<{ quota?: { used: number; running: number; limit: number } }>(+ `${BROWSER_API_BASE_URL}/api/audits/quota`,+ { headers: { Authorization: `Bearer ${token}` } },+ )+ : null,+ brandId+ ? readJson<PromptUsageSummary>(`/api/prompts/usage?brandId=${encodeURIComponent(brandId)}`)+ : null,+ ]);+ const quota = audit?.quota;+ const locationLimit = prompts?.plan.locationLimit ?? null;+ return {+ auditPages:+ quota && quota.limit > 0 ? { used: quota.used + quota.running, limit: quota.limit } : null,+ promptLocations:+ prompts && locationLimit !== null+ ? { used: prompts.account.locationsUsed, limit: locationLimit }+ : null,+ };+}diff --git a/web/src/lib/billing/ai-usage.ts b/web/src/lib/billing/ai-usage.tsindex ef73a990f..6393383c3 100644--- a/web/src/lib/billing/ai-usage.ts+++ b/web/src/lib/billing/ai-usage.ts@@ -25,6 +25,21 @@ export interface AiUsage {features: { feature: AiUsageFeature; percent: number }[];}+/** A count against its plan's limit this period. */+export interface UsageCount {+ used: number;+ limit: number;+}++/**+ * The limits that aren't AI, beside the header meter (AI usage spec §2):+ * each null when the plan has no cap or it couldn't be read.+ */+export interface UsageLimits {+ auditPages: UsageCount | null;+ promptLocations: UsageCount | null;+}+/*** A share as it reads: a sliver as "<1%", else whole percents, rounded down* so nothing reads as all of it before it is (the server sends 100 only