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(action-center): label the Action Center's and Opportunities' AI volumes as estimates (#1364)
Cihan9f42bbaa19e7
diff --git a/web/messages/en.json b/web/messages/en.jsonindex df8ca90f0..209295ea0 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1027,6 +1027,9 @@"sentToWebhook": "Sent to the webhook","item": "Item","volume": "Volume",+ "volumeType": "Volume type",+ "volumeConfidence": "Volume confidence",+ "estimatedVolume": "{volume} (estimate, {confidence} confidence)","lostPage": "Lost page","citedInstead": "Cited instead","affectedPrompt": "Prompt",@@ -1093,7 +1096,7 @@"page": "{label}","topic": "prompts in {label}","inTopic": " in {topic}",- "volume": " (~{volume} AI searches a month)"+ "volume": " ({volume} AI searches a month, estimated)"},"noun": {"prompts": "{count, plural, one {prompt} other {prompts}}",@@ -1371,8 +1374,7 @@"planNew": "Write new content: none of your prompts tracked this topic when it was sent","planExpand": "Grow what covers it: your prompts tracked this topic when it was sent","demand": "Suggested prompts when sent",- "demandValue": "{count, plural, one {# prompt} other {# prompts}} · ~{volume}/mo",- "volume": "~{volume}/mo"+ "demandValue": "{count, plural, one {# prompt} other {# prompts}} · <range></range>"},"contentDraft": {"source": "Source",@@ -2101,7 +2103,7 @@"goal": "Lead the topic, or close most of the gap."},"topic_opportunity": {- "title": "Capture ~{demand}/mo of AI demand in {topic}",+ "title": "Capture {demand}/mo of estimated AI demand in {topic}","titleGeneric": "Capture the AI demand in a topic","description": "Sent from Insights: prompts suggested for one of your topics, with the monthly AI demand behind them.","goal": "Get the brand into AI answers for the topic's suggested prompts."@@ -3011,7 +3013,6 @@"topicKind": "Topic","promptKind": "Prompt","prompts": "{count, plural, one {# prompt} other {# prompts}}",- "volume": "~{volume}/mo","notTracked": "not tracked","competitorLeads": "{name} leads","leaderScore": "leader {score}",@@ -5374,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.",+ "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.","noKeywords": "None of its related keywords has Google search data yet.",@@ -5388,6 +5390,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.",+ "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": {"high": "High",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsxnew file mode 100644index 000000000..9b64ce389--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsx@@ -0,0 +1,76 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import { Opportunities } from './_opportunities';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++vi.mock('@/i18n/navigation', () => ({+ Link: ({ children, ...props }: React.ComponentProps<'a'>) => <a {...props}>{children}</a>,+ useRouter: () => ({ push: vi.fn() }),+}));+vi.mock('@/lib/actions/prompt-suggestions', () => ({ trackSuggestions: vi.fn() }));+vi.mock('@/lib/actions/topic', () => ({ sendTopicOpportunityToActionCenter: vi.fn() }));+vi.mock('@/lib/actions/content', () => ({+ generateOpportunitiesOnDemand: vi.fn(),+ getGenerationJobStatus: vi.fn(),+}));++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++const suggestion = (id: string, topic: string | null, estVolume: number) => ({+ id,+ text: `Prompt ${id}`,+ topicId: topic ? `t-${topic}` : null,+ topicName: topic,+ estVolume,+ relevance: 0.9,+});++describe('Opportunities — estimated volume (PROMPT-013)', () => {+ it("shows the suggestions' AI-guessed volume as a grey range, never a bare number", () => {+ act(() =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <Opportunities+ brandId="b1"+ suggestions={[+ suggestion('s1', 'Espresso', 800),+ suggestion('s2', 'Espresso', 400),+ suggestion('s3', null, 350),+ ]}+ trackedTopicIds={[]}+ topics={null}+ entities={null}+ slotsLeft={null}+ contentUsage={null}+ onTracked={() => {}}+ />+ </NextIntlClientProvider>,+ ),+ );+ const ranges = [+ ...container.querySelectorAll<HTMLButtonElement>('button[aria-label*="a month, estimated"]'),+ ];+ // The topic's 1,200 and the lone prompt's 350, each half to twice, low.+ expect(ranges.map((r) => r.textContent)).toEqual(['600–2.4k/mo', '170–700/mo']);+ expect(ranges.every((r) => r.className.includes('text-muted-foreground'))).toBe(true);+ expect(container.textContent).toContain('2 prompts\u00a0·\u00a0600–2.4k/mo');+ expect(container.textContent).not.toContain('~');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsxindex 037df7bfb..b53cc7e4e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx@@ -23,6 +23,8 @@ import {type OpportunitySuggestion,} from '@/lib/insights-opportunities';import type { TopicCompetitors } from '@/lib/insights-topics';+import { guessedVolumeEstimate } from '@/lib/volume-estimate';+import { EstimateRange } from '@/components/prompts/volume-estimate';/** Items shown, as in the mockup; "See all" opens the rest. */const VISIBLE_ITEMS = 4;@@ -257,9 +259,22 @@ export function Opportunities({}};- const meta = (item: Opportunity): string => {- const volume = item.volume === null ? null : t('volume', { volume: f.compact(item.volume) });- if (item.kind === 'prompt') return [volume, t('notTracked')].filter(Boolean).join(' · ');+ /** The parts of a row's line under its title, between dots. */+ const dotted = (parts: React.ReactNode[]) =>+ parts.filter(Boolean).flatMap((part, i) => (i === 0 ? [part] : ['\u00a0·\u00a0', part]));++ const meta = (item: Opportunity): React.ReactNode[] => {+ // The suggestions' volume is an AI's guess: a grey range with its note (PROMPT-013).+ const volume =+ item.volume === null ? null : (+ <EstimateRange+ key="volume"+ estimate={guessedVolumeEstimate(item.volume, null)}+ kind={item.kind === 'topic' ? 'total' : 'prompt'}+ perMonth+ />+ );+ if (item.kind === 'prompt') return dotted([volume, t('notTracked')]);const s = item.standing;const standing =s.kind === 'competitor'@@ -271,9 +286,7 @@ export function Opportunities({: s.kind === 'notTracked'? t('notTracked'): null;- return [t('prompts', { count: item.suggestionIds.length }), volume, standing]- .filter(Boolean)- .join(' · ');+ return dotted([t('prompts', { count: item.suggestionIds.length }), volume, standing]);};return (@@ -312,8 +325,19 @@ export function Opportunities({<span className="block truncate text-[13px] font-medium" title={item.title}>{item.title}</span>- <span className="block truncate text-xs text-muted-foreground">- {meta(item)}+ {/* Text truncates, the range doesn't: its focus ring and button stay whole. */}+ <span className="flex min-w-0 items-baseline text-xs text-muted-foreground">+ {meta(item).map((part, i) =>+ typeof part === 'string' ? (+ <span key={i} className="truncate">+ {part}+ </span>+ ) : (+ <span key={i} className="shrink-0">+ {part}+ </span>+ ),+ )}</span></span><span className="flex shrink-0 items-center gap-1.5">diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsxindex 6d4e79b6f..1566fd1df 100644--- a/web/src/components/action-center/action-export-buttons.tsx+++ b/web/src/components/action-center/action-export-buttons.tsx@@ -33,6 +33,7 @@ import { viewerTimeZone } from '@/lib/time-zone';import { affectedCounts, type Affected } from '@/lib/action-center/affected';import type { ActionStory } from '@/lib/action-center/story';import { saveBlob } from '@/lib/download';+import type { VolumeEstimate } from '@/lib/volume-estimate';/*** Copy all, Export CSV and Export Excel for one action (AC-005): what every@@ -52,7 +53,7 @@ export function ActionExportButtons({detail: ActionDetail | null;/** The Affected tab's list and its prompts' demand, as the drawer shows them (AC-003). */affected?: Affected | null;- volumes?: Map<string, number> | null;+ volumes?: Map<string, VolumeEstimate> | null;/** Why and Goal as the drawer words them, from the action's data (AC-003). */story?: ActionStory | null;}) {@@ -75,6 +76,7 @@ export function ActionExportButtons({signalCategories: useTranslations(EXPORT_NAMESPACES.signalCategories),priority: useTranslations(EXPORT_NAMESPACES.priority),affected: useTranslations(EXPORT_NAMESPACES.affected),+ estimate: useTranslations(EXPORT_NAMESPACES.estimate),};const [isBusy, setIsBusy] = useState(false);// The Markdown Copy Data shows, and what to say once it is copied.diff --git a/web/src/components/action-center/affected-tab.test.tsx b/web/src/components/action-center/affected-tab.test.tsxindex 00f81f18f..0617ff268 100644--- a/web/src/components/action-center/affected-tab.test.tsx+++ b/web/src/components/action-center/affected-tab.test.tsx@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../messages/en.json';import type { Affected } from '@/lib/action-center/affected';import { AffectedTab } from './affected-tab';+import { promptVolumeEstimate } from '@/lib/volume-estimate';vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (@@ -76,12 +77,26 @@ describe('AffectedTab', () => {},],}}- volumes={new Map([['p1', 25100]])}+ volumes={+ new Map([+ [+ 'p1',+ promptVolumeEstimate({+ estAiVolume: 25_100,+ googleVolumes: { a: 40_000, b: 55_800, c: 70_000 },+ aiVolumeMultiplier: 0.45,+ keywords: ['a', 'b', 'c'],+ fetchedAt: new Date(Date.now() - 12 * 86_400_000).toISOString(),+ }),+ ],+ ])+ }/>,);expect(headers()).toEqual(['Prompt', 'Volume', 'Lost on', 'Your lost page', 'Cited instead']);const cells = [...container.querySelectorAll('td')].map((td) => td.textContent);- expect(cells[1]).toBe('~25.1k');+ // An estimate: its range (PROMPT-013).+ expect(cells[1]).toBe('18–32k');expect(cells[3]).toContain('/blog/best-tools');expect(cells[4]).toContain('profound.com');// The prompt opens its page; its chart icon, the Positions panel.diff --git a/web/src/components/action-center/affected-tab.tsx b/web/src/components/action-center/affected-tab.tsxindex aadfecbfb..4f228970c 100644--- a/web/src/components/action-center/affected-tab.tsx+++ b/web/src/components/action-center/affected-tab.tsx@@ -1,5 +1,6 @@'use client';+import { useMemo } from 'react';import { useTranslations } from 'next-intl';import { ArrowUpRight, BarChart3 } from 'lucide-react';import { Link } from '@/i18n/navigation';@@ -22,7 +23,12 @@ import {type AffectedPrompt,} from '@/lib/action-center/affected';import { getPlatformName } from '@/lib/traffic-platforms';-import { formatCompactNumber } from '@/lib/format';+import type { VolumeEstimate } from '@/lib/volume-estimate';+import {+ EstimateNoteTooltip,+ EstimateRange,+ createEstimateNoteHandle,+} from '@/components/prompts/volume-estimate';import { SignalWhereLine } from './signal-table';/**@@ -38,7 +44,7 @@ export function AffectedTab({}: {affected: Affected;/** Estimated monthly AI searches per prompt id; null until read, or when they can't be. */- volumes: Map<string, number> | null;+ volumes: Map<string, VolumeEstimate> | null;}) {const t = useTranslations('actionCenter.actionsPage.drawer.affected');const hasRows = affected.prompts.length > 0 || affected.pages.length > 0;@@ -68,9 +74,11 @@ function PromptsTable({}: {rows: AffectedPrompt[];total: number;- volumes: Map<string, number> | null;+ volumes: Map<string, VolumeEstimate> | null;}) {const t = useTranslations('actionCenter.actionsPage.drawer.affected');+ // One method note for the column's ranges, as the Prompts tables do.+ const volumeNote = useMemo(() => createEstimateNoteHandle(), []);const volumeOf = (row: AffectedPrompt) => (row.id ? (volumes?.get(row.id) ?? null) : null);const show = {volume: rows.some((row) => volumeOf(row) !== null),@@ -137,7 +145,11 @@ function PromptsTable({</TableCell>{show.volume && (<TableCell className="text-right align-top text-xs tabular-nums">- {volume !== null ? `~${formatCompactNumber(volume)}` : '—'}+ {volume !== null ? (+ <EstimateRange estimate={volume} handle={volumeNote} />+ ) : (+ '—'+ )}</TableCell>)}{show.platforms && (@@ -177,6 +189,7 @@ function PromptsTable({})}</TableBody></Table>+ <EstimateNoteTooltip handle={volumeNote} /></div></section>);diff --git a/web/src/components/action-center/history-drawer.test.tsx b/web/src/components/action-center/history-drawer.test.tsxindex 37636d435..69707a9e4 100644--- a/web/src/components/action-center/history-drawer.test.tsx+++ b/web/src/components/action-center/history-drawer.test.tsx@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../messages/en.json';import type { ActionHistoryItem } from '@/lib/action-center/history';import type { Signal } from '@/lib/signals/map';+import { guessedVolumeEstimate } from '@/lib/volume-estimate';/*** The History drawer's goal and what happened, told from the action's own@@ -112,7 +113,7 @@ describe('HistoryDrawer', () => {it("tells the goal and what happened from the action's signals once they are read", async () => {let answer: (value: unknown) => void = () => {};getActionSignals.mockReturnValue(new Promise((resolve) => (answer = resolve)));- getPromptDemand.mockResolvedValue({ p1: 5500 });+ getPromptDemand.mockResolvedValue({ p1: guessedVolumeEstimate(5500, null) });render(<HistoryDrawer brandId="b1" item={item} onOpenChange={() => {}} />);// Placeholders while reading, not the general sentences.@@ -122,7 +123,7 @@ describe('HistoryDrawer', () => {await act(async () => answer([signal]));const happened = under('What happened?');expect(happened).toContain('Best coffee subscription?');- expect(happened).toContain('~5.5k');+ expect(happened).toContain('2.7–11k AI searches a month, estimated');expect(happened).toContain('Oct 9');// The goal is dated by the action's due date.expect(under('What was the goal?')).toContain('Nov 9');diff --git a/web/src/components/action-center/topic-opportunity-context.tsx b/web/src/components/action-center/topic-opportunity-context.tsxindex 62d90f00d..6b221b1b8 100644--- a/web/src/components/action-center/topic-opportunity-context.tsx+++ b/web/src/components/action-center/topic-opportunity-context.tsx@@ -3,7 +3,13 @@import { useTranslations } from 'next-intl';import { ExternalLink } from 'lucide-react';import { Link } from '@/i18n/navigation';-import { formatCompactNumber } from '@/lib/format';+import { useMemo } from 'react';+import { guessedVolumeEstimate } from '@/lib/volume-estimate';+import {+ EstimateNoteTooltip,+ EstimateRange,+ createEstimateNoteHandle,+} from '@/components/prompts/volume-estimate';interface SuggestedPrompt {text: string;@@ -18,6 +24,8 @@ interface SuggestedPrompt {*/export function TopicOpportunityContext({ payload }: { payload: Record<string, unknown> }) {const t = useTranslations('actionCenter.actionsPage.drawer.topicOpportunity');+ // One method note for the suggestions' ranges, however many were sent.+ const suggestionNote = useMemo(() => createEstimateNoteHandle(), []);const topicId = typeof payload.topicId === 'string' ? payload.topicId : null;const topicName = typeof payload.topicName === 'string' ? payload.topicName : null;const demand = typeof payload.demand === 'number' ? payload.demand : null;@@ -62,9 +70,16 @@ export function TopicOpportunityContext({ payload }: { payload: Record<string, u<p className="text-xs font-medium text-muted-foreground">{t('demand')}</p>{demand !== null && (<p className="mt-1 tabular-nums">- {t('demandValue', {+ {/* The suggestions' AI-guessed demand: a grey range (PROMPT-013). */}+ {t.rich('demandValue', {count: suggestions.length,- volume: formatCompactNumber(demand),+ range: () => (+ <EstimateRange+ estimate={guessedVolumeEstimate(demand, null)}+ kind="total"+ perMonth+ />+ ),})}</p>)}@@ -73,11 +88,16 @@ export function TopicOpportunityContext({ payload }: { payload: Record<string, u<li key={s.text} className="flex items-baseline justify-between gap-3"><span className="min-w-0">{s.text}</span><span className="shrink-0 tabular-nums text-muted-foreground">- {t('volume', { volume: formatCompactNumber(s.volume) })}+ <EstimateRange+ estimate={guessedVolumeEstimate(s.volume, null)}+ handle={suggestionNote}+ perMonth+ /></span></li>))}</ul>+ <EstimateNoteTooltip handle={suggestionNote} /></div>)}</section>diff --git a/web/src/components/action-center/use-action-story.ts b/web/src/components/action-center/use-action-story.tsindex cee114346..199e6c842 100644--- a/web/src/components/action-center/use-action-story.ts+++ b/web/src/components/action-center/use-action-story.ts@@ -6,6 +6,7 @@ import { getPromptDemand } from '@/lib/actions/action-center';import type { Signal } from '@/lib/signals/map';import { affectedOf, affectedSignals, type Affected } from '@/lib/action-center/affected';import { actionStory, type ActionStory } from '@/lib/action-center/story';+import type { VolumeEstimate } from '@/lib/volume-estimate';/** What the story reads of an action. */export interface StoryAction {@@ -29,7 +30,7 @@ export function useActionStory(signals: Signal[] | null,): {affected: Affected | null;- volumes: Map<string, number> | null;+ volumes: Map<string, VolumeEstimate> | null;story: ActionStory | null;ready: boolean;} {@@ -55,7 +56,7 @@ export function useActionStory(const demandKey = `${brandId}:${promptIdsKey}`;const [demand, setDemand] = useState<{key: string;- volumes: Map<string, number> | null;+ volumes: Map<string, VolumeEstimate> | null;} | null>(null);useEffect(() => {if (!promptIdsKey) return;diff --git a/web/src/components/prompts/volume-estimate.test.tsx b/web/src/components/prompts/volume-estimate.test.tsxindex c696b0c3b..e444d4df4 100644--- a/web/src/components/prompts/volume-estimate.test.tsx+++ b/web/src/components/prompts/volume-estimate.test.tsx@@ -124,6 +124,16 @@ describe('the note for other kinds of estimate', () => {});});+describe("the note for a sum of an AI's guesses", () => {+ it('says it adds up guesses, and that low here only means grey', async () => {+ render(<EstimateRange estimate={guessedVolumeEstimate(1200, null)} kind="total" perMonth />);+ const note = await noteOf(container.querySelector('button')!);+ expect(note).toContain("The sum of an AI's estimates for suggested prompts");+ expect(note).toContain("Low confidence: an AI's guess, shown in grey.");+ expect(note).not.toContain('not used to rank');+ });+});+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 e07f01476..7aa28579b 100644--- a/web/src/components/prompts/volume-estimate.tsx+++ b/web/src/components/prompts/volume-estimate.tsx@@ -40,7 +40,7 @@ function EstimateNote({ estimate, kind }: { estimate: Estimate; kind: EstimateKi<><p className="font-medium">{t('title')}</p>{estimate.basis === 'guess' ? (- <p>{t('methodGuess')}</p>+ <p>{t(kind === 'total' ? 'methodGuessTotal' : 'methodGuess')}</p>) : estimate.basis === 'keyword' ? (<p>{t('methodKeyword', { rate })}</p>) : kind === 'prompt' || !isTotal(estimate) ? (@@ -86,7 +86,10 @@ function EstimateNote({ estimate, kind }: { estimate: Estimate; kind: EstimateKi: t('confidenceUndated', { level })}</p>{estimate.stale && <p>{t('stale')}</p>}- {estimate.confidence === 'low' && <p>{t('lowNote')}</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>+ )}<p className="opacity-80">{t('measuredNote')}</p></>);diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex 5ffc9f810..c047cf054 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -121,7 +121,7 @@ describe('actionTexts', () => {it('names a topic opportunity after its topic and demand (VIS-011)', () => {const payload = { topicName: 'GEO tools for agencies', demand: 92_000 };expect(actionTexts(action({ kind: 'topic_opportunity', payload }), t).title).toBe(- 'Capture ~92k/mo of AI demand in GEO tools for agencies',+ 'Capture 46–190k/mo of estimated AI demand in GEO tools for agencies',);const tags = actionContextTags(action({ kind: 'topic_opportunity', payload, signalCount: 0 }),diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 3c8ad817c..f5300c2f2 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -1,6 +1,6 @@import type { ActionEvent, ActionItem } from '@/lib/actions/action-center';import { isActionKind } from '@/lib/action-center/registry';-import { formatCompactNumber } from '@/lib/format';+import { formatEstimateRange, guessedVolumeEstimate } from '@/lib/volume-estimate';/*** Composes what an action row shows from `kind` + `payload`, mirroring the@@ -117,7 +117,8 @@ export function actionTexts() {return {title: t(`${action.kind}.title`, {- demand: formatCompactNumber(p.demand),+ // The suggestions' AI-guessed demand: a range, not a count (PROMPT-013).+ demand: formatEstimateRange(guessedVolumeEstimate(p.demand, null)),topic: p.topicName,}),description: t(`${action.kind}.description`),diff --git a/web/src/lib/action-center/export-labels.ts b/web/src/lib/action-center/export-labels.tsindex 3775fda7b..3ea65d1c5 100644--- a/web/src/lib/action-center/export-labels.ts+++ b/web/src/lib/action-center/export-labels.ts@@ -21,7 +21,7 @@ import { isKpiKey } from '@/lib/kpis/registry';import { isSuperseded, signalAffected, signalTexts, signalTypeLabel } from '@/lib/signals/display';import { platformName } from '@/lib/signals/names';import { getPlatformName } from '@/lib/traffic-platforms';-import { formatCompactNumber } from '@/lib/format';+import { formatEstimateRange, type VolumeEstimate } from '@/lib/volume-estimate';/*** An action's export, labelled (AC-005): what the drawer's Copy Data, Export@@ -52,6 +52,7 @@ export const EXPORT_NAMESPACES = {signalCategories: 'actionCenter.signalCategories',priority: 'actionCenter.actionsPage.priority',affected: 'actionCenter.actionsPage.drawer.affected',+ estimate: 'volumeEstimate',} as const;export type ExportTranslators = Record<keyof typeof EXPORT_NAMESPACES, Translator>;@@ -166,7 +167,7 @@ export function sentFromFacts(/** The Affected tab's rows, labelled for the exports (AC-003). */export function exportAffectedRows(affected: Affected | null,- volumes: Map<string, number> | null,+ volumes: Map<string, VolumeEstimate> | null,origin: string,t: ExportTranslators,): ExportAffected[] {@@ -175,6 +176,9 @@ export function exportAffectedRows(entity: '',label: '',volume: '',+ volumeType: '',+ volumeConfidence: '',+ volumeConfidenceLabel: '',platforms: [],lostPages: [],citedInstead: [],@@ -189,7 +193,11 @@ export function exportAffectedRows(return row({entity: t.export('affectedPrompt'),label: prompt.text,- volume: volume ? `~${formatCompactNumber(volume)}` : '',+ // An estimate (PROMPT-013): its range, marked as such.+ volume: volume ? formatEstimateRange(volume) : '',+ volumeType: volume ? 'estimate' : '',+ volumeConfidence: volume?.confidence ?? '',+ volumeConfidenceLabel: volume ? t.estimate(`level.${volume.confidence}`) : '',platforms: prompt.platforms.map(platformName),lostPages: prompt.lostPages,citedInstead: prompt.citedInstead,@@ -227,7 +235,7 @@ export interface ActionExportInput {detail: ActionDetail;/** The Affected tab's list and its prompts' demand (AC-003). */affected: Affected | null;- volumes: Map<string, number> | null;+ volumes: Map<string, VolumeEstimate> | null;/** Why and Goal in the action's own terms (AC-003); null for an action a person sent. */story: ActionStory | null;/** A Content action's opportunity, read by the caller. */diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.tsindex 07549ddb0..ed25ac3a8 100644--- a/web/src/lib/action-center/export.test.ts+++ b/web/src/lib/action-center/export.test.ts@@ -112,7 +112,10 @@ const texts: ExportTexts = {{entity: 'Prompt',label: 'Which tools track AI search?',- volume: '~25.1k',+ volume: '18–32k',+ volumeType: 'estimate',+ volumeConfidence: 'medium',+ volumeConfidenceLabel: 'Medium',platforms: ['ChatGPT', 'Gemini'],lostPages: ['https://acme.example/blog/best-tools'],citedInstead: ['https://profound.com/features'],@@ -198,7 +201,7 @@ describe('actionMarkdown', () => {'link: https://app.example/dashboard/action-center/actions?action=a1','','## affectedHeading(1)',- '- Which tools track AI search? · ~25.1k · ChatGPT, Gemini · lostPage: https://acme.example/blog/best-tools · citedInstead: https://profound.com/features',+ '- Which tools track AI search? · estimatedVolume(18–32k,Medium) · ChatGPT, Gemini · lostPage: https://acme.example/blog/best-tools · citedInstead: https://profound.com/features','','## tasksHeading(2)','1. Add a 2026 comparison table to /blog/best-tools (Completed)',@@ -259,7 +262,7 @@ describe('actionCsv', () => {'signal,AC-52',]);expect(rows[0]).toContain(- '~25.1k,https://acme.example/blog/best-tools,https://profound.com/features,ChatGPT; Gemini',+ '18–32k,estimate,medium,https://acme.example/blog/best-tools,https://profound.com/features,ChatGPT; Gemini',);// A cell a spreadsheet would run as a formula is kept as text.expect(rows[2]).toContain(`"'=HYPERLINK(""x"")"`);@@ -330,10 +333,12 @@ describe('actionWorkbook', () => {{ value: 'Platforms at send time', fontWeight: 'bold' },'Gemini · No runs; ChatGPT · Not cited',]);- expect(sheets[1].data[1].slice(0, 4)).toEqual([+ expect(sheets[1].data[1].slice(0, 6)).toEqual(['Prompt','Which tools track AI search?',- '~25.1k',+ '18–32k',+ 'estimate',+ 'Medium','ChatGPT, Gemini',]);expect(sheets[2].data[0][1]).toEqual({ value: 'task', fontWeight: 'bold' });diff --git a/web/src/lib/action-center/export.ts b/web/src/lib/action-center/export.tsindex 0db6e3078..521efdc3d 100644--- a/web/src/lib/action-center/export.ts+++ b/web/src/lib/action-center/export.ts@@ -61,8 +61,14 @@ export interface ExportAffected {/** "Prompt", "Page", "Competitor", "Topic". */entity: string;label: string;- /** "~5.5k", or empty when unknown. */+ /** "4.4–7.5k", or empty when unknown. */volume: string;+ /** 'estimate' beside a volume (PROMPT-013), else empty. */+ volumeType: string;+ /** high, medium or low beside a volume, else empty: the CSV's code. */+ volumeConfidence: string;+ /** The same, worded for people ("Medium"): Markdown and Excel. */+ volumeConfidenceLabel: string;/** Display names. */platforms: string[];/** The brand's pages that lost a citation, and those cited instead. */@@ -253,7 +259,9 @@ function signalLine(signal: ExportSignal): string {function affectedLine(item: ExportAffected, label: Labels): string {return [item.label,- item.volume,+ item.volume+ ? label('estimatedVolume', { volume: item.volume, confidence: item.volumeConfidenceLabel })+ : '',item.platforms.join(', '),item.lostPages.length ? `${label('lostPage')}: ${item.lostPages.join(', ')}` : '',item.citedInstead.length ? `${label('citedInstead')}: ${item.citedInstead.join(', ')}` : '',@@ -348,6 +356,8 @@ export const ACTION_CSV_HEADERS = ['category','impact','volume',+ 'volume_type',+ 'volume_confidence','lost_pages','cited_instead','platforms',@@ -368,6 +378,8 @@ export function actionCsv(a: ActionExport): string {type: item.entity,details: item.details,volume: item.volume,+ volume_type: item.volumeType,+ volume_confidence: item.volumeConfidence,lost_pages: item.lostPages.join('; '),cited_instead: item.citedInstead.join('; '),platforms: item.platforms.join('; '),@@ -510,6 +522,8 @@ export function actionWorkbook(a: ActionExport, label: Labels): Sheet<Blob>[] {{ width: 10 },{ width: 60 },{ width: 10 },+ { width: 10 },+ { width: 12 },{ width: 24 },{ width: 40 },{ width: 40 },@@ -521,6 +535,8 @@ export function actionWorkbook(a: ActionExport, label: Labels): Sheet<Blob>[] {label('type'),label('item'),label('volume'),+ label('volumeType'),+ label('volumeConfidence'),label('platforms'),label('lostPage'),label('citedInstead'),@@ -531,6 +547,8 @@ export function actionWorkbook(a: ActionExport, label: Labels): Sheet<Blob>[] {item.entity,item.label,item.volume,+ item.volumeType,+ item.volumeConfidenceLabel,item.platforms.join(', '),item.lostPages.join(', '),item.citedInstead.join(', '),diff --git a/web/src/lib/action-center/prompt-demand.ts b/web/src/lib/action-center/prompt-demand.tsindex 64225b781..aed0fba75 100644--- a/web/src/lib/action-center/prompt-demand.ts+++ b/web/src/lib/action-center/prompt-demand.ts@@ -1,12 +1,14 @@import type { SupabaseClient } from '@supabase/supabase-js';import { supabaseAdmin } from '@/lib/supabase/admin';+import { promptVolumeEstimate, type VolumeEstimate } from '@/lib/volume-estimate';/** Prompt ids per request, so the filter stays well inside a URL's length. */const DEMAND_CHUNK = 150;/*** The estimated monthly AI searches of these prompts, for the Affected tab's- * Volume column and the Why (AC-003). prompt_volumes is a server-only table,+ * Volume column and the Why (AC-003): each as an estimate, a range and how+ * sure it is (PROMPT-013). prompt_volumes is a server-only table,* so the prompts are first checked to be the brand's with `client` — the* signed-in user's (RLS), or the admin client once the API has checked the* key's organization — and only theirs are read with the admin client.@@ -15,8 +17,8 @@ export async function readPromptDemand(client: SupabaseClient,brandId: string,promptIds: string[],-): Promise<Map<string, number>> {- const demand = new Map<string, number>();+): Promise<Map<string, VolumeEstimate>> {+ const demand = new Map<string, VolumeEstimate>();const ids = [...new Set(promptIds)];for (let i = 0; i < ids.length; i += DEMAND_CHUNK) {const chunk = ids.slice(i, i + DEMAND_CHUNK);@@ -30,12 +32,24 @@ export async function readPromptDemand(if (allowed.length === 0) continue;const { data: rows, error: volumeError } = await supabaseAdmin.from('prompt_volumes')- .select('prompt_id, est_ai_volume')+ .select(+ 'prompt_id, est_ai_volume, google_volumes, ai_volume_multiplier, keywords, fetched_at',+ ).in('prompt_id', allowed);if (volumeError) throw new Error(volumeError.message);for (const row of rows ?? []) {const volume = Number(row.est_ai_volume ?? 0);- if (volume > 0) demand.set(row.prompt_id as string, volume);+ if (volume <= 0) continue;+ demand.set(+ row.prompt_id as string,+ promptVolumeEstimate({+ estAiVolume: volume,+ googleVolumes: (row.google_volumes ?? {}) as Record<string, number>,+ aiVolumeMultiplier: Number(row.ai_volume_multiplier ?? 0),+ keywords: (row.keywords ?? []) as string[],+ fetchedAt: row.fetched_at as string,+ }),+ );}}return demand;diff --git a/web/src/lib/action-center/story.test.ts b/web/src/lib/action-center/story.test.tsindex 9ed4c2702..7d9ca1eb1 100644--- a/web/src/lib/action-center/story.test.ts+++ b/web/src/lib/action-center/story.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import messages from '../../../messages/en.json';import type { Signal } from '@/lib/signals/map';import { actionStory, storyFamily, type StoryFamily } from './story';+import type { VolumeEstimate } from '@/lib/volume-estimate';// Days are read where the reader is; pin it so the fixtures' days hold anywhere.process.env.TZ = 'UTC';@@ -42,9 +43,23 @@ const signal = (over: Partial<Signal> = {}): Signal =>...over,}) as Signal;+/** A prompt's volume as an estimate (PROMPT-013): ±20% around it, medium. */+const est = (value: number): VolumeEstimate => ({+ basis: 'keywords',+ value,+ low: value * 0.8,+ high: value * 1.2,+ confidence: 'medium',+ measured: 3,+ keywords: 5,+ rate: 0.45,+ asOf: '2026-10-10T00:00:00Z',+ stale: false,+});+const tell = (signals: Signal[],- opts: { volumes?: Map<string, number>; dueDate?: string | null } = {},+ opts: { volumes?: Map<string, VolumeEstimate>; dueDate?: string | null } = {},) =>actionStory({@@ -80,12 +95,12 @@ const lostSeven = Array.from({ length: 7 }, (_, i) =>describe('actionStory', () => {it('names the prompts, their topic and demand, the domain, the platforms and the days', () => {- const volumes = new Map(lostSeven.map((_, i) => [`p${i}`, 5_000]));+ const volumes = new Map(lostSeven.map((_, i) => [`p${i}`, est(5_000)]));const told = tell(lostSeven, { volumes })!;expect(told.family).toBe('citationLoss');expect(told.why).toBe(- '7 prompts in AI Rank Tracker (~35k AI searches a month) lost their citations to acme.example on Gemini, Google AI Overview, and ChatGPT between Oct 2 and Oct 9.',+ '7 prompts in AI Rank Tracker (28–42k AI searches a month, estimated) lost their citations to acme.example on Gemini, Google AI Overview, and ChatGPT between Oct 2 and Oct 9.',);// 70% of 7, rounded up; 30 days after the action was raised.expect(told.goal).toBe('Citations back on ≥5 of 7 prompts by Nov 8.');@@ -107,7 +122,7 @@ describe('actionStory', () => {},currentValue: 60,});- const told = tell([grouped], { volumes: new Map([['p1', 9_000]]) })!;+ const told = tell([grouped], { volumes: new Map([['p1', est(9_000)]]) })!;expect(told.why).toBe('Your brand is missing from AI answers to 60 prompts on Oct 9.');expect(told.goal).toBe('In AI answers to ≥42 of 60 prompts by Nov 8.');});diff --git a/web/src/lib/action-center/story.ts b/web/src/lib/action-center/story.tsindex d6e296ea2..8a6ba5952 100644--- a/web/src/lib/action-center/story.ts+++ b/web/src/lib/action-center/story.ts@@ -2,7 +2,7 @@ import type { Signal } from '@/lib/signals/map';import { signalWhereValue } from '@/lib/signals/detail';import { SIGNAL_KINDS, isSignalKind } from '@/lib/signals/registry';import { platformName } from '@/lib/signals/names';-import { formatCompactNumber } from '@/lib/format';+import { formatEstimateRange, sumEstimates, type VolumeEstimate } from '@/lib/volume-estimate';import { affectedOf, bareUrl, hostOf, type Affected } from './affected';/**@@ -215,8 +215,8 @@ export function actionStory(}: {/** The signals the Affected list was built from. */signals: Signal[];- /** Estimated monthly AI searches per prompt id, when read. */- volumes: Map<string, number> | null;+ /** Estimated monthly AI searches per prompt id, when read (PROMPT-013). */+ volumes: Map<string, VolumeEstimate> | null;createdAt: string;dueDate: string | null;},@@ -231,7 +231,7 @@ export function actionStory(const affected = affectedOf(mine);const subject = subjectOf(affected, family, mine);- // The subject: "7 prompts in AI Rank Tracker (~41k AI searches a month)".+ // The subject: "7 prompts in AI Rank Tracker (28–42k AI searches a month, estimated)".// The goal names the same items without their demand.let named = '';let demand = '';@@ -263,11 +263,14 @@ export function actionStory(if (topic) named += t('subject.inTopic', { topic });// Only when every prompt is listed: a sum over the first 50 would undercount.if (volumes && affected.prompts.length === affected.promptTotal) {- const volume = affected.prompts.reduce(- (sum, row) => sum + (row.id ? (volumes.get(row.id) ?? 0) : 0),- 0,+ // An estimate, so a range: the prompts' lows to their highs.+ const total = sumEstimates(+ affected.prompts.flatMap((row) => {+ const estimate = row.id ? volumes.get(row.id) : undefined;+ return estimate ? [estimate] : [];+ }),);- if (volume > 0) demand = t('subject.volume', { volume: formatCompactNumber(volume) });+ if (total.value > 0) demand = t('subject.volume', { volume: formatEstimateRange(total) });}}diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex c07d8ad3b..e1adce031 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -24,6 +24,7 @@ import { OPEN_SIGNAL_STATUSES, type SignalStatus } from '@/lib/signals/registry'import { readPromptPlaces } from '@/lib/signals/prompt-places';import { affectedOf, affectedSignals, affectedSummary } from '@/lib/action-center/affected';import { readPromptDemand } from '@/lib/action-center/prompt-demand';+import type { VolumeEstimate } from '@/lib/volume-estimate';import { readAssignees } from '@/lib/action-center/assignees';import {ACTION_COLUMNS,@@ -518,7 +519,7 @@ export async function deleteTask(brandId: string, actionId: string, taskId: striexport async function getPromptDemand(brandId: string,promptIds: string[],-): Promise<Record<string, number>> {+): Promise<Record<string, VolumeEstimate>> {if (promptIds.length === 0) return {};const supabase = await createClient();return Object.fromEntries(await readPromptDemand(supabase, brandId, promptIds));diff --git a/web/src/lib/actions/prompt-demand.test.ts b/web/src/lib/actions/prompt-demand.test.tsindex 0e0e86e02..42e70486f 100644--- a/web/src/lib/actions/prompt-demand.test.ts+++ b/web/src/lib/actions/prompt-demand.test.ts@@ -35,7 +35,15 @@ vi.mock('@/lib/supabase/admin', () => ({},then: (resolve: (value: unknown) => unknown) =>resolve({- data: ids.map((id) => ({ prompt_id: id, est_ai_volume: id === 'p2' ? 0 : 1200 })),+ data: ids.map((id) => ({+ prompt_id: id,+ est_ai_volume: id === 'p2' ? 0 : 1200,+ google_volumes: { a: 2400, b: 2700, c: 3000 },+ ai_volume_multiplier: '0.450',+ keywords: ['a', 'b', 'c'],+ // Recent, so the estimate isn't a level down for its age whenever this runs.+ fetched_at: new Date(Date.now() - 12 * 86_400_000).toISOString(),+ })),error: null,}),};@@ -56,11 +64,14 @@ describe('getPromptDemand', () => {visible = [{ id: 'p1' }];const demand = await getPromptDemand('b1', ['p1', 'other-brand']);expect(volumeReads).toEqual([['p1']]);- expect(demand).toEqual({ p1: 1200 });+ // Each as an estimate (PROMPT-013): three keywords close together read high.+ expect(demand).toEqual({+ p1: expect.objectContaining({ value: 1200, low: 900, high: 1500, confidence: 'high' }),+ });});it('leaves out a prompt without demand', async () => {- await expect(getPromptDemand('b1', ['p1', 'p2'])).resolves.toEqual({ p1: 1200 });+ expect(Object.keys(await getPromptDemand('b1', ['p1', 'p2']))).toEqual(['p1']);});it('reads nothing for no prompts', async () => {diff --git a/web/src/lib/mcp/action-export.test.ts b/web/src/lib/mcp/action-export.test.tsindex 75195da15..c57421d0a 100644--- a/web/src/lib/mcp/action-export.test.ts+++ b/web/src/lib/mcp/action-export.test.ts@@ -165,7 +165,17 @@ beforeEach(() => {topics: null,},],- prompt_volumes: [{ prompt_id: 'p1', est_ai_volume: 5500 }],+ prompt_volumes: [+ {+ prompt_id: 'p1',+ est_ai_volume: 5500,+ google_volumes: { a: 10_000, b: 12_200, c: 14_000 },+ ai_volume_multiplier: '0.450',+ keywords: ['a', 'b', 'c'],+ // Recent, so the confidence doesn't drop for its age whenever this runs.+ fetched_at: new Date(Date.now() - 12 * 86_400_000).toISOString(),+ },+ ],};});@@ -186,7 +196,8 @@ describe('exportActionFor', () => {expect(md).toContain('Link: https://app.example.com/dashboard/action-center/actions?action=a1');expect(md).toContain('## Affected (1)');expect(md).toContain('Best coffee subscription?');- expect(md).toContain('~5.5k');+ // An estimate: its range and how sure (PROMPT-013).+ expect(md).toContain('4.1–6.9k (estimate, High confidence)');expect(md).toContain('## Tasks (1)\n1. Add a 2026 table to /pricing (To Do)');expect(md).toContain('## Signals (1)');// The Why in the action's own terms, from its signal, with the day in UTC.@@ -197,7 +208,7 @@ describe('exportActionFor', () => {failing.add('prompt_volumes');const md = (await exportActionFor(auth, 'a1', 'markdown'))!.body;expect(md).toContain('Best coffee subscription?');- expect(md).not.toContain('~5.5k');+ expect(md).not.toContain('(estimate,');});it('dates the goal by its due date on a server east of UTC', async () => {