Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(metrics): visibility rate becomes the AI visibility score on every surface (#574)

Gökhan Geyikf376e95b9129
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f5a53edf0..e44f2cc7f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
+- **Visibility Rate is now the AI Visibility Score** — a 0-100 blend of how often AI answers mention the brand (60%), cite its site (25%) and how early it's named among tracked brands (15%), computed identically on every surface: Insights KPI header and trend chart, the leaderboard, All Prompts column and prompt detail, Topics overview and detail, Competitors cards, Reports (new reports; older snapshots keep rendering their stored values) and the Daily Pulse email. Coverage (appeared in X of Y prompts) stays visible as a secondary line, and detection remains fully deterministic — no LLM judges
+
+### Changed
+
- Prompts: the All Prompts **Visibility column now shows the prompt-level Visibility Rate** (share of runs in the last 30 days with a brand mention or citation) instead of the all-runs average score, which runs without any brand presence diluted into misleading single digits — same rate language as the Insights headline and topic pages; the tooltip keeps run counts and the average score across visible runs, and the CSV export gains `visibility_rate_30d` / `visible_runs_30d`
### Added
diff --git a/server/src/lib/pulse/email.js b/server/src/lib/pulse/email.js
index 0fa61643a..3a710478f 100644
--- a/server/src/lib/pulse/email.js
+++ b/server/src/lib/pulse/email.js
@@ -67,7 +67,7 @@ function highlightLine(h) {
);
case 'competitor_overtaken':
return listItem(
- `You overtook <strong>${escapeHtml(h.competitorName)}</strong> on the leaderboard (${escapeHtml(String(h.brandRate))}% vs ${escapeHtml(String(h.competitorRate))}%)`,
+ `You overtook <strong>${escapeHtml(h.competitorName)}</strong> on the leaderboard (${escapeHtml(String(h.brandRate))} vs ${escapeHtml(String(h.competitorRate))})`,
);
case 'new_engine':
return listItem(
@@ -82,15 +82,15 @@ function warningLine(w) {
switch (w.type) {
case 'sharp_drop':
return listItem(
- `Visibility rate dropped sharply: <strong>${escapeHtml(String(w.from))}% → ${escapeHtml(String(w.to))}%</strong> week-over-week`,
+ `Visibility score dropped sharply: <strong>${escapeHtml(String(w.from))} → ${escapeHtml(String(w.to))}</strong> week-over-week`,
);
case 'competitor_surge':
return listItem(
- `<strong>${escapeHtml(w.competitorName)}</strong> surged from ${escapeHtml(String(w.from))}% to ${escapeHtml(String(w.to))}% week-over-week`,
+ `<strong>${escapeHtml(w.competitorName)}</strong> surged from ${escapeHtml(String(w.from))} to ${escapeHtml(String(w.to))} week-over-week`,
);
case 'competitor_crossed':
return listItem(
- `<strong>${escapeHtml(w.competitorName)}</strong> crossed above your visibility rate (${escapeHtml(String(w.competitorRate))}% vs ${escapeHtml(String(w.brandRate))}%)`,
+ `<strong>${escapeHtml(w.competitorName)}</strong> crossed above your visibility score (${escapeHtml(String(w.competitorRate))} vs ${escapeHtml(String(w.brandRate))})`,
);
case 'lost_citations':
return listItem(
@@ -109,7 +109,7 @@ export function renderPulseEmail({ brandName, metrics, insightsUrl, settingsUrl
const windowLabel = windowDays === 7 ? 'last 7 days' : 'last 24 hours';
const trend = kpis.weekTrend;
- const subject = `${brandName} Daily Pulse — visibility ${kpis.visibilityRate}% (${signed(trend)} pts this week)`;
+ const subject = `${brandName} Daily Pulse — visibility ${kpis.visibilityRate} (${signed(trend)} pts this week)`;
const highlightItems = highlights.map(highlightLine).filter(Boolean).join('');
const warningItems = warnings.map(warningLine).filter(Boolean).join('');
@@ -126,8 +126,8 @@ export function renderPulseEmail({ brandName, metrics, insightsUrl, settingsUrl
<table role="presentation" cellspacing="8" style="border-collapse:separate;width:100%;margin-bottom:8px;">
<tr>
- ${kpiCell('Visibility rate', `${kpis.visibilityRate}%`, null)}
- ${kpiCell('7-day trend', `${kpis.weekRate}%`, kpis.weekTrend)}
+ ${kpiCell('Visibility', String(kpis.visibilityRate), null)}
+ ${kpiCell('7-day trend', String(kpis.weekRate), kpis.weekTrend)}
</tr>
<tr>
${kpiCell('Mentions', String(kpis.mentions), kpis.mentionsChange)}
diff --git a/server/src/lib/pulse/metrics.js b/server/src/lib/pulse/metrics.js
index 7e339a2a4..d31139bdd 100644
--- a/server/src/lib/pulse/metrics.js
+++ b/server/src/lib/pulse/metrics.js
@@ -1,4 +1,5 @@
import supabaseAdmin from '../../config/supabase.js';
+import { computeAiVisibilityScore } from '../../config/visibility-score.js';
/**
* Daily Pulse metric computation (#540).
@@ -40,12 +41,6 @@ const TRACKED_PLATFORMS = [
'gemini-web',
];
-/** Same rounding as the Insights headline: one decimal. */
-function rateOf(visible, prompts) {
- if (!prompts) return 0;
- return Math.round((visible / prompts) * 1000) / 10;
-}
-
function round1(n) {
return Math.round(n * 10) / 10;
}
@@ -62,13 +57,23 @@ async function visibilityRate(brandId, from, to) {
p_date_from: from.toISOString(),
p_date_to: to.toISOString(),
};
- const [stats, tracked] = await Promise.all([
+ const [stats, tracked, vis] = await Promise.all([
rpc('visible_prompt_stats', params),
rpc('tracked_prompt_count', params),
+ rpc('ai_visibility_aggregates', params),
]);
const visible = stats?.visible_prompts ?? 0;
const total = tracked ?? 0;
- return { visible, total, rate: rateOf(visible, total) };
+ // `rate` carries the AI Visibility Score (0-100) — the same blend every
+ // dashboard surface shows; coverage stays available as visible/total.
+ const score =
+ computeAiVisibilityScore({
+ answers: vis?.answers ?? 0,
+ mentionAnswers: vis?.mention_answers ?? 0,
+ citationAnswers: vis?.citation_answers ?? 0,
+ positionFactor: vis?.position_factor ?? null,
+ }) ?? 0;
+ return { visible, total, rate: score };
}
async function insightsWindow(brandId, from, to) {
@@ -87,20 +92,32 @@ async function insightsWindow(brandId, from, to) {
}
async function competitorRates(brandId, from, to) {
- const agg = await rpc('competitor_aggregates', {
+ const agg = await rpc('ai_visibility_aggregates', {
p_brand_id: brandId,
p_date_from: from.toISOString(),
p_date_to: to.toISOString(),
});
- // Shared denominator, same as getCompetitorComparison in the web app.
- const promptCount = agg?.brand_prompt_count ?? 0;
- const brandRate = rateOf(agg?.brand_visible_prompts ?? 0, promptCount);
+ // Shared denominator (the brand's answers), same as the web leaderboard.
+ const answers = agg?.answers ?? 0;
+ const brandRate =
+ computeAiVisibilityScore({
+ answers,
+ mentionAnswers: agg?.mention_answers ?? 0,
+ citationAnswers: agg?.citation_answers ?? 0,
+ positionFactor: agg?.position_factor ?? null,
+ }) ?? 0;
const competitors = new Map();
for (const c of agg?.by_competitor ?? []) {
competitors.set(c.competitor_id, {
id: c.competitor_id,
name: c.name,
- rate: rateOf(c.visible_prompts ?? 0, promptCount),
+ rate:
+ computeAiVisibilityScore({
+ answers,
+ mentionAnswers: c.mention_answers ?? 0,
+ citationAnswers: c.citation_answers ?? 0,
+ positionFactor: c.position_factor ?? null,
+ }) ?? 0,
});
}
return { brandRate, competitors };
diff --git a/server/src/routes/reports.js b/server/src/routes/reports.js
index dd1f9c400..ce7a229b6 100644
--- a/server/src/routes/reports.js
+++ b/server/src/routes/reports.js
@@ -24,7 +24,7 @@ const SUMMARY_SYSTEM_PROMPT = `You are an AI search visibility analyst writing t
You will receive a JSON snapshot of the brand's metrics for the report period. Depending on the report's sections it may include: overall visibility KPIs (with deltas vs the previous period), a daily visibility trend, share of voice, a competitor comparison, per-topic performance, best/weakest prompts, observed query fan-outs, AI-referred traffic, shopping visibility, a site audit score, and a citations overview. Every delta in the snapshot compares against the previous period of equal length.
-In promptPerformance and topicPerformance, visibilityRate is the percentage of runs in which the brand appeared at all — that is the number to quote for a prompt or topic, and topicPerformance.change is a percentage-point change in that rate. Their avgVisibility is a 0-100 intensity score, not a percentage: never write it with a % sign, and prefer visibilityRate whenever it is present.
+The headline metric is the AI Visibility Score, a 0-100 blend (60% how often answers mention the brand, 25% how often they cite its site, 15% how early it is named). Where a "score" field is present — visibilityRate.score, promptPerformance[].score, topicPerformance[].score — that is the number to quote, written WITHOUT a % sign, and topicPerformance.change is a point change in that score. On older snapshots without "score": visibilityRate is the percentage of runs the brand appeared in (quote with %), and avgVisibility is a 0-100 intensity score (never a %).
For insights KPIs, mentionsChange and citationsChange are percentage changes, never raw counts. A null change with prevMentions or prevCitations equal to 0 means there is no meaningful percentage base: describe the current total as new growth from zero (for example, "354 new mentions"), not as a percentage. A null previous count means comparison data is unavailable. visibilityChange and sentimentChange are percentage-point changes.
diff --git a/web/messages/en.json b/web/messages/en.json
index b20d83579..610bb968a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -578,7 +578,7 @@
"executiveSummary": "Executive Summary",
"kpi": {
"visibility": "Visibility",
- "visibilityRate": "Visibility Rate",
+ "visibilityRate": "Visibility",
"visibilityRateSub": "{visible}/{total} prompts",
"avgScore": "Avg. Score",
"mentions": "Mentions",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
index f1f47f377..e8548ae05 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
@@ -290,10 +290,12 @@ function CompetitorCard({
}: {
competitor: Competitor;
stats: {
- rate: number;
+ score: number | null;
+ mentionAnswers: number;
+ citationAnswers: number;
+ positionFactor: number | null;
visiblePrompts: number;
promptCount: number;
- avg: number;
mentions: number;
citations: number;
} | null;
@@ -349,9 +351,13 @@ function CompetitorCard({
{stats ? (
<div
className="text-right"
- title={`Appeared in ${stats.visiblePrompts} of ${stats.promptCount} prompts · ${stats.mentions} mentions · ${stats.citations} citations · avg score ${stats.avg}%`}
+ title={`Mentioned in ${stats.mentionAnswers} answers · cited in ${stats.citationAnswers}${
+ stats.positionFactor !== null
+ ? ` · position factor ${stats.positionFactor.toFixed(2)}`
+ : ''
+ } · ${stats.mentions} mentions · ${stats.citations} citations`}
>
- <div className="text-sm font-semibold tabular-nums">{stats.rate}%</div>
+ <div className="text-sm font-semibold tabular-nums">{stats.score ?? '—'}</div>
<div className="text-[10px] text-muted-foreground tabular-nums">
{stats.visiblePrompts}/{stats.promptCount} prompts
</div>
@@ -1195,16 +1201,18 @@ export default function CompetitorsPage() {
if (!brand) return <NoBrandSelected />;
- // Build score map from comparison data. The headline number is the
- // prompt-level visibility rate (#493) — the same metric as the Insights
- // leaderboard — with the raw score average kept for the tooltip.
+ // Build score map from comparison data. The headline number is the AI
+ // Visibility Score — the same metric as the Insights leaderboard — with
+ // coverage kept for the sub-line and components in the tooltip.
const scoreMap = new Map<
string,
{
- rate: number;
+ score: number | null;
+ mentionAnswers: number;
+ citationAnswers: number;
+ positionFactor: number | null;
visiblePrompts: number;
promptCount: number;
- avg: number;
mentions: number;
citations: number;
}
@@ -1213,10 +1221,12 @@ export default function CompetitorsPage() {
for (const entry of comparisonData.brands) {
if (!entry.isOwnBrand) {
scoreMap.set(entry.name, {
- rate: entry.visibilityRate,
+ score: entry.score,
+ mentionAnswers: entry.mentionAnswers,
+ citationAnswers: entry.citationAnswers,
+ positionFactor: entry.positionFactor,
visiblePrompts: entry.visiblePrompts,
promptCount: entry.promptCount,
- avg: entry.avgVisibilityScore,
mentions: entry.totalMentions,
citations: entry.totalCitations,
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
index fb76a320f..042e854c4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
@@ -472,8 +472,8 @@ export function VisibilityRateTrendChart({ data }: { data: VisibilityRateTrendDa
const lastIndex = points.length - 1;
// Y axis ticks run 5, 15, 25, … and the top one sits just above the
- // highest rate in view (60% peak → axis ends at 65%), so the lines use
- // the full canvas instead of being squashed under an always-100% scale.
+ // highest score in view (a 60 peak → axis ends at 65), so the lines use
+ // the full canvas instead of being squashed under an always-100 scale.
const dataMax = Math.max(0, ...shown.flatMap((e) => points.map((p) => p.values[e.key] ?? 0)));
let yTop = 5;
while (yTop <= dataMax) yTop += 10;
@@ -503,7 +503,6 @@ export function VisibilityRateTrendChart({ data }: { data: VisibilityRateTrendDa
tick={{ fontSize: 11 }}
tickLine={false}
axisLine={false}
- tickFormatter={(v: number) => `${v}%`}
className="fill-muted-foreground"
/>
<Tooltip
@@ -526,7 +525,7 @@ export function VisibilityRateTrendChart({ data }: { data: VisibilityRateTrendDa
style={{ backgroundColor: entity.color }}
/>
<span className="text-muted-foreground">{entity.name}:</span>
- <span className="font-medium text-foreground">{entry.value}%</span>
+ <span className="font-medium text-foreground">{entry.value}</span>
</div>
);
})}
@@ -689,17 +688,24 @@ function LeaderboardEntry({ entry, rank }: { entry: CompetitorComparisonEntry; r
</div>
</div>
<div className="flex flex-col items-end gap-0.5 shrink-0">
- <span className="text-sm font-semibold tabular-nums">{entry.visibilityRate}%</span>
- {entry.change !== null && entry.change !== 0 && (
+ <span
+ className="text-sm font-semibold tabular-nums"
+ title={`Mentioned in ${entry.mentionAnswers} answers · cited in ${entry.citationAnswers} · position factor ${
+ entry.positionFactor === null ? '—' : entry.positionFactor.toFixed(2)
+ }`}
+ >
+ {entry.score ?? '—'}
+ </span>
+ {entry.scoreChange !== null && entry.scoreChange !== 0 && (
<span
className={`text-[10px] font-medium tabular-nums ${
- entry.change > 0 ? 'text-green-500' : 'text-red-500'
+ entry.scoreChange > 0 ? 'text-green-500' : 'text-red-500'
}`}
>
- {entry.change > 0 ? '↑' : '↓'} {Math.abs(entry.change).toFixed(1)} pts
+ {entry.scoreChange > 0 ? '↑' : '↓'} {Math.abs(entry.scoreChange).toFixed(1)} pts
</span>
)}
- {entry.change === 0 && (
+ {entry.scoreChange === 0 && (
<span className="text-[10px] font-medium tabular-nums text-muted-foreground">— 0</span>
)}
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 64947fc9b..ccef6a0f9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -1259,10 +1259,13 @@ export default function InsightsPage() {
// content stays visible under the overlay instead of flashing a skeleton.
const isRefetching = isLoading && summary !== null;
- // Visibility Rate = prompts the brand appeared in ÷ prompts that produced
- // results, both under the same filters (the Tracked Prompts KPI is the
- // denominator on purpose — the two cards must agree).
- const visibilityRatePct =
+ // Visibility Rate now IS the AI Visibility Score (0-100): 0.6×mention
+ // rate + 0.25×citation rate + 0.15×position factor over the filtered
+ // answers. Sourced from the trend action so this card, the trend card
+ // header and the leaderboard all read the exact same number. Coverage
+ // (appeared in X of Y prompts) survives as the sub-line.
+ const headlineScore = rateTrend?.summary.rate ?? 0;
+ const coveragePct =
visibilityRate && trackedPrompts && trackedPrompts.activeInPeriod > 0
? Math.round((visibilityRate.visiblePrompts / trackedPrompts.activeInPeriod) * 1000) / 10
: 0;
@@ -1397,11 +1400,18 @@ export default function InsightsPage() {
own chart section below. */}
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-5">
<KpiCard
- title="Visibility Rate"
- tooltip="Share of tracked prompts where your brand appeared in at least one AI answer under the current filters."
+ title="Visibility"
+ tooltip="AI Visibility Score (0-100): how often AI answers mention you (60%), cite your site (25%) and how early you're named (15%), under the current filters."
icon={Eye}
- value={`${visibilityRatePct}%`}
- sub={null}
+ value={headlineScore}
+ sub={
+ visibilityRate && trackedPrompts ? (
+ <span className="tabular-nums">
+ appeared in {visibilityRate.visiblePrompts}/{trackedPrompts.activeInPeriod}{' '}
+ prompts ({coveragePct}%)
+ </span>
+ ) : null
+ }
onClick={() => setBreakdownMetric('visibility')}
/>
<KpiCard
@@ -1494,7 +1504,7 @@ export default function InsightsPage() {
{rateTrend ? (
<div>
<div className="text-3xl font-bold tabular-nums">
- {rateTrend.summary.rate}%
+ {rateTrend.summary.rate}
</div>
<div className="mt-1 flex items-center gap-2 text-xs">
{rateTrend.summary.change !== null && (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx
index 77a14f558..a200d948d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx
@@ -762,8 +762,8 @@ export default function PromptDetailPage() {
<div className={cn('space-y-6', isRefetching && 'opacity-60')}>
<div className="grid gap-4 sm:grid-cols-3">
<KpiCard
- title={`Visibility Rate — appeared in ${data.summary.visibleResults} of ${data.summary.totalResults} answers`}
- value={data.summary.visibilityRate}
+ title={`Visibility — mentioned in ${data.summary.mentionAnswers} of ${data.summary.totalResults} answers, cited in ${data.summary.citationAnswers}`}
+ value={data.summary.score ?? 0}
icon={Eye}
/>
<KpiCard
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 1f0fab6f9..5e9871f9f 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -222,6 +222,7 @@ const PROMPT_EXPORT_HEADERS = [
'est_ai_volume',
'total_google_volume',
'intent',
+ 'ai_visibility_score_30d',
'visibility_rate_30d',
'visible_runs_30d',
'avg_visibility_30d',
@@ -1128,6 +1129,7 @@ export default function PromptsPage() {
est_ai_volume: volumeByPromptId.get(p.id)?.estAiVolume ?? '',
total_google_volume: volumeByPromptId.get(p.id)?.totalGoogleVolume ?? '',
intent: volumeByPromptId.get(p.id)?.intent ?? '',
+ ai_visibility_score_30d: visibility[p.id]?.score ?? '',
visibility_rate_30d: visibility[p.id]?.visibilityRate ?? '',
visible_runs_30d: visibility[p.id]?.visibleRuns ?? '',
avg_visibility_30d: visibility[p.id]?.avgVisibility ?? '',
@@ -1746,7 +1748,7 @@ function AllPromptsTab({
const vol = volumeByPromptId.get(p.id);
switch (activeSort) {
case 'visibility':
- return vis ? vis.visibilityRate : null;
+ return vis ? (vis.score ?? 0) : null;
case 'mentions':
return vis ? vis.totalMentions : null;
case 'citations':
@@ -1858,7 +1860,7 @@ function AllPromptsTab({
</ColHead>
<SortableHead
className="text-right"
- tooltip="Visibility Rate: the percentage of AI answers for this prompt (last 30 days) that mentioned or cited the brand. Hover a value for run counts and the average score across visible answers."
+ tooltip="AI Visibility Score (0-100) for this prompt over the last 30 days: how often answers mention the brand (60%), cite its site (25%) and how early it's named (15%). Hover a value for the components."
sortKey="visibility"
activeSort={activeSort}
dir={dir}
@@ -1982,28 +1984,28 @@ function AllPromptsTab({
{vis ? (
<div
className="inline-flex items-center gap-2 justify-end min-w-[110px]"
- title={`Appeared in ${vis.visibleRuns} of ${vis.runs} runs (30d)${
- vis.avgVisibilityVisible !== null
- ? ` · avg score when visible: ${vis.avgVisibilityVisible.toFixed(0)}`
+ title={`Mentioned in ${vis.mentionAnswers} of ${vis.runs} answers (30d) · cited in ${vis.citationAnswers}${
+ vis.positionFactor !== null
+ ? ` · position factor ${vis.positionFactor.toFixed(2)}`
: ''
- }`}
+ } · coverage ${vis.visibilityRate}% (${vis.visibleRuns}/${vis.runs} runs)`}
>
<span
className={cn(
'text-sm font-semibold tabular-nums',
- visibilityColorClass(vis.visibilityRate),
+ visibilityColorClass(vis.score ?? 0),
)}
>
- {vis.visibilityRate}
+ {vis.score ?? 0}
</span>
<div className="h-1.5 w-16 rounded-full bg-muted overflow-hidden">
<div
className={cn(
'h-full rounded-full',
- visibilityBarClass(vis.visibilityRate),
+ visibilityBarClass(vis.score ?? 0),
)}
style={{
- width: `${Math.min(100, Math.max(0, vis.visibilityRate))}%`,
+ width: `${Math.min(100, Math.max(0, vis.score ?? 0))}%`,
}}
/>
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx
index f1fe89ab9..baae007be 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx
@@ -201,27 +201,23 @@ function HBar({ label, pct, value }: { label: string; pct: number; value: string
}
function PromptTable({ title, prompts }: { title: string; prompts: ReportPromptPerf[] }) {
- // Reports generated before the rate switch stored an all-runs average score
- // (0-100 intensity, not a percentage) — render those unchanged, without a
- // misleading % sign.
- const hasVisibilityRate = prompts.some((p) => typeof p.visibilityRate === 'number');
return (
<View style={styles.section} wrap={false}>
<Text style={styles.sectionTitle}>{title}</Text>
<View style={styles.tableHeader}>
<Text style={[styles.tableHeaderCell, { flex: 1 }]}>Prompt</Text>
- <Text style={[styles.tableHeaderCell, { width: 60, textAlign: 'right' }]}>
- {hasVisibilityRate ? 'Visibility Rate' : 'Visibility'}
- </Text>
+ <Text style={[styles.tableHeaderCell, { width: 60, textAlign: 'right' }]}>Visibility</Text>
<Text style={[styles.tableHeaderCell, { width: 40, textAlign: 'right' }]}>Runs</Text>
</View>
{prompts.map((p) => (
<View key={p.text} style={styles.tableRow}>
<Text style={[styles.cell, { flex: 1, paddingRight: 8 }]}>{p.text}</Text>
<Text style={[styles.cell, { width: 60, textAlign: 'right' }]}>
- {typeof p.visibilityRate === 'number'
- ? `${p.visibilityRate}%`
- : `${p.avgVisibility}/100`}
+ {typeof p.score === 'number'
+ ? p.score
+ : typeof p.visibilityRate === 'number'
+ ? `${p.visibilityRate}%`
+ : `${p.avgVisibility}/100`}
</Text>
<Text style={[styles.cell, { width: 40, textAlign: 'right', color: MUTED }]}>
{p.runs}
@@ -260,8 +256,11 @@ export function ReportPdfDocument({ report }: { report: Report }) {
...(payload.visibilityRate
? [
{
- label: 'Visibility Rate',
- value: `${payload.visibilityRate.ratePct}%`,
+ label: 'Visibility',
+ value:
+ typeof payload.visibilityRate.score === 'number'
+ ? String(payload.visibilityRate.score)
+ : `${payload.visibilityRate.ratePct}%`,
change: null,
sub: `${payload.visibilityRate.visiblePrompts}/${payload.visibilityRate.promptCount} prompts`,
},
@@ -315,11 +314,6 @@ export function ReportPdfDocument({ report }: { report: Report }) {
typeof payload.competitors[0].visibilityRate === 'number' &&
typeof payload.competitors[0].promptCount === 'number',
);
- // Topics switched from an all-runs average score to the rate too; older
- // payloads keep their stored score (no % sign — it isn't one).
- const hasTopicVisibilityRate = Boolean(
- payload.topicPerformance?.some((tp) => typeof tp.visibilityRate === 'number'),
- );
return (
<Document title={report.title} author="Ansvisor" creator="Ansvisor">
@@ -407,7 +401,7 @@ export function ReportPdfDocument({ report }: { report: Report }) {
<View style={styles.tableHeader}>
<Text style={[styles.tableHeaderCell, { flex: 1 }]}>Brand</Text>
<Text style={[styles.tableHeaderCell, { width: 60, textAlign: 'right' }]}>
- {hasCompetitorVisibilityRate ? 'Visibility Rate' : 'Visibility'}
+ Visibility
</Text>
<Text style={[styles.tableHeaderCell, { width: 50, textAlign: 'right' }]}>
Change
@@ -433,7 +427,9 @@ export function ReportPdfDocument({ report }: { report: Report }) {
</Text>
<View style={{ width: 60, alignItems: 'flex-end' }}>
<Text style={styles.cell}>
- {hasCompetitorVisibilityRate ? c.visibilityRate : c.avgVisibilityScore}%
+ {typeof c.score === 'number'
+ ? c.score
+ : `${hasCompetitorVisibilityRate ? c.visibilityRate : c.avgVisibilityScore}%`}
</Text>
{hasCompetitorVisibilityRate && (
<Text style={styles.kpiSub}>
@@ -462,7 +458,7 @@ export function ReportPdfDocument({ report }: { report: Report }) {
<View style={styles.tableHeader}>
<Text style={[styles.tableHeaderCell, { flex: 1 }]}>Topic</Text>
<Text style={[styles.tableHeaderCell, { width: 60, textAlign: 'right' }]}>
- {hasTopicVisibilityRate ? 'Visibility Rate' : 'Visibility'}
+ Visibility
</Text>
<Text style={[styles.tableHeaderCell, { width: 50, textAlign: 'right' }]}>
Change
@@ -475,9 +471,11 @@ export function ReportPdfDocument({ report }: { report: Report }) {
<View key={tp.name} style={styles.tableRow}>
<Text style={[styles.cell, { flex: 1, paddingRight: 8 }]}>{tp.name}</Text>
<Text style={[styles.cell, { width: 60, textAlign: 'right' }]}>
- {typeof tp.visibilityRate === 'number'
- ? `${tp.visibilityRate}%`
- : `${tp.avgVisibility}/100`}
+ {typeof tp.score === 'number'
+ ? tp.score
+ : typeof tp.visibilityRate === 'number'
+ ? `${tp.visibilityRate}%`
+ : `${tp.avgVisibility}/100`}
</Text>
<View style={{ width: 50, alignItems: 'flex-end' }}>
<DeltaText value={tp.change} />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx
index 4e23ed20e..1b22eb14c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx
@@ -247,7 +247,11 @@ export default function ReportDetailPage() {
<>
<KpiCard
label={t('kpi.visibilityRate')}
- value={`${payload.visibilityRate.ratePct}%`}
+ value={
+ typeof payload.visibilityRate.score === 'number'
+ ? String(payload.visibilityRate.score)
+ : `${payload.visibilityRate.ratePct}%`
+ }
change={null}
sub={t('kpi.visibilityRateSub', {
visible: payload.visibilityRate.visiblePrompts,
@@ -382,7 +386,17 @@ export default function ReportDetailPage() {
)}
</TableCell>
<TableCell className="text-right">
- {hasCompetitorVisibilityRate ? (
+ {typeof c.score === 'number' ? (
+ <>
+ <div>{c.score}</div>
+ <div className="text-xs font-normal text-muted-foreground">
+ {t('kpi.visibilityRateSub', {
+ visible: c.visiblePrompts,
+ total: c.promptCount,
+ })}
+ </div>
+ </>
+ ) : hasCompetitorVisibilityRate ? (
<>
<div>{c.visibilityRate}%</div>
<div className="text-xs font-normal text-muted-foreground">
@@ -434,9 +448,11 @@ export default function ReportDetailPage() {
{tp.name}
</TableCell>
<TableCell className="text-right">
- {typeof tp.visibilityRate === 'number'
- ? `${tp.visibilityRate}%`
- : `${tp.avgVisibility}/100`}
+ {typeof tp.score === 'number'
+ ? tp.score
+ : typeof tp.visibilityRate === 'number'
+ ? `${tp.visibilityRate}%`
+ : `${tp.avgVisibility}/100`}
</TableCell>
<TableCell className="text-right">
<Delta value={tp.change} />
@@ -488,9 +504,11 @@ export default function ReportDetailPage() {
{p.text}
</TableCell>
<TableCell className="text-right">
- {typeof p.visibilityRate === 'number'
- ? `${p.visibilityRate}%`
- : `${p.avgVisibility}/100`}
+ {typeof p.score === 'number'
+ ? p.score
+ : typeof p.visibilityRate === 'number'
+ ? `${p.visibilityRate}%`
+ : `${p.avgVisibility}/100`}
</TableCell>
<TableCell className="text-right text-muted-foreground">
{p.runs}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx
index cf9966fc1..fade1537d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx
@@ -256,13 +256,12 @@ export default function TopicDetailPage({ params }: { params: Promise<{ id: stri
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<KpiCard
icon={Eye}
- label="Visibility rate"
- value={ownBrand?.visibilityRate ?? 0}
- change={ownBrand?.change ?? null}
- suffix="%"
+ label="Visibility"
+ value={ownBrand?.score ?? 0}
+ change={ownBrand?.scoreChange ?? null}
hint={
ownBrand
- ? `Appeared in ${ownBrand.visiblePrompts} of ${ownBrand.promptCount} prompts · avg score ${summary.avgVisibilityScore}%`
+ ? `Mentioned in ${ownBrand.mentionAnswers} answers · cited in ${ownBrand.citationAnswers} · appeared in ${ownBrand.visiblePrompts} of ${ownBrand.promptCount} prompts`
: undefined
}
/>
@@ -356,22 +355,20 @@ export default function TopicDetailPage({ params }: { params: Promise<{ id: stri
<span className="ml-1.5 text-[10px] font-medium text-primary">YOU</span>
)}
</span>
- <span className="text-sm tabular-nums w-10 text-right">
- {c.visibilityRate}%
- </span>
- {c.change !== null && (
+ <span className="text-sm tabular-nums w-10 text-right">{c.score ?? '—'}</span>
+ {c.scoreChange !== null && (
<span
className={cn(
'text-xs tabular-nums w-12 text-right',
- c.change > 0
+ c.scoreChange > 0
? 'text-emerald-600 dark:text-emerald-400'
- : c.change < 0
+ : c.scoreChange < 0
? 'text-rose-600 dark:text-rose-400'
: 'text-muted-foreground',
)}
>
- {c.change > 0 ? '+' : ''}
- {c.change}
+ {c.scoreChange > 0 ? '+' : ''}
+ {c.scoreChange}
</span>
)}
</li>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
index f8cc5955c..47a5281bb 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
@@ -406,14 +406,14 @@ export default function TopicsPage() {
<KpiCard
icon={Trophy}
label={t('kpi.bestPerformer')}
- value={kpis.best ? `${kpis.best.visibilityRate}%` : '—'}
+ value={kpis.best ? kpis.best.visibilityRate : '—'}
sub={kpis.best?.name ?? t('kpi.noDataYet')}
tone="positive"
/>
<KpiCard
icon={TrendingDown}
label={t('kpi.biggestGap')}
- value={kpis.weakest ? `${kpis.weakest.visibilityRate}%` : '—'}
+ value={kpis.weakest ? kpis.weakest.visibilityRate : '—'}
sub={kpis.weakest?.name ?? t('kpi.noDataYet')}
tone="warning"
/>
@@ -508,7 +508,7 @@ export default function TopicsPage() {
visibilityTextColor(topic.visibilityRate),
)}
>
- {topic.visibilityRate}%
+ {topic.visibilityRate}
</span>
<div className="h-1.5 flex-1 max-w-[90px] rounded-full bg-muted overflow-hidden">
<div
diff --git a/web/src/lib/actions/reports.ts b/web/src/lib/actions/reports.ts
index 47ace4c95..5a0ad020c 100644
--- a/web/src/lib/actions/reports.ts
+++ b/web/src/lib/actions/reports.ts
@@ -2,6 +2,7 @@
import { revalidatePath } from 'next/cache';
import { createClient } from '@/lib/supabase/server';
+import { computeAiVisibilityScore } from '@/lib/visibility-score';
import type { Json } from '@/types/supabase';
import { API_BASE_URL } from '@/config/api';
import {
@@ -55,6 +56,8 @@ export interface ReportPromptPerf {
* (#562 semantics). Absent on reports generated before this shipped.
*/
visibilityRate?: number;
+ /** AI Visibility Score (0-100). Absent on reports generated before it shipped. */
+ score?: number;
totalMentions: number;
runs: number;
}
@@ -96,10 +99,12 @@ export interface ReportTopicPerf {
* shipped.
*/
visibilityRate?: number;
+ /** AI Visibility Score (0-100). Absent on reports generated before it shipped. */
+ score?: number;
/**
* Points change vs the previous window of equal length; null when no prior
- * data. Visibility-rate points on payloads carrying `visibilityRate`, score
- * points on older ones.
+ * data. Score points on payloads carrying `score`, visibility-rate points
+ * on `visibilityRate`-era ones, raw-score points on the oldest.
*/
change: number | null;
results: number;
@@ -138,8 +143,17 @@ export interface ReportVisibilityRate {
visiblePrompts: number;
/** Distinct tracked prompts that produced results in the window (shared denominator). */
promptCount: number;
- /** visiblePrompts / promptCount as a percentage, one decimal place. */
+ /** visiblePrompts / promptCount as a percentage, one decimal place (coverage). */
ratePct: number;
+ /**
+ * AI Visibility Score (0-100): 0.6×mention rate + 0.25×citation rate +
+ * 0.15×position factor over the window's answers. Absent on reports
+ * generated before the score shipped.
+ */
+ score?: number | null;
+ mentionAnswers?: number;
+ citationAnswers?: number;
+ positionFactor?: number | null;
}
/**
@@ -241,12 +255,21 @@ async function getPromptPerformance(
const acc = new Map<
string,
- { sumVis: number; mentions: number; runs: number; visibleRuns: number }
+ {
+ sumVis: number;
+ mentions: number;
+ runs: number;
+ visibleRuns: number;
+ mentionAnswers: number;
+ citationAnswers: number;
+ posSum: number;
+ posN: number;
+ }
>();
for (let offset = 0; offset < SCAN_MAX_ROWS; offset += SCAN_PAGE_SIZE) {
const { data, error } = await supabase
.from('prompt_results')
- .select('prompt_id, visibility_score, mention_count, citation_count')
+ .select('prompt_id, visibility_score, mention_count, citation_count, mention_position')
.eq('brand_id', brandId)
.neq('platform', 'chatgpt-shopping')
.gte('created_at', dateFrom)
@@ -260,13 +283,29 @@ async function getPromptPerformance(
for (const r of batch) {
const pid = r.prompt_id as string | null;
if (!pid) continue;
- const entry = acc.get(pid) ?? { sumVis: 0, mentions: 0, runs: 0, visibleRuns: 0 };
+ const entry = acc.get(pid) ?? {
+ sumVis: 0,
+ mentions: 0,
+ runs: 0,
+ visibleRuns: 0,
+ mentionAnswers: 0,
+ citationAnswers: 0,
+ posSum: 0,
+ posN: 0,
+ };
const mentions = (r.mention_count as number) ?? 0;
const citations = (r.citation_count as number) ?? 0;
+ const pos = r.mention_position as number | null;
entry.sumVis += (r.visibility_score as number) ?? 0;
entry.mentions += mentions;
entry.runs += 1;
if (mentions > 0 || citations > 0) entry.visibleRuns += 1;
+ if (mentions > 0) entry.mentionAnswers += 1;
+ if (citations > 0) entry.citationAnswers += 1;
+ if (pos !== null && pos !== undefined && pos > 0) {
+ entry.posSum += 1 / pos;
+ entry.posN += 1;
+ }
acc.set(pid, entry);
}
@@ -284,14 +323,21 @@ async function getPromptPerformance(
.map(([pid, v]) => ({
text: textById.get(pid) ?? '',
avgVisibility: Math.round((v.sumVis / v.runs) * 10) / 10,
- // Same rounding as getPromptVisibilitySummaries, so a prompt's rate
- // reads identically on the All Prompts tab and in a report.
visibilityRate: Math.round((v.visibleRuns / v.runs) * 1000) / 10,
+ // AI Visibility Score over this prompt's answers — same blend as the
+ // All Prompts column, so a prompt reads identically in a report.
+ score:
+ computeAiVisibilityScore({
+ answers: v.runs,
+ mentionAnswers: v.mentionAnswers,
+ citationAnswers: v.citationAnswers,
+ positionFactor: v.posN > 0 ? v.posSum / v.posN : null,
+ }) ?? 0,
totalMentions: v.mentions,
runs: v.runs,
}))
.filter((p) => p.text)
- .sort((a, b) => b.visibilityRate - a.visibilityRate || b.totalMentions - a.totalMentions);
+ .sort((a, b) => b.score - a.score || b.totalMentions - a.totalMentions);
const best = ranked.slice(0, REPORT_PROMPT_COUNT);
// Worst come from the remaining pool so a short prompt list doesn't show
@@ -393,12 +439,15 @@ async function getTopicPerformance(
visibility_score: number | null;
mention_count: number | null;
citation_count: number | null;
+ mention_position: number | null;
created_at: string;
}[] = [];
for (let offset = 0; offset < SCAN_MAX_ROWS; offset += SCAN_PAGE_SIZE) {
const { data, error } = await supabase
.from('prompt_results')
- .select('prompt_id, visibility_score, mention_count, citation_count, created_at')
+ .select(
+ 'prompt_id, visibility_score, mention_count, citation_count, mention_position, created_at',
+ )
.eq('brand_id', brandId)
.neq('platform', 'chatgpt-shopping')
.gte('created_at', prev.from)
@@ -428,22 +477,59 @@ async function getTopicPerformance(
sumVis: number;
n: number;
visible: number;
+ mentionAnswers: number;
+ citationAnswers: number;
+ posSum: number;
+ posN: number;
prevN: number;
prevVisible: number;
+ prevMentionAnswers: number;
+ prevCitationAnswers: number;
+ prevPosSum: number;
+ prevPosN: number;
}
const byTopic = new Map<string, Acc>();
for (const r of rows) {
const topicId = topicByPrompt.get(r.prompt_id as string);
if (!topicId) continue;
- const acc = byTopic.get(topicId) ?? { sumVis: 0, n: 0, visible: 0, prevN: 0, prevVisible: 0 };
- const isVisible = (r.mention_count ?? 0) > 0 || (r.citation_count ?? 0) > 0;
+ const acc = byTopic.get(topicId) ?? {
+ sumVis: 0,
+ n: 0,
+ visible: 0,
+ mentionAnswers: 0,
+ citationAnswers: 0,
+ posSum: 0,
+ posN: 0,
+ prevN: 0,
+ prevVisible: 0,
+ prevMentionAnswers: 0,
+ prevCitationAnswers: 0,
+ prevPosSum: 0,
+ prevPosN: 0,
+ };
+ const mentions = (r.mention_count as number | null) ?? 0;
+ const citations = (r.citation_count as number | null) ?? 0;
+ const pos = r.mention_position as number | null;
+ const isVisible = mentions > 0 || citations > 0;
if ((r.created_at as string) >= dateFrom) {
acc.sumVis += r.visibility_score ?? 0;
acc.n += 1;
if (isVisible) acc.visible += 1;
+ if (mentions > 0) acc.mentionAnswers += 1;
+ if (citations > 0) acc.citationAnswers += 1;
+ if (pos !== null && pos !== undefined && pos > 0) {
+ acc.posSum += 1 / pos;
+ acc.posN += 1;
+ }
} else {
acc.prevN += 1;
if (isVisible) acc.prevVisible += 1;
+ if (mentions > 0) acc.prevMentionAnswers += 1;
+ if (citations > 0) acc.prevCitationAnswers += 1;
+ if (pos !== null && pos !== undefined && pos > 0) {
+ acc.prevPosSum += 1 / pos;
+ acc.prevPosN += 1;
+ }
}
byTopic.set(topicId, acc);
}
@@ -457,18 +543,35 @@ async function getTopicPerformance(
return [...byTopic.entries()]
.filter(([id, acc]) => acc.n > 0 && nameById.has(id))
.map(([id, acc]) => {
- // Same rounding as the prompt-level rate (getPromptVisibilitySummaries).
const rate = Math.round((acc.visible / acc.n) * 1000) / 10;
- const prevRate = acc.prevN > 0 ? (acc.prevVisible / acc.prevN) * 100 : null;
+ // AI Visibility Score over the topic's answers, per window — same
+ // blend as the Topics page so the two surfaces agree.
+ const score =
+ computeAiVisibilityScore({
+ answers: acc.n,
+ mentionAnswers: acc.mentionAnswers,
+ citationAnswers: acc.citationAnswers,
+ positionFactor: acc.posN > 0 ? acc.posSum / acc.posN : null,
+ }) ?? 0;
+ const prevScore =
+ acc.prevN > 0
+ ? (computeAiVisibilityScore({
+ answers: acc.prevN,
+ mentionAnswers: acc.prevMentionAnswers,
+ citationAnswers: acc.prevCitationAnswers,
+ positionFactor: acc.prevPosN > 0 ? acc.prevPosSum / acc.prevPosN : null,
+ }) ?? 0)
+ : null;
return {
name: nameById.get(id)!,
avgVisibility: round1(acc.sumVis / acc.n),
visibilityRate: rate,
- change: prevRate === null ? null : round1(rate - prevRate),
+ score,
+ change: prevScore === null ? null : round1(score - prevScore),
results: acc.n,
};
})
- .sort((a, b) => b.results - a.results || b.visibilityRate - a.visibilityRate)
+ .sort((a, b) => b.results - a.results || b.score - a.score)
.slice(0, REPORT_TOPIC_COUNT);
}
@@ -588,15 +691,40 @@ async function getReportVisibilityRate(
brandId: string,
range: { dateFrom: string; dateTo: string },
): Promise<ReportVisibilityRate> {
- const [rate, tracked] = await Promise.all([
+ const supabase = await createClient();
+ const [rate, tracked, visRes] = await Promise.all([
getVisibilityRateKpi(brandId, range),
getTrackedPromptsKpi(brandId, range),
+ supabase.rpc('ai_visibility_aggregates', {
+ p_brand_id: brandId,
+ p_platform: null,
+ p_models: null,
+ p_region: null,
+ p_date_from: range.dateFrom,
+ p_date_to: range.dateTo,
+ p_prompt_id: null,
+ p_topic_id: null,
+ }),
]);
const promptCount = tracked.activeInPeriod;
+ const vis = (visRes.data ?? {}) as {
+ answers?: number;
+ mention_answers?: number;
+ citation_answers?: number;
+ position_factor?: number | null;
+ };
+ const answers = Number(vis.answers ?? 0);
+ const mentionAnswers = Number(vis.mention_answers ?? 0);
+ const citationAnswers = Number(vis.citation_answers ?? 0);
+ const positionFactor = vis.position_factor ?? null;
return {
visiblePrompts: rate.visiblePrompts,
promptCount,
ratePct: promptCount > 0 ? Math.round((rate.visiblePrompts / promptCount) * 1000) / 10 : 0,
+ score: computeAiVisibilityScore({ answers, mentionAnswers, citationAnswers, positionFactor }),
+ mentionAnswers,
+ citationAnswers,
+ positionFactor,
};
}
diff --git a/web/src/lib/actions/topic.ts b/web/src/lib/actions/topic.ts
index cf2727af2..be05222bb 100644
--- a/web/src/lib/actions/topic.ts
+++ b/web/src/lib/actions/topic.ts
@@ -1,6 +1,7 @@
'use server';
import { createClient } from '@/lib/supabase/server';
+import { computeAiVisibilityScore } from '@/lib/visibility-score';
import type { CompetitorMention, Topic } from '@/types';
function mapTopicRow(row: Record<string, unknown>): Topic {
@@ -222,6 +223,21 @@ export async function getTopicsOverview(brandId: string): Promise<TopicOverviewS
prevVisiblePrompts: Set<string>;
totalMentions: number;
totalCitations: number;
+ answers: number;
+ mentionAnswers: number;
+ citationAnswers: number;
+ posSum: number;
+ posN: number;
+ curAnswers: number;
+ curMentionAnswers: number;
+ curCitationAnswers: number;
+ curPosSum: number;
+ curPosN: number;
+ prevAnswers: number;
+ prevMentionAnswers: number;
+ prevCitationAnswers: number;
+ prevPosSum: number;
+ prevPosN: number;
brandMentions: number;
compMentions: number;
lastRunAt: number;
@@ -237,6 +253,21 @@ export async function getTopicsOverview(brandId: string): Promise<TopicOverviewS
prevVisiblePrompts: new Set(),
totalMentions: 0,
totalCitations: 0,
+ answers: 0,
+ mentionAnswers: 0,
+ citationAnswers: 0,
+ posSum: 0,
+ posN: 0,
+ curAnswers: 0,
+ curMentionAnswers: 0,
+ curCitationAnswers: 0,
+ curPosSum: 0,
+ curPosN: 0,
+ prevAnswers: 0,
+ prevMentionAnswers: 0,
+ prevCitationAnswers: 0,
+ prevPosSum: 0,
+ prevPosN: 0,
brandMentions: 0,
compMentions: 0,
lastRunAt: 0,
@@ -282,12 +313,36 @@ export async function getTopicsOverview(brandId: string): Promise<TopicOverviewS
agg.brandMentions += mentions;
if (ts > agg.lastRunAt) agg.lastRunAt = ts;
+ // AI Visibility Score components (answer-level).
+ const pos = row.mention_position as number | null;
+ agg.answers += 1;
+ if (mentions > 0) agg.mentionAnswers += 1;
+ if (citations > 0) agg.citationAnswers += 1;
+ if (pos !== null && pos !== undefined && pos > 0) {
+ agg.posSum += 1 / pos;
+ agg.posN += 1;
+ }
+
if (ts >= curFrom) {
agg.curPrompts.add(promptId);
if (visible) agg.curVisiblePrompts.add(promptId);
+ agg.curAnswers += 1;
+ if (mentions > 0) agg.curMentionAnswers += 1;
+ if (citations > 0) agg.curCitationAnswers += 1;
+ if (pos !== null && pos !== undefined && pos > 0) {
+ agg.curPosSum += 1 / pos;
+ agg.curPosN += 1;
+ }
} else if (ts >= prevFrom) {
agg.prevPrompts.add(promptId);
if (visible) agg.prevVisiblePrompts.add(promptId);
+ agg.prevAnswers += 1;
+ if (mentions > 0) agg.prevMentionAnswers += 1;
+ if (citations > 0) agg.prevCitationAnswers += 1;
+ if (pos !== null && pos !== undefined && pos > 0) {
+ agg.prevPosSum += 1 / pos;
+ agg.prevPosN += 1;
+ }
}
const day = createdAt.slice(0, 10);
@@ -320,7 +375,7 @@ export async function getTopicsOverview(brandId: string): Promise<TopicOverviewS
const { data, error } = await supabase
.from('prompt_results')
.select(
- 'prompt_id, created_at, visibility_score, mention_count, citation_count, competitor_mentions',
+ 'prompt_id, created_at, visibility_score, mention_count, citation_count, mention_position, competitor_mentions',
)
.eq('brand_id', brandId)
.neq('platform', 'chatgpt-shopping')
@@ -340,14 +395,45 @@ export async function getTopicsOverview(brandId: string): Promise<TopicOverviewS
const agg = aggByTopic.get(t.id) ?? emptyAgg();
const promptCount = promptCountByTopic.get(t.id) ?? 0;
- const rateOf = (visible: number, total: number) =>
- total > 0 ? Math.round((visible / total) * 1000) / 10 : 0;
- const visibilityRate = rateOf(agg.visiblePrompts.size, agg.allPrompts.size);
+ // Visibility Rate now IS the AI Visibility Score over the topic's
+ // answers — same blend as the Insights headline (see lib/visibility-score).
+ const scoreOf = (
+ answers: number,
+ mention: number,
+ citation: number,
+ posSum: number,
+ posN: number,
+ ) =>
+ computeAiVisibilityScore({
+ answers,
+ mentionAnswers: mention,
+ citationAnswers: citation,
+ positionFactor: posN > 0 ? posSum / posN : null,
+ }) ?? 0;
+ const visibilityRate = scoreOf(
+ agg.answers,
+ agg.mentionAnswers,
+ agg.citationAnswers,
+ agg.posSum,
+ agg.posN,
+ );
const change =
- agg.curPrompts.size > 0 && agg.prevPrompts.size > 0
+ agg.curAnswers > 0 && agg.prevAnswers > 0
? Math.round(
- (rateOf(agg.curVisiblePrompts.size, agg.curPrompts.size) -
- rateOf(agg.prevVisiblePrompts.size, agg.prevPrompts.size)) *
+ (scoreOf(
+ agg.curAnswers,
+ agg.curMentionAnswers,
+ agg.curCitationAnswers,
+ agg.curPosSum,
+ agg.curPosN,
+ ) -
+ scoreOf(
+ agg.prevAnswers,
+ agg.prevMentionAnswers,
+ agg.prevCitationAnswers,
+ agg.prevPosSum,
+ agg.prevPosN,
+ )) *
10,
) / 10
: null;
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 6462b68e7..3f8c633fb 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -2,6 +2,7 @@
import { createClient } from '@/lib/supabase/server';
import { expandDateToEndOfDay } from '@/lib/dates';
+import { computeAiVisibilityScore } from '@/lib/visibility-score';
import type {
PromptResult,
AIPlatform,
@@ -115,10 +116,15 @@ export interface PromptDetailData {
};
summary: {
avgVisibilityScore: number;
- /** visibleResults / totalResults as a percentage, one decimal. */
+ /** visibleResults / totalResults as a percentage, one decimal (coverage). */
visibilityRate: number;
/** Results with >= 1 brand mention/citation. */
visibleResults: number;
+ /** AI Visibility Score (0-100) over this prompt's loaded answers. */
+ score: number | null;
+ mentionAnswers: number;
+ citationAnswers: number;
+ positionFactor: number | null;
totalMentions: number;
totalCitations: number;
totalResults: number;
@@ -918,6 +924,24 @@ export async function getPromptDetail(
const visibilityRate =
totalResults > 0 ? Math.round((visibleResults / totalResults) * 1000) / 10 : 0;
+ // AI Visibility Score over the same answer set — identical blend to the
+ // All Prompts column and the Insights headline.
+ const mentionAnswers = results.filter((row) => row.mentionCount > 0).length;
+ const citationAnswers = results.filter((row) => row.citationCount > 0).length;
+ const positionValues = rows
+ .map((row) => row.mention_position as number | null)
+ .filter((pos): pos is number => pos !== null && pos !== undefined && pos > 0);
+ const positionFactor =
+ positionValues.length > 0
+ ? positionValues.reduce((sum, pos) => sum + 1 / pos, 0) / positionValues.length
+ : null;
+ const score = computeAiVisibilityScore({
+ answers: totalResults,
+ mentionAnswers,
+ citationAnswers,
+ positionFactor,
+ });
+
// Aggregate citations by domain — same shape and rounding as getCitationsOverview,
// but scoped to this prompt's already-loaded results.
interface SourceAgg {
@@ -1010,6 +1034,10 @@ export async function getPromptDetail(
avgVisibilityScore,
visibilityRate,
visibleResults,
+ score,
+ mentionAnswers,
+ citationAnswers,
+ positionFactor,
totalMentions: results.reduce((sum, row) => sum + row.mentionCount, 0),
totalCitations: results.reduce((sum, row) => sum + row.citationCount, 0),
totalResults,
@@ -1321,8 +1349,16 @@ export interface PromptVisibilitySummary {
runs: number;
/** Runs with >= 1 brand mention/citation — numerator of the prompt-level rate. */
visibleRuns: number;
- /** visibleRuns / runs as a percentage, one decimal — same rounding as the Insights headline. */
+ /** visibleRuns / runs as a percentage, one decimal (coverage, secondary). */
visibilityRate: number;
+ /** AI Visibility Score (0-100) over this prompt's answers; null when no runs. */
+ score: number | null;
+ /** Answers mentioning the brand (score component). */
+ mentionAnswers: number;
+ /** Answers citing the brand's domain (score component). */
+ citationAnswers: number;
+ /** Mean of 1/position over mentioning answers; null when never mentioned. */
+ positionFactor: number | null;
lastRunAt: string;
}
@@ -1358,6 +1394,9 @@ export async function getPromptVisibilitySummaries(
for (const row of data ?? []) {
const runs = Number(row.runs ?? 0);
const visibleRuns = Number(row.visible_runs ?? 0);
+ const mentionAnswers = Number(row.mention_answers ?? 0);
+ const citationAnswers = Number(row.citation_answers ?? 0);
+ const positionFactor = row.position_factor ?? null;
result[row.prompt_id] = {
avgVisibility: row.avg_visibility ?? 0,
avgVisibilityVisible: row.avg_visibility_visible ?? null,
@@ -1366,6 +1405,15 @@ export async function getPromptVisibilitySummaries(
runs,
visibleRuns,
visibilityRate: runs > 0 ? Math.round((visibleRuns / runs) * 1000) / 10 : 0,
+ score: computeAiVisibilityScore({
+ answers: runs,
+ mentionAnswers,
+ citationAnswers,
+ positionFactor,
+ }),
+ mentionAnswers,
+ citationAnswers,
+ positionFactor,
lastRunAt: row.last_run_at,
};
}
@@ -1406,6 +1454,72 @@ export async function getBrandPrompts(
}));
}
+/** Raw shape of the ai_visibility_aggregates RPC payload (00040). */
+interface AiVisibilityAggregatesRow {
+ answers: number;
+ mention_answers: number;
+ citation_answers: number;
+ position_factor: number | null;
+ by_competitor: {
+ competitor_id: string;
+ name: string | null;
+ mention_answers: number;
+ citation_answers: number;
+ position_factor: number | null;
+ }[];
+}
+
+interface AiVisibilityWindow {
+ answers: number;
+ brandScore: number | null;
+ brandComponents: {
+ mentionAnswers: number;
+ citationAnswers: number;
+ positionFactor: number | null;
+ };
+ compScore: Map<string, number | null>;
+ compComponents: Map<
+ string,
+ { mentionAnswers: number; citationAnswers: number; positionFactor: number | null }
+ >;
+}
+
+/**
+ * Fold an ai_visibility_aggregates payload into per-entity scores. Every
+ * entity divides by the same answer count (the brand's filtered answers),
+ * so brand and competitor scores are directly comparable.
+ */
+function foldAiVisibility(raw: unknown): AiVisibilityWindow {
+ const row = (raw ?? {}) as AiVisibilityAggregatesRow;
+ const answers = Number(row.answers ?? 0);
+ const brandComponents = {
+ mentionAnswers: Number(row.mention_answers ?? 0),
+ citationAnswers: Number(row.citation_answers ?? 0),
+ positionFactor: row.position_factor === null ? null : Number(row.position_factor),
+ };
+ const compScore = new Map<string, number | null>();
+ const compComponents = new Map<
+ string,
+ { mentionAnswers: number; citationAnswers: number; positionFactor: number | null }
+ >();
+ for (const c of row.by_competitor ?? []) {
+ const components = {
+ mentionAnswers: Number(c.mention_answers ?? 0),
+ citationAnswers: Number(c.citation_answers ?? 0),
+ positionFactor: c.position_factor === null ? null : Number(c.position_factor),
+ };
+ compComponents.set(c.competitor_id, components);
+ compScore.set(c.competitor_id, computeAiVisibilityScore({ answers, ...components }));
+ }
+ return {
+ answers,
+ brandScore: computeAiVisibilityScore({ answers, ...brandComponents }),
+ brandComponents,
+ compScore,
+ compComponents,
+ };
+}
+
export interface CompetitorComparisonEntry {
name: string;
avgVisibilityScore: number;
@@ -1425,6 +1539,20 @@ export interface CompetitorComparisonEntry {
* `null` when there is no comparable previous-period value.
*/
change: number | null;
+ /**
+ * AI Visibility Score (0-100, one decimal): 0.6×mention rate +
+ * 0.25×citation rate + 0.15×position factor, all over the brand's
+ * filtered answers (shared denominator). Null when the window is empty.
+ */
+ score: number | null;
+ /** Score point change vs the previous comparable window; null without one. */
+ scoreChange: number | null;
+ /** Answers naming this entity (numerator of the mention component). */
+ mentionAnswers: number;
+ /** Answers citing this entity's own domain. */
+ citationAnswers: number;
+ /** Mean of 1/position over answers naming the entity; null when never named. */
+ positionFactor: number | null;
totalMentions: number;
totalCitations: number;
resultCount: number;
@@ -1506,17 +1634,24 @@ export async function getCompetitorComparison(
p_topic_id: opts?.topicId ?? null,
};
- // Brand name + the displayed-period aggregate fire in parallel — both
+ // Brand name + the displayed-period aggregates fire in parallel — all
// are needed before we can shape the response.
- const [{ data: brand }, { data: aggDisplay, error: aggErr }] = await Promise.all([
+ const [{ data: brand }, { data: aggDisplay, error: aggErr }, visDisplayRes] = await Promise.all([
supabase.from('brands').select('name').eq('id', brandId).single(),
supabase.rpc('competitor_aggregates', {
...baseArgs,
p_date_from: opts?.dateFrom ?? null,
p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? null,
}),
+ supabase.rpc('ai_visibility_aggregates', {
+ ...baseArgs,
+ p_date_from: opts?.dateFrom ?? null,
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? null,
+ }),
]);
if (aggErr) throw new Error(aggErr.message);
+ if (visDisplayRes.error) throw new Error(visDisplayRes.error.message);
+ const visDisplay = foldAiVisibility(visDisplayRes.data);
const agg = aggDisplay as unknown as CompetitorAggregatesRow;
if (agg.brand_row_count === 0) return { brands: [], providerRows: [] };
@@ -1541,7 +1676,7 @@ export async function getCompetitorComparison(
const duration = currentTo.getTime() - currentFrom.getTime();
const prevFrom = new Date(currentFrom.getTime() - duration);
- const [curRes, prevRes] = await Promise.all([
+ const [curRes, prevRes, visPrevRes] = await Promise.all([
supabase.rpc('competitor_aggregates', {
...baseArgs,
p_date_from: opts?.dateFrom ?? currentFrom.toISOString(),
@@ -1552,9 +1687,21 @@ export async function getCompetitorComparison(
p_date_from: prevFrom.toISOString(),
p_date_to: currentFrom.toISOString(),
}),
+ supabase.rpc('ai_visibility_aggregates', {
+ ...baseArgs,
+ p_date_from: prevFrom.toISOString(),
+ p_date_to: currentFrom.toISOString(),
+ }),
]);
if (curRes.error) throw new Error(curRes.error.message);
if (prevRes.error) throw new Error(prevRes.error.message);
+ // Score delta compares the displayed window against the one immediately
+ // before it; a previous-window failure only costs the delta, not the page.
+ const visPrev = visPrevRes.error ? null : foldAiVisibility(visPrevRes.data);
+ const scoreDiff = (cur: number | null, prev: number | null | undefined): number | null => {
+ if (cur === null || prev === null || prev === undefined) return null;
+ return Math.round((cur - prev) * 10) / 10;
+ };
const curWin = curRes.data as unknown as CompetitorAggregatesRow | null;
const prevWin = prevRes.data as unknown as CompetitorAggregatesRow | null;
@@ -1614,6 +1761,11 @@ export async function getCompetitorComparison(
visiblePrompts: agg.brand_visible_prompts,
promptCount: agg.brand_prompt_count,
change: rateDiff(curBrandRate, prevBrandRate),
+ score: visDisplay.brandScore,
+ scoreChange: scoreDiff(visDisplay.brandScore, visPrev?.brandScore),
+ mentionAnswers: visDisplay.brandComponents.mentionAnswers,
+ citationAnswers: visDisplay.brandComponents.citationAnswers,
+ positionFactor: visDisplay.brandComponents.positionFactor,
totalMentions: agg.brand_total_mentions,
totalCitations: agg.brand_total_citations,
resultCount: agg.brand_row_count,
@@ -1625,6 +1777,7 @@ export async function getCompetitorComparison(
// Same-denominator rule as the window rates above (agg.brand_row_count
// is guaranteed > 0 by the early return).
const avg = Math.round(c.sum_visibility / agg.brand_row_count);
+ const compComponents = visDisplay.compComponents.get(c.competitor_id);
entries.push({
name: competitorDisplayName(c.name, c.competitor_id),
avgVisibilityScore: avg,
@@ -1635,6 +1788,14 @@ export async function getCompetitorComparison(
curCompRate.get(c.competitor_id) ?? null,
prevCompRate.get(c.competitor_id) ?? null,
),
+ score: visDisplay.compScore.get(c.competitor_id) ?? null,
+ scoreChange: scoreDiff(
+ visDisplay.compScore.get(c.competitor_id) ?? null,
+ visPrev?.compScore.get(c.competitor_id),
+ ),
+ mentionAnswers: compComponents?.mentionAnswers ?? 0,
+ citationAnswers: compComponents?.citationAnswers ?? 0,
+ positionFactor: compComponents?.positionFactor ?? null,
totalMentions: c.total_mentions,
totalCitations: c.total_citations,
resultCount: c.row_count,
@@ -1642,7 +1803,7 @@ export async function getCompetitorComparison(
});
}
- entries.sort((a, b) => b.visibilityRate - a.visibilityRate || b.totalMentions - a.totalMentions);
+ entries.sort((a, b) => (b.score ?? -1) - (a.score ?? -1) || b.totalMentions - a.totalMentions);
// --- Per-provider breakdown ---
// resolveProvider stays in JS so we don't keep a SQL copy of the mapping
@@ -1997,7 +2158,17 @@ interface VisibilityRateTrendRow {
day: string;
prompt_count: number;
visible_prompts: number;
- competitors: { competitor_id: string; visible_prompts: number }[];
+ answers: number;
+ mention_answers: number;
+ citation_answers: number;
+ position_factor: number | null;
+ competitors: {
+ competitor_id: string;
+ visible_prompts: number;
+ mention_answers: number;
+ citation_answers: number;
+ position_factor: number | null;
+ }[];
}
/**
@@ -2041,25 +2212,20 @@ export async function getVisibilityRateTrend(
{ data: brandDomains },
{ data: competitors },
rpcRes,
- curStats,
- curTracked,
- prevStats,
- prevTracked,
+ visCurRes,
+ visPrevRes,
] = await Promise.all([
supabase.from('brands').select('name, logo_url').eq('id', brandId).single(),
supabase.from('brand_domains').select('domain, is_primary').eq('brand_id', brandId),
supabase.from('competitors').select('id, name, domain').eq('brand_id', brandId),
supabase.rpc('visibility_rate_trend', rateArgs(dateFrom, dateTo)),
- supabase.rpc('visible_prompt_stats', rateArgs(dateFrom, dateTo)),
- supabase.rpc('tracked_prompt_count', rateArgs(dateFrom, dateTo)),
- supabase.rpc('visible_prompt_stats', rateArgs(prevFrom, prevTo)),
- supabase.rpc('tracked_prompt_count', rateArgs(prevFrom, prevTo)),
+ supabase.rpc('ai_visibility_aggregates', rateArgs(dateFrom, dateTo)),
+ supabase.rpc('ai_visibility_aggregates', rateArgs(prevFrom, prevTo)),
]);
if (rpcRes.error) throw new Error(rpcRes.error.message);
+ if (visCurRes.error) throw new Error(visCurRes.error.message);
const rows = (rpcRes.data ?? []) as unknown as VisibilityRateTrendRow[];
- const rate = (visible: number, total: number) =>
- total > 0 ? Math.round((visible / total) * 1000) / 10 : 0;
const primaryDomain =
(brandDomains ?? []).find((d) => d.is_primary)?.domain ?? brandDomains?.[0]?.domain ?? null;
@@ -2081,13 +2247,28 @@ export async function getVisibilityRateTrend(
})),
];
+ // Each day's value is the AI Visibility Score computed over that day's
+ // answers — same blend as every other surface, shared denominator.
const points: VisibilityRateTrendPoint[] = rows.map((row) => {
const values: Record<string, number> = {
- you: rate(row.visible_prompts, row.prompt_count),
+ you:
+ computeAiVisibilityScore({
+ answers: row.answers,
+ mentionAnswers: row.mention_answers,
+ citationAnswers: row.citation_answers,
+ positionFactor: row.position_factor,
+ }) ?? 0,
};
- const byId = new Map(row.competitors.map((c) => [c.competitor_id, c.visible_prompts]));
+ const byId = new Map(row.competitors.map((c) => [c.competitor_id, c]));
for (const c of competitors ?? []) {
- values[c.id] = rate(byId.get(c.id) ?? 0, row.prompt_count);
+ const entry = byId.get(c.id);
+ values[c.id] =
+ computeAiVisibilityScore({
+ answers: row.answers,
+ mentionAnswers: entry?.mention_answers ?? 0,
+ citationAnswers: entry?.citation_answers ?? 0,
+ positionFactor: entry?.position_factor ?? null,
+ }) ?? 0;
}
return {
date: new Date(row.day + 'T00:00:00').toLocaleDateString('en-US', {
@@ -2098,20 +2279,18 @@ export async function getVisibilityRateTrend(
};
});
- // Headline: overall window rate (distinct prompts over the whole window —
- // not an average of the daily points) plus the delta vs the previous
- // equal-length window, same RPC pair as the Insights KPI header.
- const curVisible = (curStats.data as { visible_prompts?: number } | null)?.visible_prompts ?? 0;
- const curCount = (curTracked.data as number | null) ?? 0;
- const prevVisible = (prevStats.data as { visible_prompts?: number } | null)?.visible_prompts ?? 0;
- const prevCount = (prevTracked.data as number | null) ?? 0;
- const headlineRate = rate(curVisible, curCount);
- const prevRate = prevCount > 0 ? rate(prevVisible, prevCount) : null;
+ // Headline: overall window score (components over the whole window — not
+ // an average of the daily points) plus the delta vs the previous
+ // equal-length window. Same RPC the leaderboard uses.
+ const visCur = foldAiVisibility(visCurRes.data);
+ const visPrev = visPrevRes.error ? null : foldAiVisibility(visPrevRes.data);
+ const headlineScore = visCur.brandScore ?? 0;
+ const prevScore = visPrev?.brandScore ?? null;
const summary: VisibilityRateTrendSummary = {
- rate: headlineRate,
- prevRate,
- change: prevRate === null ? null : Math.round((headlineRate - prevRate) * 10) / 10,
+ rate: headlineScore,
+ prevRate: prevScore,
+ change: prevScore === null ? null : Math.round((headlineScore - prevScore) * 10) / 10,
prevFrom,
prevTo,
};