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): show estimated AI volume as a range with an Estimate badge and method note (#1361)
Cihand7f186fd09d8
diff --git a/web/messages/en.json b/web/messages/en.jsonindex d80a88937..3e61d83b3 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -5184,6 +5184,19 @@},"title": "Prompt Volumes","description": "Discover query volumes and trends across AI platforms.",+ "volumeInsights": {+ "totalTitle": "Total Est. AI Volume",+ "totalSub": "from {google} Google searches",+ "averageTitle": "Avg. AI Volume",+ "averageSub": "per prompt",+ "googleColumn": "Google Vol.",+ "googleTip": "The prompt's monthly Google searches: the median of its related keywords that have search data.",+ "aiColumn": "Est. AI Vol.",+ "aiTip": "Estimated monthly AI searches, as a range: the related keywords' Google searches × the AI adoption rate. Grey when the confidence is low.",+ "footnote": "* Est. AI Volume is an estimate, shown as a range: the median Google searches of the prompt's related keywords × the AI adoption rate. Hover a range for its sources, confidence and date. For planning, not a measured count.",+ "opportunityVolumeTip": "Estimated monthly AI searches, highest first. Low-confidence estimates aren't listed on their own.",+ "opportunityLevelTip": "Opportunity level from the estimated AI volume: High = {high}+/mo, Medium = {min}–{high}/mo. A low-confidence estimate gets no level by itself."+ },"totalVolume": "Total Volume","trending": "Trending","presenceRate": "Presence Rate",@@ -5309,7 +5322,7 @@"mentions": "How often AI answers named your brand over the {range}.","citations": "How often AI answers cited your pages over the {range}.","positions": "Where AI answers name your brand, on average, over the {range}. Lower is better.",- "volume": "Estimated monthly AI searches for this prompt.",+ "volume": "Estimated monthly AI searches for this prompt, as a range. Grey when the confidence is low; those sort after the rest.","competition": "Google Ads competition for its keywords: Low, Medium or High.","runs": "AI answers collected over the {range}. One run is one AI platform answering this prompt once.","added": "When this prompt was added.",@@ -5350,6 +5363,33 @@}}},+ "volumeEstimate": {+ "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}%).",+ "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.",+ "rangeSpread": "The range is the AI share of the middle half of them, within half to twice the estimate.",+ "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}%.",+ "sourcesUndated": "Sources: Google search volume from DataForSEO and an AI answer share of {rate}%.",+ "confidence": "Confidence: {level} · updated {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.",+ "measuredNote": "Measured numbers, such as your visibility or Search Console clicks, never carry this badge.",+ "level": {+ "high": "High",+ "medium": "Medium",+ "low": "Low"+ },+ "badge": "Estimate",+ "badgeLow": "Estimate · low confidence",+ "badgeLabel": "Estimate, {level} confidence: how it's built",+ "label": "{range} a month, estimated, {level} confidence"+ },"mentions": {"title": "Mentions & Sentiment","description": "Where AI mentions your brand, how it describes you, why, and what to do about it.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_charts.tsxindex 070fe7d22..fdc9f2e77 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_charts.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_charts.tsx@@ -2,7 +2,8 @@import { useRef, useState, useEffect } from 'react';import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Cell } from 'recharts';-import { formatCompactNumber, formatNumber } from '@/lib/format';+import { formatCompactNumber } from '@/lib/format';+import { formatEstimateRange, scaleEstimate } from '@/lib/volume-estimate';// ─── Auto-sizing wrapper ─────────────────────────────────────────────────────@@ -75,7 +76,14 @@ export const AI_PLATFORM_SHARES: {{ name: 'Grok', share: 0.005, color: '#18181b' },];-export function PlatformVolumeChart({ totalVolume }: { totalVolume: number }) {+export function PlatformVolumeChart({+ totalVolume,+ totalRange,+}: {+ totalVolume: number;+ /** The total's estimated range (PROMPT-013): each platform shows its share of it. */+ totalRange: { low: number; high: number };+}) {if (totalVolume <= 0) {return (<div className="flex items-center justify-center h-[220px] text-xs text-muted-foreground">@@ -129,7 +137,9 @@ export function PlatformVolumeChart({ totalVolume }: { totalVolume: number }) {<p className="font-medium text-foreground mb-0.5">{row.name}</p><p className="text-muted-foreground">Est. queries:{' '}- <span className="font-medium text-foreground">{formatNumber(row.volume)}</span>+ <span className="font-medium text-foreground">+ {formatEstimateRange(scaleEstimate(totalRange, row.share))}+ </span></p><p className="text-muted-foreground">Share:{' '}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex 1a6c0cd45..bba693083 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -189,14 +189,26 @@ import { toCsv } from '@/lib/csv';import { formatRelative } from '@/lib/format-relative';import {compareNullsLast,+ comparePromptSortRows,isAllPromptsSortKey,- promptSortValue,type AllPromptsSortKey,type SortDir,} from './prompt-sort';import { BulkActionBar } from './_bulk-action-bar';import { promptsTableState } from './table-state';import { formatCompactNumber, formatDate, formatNumber } from '@/lib/format';+import {+ averageEstimate,+ promptVolumeEstimate,+ sumEstimates,+ type VolumeEstimate,+} from '@/lib/volume-estimate';+import {+ EstimateBadge,+ EstimateNoteTooltip,+ EstimateRange,+ createEstimateNoteHandle,+} from '@/components/prompts/volume-estimate';import { usePagination, TablePager } from '@/components/table-pager';import { PromptPositionsSheet } from '@/components/prompts/prompt-positions-sheet';import {@@ -337,6 +349,12 @@ const promptExportHeaders = (suffix: string) => ['is_active','created_at','est_ai_volume',+ // PROMPT-013: the AI volume is an estimate; these say how sure it is.+ 'volume_type',+ 'volume_confidence',+ 'est_ai_volume_low',+ 'est_ai_volume_high',+ 'volume_date','total_google_volume','intent',`ai_visibility_score_${suffix}`,@@ -1258,10 +1276,6 @@ function volumeErrorMessage(code: VolumeErrorCode, fallback: string): string {}}-function VolumePill({ value }: { value: number }) {- return <span className="tabular-nums text-sm font-semibold">~{formatCompactNumber(value)}</span>;-}-// ─── Main Page ────────────────────────────────────────────────────────────────export default function PromptsPage() {@@ -1293,6 +1307,10 @@ export default function PromptsPage() {const tCommon = useTranslations('common');const tNav = useTranslations('nav');const tPrompts = useTranslations('prompts');+ const tVolumes = useTranslations('prompts.volumeInsights');+ // One method note per table: these tables list every analyzed prompt.+ const volumeTableNote = useMemo(() => createEstimateNoteHandle(), []);+ const opportunityTableNote = useMemo(() => createEstimateNoteHandle(), []);const activeBrand = useBrandStore((s) => s.brands.find((brand) => brand.id === s.activeBrandId) ?? null,);@@ -1751,8 +1769,21 @@ export default function PromptsPage() {const handleReanalyzeAll = () => runVolumeAnalysis(true);+ // Each volume as an estimate: a range and how sure it is (PROMPT-013).+ const estimateByPromptId = useMemo(() => {+ const m = new Map<string, VolumeEstimate>();+ for (const v of volumes) m.set(v.promptId, promptVolumeEstimate(v));+ return m;+ }, [volumes]);const totalGoogleVol = volumes.reduce((s, v) => s + v.totalGoogleVolume, 0);const totalAiVol = volumes.reduce((s, v) => s + v.estAiVolume, 0);+ const totalEstimate = sumEstimates(volumes.map((v) => estimateByPromptId.get(v.promptId)!));+ const averagePerPrompt = averageEstimate(totalEstimate);+ const estimateOf = (v: PromptVolume) => estimateByPromptId.get(v.promptId)!;+ // High Opportunity Prompts: a low-confidence estimate isn't listed on its own.+ const opportunityRows = volumes+ .filter((v) => opportunityLevel(v.estAiVolume, estimateOf(v).confidence))+ .sort((a, b) => b.estAiVolume - a.estAiVolume);// Distinct keywords: prompts share many, as Similar Topics counts them.const totalKeywords = new Set(volumes.flatMap((v) => v.keywords.map((k) => k.trim().toLowerCase())),@@ -1805,6 +1836,11 @@ export default function PromptsPage() {is_active: p.isActive,created_at: p.createdAt,est_ai_volume: volumeByPromptId.get(p.id)?.estAiVolume ?? '',+ volume_type: estimateByPromptId.has(p.id) ? 'estimate' : '',+ volume_confidence: estimateByPromptId.get(p.id)?.confidence ?? '',+ est_ai_volume_low: estimateByPromptId.get(p.id)?.low ?? '',+ est_ai_volume_high: estimateByPromptId.get(p.id)?.high ?? '',+ volume_date: volumeByPromptId.get(p.id)?.fetchedAt ?? '',total_google_volume: volumeByPromptId.get(p.id)?.totalGoogleVolume ?? '',intent: volumeByPromptId.get(p.id)?.intent ?? '',[`ai_visibility_score_${rangeSuffix}`]: visibility[p.id]?.score ?? '',@@ -1829,7 +1865,15 @@ export default function PromptsPage() {link.click();URL.revokeObjectURL(url);- }, [activeBrand?.slug, canExport, allPrompts, visibility, volumeByPromptId, rangePreset]);+ }, [+ activeBrand?.slug,+ canExport,+ allPrompts,+ visibility,+ volumeByPromptId,+ estimateByPromptId,+ rangePreset,+ ]);if (!activeBrandId) {return (@@ -2064,6 +2108,7 @@ export default function PromptsPage() {prompts={allPrompts}activeBrandId={activeBrandId}volumeByPromptId={volumeByPromptId}+ estimateByPromptId={estimateByPromptId}visibility={visibility}positions={positions}rangeLabel={rangeLabel}@@ -2227,10 +2272,16 @@ export default function PromptsPage() {sub={`across ${totalKeywords} keywords`}/><KpiCard- title="Total Est. AI Volume"+ title={tVolumes('totalTitle')}icon={BarChart3}- value={`~${formatCompactNumber(totalAiVol)}`}- sub={`from ${formatCompactNumber(totalGoogleVol)} Google searches`}+ value={+ // The range, then its Estimate badge beneath (PROMPT-013 mockup).+ <span className="flex flex-col items-start gap-1">+ <EstimateRange estimate={totalEstimate} kind="total" className="text-2xl" />+ <EstimateBadge estimate={totalEstimate} kind="total" />+ </span>+ }+ sub={tVolumes('totalSub', { google: formatCompactNumber(totalGoogleVol) })}/><KpiCardtitle="AI Adoption Rate"@@ -2239,10 +2290,19 @@ export default function PromptsPage() {sub="of Google search volume"/><KpiCard- title="Avg. AI Volume"+ title={tVolumes('averageTitle')}icon={BarChart3}- value={`~${formatCompactNumber(Math.round(totalAiVol / volumes.length))}`}- sub="per prompt"+ value={+ <span className="flex flex-col items-start gap-1">+ <EstimateRange+ estimate={averagePerPrompt}+ kind="average"+ className="text-2xl"+ />+ <EstimateBadge estimate={averagePerPrompt} kind="average" />+ </span>+ }+ sub={tVolumes('averageSub')}/></div>@@ -2258,7 +2318,7 @@ export default function PromptsPage() {</p></CardHeader><CardContent>- <PlatformVolumeChart totalVolume={totalAiVol} />+ <PlatformVolumeChart totalVolume={totalAiVol} totalRange={totalEstimate} /></CardContent></Card>@@ -2307,17 +2367,11 @@ export default function PromptsPage() {<TableRow><TableHead className="pl-6">Prompt</TableHead>- <ColHead- className="text-right"- tooltip="Total monthly Google search volume across all extracted keywords."- >- Google Vol.+ <ColHead className="text-right" tooltip={tVolumes('googleTip')}>+ {tVolumes('googleColumn')}</ColHead>- <ColHead- className="text-right"- tooltip="Estimated monthly AI prompt volume. Calculated as total Google volume multiplied by the AI adoption rate."- >- Est. AI Vol.+ <ColHead className="text-right" tooltip={tVolumes('aiTip')}>+ {tVolumes('aiColumn')}</ColHead><ColHeadclassName="text-center"@@ -2338,7 +2392,11 @@ export default function PromptsPage() {{formatNumber(row.totalGoogleVolume)}</TableCell><TableCell className="text-right">- <VolumePill value={row.estAiVolume} />+ <EstimateRange+ estimate={estimateOf(row)}+ handle={volumeTableNote}+ className="text-sm font-semibold"+ /></TableCell><TableCell className="text-center"><Badge@@ -2355,23 +2413,20 @@ export default function PromptsPage() {))}</TableBody></Table>+ <EstimateNoteTooltip handle={volumeTableNote} />{filtered.length === 0 && (<div className="py-10 text-center text-sm text-muted-foreground">No prompts match your search.</div>)}<div className="px-6 py-2 border-t">- <p className="text-xs text-muted-foreground">- * Est. AI Volume = the median Google search volume of the prompt's- extracted keywords × AI adoption rate. Figures are approximations for planning- purposes.- </p>+ <p className="text-xs text-muted-foreground">{tVolumes('footnote')}</p></div></CardContent></Card>{/* High Opportunity Prompts */}- {volumes.some((v) => opportunityLevel(v.estAiVolume)) && (+ {opportunityRows.length > 0 && (<Card><CardHeader className="pb-2"><div className="flex items-center gap-2">@@ -2391,7 +2446,7 @@ export default function PromptsPage() {<TableHead className="pl-6">Prompt</TableHead><ColHeadclassName="text-right"- tooltip="Estimated monthly AI prompt volume. Sorted by highest volume first."+ tooltip={tVolumes('opportunityVolumeTip')}>Est. AI Volume</ColHead>@@ -2400,49 +2455,58 @@ export default function PromptsPage() {</ColHead><ColHeadclassName="text-right pr-6"- tooltip={`Opportunity level based on estimated AI volume. High = ${formatCompactNumber(OPPORTUNITY_HIGH_VOLUME)}+/mo, Medium = ${formatCompactNumber(OPPORTUNITY_MIN_VOLUME)}–${formatCompactNumber(OPPORTUNITY_HIGH_VOLUME)}/mo.`}+ tooltip={tVolumes('opportunityLevelTip', {+ high: formatCompactNumber(OPPORTUNITY_HIGH_VOLUME),+ min: formatCompactNumber(OPPORTUNITY_MIN_VOLUME),+ })}>Opportunity</ColHead></TableRow></TableHeader><TableBody>- {volumes- .filter((v) => opportunityLevel(v.estAiVolume))- .sort((a, b) => b.estAiVolume - a.estAiVolume)- .map((row) => (- <TableRow key={row.id} className="hover:bg-muted/50">- <TableCell className="pl-6 font-medium text-sm">- {row.promptText}- </TableCell>- <TableCell className="text-right">- <VolumePill value={row.estAiVolume} />- </TableCell>- <TableCell className="text-center">- <Badge- variant="outline"- className={cn('text-xs', INTENT_COLORS[row.intent] || '')}- >- {INTENT_LABELS[row.intent] || row.intent}- </Badge>- </TableCell>- <TableCell className="text-right pr-6">- <Badge- variant="outline"- className={cn(- 'text-xs',- opportunityLevel(row.estAiVolume) === 'high'- ? 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400'- : 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',- )}- >- {opportunityLevel(row.estAiVolume) === 'high' ? 'High' : 'Medium'}- </Badge>- </TableCell>- </TableRow>- ))}+ {opportunityRows.map((row) => (+ <TableRow key={row.id} className="hover:bg-muted/50">+ <TableCell className="pl-6 font-medium text-sm">+ {row.promptText}+ </TableCell>+ <TableCell className="text-right">+ <EstimateRange+ estimate={estimateOf(row)}+ handle={opportunityTableNote}+ className="text-sm font-semibold"+ />+ </TableCell>+ <TableCell className="text-center">+ <Badge+ variant="outline"+ className={cn('text-xs', INTENT_COLORS[row.intent] || '')}+ >+ {INTENT_LABELS[row.intent] || row.intent}+ </Badge>+ </TableCell>+ <TableCell className="text-right pr-6">+ <Badge+ variant="outline"+ className={cn(+ 'text-xs',+ opportunityLevel(row.estAiVolume, estimateOf(row).confidence) ===+ 'high'+ ? 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400'+ : 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',+ )}+ >+ {opportunityLevel(row.estAiVolume, estimateOf(row).confidence) ===+ 'high'+ ? 'High'+ : 'Medium'}+ </Badge>+ </TableCell>+ </TableRow>+ ))}</TableBody></Table>+ <EstimateNoteTooltip handle={opportunityTableNote} /></CardContent></Card>)}@@ -2718,6 +2782,7 @@ function AllPromptsTab({prompts: allRows,activeBrandId,volumeByPromptId,+ estimateByPromptId,visibility,positions,rangeLabel,@@ -2737,6 +2802,8 @@ function AllPromptsTab({prompts: Prompt[];activeBrandId: string;volumeByPromptId: Map<string, PromptVolume>;+ /** Each volume as an estimate, keyed like volumeByPromptId (PROMPT-013). */+ estimateByPromptId: Map<string, VolumeEstimate>;visibility: Record<string, PromptVisibilitySummary>;/** The Positions column per prompt id. */positions: Record<string, PromptPositionCell>;@@ -2761,6 +2828,7 @@ function AllPromptsTab({const tPrompts = useTranslations('prompts');// One tooltip for every prompt and topic the table cuts short.const fullText = useMemo(() => createClampedTextHandle(), []);+ const volumeNote = useMemo(() => createEstimateNoteHandle(), []);const tUsage = useTranslations('prompts.usage');const format = useFormatter();const tDelete = useTranslations('prompts.bulkDelete');@@ -3334,15 +3402,20 @@ function AllPromptsTab({);}- const valueOf = (p: Prompt): number | null =>- promptSortValue(activeSort, {+ const rowOf = (p: Prompt) => {+ const volume = volumeByPromptId.get(p.id);+ return {createdAt: p.createdAt,visibility: visibility[p.id],position: positions[p.id],- volume: volumeByPromptId.get(p.id),- });+ volume: volume && {+ estAiVolume: volume.estAiVolume,+ confidence: estimateByPromptId.get(p.id)?.confidence,+ },+ };+ };- const sorted = list.sort((a, b) => compareNullsLast(valueOf(a), valueOf(b), dir));+ const sorted = list.sort((a, b) => comparePromptSortRows(activeSort, rowOf(a), rowOf(b), dir));// Until a column is picked, prompts added within the last day lead: Track// on Insights opens this table to show them.return isAllPromptsSortKey(rawSort) ? sorted : newFirst(sorted, now);@@ -3356,6 +3429,7 @@ function AllPromptsTab({visibility,positions,volumeByPromptId,+ estimateByPromptId,now,]);@@ -3830,7 +3904,11 @@ function AllPromptsTab({</TableCell><TableCell className="text-right">{vol ? (- <VolumePill value={vol.estAiVolume} />+ <EstimateRange+ estimate={estimateByPromptId.get(p.id)!}+ handle={volumeNote}+ className="text-sm font-semibold"+ />) : (<span className="text-xs text-muted-foreground">—</span>)}@@ -3895,6 +3973,7 @@ function AllPromptsTab({</TableBody></Table><ClampedTextTooltip handle={fullText} />+ <EstimateNoteTooltip handle={volumeNote} /><TablePagerpage={promptsPager.page}totalPages={promptsPager.totalPages}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.test.tsindex 3673d4ea5..a2e4fbb35 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.test.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from 'vitest';-import { compareNullsLast, isAllPromptsSortKey, promptSortValue } from './prompt-sort';+import {+ compareNullsLast,+ comparePromptSortRows,+ isAllPromptsSortKey,+ promptSortValue,+ type PromptSortRow,+} from './prompt-sort';describe('compareNullsLast', () => {it('sorts non-null values ascending', () => {@@ -72,3 +78,38 @@ describe('promptSortValue', () => {expect(isAllPromptsSortKey(null)).toBe(false);});});++describe('comparePromptSortRows', () => {+ const row = (+ estAiVolume: number | null,+ confidence?: 'high' | 'medium' | 'low',+ ): PromptSortRow => ({+ createdAt: '2026-10-01T00:00:00Z',+ volume: estAiVolume === null ? undefined : { estAiVolume, confidence },+ });++ it('puts low-confidence volumes after the confident ones, before rows with none', () => {+ const rows = [+ row(9000, 'low'),+ row(null),+ row(500, 'high'),+ row(2000, 'medium'),+ row(100, 'low'),+ ];+ const order = (dir: 'asc' | 'desc') =>+ [...rows]+ .sort((a, b) => comparePromptSortRows('volume', a, b, dir))+ .map((r) => r.volume?.estAiVolume ?? null);+ expect(order('desc')).toEqual([2000, 500, 9000, 100, null]);+ expect(order('asc')).toEqual([500, 2000, 100, 9000, null]);+ });++ it('sorts other columns as before', () => {+ const a = {+ createdAt: '2026-10-02T00:00:00Z',+ volume: { estAiVolume: 1, confidence: 'low' as const },+ };+ const b = { createdAt: '2026-10-01T00:00:00Z' };+ expect(comparePromptSortRows('added', a, b, 'desc')).toBeLessThan(0);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.ts b/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.tsindex 721e974aa..986e6a8ed 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.ts@@ -1,3 +1,5 @@+import { rankable, type EstimateConfidence } from '@/lib/volume-estimate';+export type SortDir = 'asc' | 'desc';/**@@ -54,7 +56,7 @@ export interface PromptSortRow {lastRunAt: string;};position?: { avg: number | null };- volume?: { estAiVolume: number };+ volume?: { estAiVolume: number; confidence?: EstimateConfidence };}/** A row's value in a column; null when it has none, so it sorts last. */@@ -79,3 +81,24 @@ export function promptSortValue(key: AllPromptsSortKey, row: PromptSortRow): numreturn vis?.lastRunAt ? new Date(vis.lastRunAt).getTime() : null;}}++/**+ * Two rows in a column's order. By volume, a low-confidence estimate isn't+ * ranked on its own (PROMPT-013): it sorts after the confident ones in both+ * directions, and before the rows with no volume at all.+ */+export function comparePromptSortRows(+ key: AllPromptsSortKey,+ a: PromptSortRow,+ b: PromptSortRow,+ dir: SortDir,+): number {+ const av = promptSortValue(key, a);+ const bv = promptSortValue(key, b);+ if (key === 'volume' && av !== null && bv !== null) {+ const aLow = !rankable({ confidence: a.volume?.confidence ?? 'medium' });+ const bLow = !rankable({ confidence: b.volume?.confidence ?? 'medium' });+ if (aLow !== bLow) return aLow ? 1 : -1;+ }+ return compareNullsLast(av, bv, dir);+}diff --git a/web/src/components/prompts/volume-estimate.test.tsx b/web/src/components/prompts/volume-estimate.test.tsxnew file mode 100644index 000000000..29ce8f18e--- /dev/null+++ b/web/src/components/prompts/volume-estimate.test.tsx@@ -0,0 +1,128 @@+import { act } from 'react';+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 {+ EstimateBadge,+ EstimateNoteTooltip,+ EstimateRange,+ createEstimateNoteHandle,+} from './volume-estimate';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const NOW = new Date('2026-10-22T12:00:00Z');+const row = (googleVolumes: Record<string, number>, estAiVolume: number) => ({+ estAiVolume,+ googleVolumes,+ aiVolumeMultiplier: 0.45,+ keywords: [...Object.keys(googleVolumes), 'unmeasured'],+ fetchedAt: '2026-10-10T19:28:41Z',+});+const medium = promptVolumeEstimate(row({ a: 400, b: 2000, c: 10_000 }, 900), NOW);+const low = promptVolumeEstimate(row({ a: 2000 }, 900), NOW);++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++function render(node: React.ReactNode) {+ act(() =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ {node}+ </NextIntlClientProvider>,+ ),+ );+}++/** The method note a trigger opens on focus. */+async function noteOf(trigger: HTMLElement) {+ act(() => trigger.focus());+ await act(() => new Promise((resolve) => setTimeout(resolve, 400)));+ return document.querySelector('[data-slot="tooltip-content"]')?.textContent ?? '';+}++describe('EstimateRange', () => {+ it('shows the range, not a bare number, and says how it was built on focus', async () => {+ render(<EstimateRange estimate={medium} />);+ const trigger = container.querySelector('button')!;+ expect(trigger.textContent).toBe('540–1.8k');+ expect(trigger.getAttribute('aria-label')).toBe(+ '540–1.8k a month, estimated, Medium confidence',+ );+ expect(trigger.className).not.toContain('text-muted-foreground');++ const note = await noteOf(trigger);+ expect(note).toContain('How we estimate AI search volume');+ expect(note).toContain('× the share of Google searches that now get an AI answer (45%)');+ expect(note).toContain('3 of 4 related keywords have Google search data.');+ expect(note).toContain('Sources: Google search volume from DataForSEO (Oct 2026)');+ expect(note).toContain('Confidence: Medium · updated Oct 10, 2026');+ expect(note).toContain('Measured numbers, such as your visibility');+ expect(note).not.toContain('Low confidence');+ });++ it('greys a low-confidence estimate and says it is not ranked on its own', async () => {+ render(<EstimateRange estimate={low} />);+ const trigger = container.querySelector('button')!;+ expect(trigger.textContent).toBe('450–1.8k');+ expect(trigger.className).toContain('text-muted-foreground');+ const note = await noteOf(trigger);+ expect(note).toContain('With one to go by, the range is half to twice the estimate.');+ expect(note).toContain('Low confidence: shown in grey, and not used to rank on its own.');+ });++ it('describes a total by its prompts and their confidence', async () => {+ const total = sumEstimates([medium, low]);+ render(<EstimateRange estimate={total} kind="total" />);+ const note = await noteOf(container.querySelector('button')!);+ expect(note).toContain("The sum of 2 prompts' estimates.");+ expect(note).toContain('Confidence by prompt: 0 high, 1 medium, 1 low.');+ });+});++describe('a shared note for a long table', () => {+ it('mounts one note, telling the estimate whose range has focus', async () => {+ const handle = createEstimateNoteHandle();+ render(+ <>+ <EstimateRange estimate={medium} handle={handle} />+ <EstimateRange estimate={low} handle={handle} />+ <EstimateNoteTooltip handle={handle} />+ </>,+ );+ const [first, second] = container.querySelectorAll('button');+ expect(await noteOf(second as HTMLElement)).toContain('Confidence: Low');+ expect(document.querySelectorAll('[data-slot="tooltip-content"]')).toHaveLength(1);+ act(() => (second as HTMLElement).blur());+ expect(await noteOf(first as HTMLElement)).toContain('Confidence: Medium');+ });+});++describe('EstimateBadge', () => {+ it('reads "Estimate", or "Estimate · low confidence"', () => {+ const badge = (estimate: VolumeEstimate) => {+ render(<EstimateBadge estimate={estimate} />);+ return container.querySelector('button')!;+ };+ expect(badge(medium).textContent).toBe('Estimate');+ expect(badge(medium).getAttribute('aria-label')).toBe(+ "Estimate, Medium confidence: how it's built",+ );+ expect(badge(low).textContent).toBe('Estimate · low confidence');+ });+});diff --git a/web/src/components/prompts/volume-estimate.tsx b/web/src/components/prompts/volume-estimate.tsxnew file mode 100644index 000000000..825d860f1--- /dev/null+++ b/web/src/components/prompts/volume-estimate.tsx@@ -0,0 +1,223 @@+'use client';++import { useTranslations } from 'next-intl';+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ createTooltipHandle,+} from '@/components/ui/tooltip';+import { formatDate } from '@/lib/format';+import { cn } from '@/lib/utils';+import {+ formatEstimateRange,+ type EstimateTotal,+ type VolumeEstimate,+} from '@/lib/volume-estimate';++/** One prompt's estimate, a sum of prompts', or their average per prompt. */+export type EstimateKind = 'prompt' | 'total' | 'average';++type Estimate = VolumeEstimate | EstimateTotal;++const isTotal = (estimate: Estimate): estimate is EstimateTotal => 'count' in estimate;++/** "Oct 2026": the month the Google volumes are from. */+function monthOf(iso: string): string {+ return new Date(iso).toLocaleDateString('en-US', {+ month: 'short',+ year: 'numeric',+ timeZone: 'UTC',+ });+}++/** 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');+ const rate = Math.round(estimate.rate * 100);+ const level = t(`level.${estimate.confidence}`);+ return (+ <>+ <p className="font-medium">{t('title')}</p>+ {kind === 'prompt' || !isTotal(estimate) ? (+ <>+ <p>{t('method', { rate })}</p>+ <p>+ {estimate.measured === 0+ ? t('noKeywords')+ : t('keywords', { measured: estimate.measured, keywords: estimate.keywords })}{' '}+ {estimate.measured >= 2 ? t('rangeSpread') : estimate.measured === 1 && t('rangeOne')}+ </p>+ </>+ ) : (+ <>+ <p>+ {t(kind === 'average' ? 'methodAverage' : 'methodTotal', {+ count: estimate.count,+ rate,+ })}+ </p>+ <p>+ {t('mix', {+ high: estimate.byConfidence.high,+ medium: estimate.byConfidence.medium,+ low: estimate.byConfidence.low,+ })}+ </p>+ </>+ )}+ <p>+ {estimate.asOf+ ? t('sources', { month: monthOf(estimate.asOf), rate })+ : t('sourcesUndated', { rate })}+ </p>+ <p>+ {estimate.asOf+ ? t('confidence', { level, date: formatDate(estimate.asOf) })+ : t('confidenceUndated', { level })}+ </p>+ {estimate.stale && <p>{t('stale')}</p>}+ {estimate.confidence === 'low' && <p>{t('lowNote')}</p>}+ <p className="opacity-80">{t('measuredNote')}</p>+ </>+ );+}++type NotePayload = { estimate: Estimate; kind: EstimateKind };++/**+ * One method note shared by every estimate in a long table, so it mounts one+ * tooltip rather than one per row (as ClampedText does): pass it to each+ * EstimateRange and render EstimateNoteTooltip once beside them.+ */+export type EstimateNoteHandle = ReturnType<typeof createTooltipHandle<NotePayload>>;++export function createEstimateNoteHandle(): EstimateNoteHandle {+ return createTooltipHandle<NotePayload>();+}++const NOTE_CLASS = 'max-w-80 space-y-1 text-left';++/** The shared method note for a table's estimates (see createEstimateNoteHandle). */+export function EstimateNoteTooltip({ handle }: { handle: EstimateNoteHandle }) {+ return (+ <Tooltip handle={handle}>+ {({ payload }) =>+ payload ? (+ <TooltipContent className={NOTE_CLASS}>+ <EstimateNote estimate={payload.estimate} kind={payload.kind} />+ </TooltipContent>+ ) : null+ }+ </Tooltip>+ );+}++/** The trigger every estimate shares: hover or focus shows the method note. */+function WithNote({+ estimate,+ kind,+ label,+ handle,+ className,+ children,+}: {+ estimate: Estimate;+ kind: EstimateKind;+ label: string;+ handle?: EstimateNoteHandle;+ className?: string;+ children: React.ReactNode;+}) {+ const trigger = (+ <TooltipTrigger+ handle={handle}+ payload={handle ? { estimate, kind } : undefined}+ delay={300}+ closeDelay={0}+ render={+ <button+ type="button"+ aria-label={label}+ className={cn(+ 'cursor-help rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',+ className,+ )}+ />+ }+ >+ {children}+ </TooltipTrigger>+ );+ if (handle) return trigger;+ return (+ <Tooltip>+ {trigger}+ <TooltipContent className={NOTE_CLASS}>+ <EstimateNote estimate={estimate} kind={kind} />+ </TooltipContent>+ </Tooltip>+ );+}++/**+ * An estimated AI volume as its range, "400–2k": grey when its confidence is+ * low, with the method note on hover or focus.+ */+export function EstimateRange({+ estimate,+ kind = 'prompt',+ handle,+ className,+}: {+ estimate: Estimate;+ kind?: EstimateKind;+ /** A table's shared note; without one, the range carries its own. */+ handle?: EstimateNoteHandle;+ className?: string;+}) {+ const t = useTranslations('volumeEstimate');+ const range = formatEstimateRange(estimate);+ return (+ <WithNote+ estimate={estimate}+ kind={kind}+ label={t('label', { range, level: t(`level.${estimate.confidence}`) })}+ handle={handle}+ className={cn(+ 'whitespace-nowrap tabular-nums',+ estimate.confidence === 'low' && 'text-muted-foreground',+ className,+ )}+ >+ {range}+ </WithNote>+ );+}++/** The dashed "Estimate" badge, "Estimate · low confidence" when it is; the same note on hover. */+export function EstimateBadge({+ estimate,+ kind = 'prompt',+ className,+}: {+ estimate: Estimate;+ kind?: EstimateKind;+ className?: string;+}) {+ const t = useTranslations('volumeEstimate');+ const text = estimate.confidence === 'low' ? t('badgeLow') : t('badge');+ return (+ <WithNote+ estimate={estimate}+ kind={kind}+ label={t('badgeLabel', { level: t(`level.${estimate.confidence}`) })}+ className={cn(+ 'inline-flex items-center rounded-md border border-dashed border-muted-foreground/40 px-1.5 text-[11px] font-medium leading-5 text-muted-foreground',+ className,+ )}+ >+ {text}+ </WithNote>+ );+}diff --git a/web/src/lib/prompt-volume-opportunity.test.ts b/web/src/lib/prompt-volume-opportunity.test.tsindex 39d5e0016..95fd1e466 100644--- a/web/src/lib/prompt-volume-opportunity.test.ts+++ b/web/src/lib/prompt-volume-opportunity.test.ts@@ -13,4 +13,10 @@ describe('opportunityLevel', () => {expect(opportunityLevel(3000)).toBe('high');expect(opportunityLevel(3645)).toBe('high');});++ it('gives a low-confidence estimate no level on its own', () => {+ expect(opportunityLevel(5000, 'low')).toBeNull();+ expect(opportunityLevel(5000, 'medium')).toBe('high');+ expect(opportunityLevel(1500, 'high')).toBe('medium');+ });});diff --git a/web/src/lib/prompt-volume-opportunity.ts b/web/src/lib/prompt-volume-opportunity.tsindex 8e955163a..61a9a625c 100644--- a/web/src/lib/prompt-volume-opportunity.ts+++ b/web/src/lib/prompt-volume-opportunity.ts@@ -1,3 +1,5 @@+import { rankable, type EstimateConfidence } from '@/lib/volume-estimate';+/*** Insights' High Opportunity Prompts: a prompt makes the list from* OPPORTUNITY_MIN_VOLUME estimated AI searches a month, and is High rather@@ -12,7 +14,12 @@export const OPPORTUNITY_MIN_VOLUME = 1500;export const OPPORTUNITY_HIGH_VOLUME = 3000;-export function opportunityLevel(estAiVolume: number): 'high' | 'medium' | null {+export function opportunityLevel(+ estAiVolume: number,+ confidence?: EstimateConfidence,+): 'high' | 'medium' | null {+ // A low-confidence estimate isn't ranked on its own (PROMPT-013).+ if (confidence && !rankable({ confidence })) return null;if (estAiVolume >= OPPORTUNITY_HIGH_VOLUME) return 'high';if (estAiVolume >= OPPORTUNITY_MIN_VOLUME) return 'medium';return null;diff --git a/web/src/lib/volume-estimate.test.ts b/web/src/lib/volume-estimate.test.tsnew file mode 100644index 000000000..fe8836a28--- /dev/null+++ b/web/src/lib/volume-estimate.test.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from 'vitest';+import {+ averageEstimate,+ formatEstimateRange,+ promptVolumeEstimate,+ rankable,+ sumEstimates,+} from './volume-estimate';++const NOW = new Date('2026-10-22T12:00:00Z');++/** A prompt's volume row: its keywords' Google volumes at the 45% rate. */+const row = (+ googleVolumes: Record<string, number>,+ estAiVolume: number,+ fetchedAt = '2026-10-10T19:28:41Z',+) => ({+ estAiVolume,+ googleVolumes,+ aiVolumeMultiplier: 0.45,+ keywords: Object.keys(googleVolumes),+ fetchedAt,+});++describe('promptVolumeEstimate', () => {+ it('is high when three or more keywords have data and their middle half agrees within 4×', () => {+ const e = promptVolumeEstimate(row({ office: 3600, business: 1600, monthly: 1900 }, 855), NOW);+ expect(e).toMatchObject({ confidence: 'high', measured: 3, keywords: 3, value: 855 });+ // The quartiles 1,750–2,750 × 45%, widened to at least ±25% and rounded outwards.+ expect([e.low, e.high]).toEqual([640, 1300]);+ expect(formatEstimateRange(e)).toBe('640–1.3k');+ });++ it('is medium when their middle half differs by more, and spans it', () => {+ const e = promptVolumeEstimate(row({ a: 400, b: 2000, c: 10_000 }, 900), NOW);+ // Quartiles 1,200 and 6,000: 5× apart.+ expect(e.confidence).toBe('medium');+ // 540–2,700 × 45%, kept within ½× to 2× of 900.+ expect([e.low, e.high]).toEqual([540, 1800]);+ expect(formatEstimateRange(e)).toBe('540–1.8k');+ });++ it('reads past one broad head term, which the median already ignores', () => {+ // Five keywords with data, one of them far broader: still medium.+ const five = promptVolumeEstimate(row({ a: 10, b: 170, c: 210, d: 900, e: 27_100 }, 95), NOW);+ expect(five.confidence).toBe('medium');+ expect(formatEstimateRange(five)).toBe('71–190');+ // A prod row: two keywords without data, three left 170, 210 and 27,100.+ // With three, the broad one is half the upper quartile: low.+ const three = promptVolumeEstimate(row({ a: 0, b: 0, c: 170, d: 210, e: 27_100 }, 95), NOW);+ expect(three).toMatchObject({ confidence: 'low', measured: 3, keywords: 5 });+ expect(formatEstimateRange(three)).toBe('71–190');+ });++ it('is low with one keyword to go by, or volumes 10× apart', () => {+ const one = promptVolumeEstimate(row({ a: 2000, b: 0, c: 0 }, 900), NOW);+ expect(one).toMatchObject({ confidence: 'low', measured: 1, keywords: 3 });+ // ×½ to ×2 with nothing to compare against.+ expect([one.low, one.high]).toEqual([450, 1800]);++ const apart = promptVolumeEstimate(row({ a: 100, b: 2000, c: 50_000 }, 900), NOW);+ expect(apart.confidence).toBe('low');+ // Never more than 2× from the estimate either way.+ expect([apart.low, apart.high]).toEqual([470, 1800]);+ });++ it('counts volumes over six months old one level less', () => {+ const e = promptVolumeEstimate(+ row({ office: 3600, business: 1600, monthly: 1900 }, 855, '2026-03-01T00:00:00Z'),+ NOW,+ );+ expect(e).toMatchObject({ confidence: 'medium', stale: true });+ });++ it('has nothing to range over when no keyword has data', () => {+ const e = promptVolumeEstimate(row({ a: 0, b: 0 }, 0), NOW);+ expect(e).toMatchObject({ confidence: 'low', low: 0, high: 0, measured: 0 });+ expect(formatEstimateRange(e)).toBe('0');+ });+});++describe('sumEstimates', () => {+ const high = promptVolumeEstimate(row({ a: 3600, b: 1600, c: 1900 }, 855), NOW);+ const medium = promptVolumeEstimate(row({ a: 400, b: 2000, c: 10_000 }, 900), NOW);+ const low = promptVolumeEstimate(row({ a: 2000 }, 900), NOW);++ it('adds the lows and the highs, and dates it by the latest fetch', () => {+ const total = sumEstimates([high, medium]);+ expect(total).toMatchObject({+ value: 1755,+ low: 1180,+ high: 3100,+ count: 2,+ byConfidence: { high: 1, medium: 1, low: 0 },+ });+ expect(formatEstimateRange(total)).toBe('1.2–3.1k');+ });++ it('is as confident as most of its volume', () => {+ expect(sumEstimates([high]).confidence).toBe('high');+ // 49% of the volume is high, none low: medium.+ expect(sumEstimates([high, medium]).confidence).toBe('medium');+ // 900 of 1,755 is low: more than half.+ expect(sumEstimates([high, low]).confidence).toBe('low');+ expect(sumEstimates([]).confidence).toBe('low');+ });++ it('averages per prompt', () => {+ const avg = averageEstimate(sumEstimates([high, medium]));+ expect(avg).toMatchObject({ value: 878, low: 590, high: 1600 });+ });+});++describe('rankable', () => {+ it('leaves low-confidence estimates out of ranking on their own', () => {+ expect(rankable({ confidence: 'high' })).toBe(true);+ expect(rankable({ confidence: 'medium' })).toBe(true);+ expect(rankable({ confidence: 'low' })).toBe(false);+ });+});diff --git a/web/src/lib/volume-estimate.ts b/web/src/lib/volume-estimate.tsnew file mode 100644index 000000000..0ea1f5d18--- /dev/null+++ b/web/src/lib/volume-estimate.ts@@ -0,0 +1,222 @@+import { formatCompactNumber } from '@/lib/format';+import type { PromptVolume } from '@/types';++/**+ * PROMPT-013: an estimated AI search volume is shown as a range with a+ * confidence, never as a bare number that reads as measured.+ *+ * A prompt's estimate is the median Google volume of its related keywords ×+ * the AI answer rate (00154, 00155: the share of Google searches that get an+ * AI answer). The keywords are head terms that spread widely by design, which+ * is why the median is taken; so how far the estimate can be trusted is read+ * around the median too: how many keywords have Google search data, and how+ * closely the middle half of them agree (their upper over lower quartile).+ * The range is the AI share of that middle half, kept within ½× to 2× of the+ * estimate; with one keyword to go by, it is exactly that.+ */++export type EstimateConfidence = 'high' | 'medium' | 'low';++export interface VolumeEstimate {+ /** The stored point estimate: what sorting and totals add up. */+ value: number;+ low: number;+ high: number;+ confidence: EstimateConfidence;+ /** Keywords with Google search data, out of `keywords`. */+ measured: number;+ keywords: number;+ /** The AI adoption rate the estimate used (0.45 = 45%). */+ rate: number;+ /** When the Google volumes were fetched; the latest one for a total. */+ asOf: string | null;+ /** Fetched long enough ago to count one level less. */+ stale: boolean;+}++/**+ * High: at least this many keywords with data, their upper quartile at most+ * AGREE_HIGH × their lower one. Medium: at least two, within AGREE_MEDIUM ×.+ * On prod's 3,025 prompts (2026-10-22) the quartiles at these thresholds+ * split about 38% high, 40% medium and 23% low; the extremes, a median 58×+ * apart, had read 86% low.+ */+const HIGH_MIN_MEASURED = 3;+const AGREE_HIGH = 4;+const AGREE_MEDIUM = 15;+/** Volumes this old count one level less. */+export const STALE_DAYS = 183;+/** The range never strays further than this factor from the estimate (the whole range with one keyword)… */+const MAX_STRETCH = 2;+/** …and is always at least this wide either side of it. */+const MIN_BAND = 0.25;++const LEVELS: EstimateConfidence[] = ['low', 'medium', 'high'];++/**+ * The q-quantile of sorted values, interpolated between the two nearest as+ * Postgres's percentile_cont does: of five, 0.25 is the 2nd and 0.75 the 4th.+ */+function quantile(sorted: number[], q: number): number {+ const at = (sorted.length - 1) * q;+ const below = Math.floor(at);+ const above = Math.ceil(at);+ return sorted[below] + (sorted[above] - sorted[below]) * (at - below);+}++/** Rounds to two significant figures, down or up: 396 → 390, 1,980 → 2,000. */+function roundTo2(value: number, direction: 'down' | 'up'): number {+ if (value <= 0) return 0;+ const step = 10 ** Math.max(0, Math.floor(Math.log10(value)) - 1);+ return (direction === 'down' ? Math.floor(value / step) : Math.ceil(value / step)) * step;+}++/** The range around `value`: [low, high] stretched to the rules above, then rounded outwards. */+function bounds(value: number, low: number, high: number): { low: number; high: number } {+ if (value <= 0) return { low: 0, high: 0 };+ const lo = Math.min(Math.max(low, value / MAX_STRETCH), value * (1 - MIN_BAND));+ const hi = Math.max(Math.min(high, value * MAX_STRETCH), value * (1 + MIN_BAND));+ return { low: roundTo2(lo, 'down'), high: roundTo2(hi, 'up') };+}++type VolumeRow = Pick<+ PromptVolume,+ 'estAiVolume' | 'googleVolumes' | 'aiVolumeMultiplier' | 'keywords' | 'fetchedAt'+>;++/** One prompt's estimate, from its keywords' Google volumes. */+export function promptVolumeEstimate(row: VolumeRow, now: Date = new Date()): VolumeEstimate {+ const value = Math.max(0, row.estAiVolume);+ const volumes = Object.values(row.googleVolumes ?? {})+ .filter((v) => v > 0)+ .sort((a, b) => a - b);+ const measured = volumes.length;+ // The middle half of the measured volumes: one broad head term, which the+ // median already ignores, doesn't make the estimate read unsure.+ const lowerQuartile = measured > 0 ? quantile(volumes, 0.25) : 0;+ const upperQuartile = measured > 0 ? quantile(volumes, 0.75) : 0;+ const spread = measured > 0 ? upperQuartile / lowerQuartile : Infinity;++ let level =+ measured >= HIGH_MIN_MEASURED && spread <= AGREE_HIGH+ ? 2+ : 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;+ if (stale) level = Math.max(0, level - 1);+ if (value === 0) level = 0;++ const range =+ measured >= 2+ ? bounds(+ value,+ lowerQuartile * row.aiVolumeMultiplier,+ upperQuartile * row.aiVolumeMultiplier,+ )+ : bounds(value, value / MAX_STRETCH, value * MAX_STRETCH);++ return {+ value,+ ...range,+ confidence: LEVELS[level],+ measured,+ keywords: Math.max(row.keywords?.length ?? 0, Object.keys(row.googleVolumes ?? {}).length),+ rate: row.aiVolumeMultiplier,+ asOf: row.fetchedAt ?? null,+ stale,+ };+}++export interface EstimateTotal extends VolumeEstimate {+ /** How many prompts were added up, and at each confidence. */+ count: number;+ byConfidence: Record<EstimateConfidence, number>;+}++/**+ * Prompts added up: the lows and the highs summed. High when at least 80% of+ * the volume is from high-confidence prompts, low when more than half is from+ * low-confidence ones, medium in between.+ */+export function sumEstimates(estimates: VolumeEstimate[]): EstimateTotal {+ const byConfidence: Record<EstimateConfidence, number> = { high: 0, medium: 0, low: 0 };+ const volumeAt: Record<EstimateConfidence, number> = { high: 0, medium: 0, low: 0 };+ let value = 0;+ let low = 0;+ let high = 0;+ let asOf: string | null = null;+ for (const e of estimates) {+ byConfidence[e.confidence] += 1;+ volumeAt[e.confidence] += e.value;+ value += e.value;+ low += e.low;+ high += e.high;+ if (e.asOf && (!asOf || Date.parse(e.asOf) > Date.parse(asOf))) asOf = e.asOf;+ }+ const confidence: EstimateConfidence =+ value <= 0+ ? 'low'+ : volumeAt.high / value >= 0.8+ ? 'high'+ : volumeAt.low / value > 0.5+ ? 'low'+ : 'medium';+ return {+ value,+ low,+ high,+ confidence,+ measured: estimates.reduce((s, e) => s + e.measured, 0),+ keywords: estimates.reduce((s, e) => s + e.keywords, 0),+ rate: estimates[0]?.rate ?? 0,+ asOf,+ stale: estimates.some((e) => e.stale),+ count: estimates.length,+ byConfidence,+ };+}++/** An estimate's average per prompt: the total's range and value divided by its count. */+export function averageEstimate(total: EstimateTotal): EstimateTotal {+ const n = Math.max(1, total.count);+ return {+ ...total,+ value: Math.round(total.value / n),+ low: roundTo2(total.low / n, 'down'),+ high: roundTo2(total.high / n, 'up'),+ };+}++/** An estimate's range scaled by a share, e.g. one platform's part of a total. */+export function scaleEstimate(+ estimate: Pick<VolumeEstimate, 'low' | 'high'>,+ share: number,+): { low: number; high: number } {+ return {+ low: roundTo2(estimate.low * share, 'down'),+ high: roundTo2(estimate.high * share, 'up'),+ };+}++/** "400–2k", "1–3k", "1.2–4.5M"; "0" when there's nothing to estimate. */+export function formatEstimateRange(estimate: Pick<VolumeEstimate, 'low' | 'high'>): string {+ if (estimate.high <= 0) return '0';+ const low = formatCompactNumber(estimate.low);+ const high = formatCompactNumber(estimate.high);+ if (low === high) return high;+ const unit = /[kMB]$/.exec(high)?.[0];+ if (unit && low.endsWith(unit)) return `${low.slice(0, -1)}–${high}`;+ return `${low}–${high}`;+}++/**+ * An estimate isn't ranked on its own when its confidence is low: lists and+ * sorts that go by volume put it after the rest, and it earns no Opportunity+ * level by itself.+ */+export function rankable(estimate: Pick<VolumeEstimate, 'confidence'>): boolean {+ return estimate.confidence !== 'low';+}