Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(prompts): label Similar Topics, Prompt Suggestions and the prompt page's AI volume as estimates (#1362)
Cihan983c140c73a7
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 3e61d83b3..df8ca90f0 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -5184,8 +5184,13 @@},"title": "Prompt Volumes","description": "Discover query volumes and trends across AI platforms.",+ "similarTopics": {+ "aiTitle": "Est. AI Volume",+ "aiSub": "monthly AI searches, across prompts"+ },"volumeInsights": {"totalTitle": "Total Est. AI Volume",+ "detailTitle": "AI searches a month","totalSub": "from {google} Google searches","averageTitle": "Avg. AI Volume","averageSub": "per prompt",@@ -5367,6 +5372,8 @@"title": "How we estimate AI search volume","method": "The median monthly Google searches for this prompt's related keywords × the share of Google searches that now get an AI answer ({rate}%).","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.","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.","noKeywords": "None of its related keywords has Google search data yet.",@@ -5374,8 +5381,10 @@"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}%.",+ "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}",+ "confidenceSuggested": "Confidence: {level} · suggested {date}","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.",@@ -5388,7 +5397,8 @@"badge": "Estimate","badgeLow": "Estimate · low confidence","badgeLabel": "Estimate, {level} confidence: how it's built",- "label": "{range} a month, estimated, {level} confidence"+ "label": "{range} a month, estimated, {level} confidence",+ "perMonth": "/mo"},"mentions": {"title": "Mentions & Sentiment",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsxindex e0c74e564..01a499758 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx@@ -2,6 +2,7 @@import { useEffect, useMemo, useState, type ComponentType, useCallback } from 'react';import { useParams } from 'next/navigation';+import { useTranslations } from 'next-intl';import { Link, useRouter } from '@/i18n/navigation';import { buildCitationDetailHref } from '@/components/citations/filter-bar';import {@@ -36,7 +37,11 @@ import {MessageSquareText,Quote,RotateCw,+ TrendingUp,} from 'lucide-react';+import { getPromptVolume, type PromptVolumeEstimateRow } from '@/lib/actions/prompt-volume';+import { promptVolumeEstimate } from '@/lib/volume-estimate';+import { EstimateBadge, EstimateRange } from '@/components/prompts/volume-estimate';import { cn } from '@/lib/utils';import { formatRegionDisplay } from '@/lib/region';import { toast } from 'sonner';@@ -233,7 +238,7 @@ function KpiCard({icon: Icon,}: {title: string;- value: string | number;+ value: React.ReactNode;icon: ComponentType<{ className?: string }>;}) {return (@@ -241,7 +246,7 @@ function KpiCard({<CardContent className="flex items-center gap-3 p-4"><Icon className="h-5 w-5 text-muted-foreground" /><div>- <p className="text-2xl font-bold tabular-nums">{value}</p>+ <div className="text-2xl font-bold tabular-nums">{value}</div><p className="text-xs text-muted-foreground">{title}</p></div></CardContent>@@ -662,6 +667,9 @@ export default function PromptDetailPage() {const [notes, setNotes] = useState<PromptNote[]>([]);const [targetUrls, setTargetUrls] = useState<PromptTargetUrl[]>([]);const [error, setError] = useState<string | null>(null);+ // The prompt's estimated AI searches (PROMPT-013); no card without one.+ const [volume, setVolume] = useState<PromptVolumeEstimateRow | null>(null);+ const tVolumes = useTranslations('prompts.volumeInsights');// Workflow data is independent of the date window — load it once per// prompt, outside the main load cycle, so date changes don't refetch it.@@ -680,6 +688,19 @@ export default function PromptDetailPage() {};}, [promptId]);+ // Like the workflow, the volume doesn't depend on the date window.+ useEffect(() => {+ let cancelled = false;+ getPromptVolume(promptId)+ .then((row) => {+ if (!cancelled) setVolume(row);+ })+ .catch((err) => console.error('Failed to load prompt volume:', err));+ return () => {+ cancelled = true;+ };+ }, [promptId]);+useEffect(() => {let cancelled = false;if (!promptBrandId) return;@@ -911,7 +932,12 @@ export default function PromptDetailPage() {</div>)}<div className={cn('space-y-6', isRefetching && 'opacity-60')}>- <div className="grid gap-4 sm:grid-cols-3">+ <div+ className={cn(+ 'grid gap-4',+ volume ? 'sm:grid-cols-2 lg:grid-cols-4' : 'sm:grid-cols-3',+ )}+ ><KpiCardtitle={`Visibility — mentioned in ${data.summary.mentionAnswers} of ${data.summary.totalResults} answers, cited in ${data.summary.citationAnswers}`}value={data.summary.score ?? 0}@@ -927,6 +953,18 @@ export default function PromptDetailPage() {value={data.summary.totalCitations.toLocaleString()}icon={Quote}/>+ {volume && (+ <KpiCard+ title={tVolumes('detailTitle')}+ value={+ <span className="flex flex-col items-start gap-1">+ <EstimateRange estimate={promptVolumeEstimate(volume)} />+ <EstimateBadge estimate={promptVolumeEstimate(volume)} />+ </span>+ }+ icon={TrendingUp}+ />+ )}</div><Card>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsxindex 8987ae338..422001b02 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx@@ -221,3 +221,28 @@ describe('SuggestionsCard — Add All', () => {expect(toast.info).toHaveBeenCalledWith('These suggestions were already added or dismissed');});});++describe('SuggestionsCard — estimated volume', () => {+ it("shows an AI's guess as a grey range, never a bare number", async () => {+ actions.getPromptSuggestions.mockResolvedValue({+ suggestions: [{ ...suggestion(1), estVolume: 1200 }],+ });+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <SuggestionsCard+ brandId="b1"+ onAccepted={onAccepted}+ sourceStates={null}+ planId="growth"+ />+ </NextIntlClientProvider>,+ );+ });+ const range = container.querySelector<HTMLButtonElement>('button[aria-label*="a month"]')!;+ expect(range.textContent).toBe('600–2.4k/mo');+ expect(range.getAttribute('aria-label')).toBe('600–2.4k a month, estimated, Low confidence');+ expect(range.className).toContain('text-muted-foreground');+ expect(container.textContent).not.toContain('~1,200');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsxindex 98fc02111..1a9ba19f1 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx@@ -37,6 +37,12 @@ import {import { toast } from 'sonner';import { cn } from '@/lib/utils';import { formatNumber } from '@/lib/format';+import { guessedVolumeEstimate } from '@/lib/volume-estimate';+import {+ EstimateNoteTooltip,+ EstimateRange,+ createEstimateNoteHandle,+} from '@/components/prompts/volume-estimate';import { readUrlChoice } from '@/lib/url-state';import {getPromptSuggestions,@@ -280,6 +286,8 @@ export function SuggestionsCard({limitActions,}: Props) {const t = useTranslations('prompts.suggestions');+ // One method note for the list's volume ranges (PROMPT-013).+ const volumeNote = useMemo(() => createEstimateNoteHandle(), []);const [suggestions, setSuggestions] = useState<PromptSuggestion[]>([]);const [loading, setLoading] = useState(false);const [loaded, setLoaded] = useState(false);@@ -753,7 +761,13 @@ export function SuggestionsCard({variant="outline"className="gap-1 text-xs font-normal tabular-nums">- <TrendingUp className="h-3 w-3" />~{formatNumber(s.estVolume)}/mo+ <TrendingUp className="h-3 w-3" />+ {/* An AI's guess: a range, always low confidence (PROMPT-013). */}+ <EstimateRange+ estimate={guessedVolumeEstimate(s.estVolume, s.generatedAt)}+ handle={volumeNote}+ perMonth+ /></Badge>))}@@ -809,6 +823,7 @@ export function SuggestionsCard({)}</div>)}+ <EstimateNoteTooltip handle={volumeNote} /></CardContent></Card>);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/similar-topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/similar-topics/page.tsxindex 62ac63139..eddccc621 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/similar-topics/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/similar-topics/page.tsx@@ -20,8 +20,19 @@ import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';import { useBrandStore } from '@/stores/use-brand-store';import type { PromptVolume } from '@/types';import { formatCompactNumber } from '@/lib/format';+import { keywordVolumeEstimate, promptVolumeEstimate, sumEstimates } from '@/lib/volume-estimate';+import { useTranslations } from 'next-intl';+import {+ EstimateBadge,+ EstimateNoteTooltip,+ EstimateRange,+ createEstimateNoteHandle,+} from '@/components/prompts/volume-estimate';export default function SimilarTopicsPage() {+ const t = useTranslations('prompts.similarTopics');+ // One method note for the whole table: it lists every keyword.+ const rowNote = useMemo(() => createEstimateNoteHandle(), []);const { getActiveBrand } = useBrandStore();const brand = getActiveBrand();const [volumes, setVolumes] = useState<PromptVolume[]>([]);@@ -68,7 +79,8 @@ export default function SimilarTopicsPage() {() => ({clusters: aggregatePromptVolumeClusters(volumes).length,googleVolume: volumes.reduce((sum, volume) => sum + volume.totalGoogleVolume, 0),- aiVolume: volumes.reduce((sum, volume) => sum + volume.estAiVolume, 0),+ // The prompts' estimates added up: a range, as on Insights (PROMPT-013).+ aiEstimate: sumEstimates(volumes.map((volume) => promptVolumeEstimate(volume))),}),[volumes],);@@ -120,13 +132,18 @@ export default function SimilarTopicsPage() {</Card><Card><CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Est. AI Volume</CardTitle>+ <CardTitle className="text-sm font-medium">{t('aiTitle')}</CardTitle></CardHeader>- <CardContent>- <div className="text-2xl font-semibold tabular-nums">- {formatCompactNumber(totals.aiVolume)}+ <CardContent className="space-y-1">+ <div className="flex flex-wrap items-center gap-2">+ <EstimateRange+ estimate={totals.aiEstimate}+ kind="total"+ className="text-2xl font-semibold"+ />+ <EstimateBadge estimate={totals.aiEstimate} kind="total" /></div>- <p className="text-xs text-muted-foreground">monthly AI queries, across prompts</p>+ <p className="text-xs text-muted-foreground">{t('aiSub')}</p></CardContent></Card></div>@@ -183,8 +200,15 @@ export default function SimilarTopicsPage() {<TableCell className="text-right font-medium tabular-nums">{formatCompactNumber(cluster.volume)}</TableCell>- <TableCell className="text-right tabular-nums">- {formatCompactNumber(cluster.estimatedAiVolume)}+ <TableCell className="text-right">+ <EstimateRange+ estimate={keywordVolumeEstimate(+ cluster.volume,+ cluster.aiVolumeMultiplier,+ cluster.fetchedAt,+ )}+ handle={rowNote}+ /></TableCell><TableCell className="text-center"><Badge variant="outline">{cluster.occurrences}</Badge>@@ -213,6 +237,7 @@ export default function SimilarTopicsPage() {)}</TableBody></Table>+ <EstimateNoteTooltip handle={rowNote} /></CardContent></Card></div>diff --git a/web/src/components/prompts/volume-estimate.test.tsx b/web/src/components/prompts/volume-estimate.test.tsxindex 29ce8f18e..c696b0c3b 100644--- a/web/src/components/prompts/volume-estimate.test.tsx+++ b/web/src/components/prompts/volume-estimate.test.tsx@@ -3,7 +3,13 @@ import { createRoot, type Root } from 'react-dom/client';import { NextIntlClientProvider } from 'next-intl';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import messages from '../../../messages/en.json';-import { promptVolumeEstimate, sumEstimates, type VolumeEstimate } from '@/lib/volume-estimate';+import {+ guessedVolumeEstimate,+ keywordVolumeEstimate,+ promptVolumeEstimate,+ sumEstimates,+ type VolumeEstimate,+} from '@/lib/volume-estimate';import {EstimateBadge,EstimateNoteTooltip,@@ -95,6 +101,29 @@ describe('EstimateRange', () => {});});+describe('the note for other kinds of estimate', () => {+ it("says a keyword's volume is measured and only the AI share assumed", async () => {+ render(+ <EstimateRange estimate={keywordVolumeEstimate(22_200, 0.45, '2026-10-10T19:28:41Z', NOW)} />,+ );+ const note = await noteOf(container.querySelector('button')!);+ expect(note).toContain(+ "This keyword's monthly Google searches × the share of Google searches that now get an AI answer",+ );+ expect(note).toContain('the range is ±25%');+ expect(note).toContain('Confidence: Medium · updated Oct 10, 2026');+ });++ it("says a suggestion's volume is an AI's guess, dated by the suggestion", async () => {+ render(<EstimateRange estimate={guessedVolumeEstimate(1200, '2026-10-22T08:00:00Z')} />);+ const note = await noteOf(container.querySelector('button')!);+ expect(note).toContain("An AI's estimate for a prompt you don't track yet");+ expect(note).toContain("Source: Ansvisor's AI, from your tracked prompts' estimates.");+ expect(note).toContain('Confidence: Low · suggested Oct 22, 2026');+ 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.tsxindex 825d860f1..e07f01476 100644--- a/web/src/components/prompts/volume-estimate.tsx+++ b/web/src/components/prompts/volume-estimate.tsx@@ -39,7 +39,11 @@ function EstimateNote({ estimate, kind }: { estimate: Estimate; kind: EstimateKireturn (<><p className="font-medium">{t('title')}</p>- {kind === 'prompt' || !isTotal(estimate) ? (+ {estimate.basis === 'guess' ? (+ <p>{t('methodGuess')}</p>+ ) : estimate.basis === 'keyword' ? (+ <p>{t('methodKeyword', { rate })}</p>+ ) : kind === 'prompt' || !isTotal(estimate) ? (<><p>{t('method', { rate })}</p><p>@@ -67,13 +71,18 @@ function EstimateNote({ estimate, kind }: { estimate: Estimate; kind: EstimateKi</>)}<p>- {estimate.asOf- ? t('sources', { month: monthOf(estimate.asOf), rate })- : t('sourcesUndated', { rate })}+ {estimate.basis === 'guess'+ ? t('sourcesGuess')+ : estimate.asOf+ ? t('sources', { month: monthOf(estimate.asOf), rate })+ : t('sourcesUndated', { rate })}</p><p>{estimate.asOf- ? t('confidence', { level, date: formatDate(estimate.asOf) })+ ? t(estimate.basis === 'guess' ? 'confidenceSuggested' : 'confidence', {+ level,+ date: formatDate(estimate.asOf),+ }): t('confidenceUndated', { level })}</p>{estimate.stale && <p>{t('stale')}</p>}@@ -168,12 +177,15 @@ export function EstimateRange({estimate,kind = 'prompt',handle,+ perMonth = false,className,}: {estimate: Estimate;kind?: EstimateKind;/** A table's shared note; without one, the range carries its own. */handle?: EstimateNoteHandle;+ /** Adds "/mo" after the range, where nothing else says it is monthly. */+ perMonth?: boolean;className?: string;}) {const t = useTranslations('volumeEstimate');@@ -191,6 +203,7 @@ export function EstimateRange({)}>{range}+ {perMonth && <span className="font-normal">{t('perMonth')}</span>}</WithNote>);}diff --git a/web/src/lib/actions/prompt-volume.test.ts b/web/src/lib/actions/prompt-volume.test.tsnew file mode 100644index 000000000..db0e0124f--- /dev/null+++ b/web/src/lib/actions/prompt-volume.test.ts@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * PROMPT-013: a prompt's detail page reads its volume. prompt_volumes is a+ * server-only table, so it's read only for a prompt the caller can see.+ */++let visible: { id: string } | null;+let volumeRow: Record<string, unknown> | null;+const volumeReads: string[] = [];++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ from: () => {+ const chain = {+ select: () => chain,+ eq: () => chain,+ maybeSingle: async () => ({ data: visible, error: null }),+ };+ return chain;+ },+ })),+}));++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: (table: string) => {+ const chain = {+ select: () => chain,+ eq: (_column: string, value: string) => {+ volumeReads.push(`${table}:${value}`);+ return chain;+ },+ maybeSingle: async () => ({ data: volumeRow, error: null }),+ };+ return chain;+ },+ },+}));++const { getPromptVolume } = await import('./prompt-volume');++beforeEach(() => {+ visible = { id: 'p1' };+ volumeRow = {+ est_ai_volume: 1080,+ total_google_volume: 2400,+ google_volumes: { a: 4400, b: 2400, c: 880 },+ ai_volume_multiplier: '0.450',+ keywords: ['a', 'b', 'c'],+ fetched_at: '2026-10-10T19:28:41Z',+ };+ volumeReads.length = 0;+});++describe('getPromptVolume', () => {+ it("reads the prompt's volume for its estimate", async () => {+ expect(await getPromptVolume('p1')).toEqual({+ estAiVolume: 1080,+ totalGoogleVolume: 2400,+ googleVolumes: { a: 4400, b: 2400, c: 880 },+ aiVolumeMultiplier: 0.45,+ keywords: ['a', 'b', 'c'],+ fetchedAt: '2026-10-10T19:28:41Z',+ });+ expect(volumeReads).toEqual(['prompt_volumes:p1']);+ });++ it("reads nothing for a prompt the caller can't see, and null without a volume", async () => {+ visible = null;+ expect(await getPromptVolume('p1')).toBeNull();+ expect(volumeReads).toEqual([]);++ visible = { id: 'p1' };+ volumeRow = null;+ expect(await getPromptVolume('p1')).toBeNull();+ });+});diff --git a/web/src/lib/actions/prompt-volume.ts b/web/src/lib/actions/prompt-volume.tsnew file mode 100644index 000000000..f3fe2ea35--- /dev/null+++ b/web/src/lib/actions/prompt-volume.ts@@ -0,0 +1,50 @@+'use server';++import { createClient } from '@/lib/supabase/server';+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { PromptVolume } from '@/types';++/** What a prompt's estimate is worked out from (PROMPT-013). */+export type PromptVolumeEstimateRow = Pick<+ PromptVolume,+ | 'estAiVolume'+ | 'totalGoogleVolume'+ | 'googleVolumes'+ | 'aiVolumeMultiplier'+ | 'keywords'+ | 'fetchedAt'+>;++/**+ * One prompt's volume for its detail page, or null when it has none.+ * prompt_volumes is a server-only table, so the prompt is first read with+ * the signed-in user's client (RLS): one they can't see reads null.+ */+export async function getPromptVolume(promptId: string): Promise<PromptVolumeEstimateRow | null> {+ const supabase = await createClient();+ const { data: prompt, error: promptError } = await supabase+ .from('prompts')+ .select('id')+ .eq('id', promptId)+ .maybeSingle();+ if (promptError) throw new Error(promptError.message);+ if (!prompt) return null;++ const { data, error } = await supabaseAdmin+ .from('prompt_volumes')+ .select(+ 'est_ai_volume, total_google_volume, google_volumes, ai_volume_multiplier, keywords, fetched_at',+ )+ .eq('prompt_id', promptId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!data) return null;+ return {+ estAiVolume: Number(data.est_ai_volume ?? 0),+ totalGoogleVolume: Number(data.total_google_volume ?? 0),+ googleVolumes: (data.google_volumes ?? {}) as Record<string, number>,+ aiVolumeMultiplier: Number(data.ai_volume_multiplier ?? 0),+ keywords: (data.keywords ?? []) as string[],+ fetchedAt: data.fetched_at as string,+ };+}diff --git a/web/src/lib/prompt-volume-clusters.test.ts b/web/src/lib/prompt-volume-clusters.test.tsindex d5768f99b..afc3589e7 100644--- a/web/src/lib/prompt-volume-clusters.test.ts+++ b/web/src/lib/prompt-volume-clusters.test.ts@@ -69,4 +69,15 @@ describe('aggregatePromptVolumeClusters', () => {]);expect(cluster.prompts[0]).toMatchObject({ id: 'a', volume: 8100, estimatedAiVolume: 1215 });});++ it('carries the rate and the latest fetch, for the estimate shown beside it', () => {+ const [cluster] = aggregatePromptVolumeClusters([+ prompt('a', ['seo tools'], { 'seo tools': 110000 }, 110000),+ {+ ...prompt('b', ['SEO tools'], { 'SEO tools': 110000 }, 110000),+ fetchedAt: '2026-10-20T00:00:00Z',+ },+ ]);+ expect(cluster).toMatchObject({ aiVolumeMultiplier: 0.15, fetchedAt: '2026-10-20T00:00:00Z' });+ });});diff --git a/web/src/lib/prompt-volume-clusters.ts b/web/src/lib/prompt-volume-clusters.tsindex 1c73718fb..4aa0ca20c 100644--- a/web/src/lib/prompt-volume-clusters.ts+++ b/web/src/lib/prompt-volume-clusters.ts@@ -5,6 +5,9 @@ export interface PromptVolumeCluster {/** The keyword's monthly Google volume, counted once. */volume: number;estimatedAiVolume: number;+ /** The AI adoption rate behind estimatedAiVolume, and when the volume was fetched (PROMPT-013). */+ aiVolumeMultiplier: number;+ fetchedAt: string | null;/** How many prompts use the keyword. */occurrences: number;/** Those prompts, each with its own volumes (the prompt's, not the keyword's). */@@ -54,6 +57,11 @@ export function aggregatePromptVolumeClusters(volumes: PromptVolume[]): PromptVoif (volume > existing.volume) {existing.volume = volume;existing.estimatedAiVolume = Math.round(volume * v.aiVolumeMultiplier);+ existing.aiVolumeMultiplier = v.aiVolumeMultiplier;+ }+ // Dated by its latest fetch.+ if (v.fetchedAt && (!existing.fetchedAt || v.fetchedAt > existing.fetchedAt)) {+ existing.fetchedAt = v.fetchedAt;}existing.occurrences += 1;existing.prompts.push(prompt);@@ -62,6 +70,8 @@ export function aggregatePromptVolumeClusters(volumes: PromptVolume[]): PromptVokeyword: kw,volume,estimatedAiVolume: Math.round(volume * v.aiVolumeMultiplier),+ aiVolumeMultiplier: v.aiVolumeMultiplier,+ fetchedAt: v.fetchedAt ?? null,occurrences: 1,prompts: [prompt],});diff --git a/web/src/lib/volume-estimate.test.ts b/web/src/lib/volume-estimate.test.tsindex fe8836a28..e2a95cb15 100644--- a/web/src/lib/volume-estimate.test.ts+++ b/web/src/lib/volume-estimate.test.ts@@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest';import {averageEstimate,formatEstimateRange,+ guessedVolumeEstimate,+ keywordVolumeEstimate,promptVolumeEstimate,rankable,sumEstimates,@@ -118,3 +120,27 @@ describe('rankable', () => {expect(rankable({ confidence: 'low' })).toBe(false);});});++describe('keywordVolumeEstimate', () => {+ it("is medium, ±25%, from one keyword's measured volume", () => {+ const e = keywordVolumeEstimate(22_200, 0.45, '2026-10-10T19:28:41Z', NOW);+ expect(e).toMatchObject({ basis: 'keyword', value: 9990, confidence: 'medium', measured: 1 });+ expect(formatEstimateRange(e)).toBe('7.4–13k');+ });++ it('is low with no volume, or over six months old', () => {+ expect(keywordVolumeEstimate(0, 0.45, '2026-10-10T19:28:41Z', NOW).confidence).toBe('low');+ expect(keywordVolumeEstimate(22_200, 0.45, '2026-03-01T00:00:00Z', NOW)).toMatchObject({+ confidence: 'low',+ stale: true,+ });+ });+});++describe('guessedVolumeEstimate', () => {+ it("is always low, half to twice an AI's guess", () => {+ const e = guessedVolumeEstimate(1200, '2026-10-22T08:00:00Z');+ expect(e).toMatchObject({ basis: 'guess', confidence: 'low', low: 600, high: 2400 });+ expect(formatEstimateRange(e)).toBe('600–2.4k');+ });+});diff --git a/web/src/lib/volume-estimate.ts b/web/src/lib/volume-estimate.tsindex 0ea1f5d18..1c24f61a4 100644--- a/web/src/lib/volume-estimate.ts+++ b/web/src/lib/volume-estimate.ts@@ -17,7 +17,15 @@ import type { PromptVolume } from '@/types';export type EstimateConfidence = 'high' | 'medium' | 'low';+/**+ * What the estimate rests on: a prompt's related keywords, one keyword's+ * 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 interface VolumeEstimate {+ basis: EstimateBasis;/** The stored point estimate: what sorting and totals add up. */value: number;low: number;@@ -79,6 +87,12 @@ function bounds(value: number, low: number, high: number): { low: number; high:return { low: roundTo2(lo, 'down'), high: roundTo2(hi, 'up') };}+/** Fetched long enough ago to count one level less. */+const isStale = (asOf: string | null, now: Date) => {+ const fetched = asOf ? Date.parse(asOf) : NaN;+ return Number.isFinite(fetched) && now.getTime() - fetched > STALE_DAYS * 24 * 60 * 60 * 1000;+};+type VolumeRow = Pick<PromptVolume,'estAiVolume' | 'googleVolumes' | 'aiVolumeMultiplier' | 'keywords' | 'fetchedAt'@@ -103,9 +117,7 @@ export function promptVolumeEstimate(row: VolumeRow, now: Date = new Date()): Vo: measured >= 2 && spread <= AGREE_MEDIUM? 1: 0;- const fetched = row.fetchedAt ? Date.parse(row.fetchedAt) : NaN;- const stale =- Number.isFinite(fetched) && now.getTime() - fetched > STALE_DAYS * 24 * 60 * 60 * 1000;+ const stale = isStale(row.fetchedAt ?? null, now);if (stale) level = Math.max(0, level - 1);if (value === 0) level = 0;@@ -119,6 +131,7 @@ export function promptVolumeEstimate(row: VolumeRow, now: Date = new Date()): Vo: bounds(value, value / MAX_STRETCH, value * MAX_STRETCH);return {+ basis: 'keywords',value,...range,confidence: LEVELS[level],@@ -130,6 +143,51 @@ export function promptVolumeEstimate(row: VolumeRow, now: Date = new Date()): Vo};}+/**+ * One keyword's AI share, as Similar Topics lists it: its Google volume is+ * measured, so only the adoption rate is assumed. Medium, ±25%; low when+ * the keyword has no volume or it is over six months old.+ */+export function keywordVolumeEstimate(+ googleVolume: number,+ rate: number,+ asOf: string | null,+ now: Date = new Date(),+): VolumeEstimate {+ const value = Math.round(Math.max(0, googleVolume) * rate);+ const stale = isStale(asOf, now);+ return {+ basis: 'keyword',+ value,+ ...bounds(value, value, value),+ confidence: value > 0 && !stale ? 'medium' : 'low',+ measured: googleVolume > 0 ? 1 : 0,+ keywords: 1,+ rate,+ asOf,+ stale,+ };+}++/**+ * An AI's guess at a suggested prompt's volume (Prompt Suggestions): no+ * keyword behind it is measured yet, so it is always low, ×½ to ×2.+ */+export function guessedVolumeEstimate(value: number, asOf: string | null): VolumeEstimate {+ const v = Math.max(0, Math.round(value));+ return {+ basis: 'guess',+ value: v,+ ...bounds(v, v / MAX_STRETCH, v * MAX_STRETCH),+ confidence: 'low',+ measured: 0,+ keywords: 0,+ rate: 0,+ asOf,+ stale: false,+ };+}+export interface EstimateTotal extends VolumeEstimate {/** How many prompts were added up, and at each confidence. */count: number;@@ -165,6 +223,7 @@ export function sumEstimates(estimates: VolumeEstimate[]): EstimateTotal {? 'low': 'medium';return {+ basis: 'keywords',value,low,high,