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(content): show a content opportunity's AI volume as its prompts' current estimate (#1367)

Cihan130c8eef4d90
diff --git a/web/messages/en.json b/web/messages/en.json
index 209295ea0..591278780 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -5375,6 +5375,7 @@
"methodTotal": "The sum of {count, plural, one {# prompt's estimate} other {# prompts' estimates}}. Each is the median monthly Google searches for its related keywords × the share of Google searches that now get an AI answer ({rate}%).",
"methodKeyword": "This keyword's monthly Google searches × the share of Google searches that now get an AI answer ({rate}%). Its Google volume is measured; the AI share is an estimate, so the range is ±25%.",
"methodGuess": "An AI's estimate for a prompt you don't track yet, scaled to your tracked prompts' estimates. Track the prompt to get one from its keywords' Google searches.",
+ "methodSnapshot": "The sum of this opportunity's prompts' estimates when it was made or last updated. Their current estimates couldn't be read, so this one may be out of date.",
"methodGuessTotal": "The sum of an AI's estimates for suggested prompts you don't track yet, each scaled to your tracked prompts' estimates. Track them to get estimates from their keywords' Google searches.",
"methodAverage": "The average of {count, plural, one {# prompt's estimate} other {# prompts' estimates}}. Each is the median monthly Google searches for its related keywords × the share of Google searches that now get an AI answer ({rate}%).",
"keywords": "{measured} of {keywords} related keywords have Google search data.",
@@ -5383,6 +5384,7 @@
"rangeOne": "With one to go by, the range is half to twice the estimate.",
"mix": "Confidence by prompt: {high} high, {medium} medium, {low} low.",
"sources": "Sources: Google search volume from DataForSEO ({month}) and an AI answer share of {rate}%.",
+ "sourcesSnapshot": "Source: the opportunity's prompts' estimates, kept when it was made or last updated.",
"sourcesGuess": "Source: Ansvisor's AI, from your tracked prompts' estimates.",
"sourcesUndated": "Sources: Google search volume from DataForSEO and an AI answer share of {rate}%.",
"confidence": "Confidence: {level} · updated {date}",
@@ -5390,6 +5392,7 @@
"confidenceUndated": "Confidence: {level}",
"stale": "Fetched over six months ago, so one level less sure. Refresh volumes for a newer estimate.",
"lowNote": "Low confidence: shown in grey, and not used to rank on its own.",
+ "lowNoteSnapshot": "Low confidence: an old sum, shown in grey.",
"lowNoteGuess": "Low confidence: an AI's guess, shown in grey.",
"measuredNote": "Measured numbers, such as your visibility or Search Console clicks, never carry this badge.",
"level": {
diff --git a/web/src/components/content/opportunity-basket.tsx b/web/src/components/content/opportunity-basket.tsx
index 32d8c9718..58bd0cd1f 100644
--- a/web/src/components/content/opportunity-basket.tsx
+++ b/web/src/components/content/opportunity-basket.tsx
@@ -9,11 +9,7 @@ import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { useAssetTypeLabel } from '@/hooks/use-asset-type-label';
-import {
- getOpportunityActions,
- getOpportunityBasket,
- type OpportunityActionResult,
-} from '@/lib/actions/content';
+import { getOpportunityActions, type OpportunityActionResult } from '@/lib/actions/content';
import type {
ContentOpportunityDecision,
ContentOpportunitySourceData,
@@ -67,20 +63,20 @@ export function ScoreBreakdown({ sourceData }: { sourceData: ContentOpportunityS
/**
* The prompts a cluster opportunity answers and the searches AI engines ran
- * for them, included and excluded, read live from the cluster.
+ * for them, included and excluded, read live from the cluster. The page reads
+ * the basket once, for this card and the AI volume of its prompts.
*/
-export function OpportunityBasketCard({ opportunityId }: { opportunityId: string }) {
+export function OpportunityBasketCard({
+ basket,
+ failed,
+}: {
+ /** Null while it is read. */
+ basket: OpportunityBasket | null;
+ failed: boolean;
+}) {
const t = useTranslations('content.detail');
- const [basket, setBasket] = useState<OpportunityBasket | null>(null);
- const [failed, setFailed] = useState(false);
const [showExcluded, setShowExcluded] = useState(false);
- useEffect(() => {
- getOpportunityBasket(opportunityId)
- .then(setBasket)
- .catch(() => setFailed(true));
- }, [opportunityId]);
-
if (failed) return null;
const included = basket?.queries.filter((q) => q.included) ?? [];
diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsx
index ca31d9728..3eca28083 100644
--- a/web/src/components/content/opportunity-detail.tsx
+++ b/web/src/components/content/opportunity-detail.tsx
@@ -34,6 +34,8 @@ import {
getGenerationJobStatus,
type BriefQuota,
} from '@/lib/actions/content';
+import { EstimateBadge, EstimateRange } from '@/components/prompts/volume-estimate';
+import { Skeleton } from '@/components/ui/skeleton';
import {
AlternativeDialog,
DismissReasonDialog,
@@ -49,6 +51,7 @@ import {
TargetPagesCard,
} from '@/components/content/opportunity-basket';
import { opportunityDocument, opportunityToMarkdown } from '@/lib/content/opportunity-markdown';
+import { useOpportunityVolume } from '@/hooks/use-opportunity-volume';
import {
opportunityCsv,
opportunityDocx,
@@ -114,7 +117,7 @@ function StatCard({
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
<div>
<p className="text-xs text-muted-foreground">{label}</p>
- <p className="text-sm font-medium">{value}</p>
+ <div className="text-sm font-medium">{value}</div>
</div>
</div>
);
@@ -156,6 +159,7 @@ export function OpportunityDetail({
const [brief, setBrief] = useState<ContentBrief | null>(null);
const [quota, setQuota] = useState<BriefQuota | null>(null);
const [fanoutQueries, setFanoutQueries] = useState<FanoutSubQuery[]>([]);
+ const { basket, basketFailed, volume } = useOpportunityVolume(opportunity);
const router = useRouter();
// Start's page types are the opportunity's brand's, which may not be the
// active one (/dashboard/content/[id] opens any of the org's brands).
@@ -432,7 +436,7 @@ export function OpportunityDetail({
// Export (the user's spec): what Copy All Data copies, as a file.
const handleExport = async (format: OpportunityExportFormat) => {
- const doc = opportunityDocument(opportunity, brief, fanoutQueries, assetTypeLabel);
+ const doc = opportunityDocument(opportunity, brief, fanoutQueries, assetTypeLabel, volume);
const fileName = opportunityExportFileName(doc, format);
try {
if (format === 'csv') {
@@ -455,7 +459,7 @@ export function OpportunityDetail({
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(
- opportunityToMarkdown(opportunity, brief, fanoutQueries, assetTypeLabel),
+ opportunityToMarkdown(opportunity, brief, fanoutQueries, assetTypeLabel, volume),
);
toast.success(t('copiedToast'));
} catch {
@@ -632,7 +636,7 @@ export function OpportunityDetail({
onSend={canSendToActionCenter ? handleSendToActionCenter : undefined}
sendingKey={sendingAction}
/>
- <OpportunityBasketCard opportunityId={opportunity.id} />
+ <OpportunityBasketCard basket={basket} failed={basketFailed} />
</div>
<div className="space-y-4">
{(Object.keys(sd.actions ?? {}).length > 0 || (sd.pastActions ?? []).length > 0) && (
@@ -661,11 +665,30 @@ export function OpportunityDetail({
)}
<div className="grid grid-cols-2 gap-3">
- {sd.estAiVolume !== undefined && (
+ {(sd.estAiVolume !== undefined || volume !== null) && (
<StatCard
icon={TrendingUp}
label={t('detail.estAiVolume')}
- value={`~${sd.estAiVolume.toLocaleString()}/mo`}
+ value={
+ volume === undefined ? (
+ <Skeleton className="h-6 w-24" />
+ ) : volume === null ? (
+ '—'
+ ) : (
+ // The prompts' current estimates, summed (PROMPT-013).
+ <span className="flex flex-col items-start gap-1">
+ <EstimateRange
+ estimate={volume}
+ kind={'count' in volume ? 'total' : 'prompt'}
+ perMonth
+ />
+ <EstimateBadge
+ estimate={volume}
+ kind={'count' in volume ? 'total' : 'prompt'}
+ />
+ </span>
+ )
+ }
/>
)}
{sd.visibilityScore !== undefined && (
diff --git a/web/src/components/prompts/volume-estimate.test.tsx b/web/src/components/prompts/volume-estimate.test.tsx
index e444d4df4..bb6aa324f 100644
--- a/web/src/components/prompts/volume-estimate.test.tsx
+++ b/web/src/components/prompts/volume-estimate.test.tsx
@@ -7,6 +7,7 @@ import {
guessedVolumeEstimate,
keywordVolumeEstimate,
promptVolumeEstimate,
+ snapshotVolumeEstimate,
sumEstimates,
type VolumeEstimate,
} from '@/lib/volume-estimate';
@@ -134,6 +135,20 @@ describe("the note for a sum of an AI's guesses", () => {
});
});
+describe("the note for an opportunity's kept sum", () => {
+ it('says it is an old sum of its prompts, undated, in grey', async () => {
+ render(<EstimateRange estimate={snapshotVolumeEstimate(18_660)} perMonth />);
+ expect(container.querySelector('button')!.textContent).toBe('9.3–38k/mo');
+ const note = await noteOf(container.querySelector('button')!);
+ expect(note).toContain("The sum of this opportunity's prompts' estimates when it was made");
+ expect(note).toContain('kept when it was made or last updated.');
+ expect(note).toContain('Confidence: Low');
+ expect(note).not.toContain('·');
+ expect(note).toContain('Low confidence: an old sum, shown in grey.');
+ expect(note).not.toContain('DataForSEO');
+ });
+});
+
describe('a shared note for a long table', () => {
it('mounts one note, telling the estimate whose range has focus', async () => {
const handle = createEstimateNoteHandle();
diff --git a/web/src/components/prompts/volume-estimate.tsx b/web/src/components/prompts/volume-estimate.tsx
index 7aa28579b..f26f9563c 100644
--- a/web/src/components/prompts/volume-estimate.tsx
+++ b/web/src/components/prompts/volume-estimate.tsx
@@ -31,6 +31,21 @@ function monthOf(iso: string): string {
});
}
+/** The confidence line's wording for each dated basis: when the estimate is from. */
+const CONFIDENCE_KEY = {
+ keywords: 'confidence',
+ keyword: 'confidence',
+ guess: 'confidenceSuggested',
+} as const;
+
+/** What low confidence means for each basis. */
+const LOW_NOTE_KEY = {
+ keywords: 'lowNote',
+ keyword: 'lowNote',
+ guess: 'lowNoteGuess',
+ snapshot: 'lowNoteSnapshot',
+} as const;
+
/** How the estimate is built, from what, how sure it is and since when (PROMPT-013). */
function EstimateNote({ estimate, kind }: { estimate: Estimate; kind: EstimateKind }) {
const t = useTranslations('volumeEstimate');
@@ -39,7 +54,9 @@ function EstimateNote({ estimate, kind }: { estimate: Estimate; kind: EstimateKi
return (
<>
<p className="font-medium">{t('title')}</p>
- {estimate.basis === 'guess' ? (
+ {estimate.basis === 'snapshot' ? (
+ <p>{t('methodSnapshot')}</p>
+ ) : estimate.basis === 'guess' ? (
<p>{t(kind === 'total' ? 'methodGuessTotal' : 'methodGuess')}</p>
) : estimate.basis === 'keyword' ? (
<p>{t('methodKeyword', { rate })}</p>
@@ -71,15 +88,17 @@ function EstimateNote({ estimate, kind }: { estimate: Estimate; kind: EstimateKi
</>
)}
<p>
- {estimate.basis === 'guess'
- ? t('sourcesGuess')
- : estimate.asOf
- ? t('sources', { month: monthOf(estimate.asOf), rate })
- : t('sourcesUndated', { rate })}
+ {estimate.basis === 'snapshot'
+ ? t('sourcesSnapshot')
+ : estimate.basis === 'guess'
+ ? t('sourcesGuess')
+ : estimate.asOf
+ ? t('sources', { month: monthOf(estimate.asOf), rate })
+ : t('sourcesUndated', { rate })}
</p>
<p>
- {estimate.asOf
- ? t(estimate.basis === 'guess' ? 'confidenceSuggested' : 'confidence', {
+ {estimate.asOf && estimate.basis !== 'snapshot'
+ ? t(CONFIDENCE_KEY[estimate.basis], {
level,
date: formatDate(estimate.asOf),
})
@@ -87,8 +106,9 @@ function EstimateNote({ estimate, kind }: { estimate: Estimate; kind: EstimateKi
</p>
{estimate.stale && <p>{t('stale')}</p>}
{estimate.confidence === 'low' && (
- // An AI's guess can still rank (Opportunities, a topic action's impact).
- <p>{t(estimate.basis === 'guess' ? 'lowNoteGuess' : 'lowNote')}</p>
+ // A guess or an old sum can still rank (Opportunities, a topic action's
+ // impact, a content opportunity's score): only a prompt's isn't.
+ <p>{t(LOW_NOTE_KEY[estimate.basis])}</p>
)}
<p className="opacity-80">{t('measuredNote')}</p>
</>
diff --git a/web/src/hooks/use-opportunity-volume.test.tsx b/web/src/hooks/use-opportunity-volume.test.tsx
new file mode 100644
index 000000000..f96f982d1
--- /dev/null
+++ b/web/src/hooks/use-opportunity-volume.test.tsx
@@ -0,0 +1,140 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ContentOpportunity, OpportunityBasket } from '@/types';
+import { guessedVolumeEstimate, type VolumeEstimate } from '@/lib/volume-estimate';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const getOpportunityBasket = vi.fn<(id: string) => Promise<OpportunityBasket>>();
+const getPromptDemand =
+ vi.fn<(brandId: string, ids: string[]) => Promise<Record<string, VolumeEstimate>>>();
+vi.mock('@/lib/actions/content', () => ({
+ getOpportunityBasket: (id: string) => getOpportunityBasket(id),
+}));
+vi.mock('@/lib/actions/action-center', () => ({
+ getPromptDemand: (brandId: string, ids: string[]) => getPromptDemand(brandId, ids),
+}));
+
+const { useOpportunityVolume } = await import('./use-opportunity-volume');
+
+type Read = ReturnType<typeof useOpportunityVolume>;
+
+function Probe({ opportunity, seen }: { opportunity: ContentOpportunity; seen: Read[] }) {
+ seen.push(useOpportunityVolume(opportunity));
+ return null;
+}
+
+let root: Root;
+
+async function render(opportunity: ContentOpportunity): Promise<Read[]> {
+ const seen: Read[] = [];
+ root = createRoot(document.createElement('div'));
+ await act(async () => root.render(<Probe opportunity={opportunity} seen={seen} />));
+ return seen;
+}
+
+const opportunity = (over: Partial<ContentOpportunity> = {}): ContentOpportunity => ({
+ id: 'o1',
+ brandId: 'b1',
+ clusterId: 'c1',
+ title: 'Espresso grinders',
+ description: '',
+ type: 'owned',
+ impact: 'high',
+ opportunityScore: 70,
+ status: 'new',
+ sourceData: { estAiVolume: 1000 },
+ createdAt: '2026-09-01T00:00:00.000Z',
+ updatedAt: '2026-09-01T00:00:00.000Z',
+ ...over,
+});
+
+const basket = (ids: string[]): OpportunityBasket => ({
+ clusters: [
+ {
+ id: 'c1',
+ label: 'Grinders',
+ need: '',
+ topicName: null,
+ prompts: ids.map((id) => ({ id, text: id })),
+ },
+ ],
+ queries: [],
+});
+
+const estimate = (value: number) => guessedVolumeEstimate(value, '2026-10-01T00:00:00Z');
+
+beforeEach(() => {
+ getOpportunityBasket.mockReset();
+ getPromptDemand.mockReset();
+});
+
+afterEach(() => act(() => root.unmount()));
+
+/** A content opportunity's AI volume (PROMPT-013): its prompts' estimates now, read once. */
+describe('useOpportunityVolume', () => {
+ it("sums its cluster's prompts' current estimates and hands the basket on", async () => {
+ getOpportunityBasket.mockResolvedValue(basket(['p1', 'p2']));
+ getPromptDemand.mockResolvedValue({ p1: estimate(300), p2: estimate(500) });
+ const seen = await render(opportunity());
+
+ expect(seen[0].volume).toBeUndefined();
+ const last = seen.at(-1)!;
+ expect(getPromptDemand).toHaveBeenCalledWith('b1', ['p1', 'p2']);
+ expect(last.volume).toMatchObject({ value: 800, count: 2 });
+ expect(last.basket?.clusters[0].prompts).toHaveLength(2);
+ expect(getOpportunityBasket).toHaveBeenCalledTimes(1);
+ });
+
+ it('reads one prompt without a basket, keeping its own estimate', async () => {
+ getPromptDemand.mockResolvedValue({ p9: estimate(400) });
+ const last = (await render(opportunity({ clusterId: null, promptId: 'p9' }))).at(-1)!;
+
+ expect(getOpportunityBasket).not.toHaveBeenCalled();
+ expect(last.volume).toMatchObject({ value: 400, basis: 'guess' });
+ expect(last.volume).not.toHaveProperty('count');
+ });
+
+ it('sums a cluster even when only one of its prompts has an estimate', async () => {
+ getOpportunityBasket.mockResolvedValue(basket(['p1', 'p2']));
+ getPromptDemand.mockResolvedValue({ p1: estimate(300) });
+ const last = (await render(opportunity())).at(-1)!;
+
+ expect(last.volume).toMatchObject({ value: 300, count: 1 });
+ });
+
+ it('falls back to the volume kept on it, undated, when the estimates fail', async () => {
+ getOpportunityBasket.mockResolvedValue(basket(['p1']));
+ getPromptDemand.mockRejectedValue(new Error('down'));
+ const last = (await render(opportunity())).at(-1)!;
+
+ expect(last.volume).toMatchObject({
+ basis: 'snapshot',
+ value: 1000,
+ low: 500,
+ high: 2000,
+ confidence: 'low',
+ asOf: null,
+ });
+ });
+
+ it('marks a failed basket and still shows the kept volume', async () => {
+ getOpportunityBasket.mockRejectedValue(new Error('down'));
+ // A cluster's prompt_id is only its representative: never read as the whole.
+ const last = (await render(opportunity({ promptId: 'p0' }))).at(-1)!;
+
+ expect(last.basketFailed).toBe(true);
+ expect(getPromptDemand).not.toHaveBeenCalled();
+ expect(last.volume).toMatchObject({ basis: 'snapshot', value: 1000 });
+ });
+
+ it('shows nothing when no prompt has an estimate and none was kept', async () => {
+ getOpportunityBasket.mockResolvedValue(basket(['p1']));
+ getPromptDemand.mockResolvedValue({});
+ const last = (await render(opportunity({ sourceData: {} }))).at(-1)!;
+
+ expect(last.volume).toBeNull();
+ });
+});
diff --git a/web/src/hooks/use-opportunity-volume.ts b/web/src/hooks/use-opportunity-volume.ts
new file mode 100644
index 000000000..1d1d20d6a
--- /dev/null
+++ b/web/src/hooks/use-opportunity-volume.ts
@@ -0,0 +1,82 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { getOpportunityBasket } from '@/lib/actions/content';
+import { getPromptDemand } from '@/lib/actions/action-center';
+import { keptVolume } from '@/lib/content/opportunity-markdown';
+import { sumEstimates, type VolumeEstimate } from '@/lib/volume-estimate';
+import type { ContentOpportunity, OpportunityBasket } from '@/types';
+
+/**
+ * The opportunity's basket, read once for its card, and its AI volume
+ * (PROMPT-013): the sum of its prompts' current estimates, or the volume kept
+ * on it if those can't be read. `volume` is undefined while it is read.
+ */
+export function useOpportunityVolume(opportunity: ContentOpportunity | null) {
+ const id = opportunity?.id;
+ const brandId = opportunity?.brandId;
+ const promptId = opportunity?.promptId;
+ const clusterId = opportunity?.clusterId;
+ const [basket, setBasket] = useState<{
+ id: string;
+ basket: OpportunityBasket | null;
+ failed: boolean;
+ } | null>(null);
+ const [live, setLive] = useState<{ key: string; estimates: VolumeEstimate[] | null } | null>(
+ null,
+ );
+
+ useEffect(() => {
+ if (!id || !clusterId) return;
+ let cancelled = false;
+ getOpportunityBasket(id)
+ .then((read) => !cancelled && setBasket({ id, basket: read, failed: false }))
+ .catch(() => !cancelled && setBasket({ id, basket: null, failed: true }));
+ return () => {
+ cancelled = true;
+ };
+ }, [id, clusterId]);
+
+ const read = basket?.id === id ? basket : null;
+ // Its prompts: a cluster's members once its basket is in (none if it can't
+ // be read: its prompt_id is only the cluster's representative), else its one prompt.
+ const ready = !!id && (!clusterId || read !== null);
+ const promptIds = !ready
+ ? null
+ : clusterId
+ ? [...new Set(read?.basket?.clusters.flatMap((c) => c.prompts.map((p) => p.id)) ?? [])]
+ : promptId
+ ? [promptId]
+ : [];
+ const key = promptIds?.length && brandId ? `${brandId}:${promptIds.join(',')}` : null;
+
+ useEffect(() => {
+ if (!key) return;
+ let cancelled = false;
+ // The key is "brand:prompt,prompt", all UUIDs.
+ const [brand, ids] = key.split(':');
+ getPromptDemand(brand, ids.split(','))
+ .then((byPrompt) => !cancelled && setLive({ key, estimates: Object.values(byPrompt) }))
+ .catch(() => !cancelled && setLive({ key, estimates: null }));
+ return () => {
+ cancelled = true;
+ };
+ }, [key]);
+
+ const estimates = live?.key === key ? live.estimates : undefined;
+ // A cluster's prompts are summed, even one; a lone prompt keeps its own note.
+ const current = !estimates?.length
+ ? null
+ : clusterId || estimates.length > 1
+ ? sumEstimates(estimates)
+ : estimates[0];
+ const kept = opportunity && keptVolume(opportunity);
+ const volume = !promptIds
+ ? undefined
+ : !key
+ ? kept
+ : estimates === undefined
+ ? undefined
+ : (current ?? kept);
+ return { basket: read?.basket ?? null, basketFailed: read?.failed ?? false, volume };
+}
diff --git a/web/src/lib/content/opportunity-markdown.test.ts b/web/src/lib/content/opportunity-markdown.test.ts
index 22c8bc198..492560df0 100644
--- a/web/src/lib/content/opportunity-markdown.test.ts
+++ b/web/src/lib/content/opportunity-markdown.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { ContentBrief, ContentOpportunity } from '@/types';
+import { sumEstimates, keywordVolumeEstimate } from '@/lib/volume-estimate';
import { opportunityToMarkdown } from './opportunity-markdown';
const base: ContentOpportunity = {
@@ -81,11 +82,27 @@ describe('opportunityToMarkdown', () => {
expect([...positions].sort((a, b) => a - b)).toEqual(positions);
expect(md).toContain('- Flat feet shoe comparison (Comparison page, Owned, Expand)');
- expect(md).toContain('- Est. AI volume: 18,660');
+ // No current estimates given: the volume kept on it, half to twice.
+ expect(md).toContain(
+ '- Est. AI volume: 9.3–38k/mo\n- Volume type: Estimate, kept when it was made or last updated\n- Volume confidence: Low',
+ );
+ expect(md).not.toContain('18,660');
expect(md).toContain('- Visibility: 0%');
expect(md).toContain('1. What flat feet need\n - Arch support\n - Stability\n2. The shoes');
});
+ it("writes its prompts' current estimate when the page has it (PROMPT-013)", () => {
+ const now = new Date('2026-10-20T00:00:00Z');
+ const volume = sumEstimates([
+ keywordVolumeEstimate(10000, 0.5, '2026-10-01T00:00:00Z', now),
+ keywordVolumeEstimate(6000, 0.5, '2026-10-01T00:00:00Z', now),
+ ]);
+ const md = opportunityToMarkdown(base, brief, [], undefined, volume);
+ expect(md).toContain(
+ '- Est. AI volume: 5.9–10.1k/mo\n- Volume type: Estimate\n- Volume confidence: Medium',
+ );
+ });
+
it("names each asset's type as the page does", () => {
const md = opportunityToMarkdown(base, brief, [], (type) =>
type === 'comparison_page' ? 'Comparison' : null,
diff --git a/web/src/lib/content/opportunity-markdown.ts b/web/src/lib/content/opportunity-markdown.ts
index e14240456..d7f95e382 100644
--- a/web/src/lib/content/opportunity-markdown.ts
+++ b/web/src/lib/content/opportunity-markdown.ts
@@ -1,4 +1,9 @@
import type { ContentBrief, ContentOpportunity } from '@/types';
+import {
+ formatEstimateRange,
+ snapshotVolumeEstimate,
+ type VolumeEstimate,
+} from '@/lib/volume-estimate';
/** `blog_post` → `Blog post`. */
function humanize(slug: string): string {
@@ -42,14 +47,30 @@ function section(title: string | null, lines: Maybe<OpportunityLine>[]): Opportu
return { title, lines: lines.filter((l): l is OpportunityLine => !!l) };
}
+/**
+ * The AI volume an opportunity kept when it was made or last updated, as a
+ * low estimate (PROMPT-013): what shows when its prompts' current estimates
+ * can't be read. Null when it kept none.
+ */
+export function keptVolume(opportunity: ContentOpportunity): VolumeEstimate | null {
+ const kept = opportunity.sourceData.estAiVolume;
+ return kept && kept > 0 ? snapshotVolumeEstimate(kept) : null;
+}
+
export function opportunityDocument(
opportunity: ContentOpportunity,
brief: ContentBrief | null,
fanoutQueries: { query: string }[] = [],
/** An asset's type as the page names it (useAssetTypeLabel); else its key, humanized. */
assetTypeLabel: (type: string) => string | null = () => null,
+ /**
+ * Its prompts' current AI volume, summed (PROMPT-013); else the volume kept
+ * when it was made or last updated, as an estimate too.
+ */
+ volume?: VolumeEstimate | null,
): OpportunityDocument {
const sd = opportunity.sourceData;
+ const estimate = volume ?? keptVolume(opportunity);
const sections: OpportunitySection[] = [];
sections.push(
@@ -117,7 +138,15 @@ export function opportunityDocument(
field('Related prompt', sd.promptText),
field('Cluster', sd.clusterLabel),
field('Topic', sd.topicName),
- sd.estAiVolume != null && field('Est. AI volume', fmt(sd.estAiVolume)),
+ estimate && field('Est. AI volume', `${formatEstimateRange(estimate)}/mo`),
+ estimate &&
+ field(
+ 'Volume type',
+ estimate.basis === 'snapshot'
+ ? 'Estimate, kept when it was made or last updated'
+ : 'Estimate',
+ ),
+ estimate && field('Volume confidence', humanize(estimate.confidence)),
sd.visibilityScore != null && field('Visibility', `${Math.round(sd.visibilityScore)}%`),
sd.competitorGap != null && field('Competitor gap', `${Math.round(sd.competitorGap)}%`),
field('Intent', sd.intent),
@@ -189,8 +218,9 @@ export function opportunityToMarkdown(
fanoutQueries: { query: string }[] = [],
/** An asset's type as the page names it (useAssetTypeLabel); else its key, humanized. */
assetTypeLabel: (type: string) => string | null = () => null,
+ volume?: VolumeEstimate | null,
): string {
- const doc = opportunityDocument(opportunity, brief, fanoutQueries, assetTypeLabel);
+ const doc = opportunityDocument(opportunity, brief, fanoutQueries, assetTypeLabel, volume);
const parts = [
[`# ${doc.title}`, doc.description].filter(Boolean).join('\n\n'),
...doc.sections.map((s) => {
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 724187fdf..52162a365 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -24,6 +24,7 @@ import { readPromptPlaces } from '@/lib/signals/prompt-places';
import { currentActionFirst, signalDetailForApi, type SignalActionRef } from '@/lib/signals/detail';
import { parseTaskDetails } from '@/lib/action-center/task-details';
import { locationCode, isValidLocation } from '@/lib/region';
+import { promptVolumeEstimate, type EstimateConfidence } from '@/lib/volume-estimate';
import { getOrgLocationUsage, locationLimitMessage } from '@/lib/prompt-locations';
import {
filterPromptSuggestionEngines,
@@ -2286,6 +2287,16 @@ export interface PromptVolumeRow {
google_volumes: Record<string, number>;
total_google_volume: number;
est_ai_volume: number;
+ /**
+ * The estimate's likely range (PROMPT-013): from the spread of the measured
+ * keyword volumes, never under half or over twice est_ai_volume.
+ */
+ est_ai_volume_low: number;
+ est_ai_volume_high: number;
+ /** How far the measured keywords agree; one level less after six months. */
+ volume_confidence: EstimateConfidence;
+ /** Always 'estimate': AI engines publish no search volumes. */
+ volume_type: 'estimate';
ai_volume_multiplier: number;
/** Volume-weighted competition index 0-100, or null if unknown. */
competition_index: number | null;
@@ -2358,8 +2369,19 @@ export async function getPromptVolumesFor(
prompts: { text: string } | Array<{ text: string }> | null;
}> | null) ?? [];
+ const now = new Date();
return rows.map((r) => {
const prompt = Array.isArray(r.prompts) ? (r.prompts[0] ?? null) : r.prompts;
+ const estimate = promptVolumeEstimate(
+ {
+ estAiVolume: Number(r.est_ai_volume ?? 0),
+ googleVolumes: r.google_volumes ?? {},
+ aiVolumeMultiplier: Number(r.ai_volume_multiplier ?? 0),
+ keywords: r.keywords ?? [],
+ fetchedAt: r.fetched_at as string,
+ },
+ now,
+ );
return {
prompt_id: r.prompt_id,
prompt_text: prompt?.text ?? null,
@@ -2368,6 +2390,10 @@ export async function getPromptVolumesFor(
google_volumes: r.google_volumes ?? {},
total_google_volume: Number(r.total_google_volume ?? 0),
est_ai_volume: Number(r.est_ai_volume ?? 0),
+ est_ai_volume_low: estimate.low,
+ est_ai_volume_high: estimate.high,
+ volume_confidence: estimate.confidence,
+ volume_type: 'estimate' as const,
ai_volume_multiplier: Number(r.ai_volume_multiplier ?? 0),
competition_index: r.competition_index,
competition: r.competition,
diff --git a/web/src/lib/mcp/prompt-volumes.test.ts b/web/src/lib/mcp/prompt-volumes.test.ts
new file mode 100644
index 000000000..5b3218434
--- /dev/null
+++ b/web/src/lib/mcp/prompt-volumes.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * get_prompt_volumes (PROMPT-013): each prompt's estimated AI volume comes
+ * with its likely range, how sure it is and that it is an estimate, worked out
+ * as the dashboard does.
+ */
+
+let rows: Record<string, unknown>[] = [];
+
+function builder(table: string) {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ order: () => chain,
+ limit: async () => ({ data: rows, error: null }),
+ maybeSingle: async () => ({ data: table === 'brands' ? { id: 'b1' } : null, error: null }),
+ };
+ return chain;
+}
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: { from: (table: string) => builder(table) },
+}));
+
+const { getPromptVolumesFor } = await import('./data');
+
+const auth: McpAuthContext = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+};
+
+const row = (over: Record<string, unknown>) => ({
+ prompt_id: 'p1',
+ intent: 'commercial',
+ keywords: ['a', 'b', 'c'],
+ google_volumes: { a: 1000, b: 1200, c: 1500 },
+ total_google_volume: 1200,
+ est_ai_volume: 540,
+ ai_volume_multiplier: 0.45,
+ competition_index: 40,
+ competition: 'MEDIUM',
+ fetched_at: new Date().toISOString(),
+ prompts: { text: 'Best espresso grinder?' },
+ ...over,
+});
+
+describe('getPromptVolumesFor', () => {
+ it('adds the range, confidence and type to each prompt', async () => {
+ rows = [
+ row({}),
+ row({
+ prompt_id: 'p2',
+ keywords: ['x'],
+ google_volumes: { x: 2000 },
+ total_google_volume: 2000,
+ est_ai_volume: 900,
+ }),
+ ];
+ const volumes = await getPromptVolumesFor(auth, { brandId: 'b1' });
+ expect(
+ volumes!.map((v) => [
+ v.prompt_id,
+ v.est_ai_volume,
+ v.est_ai_volume_low,
+ v.est_ai_volume_high,
+ v.volume_confidence,
+ v.volume_type,
+ ]),
+ ).toEqual([
+ // Three agreeing keywords: high, ±25%.
+ ['p1', 540, 400, 680, 'high', 'estimate'],
+ // One keyword: low, half to twice.
+ ['p2', 900, 450, 1800, 'low', 'estimate'],
+ ]);
+ });
+
+ it('counts one level less once the volumes are over six months old', async () => {
+ rows = [row({ fetched_at: '2025-01-01T00:00:00Z' })];
+ const [volume] = (await getPromptVolumesFor(auth, { brandId: 'b1' }))!;
+ expect(volume.volume_confidence).toBe('medium');
+ });
+});
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 7073ffb15..5cdeddb0e 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -349,7 +349,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'list_prompt_suggestions',
{
description:
- 'List pending AI-generated prompt suggestions for a brand, including the suggested query, topic, reason, estimated volume, relevance, source provenance, generation time and expiry. The result includes a stale flag when no suggestions are available or all have expired. This only reads suggestions already generated by the dashboard; it does not generate new suggestions.',
+ 'List pending AI-generated prompt suggestions for a brand, including the suggested query, topic, reason, estimated volume, relevance, source provenance, generation time and expiry. est_volume is an AI guess, not a measurement: no keyword behind it is measured yet, so treat it as low confidence, likely anywhere from half to twice the number, and say so when you quote it. The result includes a stale flag when no suggestions are available or all have expired. This only reads suggestions already generated by the dashboard; it does not generate new suggestions.',
inputSchema: {
brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),
},
@@ -560,7 +560,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'get_content_opportunity',
{
description:
- 'Get full details of a specific content opportunity, including raw AI visibility gap metrics, intent, competitor references, and the generated content brief if one already exists. Use this when the user picks a specific opportunity from the list and wants to inspect it further or start writing.',
+ "Get full details of a specific content opportunity, including raw AI visibility gap metrics, intent, competitor references, and the generated content brief if one already exists. source_data.estAiVolume is the sum of its prompts' estimated AI searches a month when the opportunity was made or last updated: an estimate, not a measurement, and possibly out of date; get_prompt_volumes has each prompt's current estimate with its range and confidence. Use this when the user picks a specific opportunity from the list and wants to inspect it further or start writing.",
inputSchema: {
opportunity_id: relaxedUuid.describe(
'Content opportunity UUID, from list_content_opportunities.',
@@ -955,7 +955,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'get_prompt_volumes',
{
description:
- 'Get per-prompt search demand and competition for a brand. Returns one row per analyzed prompt with its keywords, the Google search volume of each keyword, total_google_volume (the Google volume of the prompt: the median of its keyword volumes, not their sum), est_ai_volume (estimated AI search demand: total_google_volume × the AI adoption rate), competition_index (0-100), and competition label (LOW / MEDIUM / HIGH). Sorted by est_ai_volume descending. Use this for "which prompts have the most demand?" or "which prompts have the least competition?" prioritization questions. Only returns prompts that already have volume analysis — triggering a new analysis is not available here.',
+ 'Get per-prompt search demand and competition for a brand. Returns one row per analyzed prompt with its keywords, the Google search volume of each keyword, total_google_volume (the Google volume of the prompt: the median of its keyword volumes, not their sum), est_ai_volume (estimated AI search demand: total_google_volume × the AI adoption rate), est_ai_volume_low and est_ai_volume_high (its likely range, from how far the keyword volumes agree), volume_confidence (high / medium / low; one level less once the volumes are over six months old), volume_type (always "estimate": AI engines publish no search volumes, so quote the range rather than a single number), competition_index (0-100), and competition label (LOW / MEDIUM / HIGH). Sorted by est_ai_volume descending. Use this for "which prompts have the most demand?" or "which prompts have the least competition?" prioritization questions. Only returns prompts that already have volume analysis — triggering a new analysis is not available here.',
inputSchema: {
brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),
limit: z
diff --git a/web/src/lib/volume-estimate.ts b/web/src/lib/volume-estimate.ts
index 1c24f61a4..f97aadf04 100644
--- a/web/src/lib/volume-estimate.ts
+++ b/web/src/lib/volume-estimate.ts
@@ -22,7 +22,7 @@ export type EstimateConfidence = 'high' | 'medium' | 'low';
* own Google volume (Similar Topics), or an AI's guess for a prompt not
* tracked yet (Prompt Suggestions).
*/
-export type EstimateBasis = 'keywords' | 'keyword' | 'guess';
+export type EstimateBasis = 'keywords' | 'keyword' | 'guess' | 'snapshot';
export interface VolumeEstimate {
basis: EstimateBasis;
@@ -188,6 +188,15 @@ export function guessedVolumeEstimate(value: number, asOf: string | null): Volum
};
}
+/**
+ * A sum kept from when something was made or last updated, e.g. a content
+ * opportunity's prompts' estimates at the time, shown when their current ones
+ * can't be read: low, ×½ to ×2, undated (a merge rewrites it unrecorded).
+ */
+export function snapshotVolumeEstimate(value: number): VolumeEstimate {
+ return { ...guessedVolumeEstimate(value, null), basis: 'snapshot' };
+}
+
export interface EstimateTotal extends VolumeEstimate {
/** How many prompts were added up, and at each confidence. */
count: number;