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): read a Content Editor page's share of the month's AI usage (AI usage display, part 3a) (#1432)

Cihanc910606bf855
diff --git a/server/src/lib/plan-guard-ai-usage.test.js b/server/src/lib/plan-guard-ai-usage.test.js
index d438e5c0b..dc3618807 100644
--- a/server/src/lib/plan-guard-ai-usage.test.js
+++ b/server/src/lib/plan-guard-ai-usage.test.js
@@ -3,20 +3,34 @@ 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.
+ * shares of the plan's budget; the editor meter reads a page's share.
*/
let org;
let spend;
let rpcCalls;
+// The page's ledger rows, and the filters its read used.
+let pageRows;
+let pageFilters;
function query(table) {
const builder = {
select: () => builder,
- eq: () => builder,
+ eq: (column, value) => {
+ if (table === 'prompt_improve_usage') pageFilters.push(['eq', column, value]);
+ return builder;
+ },
+ gte: (column, value) => {
+ if (table === 'prompt_improve_usage') pageFilters.push(['gte', column, value]);
+ return builder;
+ },
maybeSingle: () => builder,
single: () => builder,
- then: (resolve) => resolve({ data: table === 'organizations' ? org : null, error: null }),
+ then: (resolve) =>
+ resolve({
+ data: table === 'organizations' ? org : table === 'prompt_improve_usage' ? pageRows : null,
+ error: null,
+ }),
};
return builder;
}
@@ -34,6 +48,8 @@ beforeEach(async () => {
};
spend = [];
rpcCalls = [];
+ pageRows = [];
+ pageFilters = [];
vi.doMock('../config/supabase.js', () => ({
default: {
from: (t) => query(t),
@@ -148,3 +164,48 @@ describe('getAiUsage', () => {
expect(rpcCalls).toEqual([]);
});
});
+
+describe('getDraftAiUsage', () => {
+ it('reads the page’s spend this period as a share of the budget, from the org’s own rows', async () => {
+ // Starter's budget is $1: 0.0371 is 3.7%.
+ pageRows = [{ cost_usd: '0.0250' }, { cost_usd: '0.0121' }];
+ spend = [{ feature: 'content', cost_usd: '0.2' }];
+ expect(await guard.getDraftAiUsage('o1', 'd1')).toEqual({ unlimited: false, percent: 3.7 });
+ expect(pageFilters).toEqual([
+ ['eq', 'organization_id', 'o1'],
+ ['eq', 'content_draft_id', 'd1'],
+ // The same period as the month's figure: it renews on the 20th.
+ ['gte', 'used_at', '2026-10-20T09:00:00.000Z'],
+ ]);
+ });
+
+ it('reads a page with no AI calls as 0, and one with a sliver as 0.1', async () => {
+ expect(await guard.getDraftAiUsage('o1', 'd1')).toEqual({ unlimited: false, percent: 0 });
+ // A small Fix run on a big budget: $0.005 of Enterprise's $10.
+ org = { ...org, plan: 'enterprise' };
+ pageRows = [{ cost_usd: '0.005' }];
+ spend = [{ feature: 'content', cost_usd: '0.005' }];
+ expect(await guard.getDraftAiUsage('o1', 'd1')).toEqual({ unlimited: false, percent: 0.1 });
+ });
+
+ it('scales the page’s spend to fit once the month’s is past the budget, as the month’s figure', async () => {
+ // The last call took the month to $1.07 of Starter's $1, all on this page.
+ pageRows = [{ cost_usd: '1.07' }];
+ spend = [{ feature: 'content', cost_usd: '1.07' }];
+ expect(await guard.getDraftAiUsage('o1', 'd1')).toEqual({ unlimited: false, percent: 100 });
+ // Half of it on this page.
+ pageRows = [{ cost_usd: '0.535' }];
+ expect(await guard.getDraftAiUsage('o1', 'd1')).toEqual({ unlimited: false, percent: 50 });
+ });
+
+ it('rejects with plan_limit without an active plan, and shows none for an unlimited budget', async () => {
+ org = { ...org, subscription_status: 'incomplete' };
+ await expect(guard.getDraftAiUsage('o1', 'd1')).rejects.toMatchObject({ statusCode: 402 });
+
+ delete process.env.IS_CLOUD;
+ vi.resetModules();
+ guard = await import('./plan-guard.js');
+ expect(await guard.getDraftAiUsage('o1', 'd1')).toEqual({ unlimited: true, percent: null });
+ expect(pageFilters).toEqual([]);
+ });
+});
diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.js
index 232d7ab99..7758300ef 100644
--- a/server/src/lib/plan-guard.js
+++ b/server/src/lib/plan-guard.js
@@ -534,6 +534,42 @@ export async function getAiUsage(orgId) {
};
}
+/**
+ * A Content Editor page's AI usage this period, for the editor meter's "This
+ * page so far" (AI usage spec §3.1): what the page's AI calls cost (the rows
+ * its brief, Content Agent and writer charged, prompt_improve_usage.
+ * content_draft_id, holds included), as a share of the workspace's budget,
+ * in percent to a tenth, read over the same period as getAiUsage so the page
+ * is a part of the month's figure: spend past the budget is scaled to fit,
+ * as its features are, and a page that used any reads at least 0.1. Only
+ * the organization's own rows count: another workspace's page reads 0.
+ * Unlimited plans (self-hosted) show none.
+ */
+export async function getDraftAiUsage(orgId, draftId) {
+ const plan = await resolveOrgPlanByOrgId(orgId);
+ const budget = plan.limits.improveMonthlyBudgetUsd ?? -1;
+ if (budget === -1) return { unlimited: true, percent: null };
+
+ const since = (await quotaPeriodStart(orgId)).toISOString();
+ const [page, total] = await Promise.all([
+ supabaseAdmin
+ .from('prompt_improve_usage')
+ .select('cost_usd')
+ .eq('organization_id', orgId)
+ .eq('content_draft_id', draftId)
+ .gte('used_at', since),
+ supabaseAdmin.rpc('ai_usage_by_feature', { p_organization_id: orgId, p_since: since }),
+ ]);
+ if (page.error) throw new Error(page.error.message);
+ if (total.error) throw new Error(total.error.message);
+ const sum = (rows) => (rows ?? []).reduce((usd, r) => usd + (Number(r.cost_usd) || 0), 0);
+ const spent = sum(page.data);
+ if (budget <= 0 || spent <= 0) return { unlimited: false, percent: 0 };
+ const spentAll = sum(total.data);
+ const scale = spentAll > budget ? budget / spentAll : 1;
+ return { unlimited: false, percent: Math.max(0.1, tenths((spent * scale * 100) / budget)) };
+}
+
/**
* 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 243cf9b4d..52be11964 100644
--- a/server/src/routes/billing.js
+++ b/server/src/routes/billing.js
@@ -7,12 +7,16 @@
* replies going to the customer
* GET /api/billing/ai-usage — this period's AI usage (getAiUsage), for
* the Billing page's meter
+ * GET /api/billing/ai-usage/draft/:draftId
+ * — a Content Editor page's share of it
+ * (getDraftAiUsage), for the editor meter
*/
import { Router } from 'express';
+import { z } from 'zod';
import supabaseAdmin from '../config/supabase.js';
import { deliverEmail } from '../lib/email.js';
-import { PlanLimitError, getAiUsage, getOrgIdForUser } from '../lib/plan-guard.js';
+import { PlanLimitError, getAiUsage, getDraftAiUsage, getOrgIdForUser } from '../lib/plan-guard.js';
import {
DAILY_LIMIT,
SUBSCRIBED_STATUSES,
@@ -54,6 +58,27 @@ router.get('/ai-usage', async (req, res) => {
}
});
+router.get('/ai-usage/draft/:draftId', async (req, res) => {
+ const draftId = z.guid().safeParse(req.params.draftId);
+ if (!draftId.success) return res.status(400).json({ error: 'Invalid request' });
+ try {
+ const orgId = await getOrgIdForUser(req.user.id);
+ // As /ai-usage: without an org row there is no budget to share.
+ if (!orgId) return res.json({ unlimited: true, percent: null });
+ return res.json(await getDraftAiUsage(orgId, draftId.data));
+ } catch (error) {
+ if (error instanceof PlanLimitError) {
+ return res.status(error.statusCode).json({
+ success: false,
+ error: 'plan_limit',
+ message: error.message,
+ });
+ }
+ req.log.error({ err: error }, '[billing] page 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 2f0d0df8d..fb73eb34e 100644
--- a/server/src/routes/billing.test.js
+++ b/server/src/routes/billing.test.js
@@ -52,6 +52,7 @@ function table(name) {
const deliverEmail = vi.fn();
const getAiUsage = vi.fn();
+const getDraftAiUsage = 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) }));
@@ -64,6 +65,7 @@ class PlanLimitError extends Error {
vi.mock('../lib/plan-guard.js', () => ({
PlanLimitError,
getAiUsage: (...args) => getAiUsage(...args),
+ getDraftAiUsage: (...args) => getDraftAiUsage(...args),
getOrgIdForUser: (...args) => getOrgIdForUser(...args),
}));
@@ -261,3 +263,44 @@ describe('GET /ai-usage', () => {
expect(await res.json()).toEqual({ error: 'Failed to read AI usage' });
});
});
+
+describe('GET /ai-usage/draft/:draftId', () => {
+ const draftId = 'c0ffee00-0000-4000-8000-000000000001';
+
+ it('reads a page’s share of this period’s AI usage for the member’s organization', async () => {
+ getOrgIdForUser.mockResolvedValue('o1');
+ getDraftAiUsage.mockResolvedValue({ unlimited: false, percent: 3.7 });
+ const res = await fetch(`${baseUrl}/ai-usage/draft/${draftId}`);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ unlimited: false, percent: 3.7 });
+ expect(getDraftAiUsage).toHaveBeenCalledWith('o1', draftId);
+ });
+
+ it('turns away an id that isn’t one', async () => {
+ getDraftAiUsage.mockReset();
+ const res = await fetch(`${baseUrl}/ai-usage/draft/not-an-id`);
+ expect(res.status).toBe(400);
+ expect(getDraftAiUsage).not.toHaveBeenCalled();
+ });
+
+ it('has no share to show without an organization (self-hosted)', async () => {
+ getOrgIdForUser.mockResolvedValue(null);
+ getDraftAiUsage.mockReset();
+ const res = await fetch(`${baseUrl}/ai-usage/draft/${draftId}`);
+ expect(await res.json()).toEqual({ unlimited: true, percent: null });
+ expect(getDraftAiUsage).not.toHaveBeenCalled();
+ });
+
+ it('answers plan_limit without an active plan, and says it failed when it can’t read', async () => {
+ getOrgIdForUser.mockResolvedValue('o1');
+ getDraftAiUsage.mockRejectedValue(new PlanLimitError('Choose a plan', 402));
+ let res = await fetch(`${baseUrl}/ai-usage/draft/${draftId}`);
+ expect(res.status).toBe(402);
+ expect(await res.json()).toMatchObject({ error: 'plan_limit' });
+
+ getDraftAiUsage.mockRejectedValue(new Error('db down'));
+ res = await fetch(`${baseUrl}/ai-usage/draft/${draftId}`);
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({ error: 'Failed to read AI usage' });
+ });
+});