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(content): show the month's AI usage in the editor header and hold agent buttons once it's used up (AI usage display, part 3b) (#1433)
Cihanf244bff25a37
diff --git a/web/messages/en.json b/web/messages/en.jsonindex e97744716..8e426f2bc 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -27,6 +27,7 @@"popover": {"title": "AI usage this month · {plan} plan","titleNoPlan": "AI usage this month",+ "page": "This page 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.",@@ -3809,6 +3810,8 @@"decideFirst": "{count, plural, one {Review the open suggestion first, then run the agent.} other {Review the open suggestions first, then run the agent.}}","citedLoading": "Reading which passages AI quotes, so the agent leaves them as they are…","agentBusy": "Content Agent is already working on this page. Wait for it to finish.",+ "aiUsedUp": "This month's AI usage is used up. It resets on {date}.",+ "aiUsedUpNoDate": "This month's AI usage is used up until it resets.","fixErrors": {"ai_budget": "This month's AI usage is spent. Upgrade for more, or try again next month.","no_subscription": "Content Agent needs an active subscription. Choose a plan in Settings › Billing.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 77c8ec31d..4454c685b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -23,6 +23,9 @@ import {DialogTitle,} from '@/components/ui/dialog';import { LoadingDots } from '@/components/ui/loading-dots';+import { AiUsageBanner } from '@/components/ai-usage/ai-usage-banner';+import { AiUsageMeter } from '@/components/ai-usage/ai-usage-meter';+import { useAiUsage } from '@/components/providers/ai-usage-provider';import { PLATFORM_LABELS } from '@/config/platform-labels';import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';import {@@ -107,7 +110,9 @@ import {openRulesForAgent,rewriteAdvice,} from '@/lib/content/rules';+import { aiUsageTone } from '@/lib/billing/ai-usage';import { saveBlob } from '@/lib/download';+import { formatMonthDay } from '@/lib/format';import { cn } from '@/lib/utils';import { useBrandStore } from '@/stores/use-brand-store';import { AgentCard } from './_agent-card';@@ -1286,17 +1291,34 @@ export function DraftEditor({}, []);// One agent run at a time from this page: the others wait for it.const agentBusy = fixing || starting || rewriting || briefRebuilding;+ // The month's AI usage used up: each agent button says so before anything+ // else, and runs nothing (AI usage spec §4). A run ending reads the usage+ // again, so the header meter shows what it used.+ const { usage: aiUsage, refresh: refreshAiUsage } = useAiUsage();+ const aiUsedUp =+ aiUsage && aiUsageTone(aiUsage) === 'exhausted'+ ? aiUsage.periodEnd+ ? t('suggestions.aiUsedUp', { date: formatMonthDay(aiUsage.periodEnd) })+ : t('suggestions.aiUsedUpNoDate')+ : null;+ const wasBusy = useRef(false);+ useEffect(() => {+ if (wasBusy.current && !agentBusy) refreshAiUsage();+ wasBusy.current = agentBusy;+ }, [agentBusy, refreshAiUsage]);const agentFix: AgentFix = {run: (only) => void fixRules(only),running: fixing,blocked:- openSuggestions > 0- ? t('suggestions.decideFirst', { count: openSuggestions })- : !citedRead- ? t('suggestions.citedLoading')- : agentBusy && !fixing- ? t('suggestions.agentBusy')- : null,+ aiUsedUp && !fixing+ ? aiUsedUp+ : openSuggestions > 0+ ? t('suggestions.decideFirst', { count: openSuggestions })+ : !citedRead+ ? t('suggestions.citedLoading')+ : agentBusy && !fixing+ ? t('suggestions.agentBusy')+ : null,};// The card's Run Agent says why it won't run, as the Rules card does: also// when the only rules left open are ones the agent doesn't fix (one H1).@@ -1473,11 +1495,13 @@ export function DraftEditor({run: () => void startAgent(),running: starting,blocked:- openSuggestions > 0- ? t('suggestions.decideFirst', { count: openSuggestions })- : agentBusy && !starting- ? t('suggestions.agentBusy')- : null,+ aiUsedUp && !starting+ ? aiUsedUp+ : openSuggestions > 0+ ? t('suggestions.decideFirst', { count: openSuggestions })+ : agentBusy && !starting+ ? t('suggestions.agentBusy')+ : null,}: undefined;@@ -1541,13 +1565,15 @@ export function DraftEditor({run: () => void rewritePage(),running: rewriting,blocked:- openSuggestions > 0- ? t('suggestions.decideFirst', { count: openSuggestions })- : !citedRead- ? t('suggestions.citedLoading')- : agentBusy && !rewriting- ? t('suggestions.agentBusy')- : null,+ aiUsedUp && !rewriting+ ? aiUsedUp+ : openSuggestions > 0+ ? t('suggestions.decideFirst', { count: openSuggestions })+ : !citedRead+ ? t('suggestions.citedLoading')+ : agentBusy && !rewriting+ ? t('suggestions.agentBusy')+ : null,}: undefined;// Before you publish (CE-041) opens on Mark ready once Quality is live,@@ -1681,7 +1707,7 @@ export function DraftEditor({const nextBlocked = (action: NextAction): string | null => {switch (action) {case 'buildBrief':- return agentBusy ? t('suggestions.agentBusy') : null;+ return aiUsedUp ?? (agentBusy ? t('suggestions.agentBusy') : null);case 'writeWithAgent':return agentRewrite?.blocked ?? null;case 'rewritePage':@@ -1937,6 +1963,8 @@ export function DraftEditor({</button></HeaderTip>)}+ {/* The month's AI usage, with this page's share (AI usage spec §3.1). */}+ <AiUsageMeter compact draftId={draft.id} /><HeaderTip label={t('history.button')} hint={historyWaits ?? t('history.hint')}><HistoryMenudraftId={draft.id}@@ -2093,6 +2121,9 @@ export function DraftEditor({<div className="flex min-h-0 flex-1"><div className="flex min-w-0 flex-1 flex-col">+ {/* From 80% of the month's AI usage, as on the other pages, as a strip+ like the agent's own notices. */}+ <AiUsageBanner className="rounded-none border-x-0 border-t-0 px-4 py-1.5 text-[13px]" />{agentFailed && canMarkReady && (<divrole="alert"@@ -2107,7 +2138,9 @@ export function DraftEditor({variant="outline"size="sm"className="h-7"- disabled={agentBusy || !editor || (failedRewrite && !citedRead)}+ // Used up, as the red strip above says: it would only fail again.+ disabled={!!aiUsedUp || agentBusy || !editor || (failedRewrite && !citedRead)}+ title={aiUsedUp ?? undefined}onClick={() => void (failedRewrite ? rewritePage() : startAgent())}>{(starting || rewriting) && <WorkingDots className="ml-0" />}@@ -2280,7 +2313,9 @@ export function DraftEditor({setTabRequest((prev) => (prev?.build ? { tab: prev.tab, n: prev.n } : prev))}onBriefRebuilding={onBriefRebuilding}- briefBlocked={agentBusy && !briefRebuilding ? t('suggestions.agentBusy') : null}+ briefBlocked={+ briefRebuilding ? null : (aiUsedUp ?? (agentBusy ? t('suggestions.agentBusy') : null))+ }quality={quality}qualityScore={qualityScore}onShowInPage={showInPage}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex c281f8dfc..2fab8068c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx@@ -78,6 +78,26 @@ vi.mock('@/lib/actions/content-drafts', () => ({checkDraftLinks: (...args: unknown[]) => checkDraftLinks(...args),}));vi.mock('next/navigation', () => ({ useParams: () => ({ draftId: 'd1' }) }));+// The month's AI usage (AI usage spec): none to meter unless a test sets it.+const aiUsage = vi.hoisted(() => ({+ usage: null as import('@/lib/billing/ai-usage').AiUsage | null,+ refresh: vi.fn(),+}));+vi.mock('@/components/providers/ai-usage-provider', () => ({ useAiUsage: () => aiUsage }));+const readDraftAiUsage = vi.hoisted(() => vi.fn());+vi.mock('@/lib/billing/ai-usage-client', () => ({+ readDraftAiUsage: (...args: unknown[]) => readDraftAiUsage(...args),+ readUsageLimits: async () => ({ auditPages: null, promptLocations: null }),+}));+const usageAt = (percentUsed: number): import('@/lib/billing/ai-usage').AiUsage => ({+ plan: 'growth',+ planName: 'Growth',+ periodStart: '2026-10-20T09:00:00.000Z',+ periodEnd: '2026-11-20T09:00:00.000Z',+ unlimited: false,+ percentUsed,+ features: [],+});const routerPush = vi.hoisted(() => vi.fn());vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (@@ -235,6 +255,9 @@ beforeEach(() => {container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);+ aiUsage.usage = null;+ aiUsage.refresh.mockReset();+ readDraftAiUsage.mockReset().mockResolvedValue(3.7);getContentDraft.mockReset();markContentDraftReady.mockReset();unmarkContentDraftReady.mockReset().mockResolvedValue('in_review');@@ -281,6 +304,27 @@ afterEach(() => {});describe('the content editor', () => {+ it('shows the month’s AI usage before History, with this page’s share, and its banner from 80%', async () => {+ aiUsage.usage = usageAt(84);+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ const meter = button('AI 84% used this month, close to the limit')!;+ expect(meter.closest('header')).not.toBeNull();+ expect(+ meter.compareDocumentPosition(button('History')!) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ // Narrower than 1280px, the percent alone, as Next's label goes (Next step spec §3b).+ expect(meter.querySelector('span')!.className).toContain('hidden xl:inline');+ expect(container.textContent).toContain("You've used 84% of this month's AI limit.");++ await act(async () => meter.click());+ await act(async () => {});+ expect(readDraftAiUsage).toHaveBeenCalledWith('d1');+ expect(document.querySelector('[data-slot="popover-content"]')!.textContent).toContain(+ 'This page this month3%',+ );+ });+it('opens the draft with its title, type, method, status and length', async () => {getContentDraft.mockResolvedValue(draft());await renderPage();@@ -493,6 +537,35 @@ describe('the content editor', () => {});describe('the Content Agent writing it (CE-015)', () => {+ it('reads the month’s AI usage again once the agent has written the page', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ getContentDraft.mockResolvedValue(+ draft({+ status: 'draft',+ agentState: 'writing',+ agentSince: new Date().toISOString(),+ bodyHtml: '<h1>Pipeline forecasting</h1>',+ }),+ );+ await renderPage();+ expect(aiUsage.refresh).not.toHaveBeenCalled();++ getContentDraft.mockResolvedValue(+ draft({+ status: 'in_review',+ author: 'agent',+ bodyHtml: '<h1>Pipeline</h1><p>Written.</p>',+ }),+ );+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));+ await act(async () => {});+ expect(aiUsage.refresh).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });+it('waits while the agent writes, then opens on what it wrote', async () => {vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });try {@@ -3426,6 +3499,33 @@ describe('the side panel', () => {(b) => b.textContent === label,)!;+ it('says the month’s AI usage is used up before anything else, and runs nothing', async () => {+ aiUsage.usage = usageAt(100);+ getContentDraft.mockResolvedValue(traced);+ // An open suggestion would hold Run Agent too: the used-up month comes first.+ getDraftSuggestions.mockResolvedValue([agentSuggestion]);+ await openRules();+ expect(panel()!.textContent).toContain(+ "This month's AI usage is used up. It resets on Nov 20.",+ );+ await act(async () => panelButton('Run Agent').click());+ expect(fixDraftRules).not.toHaveBeenCalled();+ });++ it('reads the AI usage again once a run ends, for the header meter', async () => {+ getContentDraft.mockResolvedValue(traced);+ getDraftSuggestions.mockResolvedValue([]);+ let answer: (value: { count: number }) => void = () => {};+ fixDraftRules.mockReturnValue(new Promise((resolve) => (answer = resolve)));+ await openRules();+ await act(async () => panelButton('Run Agent').click());+ await act(async () => {});+ expect(aiUsage.refresh).not.toHaveBeenCalled();+ await act(async () => answer({ count: 0 }));+ await act(async () => {});+ expect(aiUsage.refresh).toHaveBeenCalledTimes(1);+ });+it('shows the agent card working while the agent runs, then its batch', async () => {getContentDraft.mockResolvedValue(traced);getDraftSuggestions.mockResolvedValueOnce([]).mockResolvedValueOnce([agentSuggestion]);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsxindex 9c8b4eb28..b050e5d27 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx@@ -1,9 +1,10 @@'use client';-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { useParams } from 'next/navigation';import { useTranslations } from 'next-intl';import { Link } from '@/i18n/navigation';+import { useAiUsage } from '@/components/providers/ai-usage-provider';import { Button } from '@/components/ui/button';import { buttonVariants } from '@/components/ui/button-variants';import { LoadingDots } from '@/components/ui/loading-dots';@@ -93,6 +94,15 @@ export default function ContentEditorPage() {setAgentFinishedFor(agentState === 'failed' || stoppedFor === id ? null : id);}}+ // The run's end reads the month's AI usage again, so the editor's header+ // meter shows what it used (AI usage spec §3.3): the editor wasn't open while+ // the page was being written.+ const { refresh: refreshAiUsage } = useAiUsage();+ const writingBefore = useRef(writing);+ useEffect(() => {+ if (writingBefore.current && !writing) refreshAiUsage();+ writingBefore.current = writing;+ }, [writing, refreshAiUsage]);// The agent's run ended, or was stopped: read the draft now, not on the next look.const rereadDraft = useCallback((stopped?: boolean) => {diff --git a/web/src/components/ai-usage/ai-usage-banner.tsx b/web/src/components/ai-usage/ai-usage-banner.tsxindex be0a1da93..cfb7a289e 100644--- a/web/src/components/ai-usage/ai-usage-banner.tsx+++ b/web/src/components/ai-usage/ai-usage-banner.tsx@@ -8,6 +8,7 @@ import { buttonVariants } from '@/components/ui/button-variants';import { useUserRole } from '@/hooks/use-user-role';import { aiUsageTone, percentLabel } from '@/lib/billing/ai-usage';import { formatMonthDay } from '@/lib/format';+import { cn } from '@/lib/utils';import { AiUsageGetMore } from './ai-usage-get-more';/**@@ -16,7 +17,7 @@ import { AiUsageGetMore } from './ai-usage-get-more';* saying until when AI features stop, with where to get more (other members* are told to ask an admin). Nothing below 80%.*/-export function AiUsageBanner() {+export function AiUsageBanner({ className }: { className?: string }) {const t = useTranslations('aiUsage');const { usage } = useAiUsage();const { canAdmin } = useUserRole();@@ -27,7 +28,12 @@ export function AiUsageBanner() {if (tone === 'warning') {return (- <div className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm dark:border-amber-900/50 dark:bg-amber-950/30">+ <div+ className={cn(+ 'flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm dark:border-amber-900/50 dark:bg-amber-950/30',+ className,+ )}+ ><AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" /><p className="min-w-0 flex-1 text-amber-900 dark:text-amber-200">{t('banner.warning', { percent: percentLabel(usage.percentUsed ?? 0) })}@@ -44,7 +50,12 @@ export function AiUsageBanner() {if (tone !== 'exhausted') return null;return (- <div className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm dark:border-red-900/50 dark:bg-red-950/30">+ <div+ className={cn(+ 'flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm dark:border-red-900/50 dark:bg-red-950/30',+ className,+ )}+ ><AlertCircle className="h-4 w-4 shrink-0 text-red-600 dark:text-red-500" /><p className="min-w-0 flex-1 text-red-900 dark:text-red-200">{resets ? t('banner.exhausted', { date: resets }) : t('banner.exhaustedNoDate')}diff --git a/web/src/components/ai-usage/ai-usage-meter.test.tsx b/web/src/components/ai-usage/ai-usage-meter.test.tsxindex 0a4dd258b..8be147861 100644--- a/web/src/components/ai-usage/ai-usage-meter.test.tsx+++ b/web/src/components/ai-usage/ai-usage-meter.test.tsx@@ -5,7 +5,7 @@ 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';+import { readAiUsage, readDraftAiUsage, readUsageLimits } from '@/lib/billing/ai-usage-client';/*** The header meter (AI usage spec §3.1, §4): the share of the month's AI@@ -63,6 +63,7 @@ vi.mock('sonner', () => ({ toast }));vi.mock('@/lib/billing/ai-usage-client', () => ({readAiUsage: vi.fn(),readUsageLimits: vi.fn(),+ readDraftAiUsage: vi.fn(),}));const { AiUsageProvider, AI_USAGE_STALE_MS } =@@ -288,6 +289,48 @@ describe('AiUsageMeter', () => {});});+describe('AiUsageMeter in the Content Editor', () => {+ const page = () =>+ [...popup()!.querySelectorAll('p')].find((p) => p.textContent?.startsWith('This page'));++ it('is the header’s button height, the percent alone narrower than 1280px, named on hover', async () => {+ await render('admin', <AiUsageMeter compact draftId="d1" />);+ expect(trigger()!.className).toContain('h-7');+ const [label, bar] = trigger()!.querySelectorAll('span');+ expect(label.className).toContain('hidden xl:inline');+ expect(bar.className).toContain('hidden xl:block');+ expect(trigger()!.title).toBe('AI 21% used this month');+ });++ it('adds the page’s share of the month, read on each opening', async () => {+ let answer: (value: number | null) => void = () => {};+ vi.mocked(readDraftAiUsage).mockReturnValue(new Promise((resolve) => (answer = resolve)));+ await render('admin', <AiUsageMeter compact draftId="d1" />);+ await open();+ expect(readDraftAiUsage).toHaveBeenCalledWith('d1');+ expect(page()!.textContent).toBe('This page this monthLoading...');+ await act(async () => answer(3.7));+ expect(page()!.textContent).toBe('This page this month3%');++ // A sliver reads as under 1%; one it can't read is left out.+ await act(async () => trigger()!.click());+ vi.mocked(readDraftAiUsage).mockResolvedValue(0.1);+ await open();+ expect(page()!.textContent).toBe('This page this month<1%');+ await act(async () => trigger()!.click());+ vi.mocked(readDraftAiUsage).mockResolvedValue(null);+ await open();+ expect(page()).toBeUndefined();+ });++ it('has no page line outside the editor', async () => {+ await render();+ await open();+ expect(page()).toBeUndefined();+ expect(readDraftAiUsage).not.toHaveBeenCalled();+ });+});+describe('HeaderWithAiUsage', () => {it('puts the meter after the page’s header row, under it on the right on a phone', async () => {await render(diff --git a/web/src/components/ai-usage/ai-usage-meter.tsx b/web/src/components/ai-usage/ai-usage-meter.tsxindex e924745bb..c44485c90 100644--- a/web/src/components/ai-usage/ai-usage-meter.tsx+++ b/web/src/components/ai-usage/ai-usage-meter.tsx@@ -16,7 +16,7 @@ import {type UsageCount,type UsageLimits,} from '@/lib/billing/ai-usage';-import { readUsageLimits } from '@/lib/billing/ai-usage-client';+import { readDraftAiUsage, 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';@@ -71,9 +71,20 @@ export function HeaderWithAiUsage({ children }: { children: ReactNode }) {* 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.+ * header row from shifting. In the Content Editor's header (Next step spec+ * §3b) it is `compact`, the header's button height, and the percent alone+ * narrower than 1280px, as the Next button's label goes; with the page's+ * `draftId` the popover adds the page's own share of the month.*/-export function AiUsageMeter({ className }: { className?: string }) {+export function AiUsageMeter({+ className,+ compact = false,+ draftId,+}: {+ className?: string;+ compact?: boolean;+ draftId?: string;+}) {const t = useTranslations('aiUsage');const tFeature = useTranslations('settings.aiUsageMeter.features');const tCommon = useTranslations('common');@@ -86,12 +97,20 @@ export function AiUsageMeter({ className }: { className?: string }) {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);+ // The page's share, as the limits read on each opening: 'none' when it+ // can't be read.+ const [page, setPage] = useState<number | 'loading' | 'none' | undefined>(undefined);+ const pageRead = useRef(0);if (usage === undefined) {return (<spanaria-hidden- className={cn('hidden h-8 w-[5.75rem] shrink-0 sm:inline-block', className)}+ className={cn(+ 'hidden shrink-0 sm:inline-block',+ compact ? 'h-7 w-12 xl:w-[7.5rem]' : 'h-8 w-[7.75rem]',+ className,+ )}/>);}@@ -114,6 +133,13 @@ export function AiUsageMeter({ className }: { className?: string }) {void readUsageLimits(brandId).then((read) => {if (id === limitsRead.current) setLimits(read);});+ if (draftId) {+ setPage((shown) => (typeof shown === 'number' ? shown : 'loading'));+ const pageId = ++pageRead.current;+ void readDraftAiUsage(draftId).then((read) => {+ if (pageId === pageRead.current) setPage(read ?? 'none');+ });+ }};const close = () => setOpen(false);@@ -124,14 +150,25 @@ export function AiUsageMeter({ className }: { className?: string }) {<Popover open={open} onOpenChange={onOpenChange}><PopoverTriggeraria-label={t(LABEL_KEY[tone], { percent: used })}+ // The percent alone says little: its name on hover, as the header's title has.+ title={compact ? t(LABEL_KEY[tone], { percent: used }) : undefined}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',+ 'inline-flex shrink-0 items-center gap-2 rounded-full border bg-background text-xs font-medium transition-colors outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50 aria-expanded:bg-muted',+ compact ? 'h-7 px-2.5' : 'h-8 px-3',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 aria-hidden className={cn(compact && 'hidden xl:inline')}>+ {t('meter.ai')}+ </span>+ <span+ aria-hidden+ className={cn(+ 'block h-1.5 w-11 overflow-hidden rounded-full bg-muted',+ compact && 'hidden xl:block',+ )}+ ><span className={cn('block h-full rounded-full', FILL_CLASS[tone])} style={{ width }} /></span><span aria-hidden className="tabular-nums">@@ -157,6 +194,20 @@ export function AiUsageMeter({ className }: { className?: string }) {<p className="mt-1.5 text-xs text-muted-foreground">{resets ? t('popover.shared', { date: resets }) : t('popover.sharedNoDate')}</p>+ {/* The page's own share: left out when it can't be read. */}+ {draftId && page !== undefined && page !== 'none' && (+ <p className="mt-2 flex items-center justify-between gap-3 rounded-md bg-muted px-2.5 py-1.5 text-[13px]">+ <span>{t('popover.page')}</span>+ {page === 'loading' ? (+ <span className="text-muted-foreground">+ <LoadingDots />+ <span className="sr-only">{tCommon('loading')}</span>+ </span>+ ) : (+ <span className="font-medium tabular-nums">{percentLabel(page)}</span>+ )}+ </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')}diff --git a/web/src/lib/billing/ai-usage-client.test.ts b/web/src/lib/billing/ai-usage-client.test.tsindex 57f50625b..38d46bf81 100644--- a/web/src/lib/billing/ai-usage-client.test.ts+++ b/web/src/lib/billing/ai-usage-client.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { readAiUsage, readUsageLimits } from './ai-usage-client';+import { readAiUsage, readDraftAiUsage, readUsageLimits } from './ai-usage-client';/*** The header meter's reads, from the browser through the API's proxy: the@@ -92,3 +92,26 @@ describe('readUsageLimits', () => {expect(fetchMock).toHaveBeenCalledTimes(1);});});++describe('readDraftAiUsage', () => {+ it('reads the page’s share through the proxy', async () => {+ fetchMock.mockResolvedValue(answer(200, { unlimited: false, percent: 3.7 }));+ expect(await readDraftAiUsage('d 1')).toBe(3.7);+ expect(fetchMock).toHaveBeenCalledWith('/api/aeo/api/billing/ai-usage/draft/d%201', {+ headers: { Authorization: 'Bearer token-1' },+ cache: 'no-store',+ signal: expect.any(AbortSignal),+ });+ });++ it('is null on a plan without an allowance, when it can’t be read, or without a session', async () => {+ fetchMock.mockResolvedValue(answer(200, { unlimited: true, percent: null }));+ expect(await readDraftAiUsage('d1')).toBeNull();+ fetchMock.mockResolvedValue(answer(402, { error: 'plan_limit' }));+ expect(await readDraftAiUsage('d1')).toBeNull();+ session = null;+ fetchMock.mockClear();+ expect(await readDraftAiUsage('d1')).toBeNull();+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/web/src/lib/billing/ai-usage-client.ts b/web/src/lib/billing/ai-usage-client.tsindex 81faf8b1a..78832fd37 100644--- a/web/src/lib/billing/ai-usage-client.ts+++ b/web/src/lib/billing/ai-usage-client.ts@@ -14,10 +14,14 @@ import type { AiUsage, UsageLimits } from './ai-usage';const READ_TIMEOUT_MS = 15_000;async function accessToken(): Promise<string | null> {- const {- data: { session },- } = await createClient().auth.getSession();- return session?.access_token ?? null;+ try {+ const {+ data: { session },+ } = await createClient().auth.getSession();+ return session?.access_token ?? null;+ } catch {+ return null;+ }}/**@@ -86,3 +90,18 @@ export async function readUsageLimits(brandId: string | null): Promise<UsageLimi: null,};}++/**+ * A Content Editor page's share of this period's AI usage, in percent to a+ * tenth (GET /api/billing/ai-usage/draft/:id), for the editor meter's popover.+ * Null when it can't be read, or on a plan without an allowance.+ */+export async function readDraftAiUsage(draftId: string): Promise<number | null> {+ const token = await accessToken();+ if (!token) return null;+ const read = await readJson<{ unlimited: boolean; percent: number | null }>(+ `${BROWSER_API_BASE_URL}/api/billing/ai-usage/draft/${encodeURIComponent(draftId)}`,+ { headers: { Authorization: `Bearer ${token}` } },+ );+ return read && !read.unlimited ? read.percent : null;+}