Skip to content

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

feat(billing): show this period's AI usage on the Billing page (#1386)

Cihanc45688147dbe
diff --git a/server/src/lib/action-center/task-writer/index.js b/server/src/lib/action-center/task-writer/index.js
index efb23914d..82c3b3c15 100644
--- a/server/src/lib/action-center/task-writer/index.js
+++ b/server/src/lib/action-center/task-writer/index.js
@@ -100,6 +100,7 @@ async function recordUsage({ organizationId, actionId, modelId, usage }) {
const { error } = await supabaseAdmin.from('prompt_improve_usage').insert({
organization_id: organizationId,
action_id: actionId,
+ feature: 'action_center',
model: modelId,
input_tokens: usage?.inputTokens ?? null,
output_tokens: usage?.outputTokens ?? null,
diff --git a/server/src/lib/action-center/task-writer/index.test.js b/server/src/lib/action-center/task-writer/index.test.js
index 0f3988c5c..0834924aa 100644
--- a/server/src/lib/action-center/task-writer/index.test.js
+++ b/server/src/lib/action-center/task-writer/index.test.js
@@ -255,7 +255,11 @@ describe('writeTasksForAction', () => {
const usage = ops.filter((op) => op.table === 'prompt_improve_usage');
expect(usage).toHaveLength(2);
- expect(usage[0].payload).toMatchObject({ organization_id: 'o1', action_id: 'a1' });
+ expect(usage[0].payload).toMatchObject({
+ organization_id: 'o1',
+ action_id: 'a1',
+ feature: 'action_center',
+ });
expect(ops.find((op) => op.table === 'action_events').payload).toMatchObject({
event: 'tasks_generated',
data: { count: 3, kept: 2, trigger: 'regenerate' },
diff --git a/server/src/lib/content-agent.test.js b/server/src/lib/content-agent.test.js
index e6ef6c337..4210532cc 100644
--- a/server/src/lib/content-agent.test.js
+++ b/server/src/lib/content-agent.test.js
@@ -581,7 +581,11 @@ describe('fixDraftRules', () => {
);
expect(result).toEqual({ count: 1, batchId: expect.any(String) });
const usage = writes.find((w) => w.table === 'prompt_improve_usage');
- expect(usage.value).toMatchObject({ organization_id: 'org-1', content_draft_id: DRAFT });
+ expect(usage.value).toMatchObject({
+ organization_id: 'org-1',
+ content_draft_id: DRAFT,
+ feature: 'content',
+ });
const batch = writes.find((w) => w.table === 'content_draft_suggestions');
expect(batch.value).toEqual([
expect.objectContaining({
diff --git a/server/src/lib/content-brief.js b/server/src/lib/content-brief.js
index 176d2da82..047a40a7d 100644
--- a/server/src/lib/content-brief.js
+++ b/server/src/lib/content-brief.js
@@ -281,6 +281,7 @@ export async function recordUsage({ organizationId, draftId, modelId, usage }) {
const { error } = await supabaseAdmin.from('prompt_improve_usage').insert({
organization_id: organizationId,
content_draft_id: draftId,
+ feature: 'content',
model: modelId,
input_tokens: usage?.inputTokens ?? null,
output_tokens: usage?.outputTokens ?? null,
diff --git a/server/src/lib/content-brief.test.js b/server/src/lib/content-brief.test.js
index e75bea29e..14c8fe6d4 100644
--- a/server/src/lib/content-brief.test.js
+++ b/server/src/lib/content-brief.test.js
@@ -164,6 +164,7 @@ describe('rebuildDraftBrief', () => {
value: expect.objectContaining({
organization_id: 'o1',
content_draft_id: DRAFT,
+ feature: 'content',
input_tokens: 1000,
}),
},
diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.js
index f70dfdc56..7c33da8bb 100644
--- a/server/src/lib/content-writer.test.js
+++ b/server/src/lib/content-writer.test.js
@@ -212,7 +212,9 @@ describe('startDraftWriting', () => {
expect(finish.filters).toContainEqual(['status', ['draft', 'in_review']]);
// A new page holds only its H1: nothing of the person's to keep first.
expect(rpcCalls).toEqual([]);
- expect(writes.some((w) => w.table === 'prompt_improve_usage')).toBe(true);
+ expect(writes.find((w) => w.table === 'prompt_improve_usage')).toMatchObject({
+ value: expect.objectContaining({ feature: 'content' }),
+ });
const { prompt } = generateObject.mock.calls[0][0];
expect(prompt).toContain('- ratio?');
expect(prompt).toContain('- "pour over ratio"');
diff --git a/server/src/lib/plan-guard-ai-usage.test.js b/server/src/lib/plan-guard-ai-usage.test.js
new file mode 100644
index 000000000..d438e5c0b
--- /dev/null
+++ b/server/src/lib/plan-guard-ai-usage.test.js
@@ -0,0 +1,150 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The Billing page's AI usage meter reads the period's spend on the
+ * workspace's one AI budget by feature (ai_usage_by_feature, 00242), as
+ * shares of the plan's budget.
+ */
+
+let org;
+let spend;
+let rpcCalls;
+
+function query(table) {
+ const builder = {
+ select: () => builder,
+ eq: () => builder,
+ maybeSingle: () => builder,
+ single: () => builder,
+ then: (resolve) => resolve({ data: table === 'organizations' ? org : null, error: null }),
+ };
+ return builder;
+}
+
+let guard;
+
+beforeEach(async () => {
+ vi.resetModules();
+ process.env.IS_CLOUD = 'true';
+ org = {
+ plan: 'starter',
+ subscription_status: 'active',
+ // Renews on the 20th: the period runs from the 20th of last month.
+ subscription_ends_at: '2026-11-20T09:00:00Z',
+ };
+ spend = [];
+ rpcCalls = [];
+ vi.doMock('../config/supabase.js', () => ({
+ default: {
+ from: (t) => query(t),
+ rpc: async (fn, args) => {
+ rpcCalls.push({ fn, args });
+ return { data: spend, error: null };
+ },
+ },
+ }));
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-23T12:00:00Z'));
+ guard = await import('./plan-guard.js');
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ delete process.env.IS_CLOUD;
+ vi.doUnmock('../config/supabase.js');
+});
+
+describe('getAiUsage', () => {
+ it('reads the period’s spend by feature as shares of the plan’s budget', async () => {
+ // Starter's budget is $1.
+ spend = [
+ { feature: 'improve', cost_usd: '0.125' },
+ { feature: 'content', cost_usd: '0.3004' },
+ ];
+ const usage = await guard.getAiUsage('o1');
+ expect(rpcCalls).toEqual([
+ {
+ fn: 'ai_usage_by_feature',
+ args: { p_organization_id: 'o1', p_since: usage.periodStart },
+ },
+ ]);
+ expect(usage).toMatchObject({
+ plan: 'starter',
+ unlimited: false,
+ percentUsed: 42.5,
+ features: [
+ { feature: 'improve', percent: 12.5 },
+ { feature: 'content', percent: 30 },
+ { feature: 'action_center', percent: 0 },
+ ],
+ });
+ // The period follows the subscription: it renews on the 20th.
+ expect(usage.periodStart.slice(0, 10)).toBe('2026-10-20');
+ expect(usage.periodEnd.slice(0, 10)).toBe('2026-11-20');
+ });
+
+ it('reads spend past the budget as all of it, the features scaled to fit', async () => {
+ spend = [
+ { feature: 'content', cost_usd: '1.5' },
+ { feature: 'action_center', cost_usd: '0.5' },
+ ];
+ 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 },
+ ]);
+ });
+
+ it('lists spend it can’t place only when there is some', async () => {
+ spend = [{ feature: 'other', cost_usd: '0.05' }];
+ expect((await guard.getAiUsage('o1')).features).toContainEqual({
+ 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']);
+ });
+
+ it('reads just under the budget as just under, and all of it only once spent', async () => {
+ spend = [{ feature: 'improve', cost_usd: '0.9996' }];
+ expect((await guard.getAiUsage('o1')).percentUsed).toBe(99.9);
+ spend = [{ feature: 'improve', cost_usd: '1' }];
+ expect((await guard.getAiUsage('o1')).percentUsed).toBe(100);
+ });
+
+ it('scales unknown spend with the rest when past the budget', async () => {
+ spend = [
+ { feature: 'improve', cost_usd: '1.5' },
+ { feature: 'other', cost_usd: '0.5' },
+ ];
+ const usage = await guard.getAiUsage('o1');
+ expect(usage.features).toContainEqual({ feature: 'improve', percent: 75 });
+ expect(usage.features).toContainEqual({ feature: 'other', percent: 25 });
+ });
+
+ it('reads a budget of nothing as used up, as the AI features are', async () => {
+ org = { ...org, plan: 'enterprise', plan_overrides: { improveMonthlyBudgetUsd: 0 } };
+ spend = [];
+ const usage = await guard.getAiUsage('o1');
+ expect(usage.percentUsed).toBe(100);
+ expect(usage.features.every((f) => f.percent === 0)).toBe(true);
+ });
+
+ it('has no meter without an active plan', async () => {
+ org = { ...org, subscription_status: 'incomplete' };
+ await expect(guard.getAiUsage('o1')).rejects.toMatchObject({ statusCode: 402 });
+ });
+
+ it('shows no meter for an unlimited budget', async () => {
+ delete process.env.IS_CLOUD;
+ vi.resetModules();
+ guard = await import('./plan-guard.js');
+ const usage = await guard.getAiUsage('o1');
+ expect(usage).toMatchObject({ unlimited: true, percentUsed: null, features: [] });
+ expect(rpcCalls).toEqual([]);
+ });
+});
diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.js
index d94025a91..c7d69ad68 100644
--- a/server/src/lib/plan-guard.js
+++ b/server/src/lib/plan-guard.js
@@ -354,6 +354,61 @@ export async function enforceImproveQuota(orgId, modelId) {
return quota;
}
+/** 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'];
+
+const tenths = (n) => Math.round(n * 10) / 10;
+
+/**
+ * This period's AI usage, for the Billing page's meter: how much of the
+ * workspace's AI budget (plan.limits.improveMonthlyBudgetUsd, the one
+ * Improve, the Content Editor's AI and the Action Center's task writer all
+ * charge) is used, by feature, and when it renews. Shares of the budget, in
+ * 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.
+ */
+export async function getAiUsage(orgId) {
+ const plan = await resolveOrgPlanByOrgId(orgId);
+ const periodStart = await quotaPeriodStart(orgId);
+ const base = {
+ plan: plan.id,
+ planName: plan.name,
+ periodStart: periodStart.toISOString(),
+ periodEnd: shiftMonthClamped(periodStart, 1).toISOString(),
+ };
+ const budget = plan.limits.improveMonthlyBudgetUsd ?? -1;
+ if (budget === -1) return { ...base, unlimited: true, percentUsed: null, features: [] };
+
+ const { data, error } = await supabaseAdmin.rpc('ai_usage_by_feature', {
+ p_organization_id: orgId,
+ p_since: base.periodStart,
+ });
+ if (error) throw new Error(error.message);
+ const spentOn = new Map((data ?? []).map((r) => [r.feature, Number(r.cost_usd) || 0]));
+ 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;
+ return {
+ ...base,
+ unlimited: false,
+ // 100 only once it's spent, as enforceImproveQuota stops there (a budget
+ // of 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) }] : []),
+ ],
+ };
+}
+
/**
* Suggestion-relevance allowance (VIS-011): a monthly USD budget per
* organization, 0.1% of the plan price (plan.limits.relevanceMonthlyBudgetUsd),
diff --git a/server/src/routes/billing.js b/server/src/routes/billing.js
index 74a8eced3..243cf9b4d 100644
--- a/server/src/routes/billing.js
+++ b/server/src/routes/billing.js
@@ -5,11 +5,14 @@
* POST /api/billing/cancel-feedback — { reasons, message, choice } → kept and
* e-mailed to CANCEL_FEEDBACK_EMAILS, with
* replies going to the customer
+ * GET /api/billing/ai-usage — this period's AI usage (getAiUsage), for
+ * the Billing page's meter
*/
import { Router } from 'express';
import supabaseAdmin from '../config/supabase.js';
import { deliverEmail } from '../lib/email.js';
+import { PlanLimitError, getAiUsage, getOrgIdForUser } from '../lib/plan-guard.js';
import {
DAILY_LIMIT,
SUBSCRIBED_STATUSES,
@@ -21,6 +24,36 @@ import {
const router = Router();
+router.get('/ai-usage', async (req, res) => {
+ try {
+ const orgId = await getOrgIdForUser(req.user.id);
+ // Self-hosted single-user setups may have no org row: no budget applies.
+ if (!orgId) {
+ return res.json({
+ plan: 'self_hosted',
+ planName: null,
+ periodStart: null,
+ periodEnd: null,
+ unlimited: true,
+ percentUsed: null,
+ features: [],
+ });
+ }
+ return res.json(await getAiUsage(orgId));
+ } catch (error) {
+ // No active plan (a new workspace, past due, canceled): no allowance to meter.
+ if (error instanceof PlanLimitError) {
+ return res.status(error.statusCode).json({
+ success: false,
+ error: 'plan_limit',
+ message: error.message,
+ });
+ }
+ req.log.error({ err: error }, '[billing] AI usage read failed');
+ return res.status(500).json({ error: 'Failed to read AI usage' });
+ }
+});
+
router.post('/cancel-feedback', async (req, res) => {
try {
const parsed = cancelFeedbackSchema.safeParse(req.body ?? {});
diff --git a/server/src/routes/billing.test.js b/server/src/routes/billing.test.js
index c21c3696a..2f0d0df8d 100644
--- a/server/src/routes/billing.test.js
+++ b/server/src/routes/billing.test.js
@@ -51,8 +51,21 @@ function table(name) {
}
const deliverEmail = vi.fn();
+const getAiUsage = vi.fn();
+const getOrgIdForUser = vi.fn();
vi.mock('../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));
vi.mock('../lib/email.js', () => ({ deliverEmail: (...args) => deliverEmail(...args) }));
+class PlanLimitError extends Error {
+ constructor(message, statusCode = 403) {
+ super(message);
+ this.statusCode = statusCode;
+ }
+}
+vi.mock('../lib/plan-guard.js', () => ({
+ PlanLimitError,
+ getAiUsage: (...args) => getAiUsage(...args),
+ getOrgIdForUser: (...args) => getOrgIdForUser(...args),
+}));
const { default: router } = await import('./billing.js');
@@ -211,3 +224,40 @@ describe('POST /api/billing/cancel-feedback', () => {
expect(inserted).toHaveLength(0);
});
});
+
+describe('GET /ai-usage', () => {
+ it('reads this period’s AI usage for the member’s organization', async () => {
+ const usage = { plan: 'starter', unlimited: false, percentUsed: 42.5, features: [] };
+ getOrgIdForUser.mockResolvedValue('o1');
+ getAiUsage.mockResolvedValue(usage);
+ const res = await fetch(`${baseUrl}/ai-usage`);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual(usage);
+ expect(getOrgIdForUser).toHaveBeenCalledWith('u1');
+ expect(getAiUsage).toHaveBeenCalledWith('o1');
+ });
+
+ it('has no budget to show without an organization (self-hosted)', async () => {
+ getOrgIdForUser.mockResolvedValue(null);
+ getAiUsage.mockReset();
+ const res = await fetch(`${baseUrl}/ai-usage`);
+ expect(await res.json()).toMatchObject({ unlimited: true, percentUsed: null, features: [] });
+ expect(getAiUsage).not.toHaveBeenCalled();
+ });
+
+ it('has no meter for a workspace without an active plan', async () => {
+ getOrgIdForUser.mockResolvedValue('o1');
+ getAiUsage.mockRejectedValue(new PlanLimitError('Choose a plan', 402));
+ const res = await fetch(`${baseUrl}/ai-usage`);
+ expect(res.status).toBe(402);
+ expect(await res.json()).toMatchObject({ error: 'plan_limit' });
+ });
+
+ it('says it failed when the usage can’t be read', async () => {
+ getOrgIdForUser.mockResolvedValue('o1');
+ getAiUsage.mockRejectedValue(new Error('db down'));
+ const res = await fetch(`${baseUrl}/ai-usage`);
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({ error: 'Failed to read AI usage' });
+ });
+});
diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.js
index 335c1431b..1a2972a73 100644
--- a/server/src/routes/prompts.js
+++ b/server/src/routes/prompts.js
@@ -1012,6 +1012,7 @@ async function recordImproveUsage(log, { organizationId, promptId, modelId, usag
const { error } = await supabaseAdmin.from('prompt_improve_usage').insert({
organization_id: organizationId,
prompt_id: promptId,
+ feature: 'improve',
model: modelId,
input_tokens: usage?.inputTokens ?? null,
output_tokens: usage?.outputTokens ?? null,
diff --git a/supabase/migrations/00242_ai_usage_by_feature.sql b/supabase/migrations/00242_ai_usage_by_feature.sql
new file mode 100644
index 000000000..dc6b48c6b
--- /dev/null
+++ b/supabase/migrations/00242_ai_usage_by_feature.sql
@@ -0,0 +1,53 @@
+-- What each AI usage row was for, and the period's spend by feature, for the
+-- Billing page's "This period's AI usage" meter.
+--
+-- prompt_improve_usage (00120) is the workspace's one AI budget
+-- (plan.limits.improveMonthlyBudgetUsd): Improve suggestions, the Content
+-- Editor's AI (briefs, the Content Agent, Start Agent) and the Action
+-- Center's task writer all charge it. A row named what it was for only
+-- through prompt_id / action_id (00150) / content_draft_id (00212), each set
+-- null when its prompt, action or draft is deleted; feature keeps it.
+
+alter table public.prompt_improve_usage
+ add column if not exists feature text
+ constraint prompt_improve_usage_feature_check
+ check (feature is null or feature in ('improve', 'content', 'action_center'));
+
+comment on column public.prompt_improve_usage.feature is
+ 'What the AI call was for: improve (the Improve tab), content (the Content Editor''s AI) or action_center (the task writer). Null on rows from before 00242 whose prompt, draft or action was deleted.';
+
+-- Rows from before: read from the item each still names.
+update public.prompt_improve_usage
+set feature = case
+ when action_id is not null then 'action_center'
+ when content_draft_id is not null then 'content'
+ when prompt_id is not null then 'improve'
+ end
+where feature is null
+ and (action_id is not null or content_draft_id is not null or prompt_id is not null);
+
+-- The organization's spend since p_since (its quota period's start), by
+-- feature; rows with none come back as 'other'. Summed in the database: the
+-- meter reads every row of the period, however many.
+create or replace function public.ai_usage_by_feature(
+ p_organization_id uuid,
+ p_since timestamptz
+)
+returns table (feature text, cost_usd numeric)
+language sql
+stable
+security definer
+set search_path = public
+as $$
+ select coalesce(u.feature, 'other') as feature, sum(u.cost_usd) as cost_usd
+ from public.prompt_improve_usage u
+ where u.organization_id = p_organization_id
+ and u.used_at >= p_since
+ group by 1;
+$$;
+
+comment on function public.ai_usage_by_feature(uuid, timestamptz) is
+ 'An organization''s AI spend since p_since by prompt_improve_usage.feature (''other'' when unknown), for the Billing page''s AI usage meter (getAiUsage).';
+
+revoke all on function public.ai_usage_by_feature(uuid, timestamptz) from public, anon, authenticated;
+grant execute on function public.ai_usage_by_feature(uuid, timestamptz) to service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 4250776ee..86c9651ad 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -36370,3 +36370,60 @@ $$;
revoke all on function public.health_probe(uuid, uuid, text, integer) from public, anon, authenticated;
grant execute on function public.health_probe(uuid, uuid, text, integer) to service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00242_ai_usage_by_feature.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- What each AI usage row was for, and the period's spend by feature, for the
+-- Billing page's "This period's AI usage" meter.
+--
+-- prompt_improve_usage (00120) is the workspace's one AI budget
+-- (plan.limits.improveMonthlyBudgetUsd): Improve suggestions, the Content
+-- Editor's AI (briefs, the Content Agent, Start Agent) and the Action
+-- Center's task writer all charge it. A row named what it was for only
+-- through prompt_id / action_id (00150) / content_draft_id (00212), each set
+-- null when its prompt, action or draft is deleted; feature keeps it.
+
+alter table public.prompt_improve_usage
+ add column if not exists feature text
+ constraint prompt_improve_usage_feature_check
+ check (feature is null or feature in ('improve', 'content', 'action_center'));
+
+comment on column public.prompt_improve_usage.feature is
+ 'What the AI call was for: improve (the Improve tab), content (the Content Editor''s AI) or action_center (the task writer). Null on rows from before 00242 whose prompt, draft or action was deleted.';
+
+-- Rows from before: read from the item each still names.
+update public.prompt_improve_usage
+set feature = case
+ when action_id is not null then 'action_center'
+ when content_draft_id is not null then 'content'
+ when prompt_id is not null then 'improve'
+ end
+where feature is null
+ and (action_id is not null or content_draft_id is not null or prompt_id is not null);
+
+-- The organization's spend since p_since (its quota period's start), by
+-- feature; rows with none come back as 'other'. Summed in the database: the
+-- meter reads every row of the period, however many.
+create or replace function public.ai_usage_by_feature(
+ p_organization_id uuid,
+ p_since timestamptz
+)
+returns table (feature text, cost_usd numeric)
+language sql
+stable
+security definer
+set search_path = public
+as $$
+ select coalesce(u.feature, 'other') as feature, sum(u.cost_usd) as cost_usd
+ from public.prompt_improve_usage u
+ where u.organization_id = p_organization_id
+ and u.used_at >= p_since
+ group by 1;
+$$;
+
+comment on function public.ai_usage_by_feature(uuid, timestamptz) is
+ 'An organization''s AI spend since p_since by prompt_improve_usage.feature (''other'' when unknown), for the Billing page''s AI usage meter (getAiUsage).';
+
+revoke all on function public.ai_usage_by_feature(uuid, timestamptz) from public, anon, authenticated;
+grant execute on function public.ai_usage_by_feature(uuid, timestamptz) to service_role;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 195de09cf..12b287de3 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -6057,6 +6057,23 @@
"month": "mo",
"year": "yr",
"renewsOn": "Renews on {date}",
+ "aiUsageMeter": {
+ "title": "This period's AI usage",
+ "description": "Improve suggestions, the Content Editor's AI and the Action Center's task writing share your plan's monthly AI allowance.",
+ "used": "{percent} used",
+ "resets": "Resets on {date}",
+ "exhausted": "This period's AI usage is used up. AI features resume on {date}.",
+ "exhaustedNoDate": "This period's AI usage is used up. AI features resume when it resets.",
+ "morePlans": "A bigger plan below comes with more.",
+ "features": {
+ "improve": "Improve suggestions",
+ "content": "Content Editor (briefs, Content Agent)",
+ "action_center": "Action Center task writing",
+ "other": "Other"
+ },
+ "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."
+ },
"cancelsOn": "Subscription ends on {date}",
"changePlan": "Change Plan",
"upgradeTo": "Upgrade to {plan}",
@@ -6158,7 +6175,7 @@
"briefs": "{count, number} content briefs a month",
"audits": "{count, number} site audits a month",
"aiUsage": "{count}x AI usage",
- "aiUsageHint": "A monthly allowance for Ansvisor's AI features: Improve suggestions and the Content Editor's AI. Agent Chat runs on your own AI key."
+ "aiUsageHint": "A monthly allowance for Ansvisor's AI features: Improve suggestions, the Content Editor's AI and the Action Center's task writing. Agent Chat runs on your own AI key."
},
"contactUs": "Contact Us",
"integrations": "Integrations",
diff --git a/web/src/components/settings/ai-usage-card.test.tsx b/web/src/components/settings/ai-usage-card.test.tsx
new file mode 100644
index 000000000..a015e59ff
--- /dev/null
+++ b/web/src/components/settings/ai-usage-card.test.tsx
@@ -0,0 +1,138 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+import { getAiUsage } from '@/lib/actions/ai-usage';
+import { aiUsageTone, percentLabel, type AiUsage } from '@/lib/billing/ai-usage';
+import { AiUsageCard } from './ai-usage-card';
+
+vi.mock('@/lib/actions/ai-usage', () => ({ getAiUsage: vi.fn() }));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const usage = (over: Partial<AiUsage> = {}): AiUsage => ({
+ plan: 'starter',
+ planName: 'Starter',
+ periodStart: '2026-10-20T09:00:00.000Z',
+ periodEnd: '2026-11-20T09:00:00.000Z',
+ unlimited: false,
+ percentUsed: 42.5,
+ features: [
+ { feature: 'improve', percent: 12.5 },
+ { feature: 'content', percent: 30 },
+ { feature: 'action_center', percent: 0.4 },
+ ],
+ ...over,
+});
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <AiUsageCard />
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ vi.mocked(getAiUsage).mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('AiUsageCard', () => {
+ it('shows the share used, when it resets, and what used it', async () => {
+ vi.mocked(getAiUsage).mockResolvedValue(usage());
+ await render();
+ const text = container.textContent;
+ expect(text).toContain("This period's AI usage");
+ expect(text).toContain('42% used');
+ expect(text).toContain('Resets on November 20, 2026');
+ expect([...container.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Improve suggestions12%',
+ 'Content Editor (briefs, Content Agent)30%',
+ 'Action Center task writing<1%',
+ ]);
+ expect(text).toContain("Agent Chat runs on your own AI key, so it doesn't use this allowance.");
+ const bar = container.querySelector('[role="progressbar"]')!;
+ expect(bar.getAttribute('aria-valuenow')).toBe('42');
+ expect(bar.getAttribute('aria-valuetext')).toBe('42% used');
+ expect((bar.firstElementChild as HTMLElement).style.width).toBe('42.5%');
+ expect(text).not.toContain('used up');
+ });
+
+ it('says when the allowance is used up', async () => {
+ vi.mocked(getAiUsage).mockResolvedValue(usage({ percentUsed: 100 }));
+ await render();
+ expect(container.textContent).toContain('100% used');
+ expect(container.textContent).toContain(
+ "This period's AI usage is used up. AI features resume on November 20, 2026. A bigger plan below comes with more.",
+ );
+ expect(container.querySelector('[role="progressbar"] > div')!.className).toContain(
+ 'bg-red-500',
+ );
+ });
+
+ it('offers no bigger plan on Enterprise', async () => {
+ vi.mocked(getAiUsage).mockResolvedValue(usage({ plan: 'enterprise', percentUsed: 100 }));
+ await render();
+ expect(container.textContent).toContain('AI features resume on November 20, 2026.');
+ expect(container.textContent).not.toContain('A bigger plan');
+ });
+
+ it('shows nothing without an active plan', async () => {
+ vi.mocked(getAiUsage).mockResolvedValue(null);
+ await render();
+ expect(container.textContent).toBe('');
+ });
+
+ it('shows nothing for a plan without an allowance', async () => {
+ vi.mocked(getAiUsage).mockResolvedValue(
+ usage({ unlimited: true, percentUsed: null, features: [] }),
+ );
+ await render();
+ expect(container.textContent).toBe('');
+ });
+
+ it('says it couldn’t read the usage', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(getAiUsage).mockRejectedValue(new Error('down'));
+ await render();
+ expect(container.textContent).toContain("Couldn't read this period's AI usage.");
+ error.mockRestore();
+ });
+});
+
+describe('the meter’s reading', () => {
+ it('reads a sliver as under 1%, else whole percents, rounded down', () => {
+ expect(percentLabel(0)).toBe('0%');
+ expect(percentLabel(0.4)).toBe('<1%');
+ expect(percentLabel(12.5)).toBe('12%');
+ // Never all of it before it is.
+ expect(percentLabel(99.9)).toBe('99%');
+ expect(percentLabel(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');
+ expect(aiUsageTone(usage({ percentUsed: 100 }))).toBe('exhausted');
+ expect(aiUsageTone(usage({ unlimited: true, percentUsed: null }))).toBe('unlimited');
+ });
+});
diff --git a/web/src/components/settings/ai-usage-card.tsx b/web/src/components/settings/ai-usage-card.tsx
new file mode 100644
index 000000000..0db5aa40c
--- /dev/null
+++ b/web/src/components/settings/ai-usage-card.tsx
@@ -0,0 +1,120 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+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 type { UsageTone } from '@/lib/content-usage';
+import { cn } from '@/lib/utils';
+
+const BAR_CLASS: Record<UsageTone, string> = {
+ normal: 'bg-emerald-500',
+ warning: 'bg-amber-500',
+ exhausted: 'bg-red-500',
+ unlimited: 'bg-muted-foreground/30',
+};
+
+/**
+ * This period's AI usage on the Billing page: how much of the plan's
+ * monthly AI allowance the workspace has used, what used it, and when it
+ * renews. Agent Chat runs on the workspace's own AI key, so it is a line
+ * of text, not a share. Renders nothing for a plan without an allowance,
+ * or a workspace without an active plan.
+ */
+export function AiUsageCard() {
+ const t = useTranslations('settings.aiUsageMeter');
+ // 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);
+
+ useEffect(() => {
+ let cancelled = false;
+ getAiUsage()
+ .then((read) => {
+ if (!cancelled) setUsage(read);
+ })
+ .catch((err) => {
+ console.error('Failed to read AI usage:', err);
+ if (!cancelled) setFailed(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ if (usage === null || usage?.unlimited) return null;
+
+ const tone = usage ? aiUsageTone(usage) : 'normal';
+ // As the plan card's "Renews on" above reads its date.
+ const resets = usage?.periodEnd
+ ? new Date(usage.periodEnd).toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ })
+ : null;
+ const used = t('used', { percent: percentLabel(usage?.percentUsed ?? 0) });
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('title')}</CardTitle>
+ <CardDescription>{t('description')}</CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {failed ? (
+ <p className="text-sm text-muted-foreground">{t('failed')}</p>
+ ) : !usage ? (
+ <Skeleton className="h-16 w-full" />
+ ) : (
+ <>
+ <div>
+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
+ <span className="text-lg font-semibold tabular-nums">{used}</span>
+ {resets && (
+ <span className="text-sm text-muted-foreground">
+ {t('resets', { date: resets })}
+ </span>
+ )}
+ </div>
+ <div
+ role="progressbar"
+ aria-label={t('title')}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.floor(usage.percentUsed ?? 0)}
+ aria-valuetext={used}
+ className="mt-2 h-2 overflow-hidden rounded-full bg-muted"
+ >
+ <div
+ className={cn('h-full rounded-full', BAR_CLASS[tone])}
+ style={{ width: `${Math.min(100, usage.percentUsed ?? 0)}%` }}
+ />
+ </div>
+ {tone === 'exhausted' && (
+ <p className="mt-1.5 text-sm text-red-600 dark:text-red-400">
+ {resets ? t('exhausted', { date: resets }) : t('exhaustedNoDate')}
+ {/* Enterprise has no bigger plan to move to. */}
+ {usage.plan !== 'enterprise' && <> {t('morePlans')}</>}
+ </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>
+ <p className="text-xs text-muted-foreground">{t('chat')}</p>
+ </>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/components/settings/billing-section.tsx b/web/src/components/settings/billing-section.tsx
index fadafeb54..e2b109898 100644
--- a/web/src/components/settings/billing-section.tsx
+++ b/web/src/components/settings/billing-section.tsx
@@ -8,6 +8,7 @@ import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { PlanSwitcher } from '@/components/settings/plan-switcher';
import { InvoiceList } from '@/components/settings/invoice-list';
+import { AiUsageCard } from '@/components/settings/ai-usage-card';
import { usePlanContext } from '@/components/providers/plan-provider';
import { createClient } from '@/lib/supabase/client';
import { PLANS, type PlanId } from '@/config/plans';
@@ -191,6 +192,8 @@ export function BillingSection() {
</CardContent>
</Card>
+ <AiUsageCard />
+
{/* Plan Switcher */}
<Card>
<CardHeader>
diff --git a/web/src/components/settings/plan-switcher.test.tsx b/web/src/components/settings/plan-switcher.test.tsx
index 02ff54064..052e5f3fd 100644
--- a/web/src/components/settings/plan-switcher.test.tsx
+++ b/web/src/components/settings/plan-switcher.test.tsx
@@ -123,7 +123,9 @@ describe('the plan cards', () => {
const ai = [...container.querySelectorAll('li span')].find(
(el) => el.textContent === '5x AI usage',
);
- expect(ai?.getAttribute('title')).toContain('Improve suggestions and the Content Editor');
+ expect(ai?.getAttribute('title')).toContain(
+ "Improve suggestions, the Content Editor's AI and the Action Center",
+ );
expect(container.textContent).toContain(
'For small teams getting started with AI visibility monitoring and optimization.',
);
diff --git a/web/src/lib/actions/ai-usage.ts b/web/src/lib/actions/ai-usage.ts
new file mode 100644
index 000000000..ae4d95347
--- /dev/null
+++ b/web/src/lib/actions/ai-usage.ts
@@ -0,0 +1,30 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+import { API_BASE_URL } from '@/config/api';
+import type { AiUsage } from '@/lib/billing/ai-usage';
+
+/**
+ * This period's AI usage for the member's workspace, for the Billing page's
+ * meter. Null without an active plan (a new workspace, past due, canceled):
+ * there is no allowance to meter.
+ */
+export async function getAiUsage(): Promise<AiUsage | null> {
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) throw new Error('Not authenticated');
+
+ const res = await fetch(`${API_BASE_URL}/api/billing/ai-usage`, {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ cache: 'no-store',
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ if (body.error === 'plan_limit') return null;
+ throw new Error(body.message || body.error || `Server error: ${res.status}`);
+ }
+ return res.json();
+}
diff --git a/web/src/lib/billing/ai-usage.ts b/web/src/lib/billing/ai-usage.ts
new file mode 100644
index 000000000..ef73a990f
--- /dev/null
+++ b/web/src/lib/billing/ai-usage.ts
@@ -0,0 +1,43 @@
+import { USAGE_WARNING_RATIO, type UsageTone } from '@/lib/content-usage';
+
+/**
+ * The Billing page's "This period's AI usage" meter: how much of the
+ * workspace's monthly AI allowance (the plan's AI usage, one budget that
+ * Improve suggestions, the Content Editor's AI and the Action Center's task
+ * writer all draw on) is used, by feature, and when it renews. The figures
+ * come from GET /api/billing/ai-usage, as shares of the allowance; this
+ * only decides how they read.
+ */
+
+export const AI_USAGE_FEATURES = ['improve', 'content', 'action_center', 'other'] as const;
+export type AiUsageFeature = (typeof AI_USAGE_FEATURES)[number];
+
+export interface AiUsage {
+ plan: string;
+ planName: string | null;
+ periodStart: string | null;
+ periodEnd: string | null;
+ /** No allowance to meter (self-hosted, or a plan without one). */
+ 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. */
+ features: { feature: AiUsageFeature; percent: number }[];
+}
+
+/**
+ * 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
+ * once the allowance is spent).
+ */
+export function percentLabel(percent: number): string {
+ if (percent > 0 && percent < 1) return '<1%';
+ return `${Math.floor(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';
+ if (usage.percentUsed >= 100) return 'exhausted';
+ return usage.percentUsed >= USAGE_WARNING_RATIO * 100 ? 'warning' : 'normal';
+}