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.

fix(reports): lead the KPI section with the visibility rate, with a fallback for old snapshots (#515)

Patel Dhritdaa874ce3d7b
diff --git a/server/src/routes/reports.js b/server/src/routes/reports.js
index 24beecc52..ed2123f03 100644
--- a/server/src/routes/reports.js
+++ b/server/src/routes/reports.js
@@ -25,7 +25,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.
Write a 1-2 paragraph executive summary in English for a marketing executive. It must tell the CHANGE STORY of the period, not describe a static snapshot:
-- Open with the headline movement as an arc — e.g. "Visibility climbed from 42 to 48" — using the trend's first/last points or the KPI deltas.
+- Open with the headline movement as an arc — e.g. "Visibility climbed from 42 to 48" — using the trend's first/last points or the KPI deltas. When the snapshot includes visibilityRate.ratePct, that — not insights.avgVisibilityScore — is the headline visibility number: the report's KPI section leads with it, so the summary must agree with it. visibilityRate has no previous-period value in the snapshot, so state its ratePct as a plain current fact and never invent a change or percentage-point delta for it — do not subtract or compare it against insights.avgVisibilityScore or insights.visibilityChange, which describe a different metric's history. Draw the period's change story from metrics that do carry real deltas: mentions, citations, sentiment, share of voice, competitor movement.
- Name the DRIVER behind that movement when the data shows one: the platform, topic or prompt that moved most (share-of-voice shifts, best/weakest prompts, topic deltas).
- Name the biggest RISK when the data shows one: a competitor gaining ground, a topic or platform sliding, or citation share concentrating away from the brand.
- Close with the single most consequential implication or next focus, in one sentence.
diff --git a/web/messages/en.json b/web/messages/en.json
index a7e797228..e2cc070d5 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -502,6 +502,9 @@
"executiveSummary": "Executive Summary",
"kpi": {
"visibility": "Visibility",
+ "visibilityRate": "Visibility Rate",
+ "visibilityRateSub": "{visible}/{total} prompts",
+ "avgScore": "Avg. Score",
"mentions": "Mentions",
"citations": "Brand Citations",
"sentiment": "Positive Sentiment"
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 2abdd4159..e750f5fa5 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
@@ -68,6 +68,7 @@ const styles = StyleSheet.create({
kpiLabel: { fontSize: 7, color: MUTED, textTransform: 'uppercase', marginBottom: 3 },
kpiValueRow: { flexDirection: 'row', alignItems: 'flex-end', gap: 4 },
kpiValue: { fontSize: 14, fontWeight: 700 },
+ kpiSub: { fontSize: 7, color: MUTED, marginTop: 2 },
delta: { fontSize: 8, marginBottom: 1 },
axisLabelRow: {
flexDirection: 'row',
@@ -233,6 +234,57 @@ export function ReportPdfDocument({ report }: { report: Report }) {
const maxSov = Math.max(...(payload.shareOfVoice?.byPlatform.map((p) => p.sov) ?? []), 1);
const trend = payload.visibilityTrend ?? [];
const hasCompetitorTrend = trend.some((d) => d.competitors !== null);
+ // Reports generated before #492 have no `visibilityRate` — fall back to
+ // the old score-only KPI box so those snapshots keep rendering unchanged.
+ const kpiEntries: { label: string; value: string; change: number | null; sub?: string }[] =
+ payload.insights
+ ? [
+ ...(payload.visibilityRate
+ ? [
+ {
+ label: 'Visibility Rate',
+ value: `${payload.visibilityRate.ratePct}%`,
+ change: null,
+ sub: `${payload.visibilityRate.visiblePrompts}/${payload.visibilityRate.promptCount} prompts`,
+ },
+ {
+ label: 'Avg. Score',
+ value: `${payload.insights.avgVisibilityScore}%`,
+ change: payload.insights.visibilityChange,
+ },
+ ]
+ : [
+ {
+ label: 'Visibility',
+ value: `${payload.insights.avgVisibilityScore}%`,
+ change: payload.insights.visibilityChange,
+ },
+ ]),
+ {
+ label: 'Mentions',
+ value: String(payload.insights.totalMentions),
+ change: payload.insights.mentionsChange,
+ },
+ {
+ label: 'Brand Citations',
+ value: String(payload.insights.totalCitations),
+ change: payload.insights.citationsChange,
+ },
+ {
+ label: 'Positive Sentiment',
+ value: `${payload.insights.positiveSentimentPct}%`,
+ change: payload.insights.sentimentChange,
+ },
+ ]
+ : [];
+ // Reports generated before #492 stored competitor entries without these
+ // fields even though the type now declares them required — check at
+ // runtime rather than trusting the type for immutable, pre-existing data.
+ const hasCompetitorVisibilityRate = Boolean(
+ payload.competitors?.length &&
+ typeof payload.competitors[0].visibilityRate === 'number' &&
+ typeof payload.competitors[0].promptCount === 'number',
+ );
return (
<Document title={report.title} author="Ansvisor" creator="Ansvisor">
@@ -254,36 +306,14 @@ export function ReportPdfDocument({ report }: { report: Report }) {
{/* KPI row */}
{payload.insights && (
<View style={[styles.section, styles.kpiRow]} wrap={false}>
- {(
- [
- [
- 'Visibility',
- `${payload.insights.avgVisibilityScore}%`,
- payload.insights.visibilityChange,
- ],
- [
- 'Mentions',
- String(payload.insights.totalMentions),
- payload.insights.mentionsChange,
- ],
- [
- 'Brand Citations',
- String(payload.insights.totalCitations),
- payload.insights.citationsChange,
- ],
- [
- 'Positive Sentiment',
- `${payload.insights.positiveSentimentPct}%`,
- payload.insights.sentimentChange,
- ],
- ] as const
- ).map(([label, value, change]) => (
- <View key={label} style={styles.kpiBox}>
- <Text style={styles.kpiLabel}>{label}</Text>
+ {kpiEntries.map((entry) => (
+ <View key={entry.label} style={styles.kpiBox}>
+ <Text style={styles.kpiLabel}>{entry.label}</Text>
<View style={styles.kpiValueRow}>
- <Text style={styles.kpiValue}>{value}</Text>
- <DeltaText value={change} />
+ <Text style={styles.kpiValue}>{entry.value}</Text>
+ <DeltaText value={entry.change} />
</View>
+ {entry.sub && <Text style={styles.kpiSub}>{entry.sub}</Text>}
</View>
))}
</View>
@@ -342,7 +372,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' }]}>
- Visibility
+ {hasCompetitorVisibilityRate ? 'Visibility Rate' : 'Visibility'}
</Text>
<Text style={[styles.tableHeaderCell, { width: 50, textAlign: 'right' }]}>
Change
@@ -366,9 +396,16 @@ export function ReportPdfDocument({ report }: { report: Report }) {
{c.name}
{c.isOwnBrand ? ' (you)' : ''}
</Text>
- <Text style={[styles.cell, { width: 60, textAlign: 'right' }]}>
- {c.avgVisibilityScore}%
- </Text>
+ <View style={{ width: 60, alignItems: 'flex-end' }}>
+ <Text style={styles.cell}>
+ {hasCompetitorVisibilityRate ? c.visibilityRate : c.avgVisibilityScore}%
+ </Text>
+ {hasCompetitorVisibilityRate && (
+ <Text style={styles.kpiSub}>
+ {c.visiblePrompts}/{c.promptCount} prompts
+ </Text>
+ )}
+ </View>
<View style={{ width: 50, alignItems: 'flex-end' }}>
<DeltaText value={c.change} />
</View>
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 21d304b9c..1a79fd00e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx
@@ -56,10 +56,12 @@ function KpiCard({
label,
value,
change,
+ sub,
}: {
label: string;
value: string;
change: number | null;
+ sub?: string;
}) {
return (
<Card>
@@ -71,6 +73,7 @@ function KpiCard({
<span className="text-2xl font-bold">{value}</span>
<Delta value={change} />
</div>
+ {sub && <p className="mt-1 text-xs text-muted-foreground">{sub}</p>}
</CardContent>
</Card>
);
@@ -125,6 +128,14 @@ export default function ReportDetailPage() {
const { payload } = report;
const maxSov = Math.max(...(payload.shareOfVoice?.byPlatform.map((p) => p.sov) ?? []), 1);
+ // Reports generated before #492 stored competitor entries without these
+ // fields even though the type now declares them required — check at
+ // runtime rather than trusting the type for immutable, pre-existing data.
+ const hasCompetitorVisibilityRate = Boolean(
+ payload.competitors?.length &&
+ typeof payload.competitors[0].visibilityRate === 'number' &&
+ typeof payload.competitors[0].promptCount === 'number',
+ );
// Render a true vector PDF from the saved payload with @react-pdf/renderer
// (selectable text, exact layout — no screenshot artifacts). The renderer
@@ -207,12 +218,38 @@ export default function ReportDetailPage() {
gather their own sections, and older (immutable) reports may
predate a field entirely. */}
{payload.insights && (
- <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
- <KpiCard
- label={t('kpi.visibility')}
- value={`${payload.insights.avgVisibilityScore}%`}
- change={payload.insights.visibilityChange}
- />
+ <div
+ className={cn(
+ 'grid gap-4',
+ payload.visibilityRate
+ ? 'grid-cols-2 sm:grid-cols-3 xl:grid-cols-5'
+ : 'sm:grid-cols-2 lg:grid-cols-4',
+ )}
+ >
+ {payload.visibilityRate ? (
+ <>
+ <KpiCard
+ label={t('kpi.visibilityRate')}
+ value={`${payload.visibilityRate.ratePct}%`}
+ change={null}
+ sub={t('kpi.visibilityRateSub', {
+ visible: payload.visibilityRate.visiblePrompts,
+ total: payload.visibilityRate.promptCount,
+ })}
+ />
+ <KpiCard
+ label={t('kpi.avgScore')}
+ value={`${payload.insights.avgVisibilityScore}%`}
+ change={payload.insights.visibilityChange}
+ />
+ </>
+ ) : (
+ <KpiCard
+ label={t('kpi.visibility')}
+ value={`${payload.insights.avgVisibilityScore}%`}
+ change={payload.insights.visibilityChange}
+ />
+ )}
<KpiCard
label={t('kpi.mentions')}
value={String(payload.insights.totalMentions)}
@@ -228,7 +265,14 @@ export default function ReportDetailPage() {
value={`${payload.insights.positiveSentimentPct}%`}
change={payload.insights.sentimentChange}
/>
- <p className="text-xs text-muted-foreground sm:col-span-2 lg:col-span-4">
+ <p
+ className={cn(
+ 'text-xs text-muted-foreground',
+ payload.visibilityRate
+ ? 'col-span-2 sm:col-span-3 xl:col-span-5'
+ : 'sm:col-span-2 lg:col-span-4',
+ )}
+ >
{t('kpiCitationsNote')}
</p>
</div>
@@ -287,7 +331,11 @@ export default function ReportDetailPage() {
<TableHeader>
<TableRow>
<TableHead>{t('columns.brand')}</TableHead>
- <TableHead className="text-right">{t('kpi.visibility')}</TableHead>
+ <TableHead className="text-right">
+ {hasCompetitorVisibilityRate
+ ? t('kpi.visibilityRate')
+ : t('kpi.visibility')}
+ </TableHead>
<TableHead className="text-right">{t('columns.change')}</TableHead>
<TableHead className="text-right">{t('kpi.mentions')}</TableHead>
<TableHead className="text-right">{t('kpi.citations')}</TableHead>
@@ -302,7 +350,21 @@ export default function ReportDetailPage() {
<span className="ml-2 text-xs text-muted-foreground">{t('you')}</span>
)}
</TableCell>
- <TableCell className="text-right">{c.avgVisibilityScore}%</TableCell>
+ <TableCell className="text-right">
+ {hasCompetitorVisibilityRate ? (
+ <>
+ <div>{c.visibilityRate}%</div>
+ <div className="text-xs font-normal text-muted-foreground">
+ {t('kpi.visibilityRateSub', {
+ visible: c.visiblePrompts,
+ total: c.promptCount,
+ })}
+ </div>
+ </>
+ ) : (
+ `${c.avgVisibilityScore}%`
+ )}
+ </TableCell>
<TableCell className="text-right">
<Delta value={c.change} />
</TableCell>
diff --git a/web/src/lib/actions/reports.ts b/web/src/lib/actions/reports.ts
index 095a8e633..df360fd01 100644
--- a/web/src/lib/actions/reports.ts
+++ b/web/src/lib/actions/reports.ts
@@ -9,6 +9,8 @@ import {
getShareOfVoiceData,
getCompetitorComparison,
getVisibilityTrend,
+ getVisibilityRateKpi,
+ getTrackedPromptsKpi,
type InsightsSummary,
type CompetitorComparisonEntry,
type SoVByPlatform,
@@ -113,6 +115,16 @@ export interface ReportAuditScore {
auditedAt: string;
}
+/** Prompt-level Visibility Rate KPI (#492) — mirrors the Insights dashboard's headline metric. */
+export interface ReportVisibilityRate {
+ /** Distinct prompts the brand appeared in (the rate's numerator). */
+ visiblePrompts: number;
+ /** Distinct tracked prompts that produced results in the window (shared denominator). */
+ promptCount: number;
+ /** visiblePrompts / promptCount as a percentage, one decimal place. */
+ ratePct: number;
+}
+
/**
* All metric fields are optional: a template only gathers its own sections
* (see lib/reports/templates.ts), and the detail page + PDF render purely by
@@ -124,6 +136,8 @@ export interface ReportPayload {
/** AI-generated executive summary (plain prose). */
summaryText: string;
insights?: InsightsSummary;
+ /** Prompt-level Visibility Rate — leads the KPI row (#492); absent on reports generated before this shipped. */
+ visibilityRate?: ReportVisibilityRate;
/** Daily visibility trend over the report period. */
visibilityTrend?: VisibilityTrendPoint[];
/** Best/worst performing prompts in the period. */
@@ -496,6 +510,27 @@ async function getAuditSnapshot(brandId: string, dateTo: string): Promise<Report
};
}
+/**
+ * Visibility Rate KPI for the report snapshot (#492) — same shape and
+ * denominator as the Insights dashboard's headline metric, so a report's KPI
+ * row matches what the Insights page shows for the identical date range.
+ */
+async function getReportVisibilityRate(
+ brandId: string,
+ range: { dateFrom: string; dateTo: string },
+): Promise<ReportVisibilityRate> {
+ const [rate, tracked] = await Promise.all([
+ getVisibilityRateKpi(brandId, range),
+ getTrackedPromptsKpi(brandId, range),
+ ]);
+ const promptCount = tracked.activeInPeriod;
+ return {
+ visiblePrompts: rate.visiblePrompts,
+ promptCount,
+ ratePct: promptCount > 0 ? Math.round((rate.visiblePrompts / promptCount) * 1000) / 10 : 0,
+ };
+}
+
/** How many evidence rows a report keeps per evidence section (#429). */
const REPORT_EVIDENCE_COUNT = 10;
/** How many sourcing prompts each cited URL lists. */
@@ -735,6 +770,7 @@ export async function createReport(
// only the picked sections (null = section not gathered).
const [
insights,
+ visibilityRate,
sov,
comparison,
citations,
@@ -749,6 +785,7 @@ export async function createReport(
auditScore,
] = await Promise.all([
has('kpis') ? getInsightsSummary(brandId, range) : null,
+ has('kpis') ? getReportVisibilityRate(brandId, range) : null,
has('shareOfVoice') ? getShareOfVoiceData(brandId, range) : null,
has('competitors') ? getCompetitorComparison(brandId, range) : null,
has('citations')
@@ -768,6 +805,7 @@ export async function createReport(
const snapshot: Omit<ReportPayload, 'summaryText'> = {
brandName,
...(insights ? { insights } : {}),
+ ...(visibilityRate ? { visibilityRate } : {}),
...(trend ? { visibilityTrend: trend } : {}),
...(promptPerformance ? { promptPerformance } : {}),
...(mentionEvidence && mentionEvidence.length > 0 ? { mentionEvidence } : {}),