Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

fix(billing): show the AI usage breakdown by what was used: quality checks under the Content Editor, no empty rows, "<0.1%" for a small share (#1629)

Cihan6bbe099db6f3
diff --git a/server/src/lib/plan-guard-ai-usage.test.js b/server/src/lib/plan-guard-ai-usage.test.js
index e44a76584..51fca7ca7 100644
--- a/server/src/lib/plan-guard-ai-usage.test.js
+++ b/server/src/lib/plan-guard-ai-usage.test.js
@@ -88,11 +88,10 @@ describe('getAiUsage', () => {
plan: 'starter',
unlimited: false,
percentUsed: 42.5,
+ // Only what used some: the task writer and the quality checks had none.
features: [
{ feature: 'improve', percent: 12.5 },
{ feature: 'content', percent: 30 },
- { feature: 'action_center', percent: 0 },
- { feature: 'quality', percent: 0 },
],
});
// The period follows the subscription: it renews on the 20th.
@@ -108,28 +107,53 @@ describe('getAiUsage', () => {
const usage = await guard.getAiUsage('o1');
expect(usage.percentUsed).toBe(100);
expect(usage.features).toEqual([
- { feature: 'improve', percent: 0 },
{ feature: 'content', percent: 75 },
{ feature: 'action_center', percent: 25 },
- { feature: 'quality', percent: 0 },
]);
});
- it('lists spend it can’t place only when there is some', async () => {
- spend = [{ feature: 'other', cost_usd: '0.25' }];
- expect((await guard.getAiUsage('o1')).features).toContainEqual({
- feature: 'other',
- percent: 5,
- });
+ it('counts the Content Editor’s quality checks in its row, which has no row of its own', async () => {
+ spend = [
+ { feature: 'quality', cost_usd: '0.25' },
+ { feature: 'improve', cost_usd: '0.5' },
+ { feature: 'content', cost_usd: '1' },
+ ];
+ const usage = await guard.getAiUsage('o1');
+ expect(usage.percentUsed).toBe(35);
+ // In the meter's order, whatever order the spend comes in.
+ expect(usage.features).toEqual([
+ { feature: 'improve', percent: 10 },
+ { feature: 'content', percent: 25 },
+ ]);
+ // Quality checks alone still make the Content Editor's row.
+ spend = [{ feature: 'quality', cost_usd: '0.05' }];
+ expect((await guard.getAiUsage('o1')).features).toEqual([{ feature: 'content', percent: 1 }]);
+ });
+
+ it('lists a sliver of spend at 0, for the page to read as under a tenth', async () => {
+ // $0.002 of Starter's $5 is 0.04%: under a tenth, but used.
+ spend = [
+ { feature: 'action_center', cost_usd: '0.002' },
+ { feature: 'content', cost_usd: '0' },
+ ];
+ const usage = await guard.getAiUsage('o1');
+ expect(usage.percentUsed).toBe(0);
+ expect(usage.features).toEqual([{ feature: 'action_center', percent: 0 }]);
+ });
+
+ it('lists spend it can’t place last, and nothing when nothing was spent', async () => {
+ spend = [
+ { feature: 'other', cost_usd: '0.25' },
+ { feature: 'improve', cost_usd: '0.5' },
+ ];
+ expect((await guard.getAiUsage('o1')).features).toEqual([
+ { feature: 'improve', percent: 10 },
+ { feature: 'other', percent: 5 },
+ ]);
spend = [];
const empty = await guard.getAiUsage('o1');
expect(empty.percentUsed).toBe(0);
- expect(empty.features.map((f) => f.feature)).toEqual([
- 'improve',
- 'content',
- 'action_center',
- 'quality',
- ]);
+ expect(empty.features).toEqual([]);
});
it('reads just under the budget as just under, and all of it only once spent', async () => {
@@ -154,7 +178,7 @@ describe('getAiUsage', () => {
spend = [];
const usage = await guard.getAiUsage('o1');
expect(usage.percentUsed).toBe(100);
- expect(usage.features.every((f) => f.percent === 0)).toBe(true);
+ expect(usage.features).toEqual([]);
});
it('has no meter without an active plan', async () => {
diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.js
index c41b4e202..857b0d336 100644
--- a/server/src/lib/plan-guard.js
+++ b/server/src/lib/plan-guard.js
@@ -541,8 +541,18 @@ async function holdCostUsd(orgId, modelId, since) {
return Math.max(typical, recent ?? 0);
}
-/** What the workspace's AI budget is spent on, as prompt_improve_usage.feature says (00242). */
-export const AI_USAGE_FEATURES = ['improve', 'content', 'action_center', 'quality'];
+/**
+ * The meter's rows, in order, and what the workspace's AI budget spent on
+ * each, as prompt_improve_usage.feature says (00242): the Content Editor's
+ * quality checks ('quality', 00264) are its AI too, so they count in its
+ * row. 'other' is spend whose feature isn't known.
+ */
+export const AI_USAGE_FEATURES = {
+ improve: ['improve'],
+ content: ['content', 'quality'],
+ action_center: ['action_center'],
+ other: ['other'],
+};
const tenths = (n) => Math.round(n * 10) / 10;
@@ -554,8 +564,10 @@ const tenths = (n) => Math.round(n * 10) / 10;
* percent to a tenth; dollars stay on the server, as the Improve tab's quota
* does. Spend past the budget (calls already running when it ran out) reads
* as 100%, its features scaled to fit. Rows whose feature isn't known (from
- * before 00242, their item deleted) count as 'other', listed only when there
- * are some. Unlimited plans (self-hosted) show no meter.
+ * before 00242, their item deleted) count as 'other'. Only what used some is
+ * listed (an Action Center whose task writer is off has no row), so a row
+ * can read 0 when its share is under a twentieth of a percent: the page
+ * reads that as "<0.1%". Unlimited plans (self-hosted) show no meter.
*/
export async function getAiUsage(orgId) {
const plan = await resolveOrgPlanByOrgId(orgId);
@@ -580,7 +592,10 @@ export async function getAiUsage(orgId) {
const spent = [...spentOn.values()].reduce((a, b) => a + b, 0);
const scale = budget > 0 && spent > budget ? budget / spent : 1;
const percentOf = (usd) => (budget > 0 ? tenths((usd * scale * 100) / budget) : 0);
- const other = spentOn.get('other') ?? 0;
+ const features = Object.entries(AI_USAGE_FEATURES)
+ .map(([feature, from]) => [feature, from.reduce((usd, f) => usd + (spentOn.get(f) ?? 0), 0)])
+ .filter(([, usd]) => usd > 0)
+ .map(([feature, usd]) => ({ feature, percent: percentOf(usd) }));
return {
...base,
unlimited: false,
@@ -588,13 +603,7 @@ export async function getAiUsage(orgId) {
// 0 included); just under reads as 99.9, never rounded up to "used up".
percentUsed:
budget <= 0 || spent >= budget ? 100 : Math.min(99.9, tenths((spent * 100) / budget)),
- features: [
- ...AI_USAGE_FEATURES.map((feature) => ({
- feature,
- percent: percentOf(spentOn.get(feature) ?? 0),
- })),
- ...(other > 0 ? [{ feature: 'other', percent: percentOf(other) }] : []),
- ],
+ features,
};
}
diff --git a/web/messages/en.json b/web/messages/en.json
index c2a6bf576..a78cc324b 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -35,6 +35,7 @@
"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.",
"exhaustedTrial": "The free trial's AI usage is used up. Starting the plan gives its full monthly allowance; Agent Chat on your own AI key keeps working.",
+ "none": "No AI usage yet this month.",
"ownKey": "Agent Chat, on your own AI key",
"notCounted": "Not counted",
"otherLimits": "Other limits this month",
@@ -7825,11 +7826,11 @@
"morePlans": "A bigger plan below comes with more.",
"features": {
"improve": "Improve suggestions",
- "content": "Content Editor (briefs, Content Agent)",
+ "content": "Content Editor (briefs, Content Agent, quality checks)",
"action_center": "Action Center task writing",
- "quality": "Content Editor quality checks",
"other": "Other"
},
+ "none": "No AI usage yet this period.",
"chat": "Agent Chat runs on your own AI key, so it doesn't use this allowance.",
"failed": "Couldn't read this period's AI usage. Try again later."
},
diff --git a/web/src/components/ai-usage/ai-usage-meter.test.tsx b/web/src/components/ai-usage/ai-usage-meter.test.tsx
index 8c889b53d..233c0d2cf 100644
--- a/web/src/components/ai-usage/ai-usage-meter.test.tsx
+++ b/web/src/components/ai-usage/ai-usage-meter.test.tsx
@@ -208,7 +208,7 @@ describe('AiUsageMeter', () => {
const rows = [...popup()!.querySelectorAll('li')].map((li) => li.textContent);
expect(rows).toEqual([
'Improve suggestions4%',
- 'Content Editor (briefs, Content Agent)17.2%',
+ 'Content Editor (briefs, Content Agent, quality checks)17.2%',
'Action Center task writing0.2%',
'Agent Chat, on your own AI keyNot counted',
'Site Audit pages42 of 500',
@@ -224,6 +224,29 @@ describe('AiUsageMeter', () => {
]);
});
+ it('lists only what used some, a sliver as under a tenth, and says when nothing has', async () => {
+ vi.mocked(readAiUsage).mockResolvedValue(
+ usage({ percentUsed: 0, features: [{ feature: 'content', percent: 0 }] }),
+ );
+ await render();
+ await open();
+ expect([...popup()!.querySelectorAll('li')].map((li) => li.textContent)).toContain(
+ 'Content Editor (briefs, Content Agent, quality checks)<0.1%',
+ );
+ expect(popup()!.textContent).not.toContain('Improve suggestions');
+ expect(popup()!.textContent).not.toContain('No AI usage yet');
+
+ vi.mocked(readAiUsage).mockResolvedValue(usage({ percentUsed: 0, features: [] }));
+ await remount();
+ await open();
+ expect(popup()!.textContent).toContain('No AI usage yet this month.');
+ expect([...popup()!.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Agent Chat, on your own AI keyNot counted',
+ 'Site Audit pages42 of 500',
+ 'Prompt locations1,148 of 2,000',
+ ]);
+ });
+
it('closes when one of its links is followed', async () => {
await render();
await open();
diff --git a/web/src/components/ai-usage/ai-usage-meter.tsx b/web/src/components/ai-usage/ai-usage-meter.tsx
index cd6261ddb..9603766c4 100644
--- a/web/src/components/ai-usage/ai-usage-meter.tsx
+++ b/web/src/components/ai-usage/ai-usage-meter.tsx
@@ -12,6 +12,7 @@ import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@/compone
import { useUserRole } from '@/hooks/use-user-role';
import {
aiUsageTone,
+ featurePercentLabel,
percentLabel,
type UsageCount,
type UsageLimits,
@@ -231,14 +232,21 @@ export function AiUsageMeter({
</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>
+ {/* Only what used some is listed: none yet, a line says so. */}
+ {usage.features.length > 0 ? (
+ <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">{featurePercentLabel(share)}</span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="mt-3 border-t py-1.5 text-[13px] text-muted-foreground">
+ {t('popover.none')}
+ </p>
+ )}
<ul className="mt-1 border-t text-[13px]">
<li className="flex items-center justify-between gap-3 py-1.5">
diff --git a/web/src/components/settings/ai-usage-card.test.tsx b/web/src/components/settings/ai-usage-card.test.tsx
index d005e58e3..323068912 100644
--- a/web/src/components/settings/ai-usage-card.test.tsx
+++ b/web/src/components/settings/ai-usage-card.test.tsx
@@ -4,7 +4,13 @@ import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../messages/en.json';
import { getAiUsage } from '@/lib/actions/ai-usage';
-import { aiUsageTone, percentLabel, type AiUsage } from '@/lib/billing/ai-usage';
+import {
+ aiUsageFromApi,
+ aiUsageTone,
+ featurePercentLabel,
+ percentLabel,
+ type AiUsage,
+} from '@/lib/billing/ai-usage';
import { AiUsageCard } from './ai-usage-card';
vi.mock('@/lib/actions/ai-usage', () => ({ getAiUsage: vi.fn() }));
@@ -66,7 +72,7 @@ describe('AiUsageCard', () => {
expect(text).toContain('Resets on November 20, 2026');
expect([...container.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
'Improve suggestions12.5%',
- 'Content Editor (briefs, Content Agent)30%',
+ 'Content Editor (briefs, Content Agent, quality checks)30%',
'Action Center task writing0.4%',
]);
expect(text).toContain("Agent Chat runs on your own AI key, so it doesn't use this allowance.");
@@ -77,6 +83,49 @@ describe('AiUsageCard', () => {
expect(text).not.toContain('used up');
});
+ it('lists only what the server sends, a sliver that rounds to 0 as under a tenth', async () => {
+ vi.mocked(getAiUsage).mockResolvedValue(
+ usage({
+ percentUsed: 12.5,
+ features: [
+ { feature: 'improve', percent: 12.5 },
+ { feature: 'content', percent: 0 },
+ ],
+ }),
+ );
+ await render();
+ expect([...container.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Improve suggestions12.5%',
+ 'Content Editor (briefs, Content Agent, quality checks)<0.1%',
+ ]);
+ expect(container.textContent).not.toContain('Action Center task writing');
+ expect(container.textContent).not.toContain('No AI usage yet');
+ });
+
+ it('says nothing has used it yet, in place of the list', async () => {
+ vi.mocked(getAiUsage).mockResolvedValue(usage({ percentUsed: 0, features: [] }));
+ await render();
+ expect(container.textContent).toContain('0% used');
+ expect(container.textContent).toContain('No AI usage yet this period.');
+ expect(container.querySelector('ul')).toBeNull();
+ });
+
+ it('reads an older API’s answer of every feature at 0 as no usage, not as slivers', async () => {
+ const zero = (feature: string) => ({ feature, percent: 0 }) as AiUsage['features'][number];
+ vi.mocked(getAiUsage).mockResolvedValue(
+ aiUsageFromApi(
+ usage({
+ percentUsed: 0,
+ features: ['improve', 'content', 'action_center', 'quality'].map(zero),
+ }),
+ ),
+ );
+ await render();
+ expect(container.textContent).toContain('No AI usage yet this period.');
+ expect(container.textContent).not.toContain('<0.1%');
+ expect(container.querySelector('ul')).toBeNull();
+ });
+
it('says when the allowance is used up', async () => {
vi.mocked(getAiUsage).mockResolvedValue(usage({ percentUsed: 100 }));
await render();
@@ -165,6 +214,13 @@ describe('the meter’s reading', () => {
expect(percentLabel(100)).toBe('100%');
});
+ it('reads a listed feature’s 0 as a sliver: the server lists only what used some', () => {
+ expect(featurePercentLabel(0)).toBe('<0.1%');
+ expect(featurePercentLabel(0.1)).toBe('0.1%');
+ expect(featurePercentLabel(12.5)).toBe('12.5%');
+ expect(featurePercentLabel(100)).toBe('100%');
+ });
+
it('warns from 80% and is used up at 100%', () => {
expect(aiUsageTone(usage({ percentUsed: 79.9 }))).toBe('normal');
expect(aiUsageTone(usage({ percentUsed: 80 }))).toBe('warning');
diff --git a/web/src/components/settings/ai-usage-card.tsx b/web/src/components/settings/ai-usage-card.tsx
index 02ef58a24..e035ff471 100644
--- a/web/src/components/settings/ai-usage-card.tsx
+++ b/web/src/components/settings/ai-usage-card.tsx
@@ -5,7 +5,12 @@ import { useTranslations } from 'next-intl';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { getAiUsage } from '@/lib/actions/ai-usage';
-import { aiUsageTone, percentLabel, type AiUsage } from '@/lib/billing/ai-usage';
+import {
+ aiUsageTone,
+ featurePercentLabel,
+ percentLabel,
+ type AiUsage,
+} from '@/lib/billing/ai-usage';
import type { UsageTone } from '@/lib/content-usage';
import { cn } from '@/lib/utils';
@@ -117,16 +122,21 @@ export function AiUsageCard() {
</p>
)}
</div>
- <ul className="divide-y rounded-lg border text-sm">
- {usage.features.map(({ feature, percent }) => (
- <li key={feature} className="flex items-center justify-between gap-3 px-3 py-2">
- <span>{t(`features.${feature}`)}</span>
- <span className="tabular-nums text-muted-foreground">
- {percentLabel(percent)}
- </span>
- </li>
- ))}
- </ul>
+ {/* Only what used some is listed: none yet, a line says so. */}
+ {usage.features.length > 0 ? (
+ <ul className="divide-y rounded-lg border text-sm">
+ {usage.features.map(({ feature, percent }) => (
+ <li key={feature} className="flex items-center justify-between gap-3 px-3 py-2">
+ <span>{t(`features.${feature}`)}</span>
+ <span className="tabular-nums text-muted-foreground">
+ {featurePercentLabel(percent)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-sm text-muted-foreground">{t('none')}</p>
+ )}
<p className="text-xs text-muted-foreground">{t('chat')}</p>
</>
)}
diff --git a/web/src/lib/actions/ai-usage.ts b/web/src/lib/actions/ai-usage.ts
index ae4d95347..d8808643b 100644
--- a/web/src/lib/actions/ai-usage.ts
+++ b/web/src/lib/actions/ai-usage.ts
@@ -2,7 +2,7 @@
import { createClient } from '@/lib/supabase/server';
import { API_BASE_URL } from '@/config/api';
-import type { AiUsage } from '@/lib/billing/ai-usage';
+import { aiUsageFromApi, type AiUsage } from '@/lib/billing/ai-usage';
/**
* This period's AI usage for the member's workspace, for the Billing page's
@@ -26,5 +26,5 @@ export async function getAiUsage(): Promise<AiUsage | null> {
if (body.error === 'plan_limit') return null;
throw new Error(body.message || body.error || `Server error: ${res.status}`);
}
- return res.json();
+ return aiUsageFromApi(await res.json());
}
diff --git a/web/src/lib/billing/ai-usage-client.test.ts b/web/src/lib/billing/ai-usage-client.test.ts
index 38d46bf81..73f6e70d1 100644
--- a/web/src/lib/billing/ai-usage-client.test.ts
+++ b/web/src/lib/billing/ai-usage-client.test.ts
@@ -36,6 +36,26 @@ describe('readAiUsage', () => {
});
});
+ it('reads an older API’s answer the new way: quality in the Content Editor, no unused rows', async () => {
+ fetchMock.mockResolvedValue(
+ answer(200, {
+ unlimited: false,
+ percentUsed: 1.3,
+ features: [
+ { feature: 'improve', percent: 0 },
+ { feature: 'content', percent: 1.2 },
+ { feature: 'action_center', percent: 0 },
+ { feature: 'quality', percent: 0.1 },
+ ],
+ }),
+ );
+ expect(await readAiUsage()).toEqual({
+ unlimited: false,
+ percentUsed: 1.3,
+ features: [{ feature: 'content', percent: 1.3 }],
+ });
+ });
+
it('is null without an active plan', async () => {
fetchMock.mockResolvedValue(answer(402, { error: 'plan_limit' }));
expect(await readAiUsage()).toBeNull();
diff --git a/web/src/lib/billing/ai-usage-client.ts b/web/src/lib/billing/ai-usage-client.ts
index 78832fd37..33b3b51f6 100644
--- a/web/src/lib/billing/ai-usage-client.ts
+++ b/web/src/lib/billing/ai-usage-client.ts
@@ -1,7 +1,7 @@
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';
+import { aiUsageFromApi, type AiUsage, type UsageLimits } from './ai-usage';
/**
* The header meter's reads (AI usage spec §3.1), from the browser through
@@ -43,7 +43,7 @@ export async function readAiUsage(): Promise<AiUsage | null> {
if (body.error === 'plan_limit') return null;
throw new Error(body.message || body.error || `Server error: ${res.status}`);
}
- return (await res.json()) as AiUsage;
+ return aiUsageFromApi((await res.json()) as AiUsage);
}
async function readJson<T>(url: string, init?: RequestInit): Promise<T | null> {
diff --git a/web/src/lib/billing/ai-usage.test.ts b/web/src/lib/billing/ai-usage.test.ts
index a3cee4c16..4222a2ef8 100644
--- a/web/src/lib/billing/ai-usage.test.ts
+++ b/web/src/lib/billing/ai-usage.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { aiUsageToastDue, aiUsageToastMark, type AiUsage } from './ai-usage';
+import { aiUsageFromApi, aiUsageToastDue, aiUsageToastMark, type AiUsage } from './ai-usage';
/** The AI usage toast (AI usage spec §4): once a period in a browser, on reaching 80%. */
@@ -41,3 +41,36 @@ describe('aiUsageToastDue', () => {
expect(aiUsageToastDue(usage({ unlimited: true, percentUsed: null }), null)).toBe(false);
});
});
+
+describe('aiUsageFromApi', () => {
+ /** An API from before the quality checks joined the Content Editor's row. */
+ const old = (improve: number, content: number, action: number, quality: number) =>
+ usage({
+ features: [
+ { feature: 'improve', percent: improve },
+ { feature: 'content', percent: content },
+ { feature: 'action_center', percent: action },
+ { feature: 'quality' as AiUsage['features'][number]['feature'], percent: quality },
+ ],
+ });
+
+ it('drops an older API’s unused rows: nothing used reads as no usage', () => {
+ expect(aiUsageFromApi(old(0, 0, 0, 0)).features).toEqual([]);
+ });
+
+ it('adds an older API’s quality checks into the Content Editor, once rounded', () => {
+ expect(aiUsageFromApi(old(0, 1.2, 0, 0.1)).features).toEqual([
+ { feature: 'content', percent: 1.3 },
+ ]);
+ expect(aiUsageFromApi(old(4.5, 0, 0.2, 0.3)).features).toEqual([
+ { feature: 'improve', percent: 4.5 },
+ { feature: 'content', percent: 0.3 },
+ { feature: 'action_center', percent: 0.2 },
+ ]);
+ });
+
+ it('keeps a new API’s answer as it is, a listed 0 and all', () => {
+ const now = usage({ features: [{ feature: 'content', percent: 0 }] });
+ expect(aiUsageFromApi(now)).toBe(now);
+ });
+});
diff --git a/web/src/lib/billing/ai-usage.ts b/web/src/lib/billing/ai-usage.ts
index 6133bcddb..9f835ab0b 100644
--- a/web/src/lib/billing/ai-usage.ts
+++ b/web/src/lib/billing/ai-usage.ts
@@ -10,13 +10,7 @@ import { USAGE_WARNING_RATIO, type UsageTone } from '@/lib/content-usage';
* only decides how they read.
*/
-export const AI_USAGE_FEATURES = [
- 'improve',
- 'content',
- 'action_center',
- 'quality',
- 'other',
-] as const;
+export const AI_USAGE_FEATURES = ['improve', 'content', 'action_center', 'other'] as const;
export type AiUsageFeature = (typeof AI_USAGE_FEATURES)[number];
export interface AiUsage {
@@ -30,7 +24,11 @@ export interface AiUsage {
unlimited: boolean;
/** Share of the allowance used, 0–100, to a tenth; null when unlimited. */
percentUsed: number | null;
- /** Each feature's share of the allowance; 'other' only when there is some. */
+ /**
+ * Each feature's share of the allowance, listed only when it used some (the
+ * Content Editor's quality checks in its row): one under a twentieth of a
+ * percent comes as 0, read with featurePercentLabel.
+ */
features: { feature: AiUsageFeature; percent: number }[];
}
@@ -61,6 +59,39 @@ export function percentLabel(percent: number): string {
return `${Math.floor(percent * 10 + 1e-9) / 10}%`;
}
+/**
+ * A feature's share in the list of what used the allowance: the server lists
+ * only features that used some, so one it rounds to 0 reads as "<0.1%", not
+ * as unused.
+ */
+export function featurePercentLabel(percent: number): string {
+ return percent > 0 ? percentLabel(percent) : '<0.1%';
+}
+
+/**
+ * The usage as the API answers it, read the same from an API older than
+ * the web: that one lists every feature, unused ones at 0, and the quality
+ * checks in a row of their own. Those fold into the Content Editor's row
+ * and the unused rows drop, so none reads as "<0.1%" and a workspace that
+ * used nothing reads as such. Drop it once every API answers the new way.
+ */
+export function aiUsageFromApi(raw: AiUsage): AiUsage {
+ const rows = raw?.features as { feature: string; percent: number }[] | undefined;
+ if (!Array.isArray(rows) || !rows.some((f) => f.feature === 'quality')) return raw;
+ const by = new Map<string, number>();
+ for (const { feature, percent } of rows) {
+ const key = feature === 'quality' ? 'content' : feature;
+ by.set(key, (by.get(key) ?? 0) + percent);
+ }
+ return {
+ ...raw,
+ features: AI_USAGE_FEATURES.flatMap((feature) => {
+ const percent = Math.round((by.get(feature) ?? 0) * 10) / 10;
+ return percent > 0 ? [{ feature, percent }] : [];
+ }),
+ };
+}
+
/** Warning from 80% of the allowance, used up at 100%. */
export function aiUsageTone(usage: AiUsage): UsageTone {
if (usage.unlimited || usage.percentUsed === null) return 'unlimited';