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: handle zero-base insight deltas (#521)

Abdullahe88ca92b073a
diff --git a/server/src/routes/reports.js b/server/src/routes/reports.js
index ed2123f03..f2ad84ecd 100644
--- a/server/src/routes/reports.js
+++ b/server/src/routes/reports.js
@@ -24,6 +24,8 @@ 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.
+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.
+
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. 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).
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index d4eb52b60..55f2aea0e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -213,6 +213,25 @@ function DeltaBadge({ delta, suffix = '%' }: { delta: number | null; suffix?: st
);
}
+function CountDeltaBadge({
+ current,
+ previous,
+ delta,
+}: {
+ current: number;
+ previous: number | null;
+ delta: number | null;
+}) {
+ if (previous === 0 && current > 0) {
+ return (
+ <span className="text-xs font-medium text-emerald-600 dark:text-emerald-400">
+ +{current} new
+ </span>
+ );
+ }
+ return <DeltaBadge delta={delta} />;
+}
+
// ─── KPI Card ─────────────────────────────────────────────────────────────────
function KpiCard({
@@ -1399,7 +1418,13 @@ export default function InsightsPage() {
tooltip="How many times your brand was referenced by name in AI-generated responses."
icon={Zap}
value={summary!.totalMentions}
- sub={<DeltaBadge delta={summary!.mentionsChange} />}
+ sub={
+ <CountDeltaBadge
+ current={summary!.totalMentions}
+ previous={summary!.prevMentions}
+ delta={summary!.mentionsChange}
+ />
+ }
subVariant={
summary!.mentionsChange !== null && summary!.mentionsChange > 0
? 'positive'
@@ -1412,7 +1437,13 @@ export default function InsightsPage() {
tooltip="Times your brand's domain was cited as a source with a direct link in AI responses."
icon={Quote}
value={summary!.totalCitations}
- sub={<DeltaBadge delta={summary!.citationsChange} />}
+ sub={
+ <CountDeltaBadge
+ current={summary!.totalCitations}
+ previous={summary!.prevCitations}
+ delta={summary!.citationsChange}
+ />
+ }
subVariant={
summary!.citationsChange !== null && summary!.citationsChange > 0
? 'positive'
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 e750f5fa5..d7664b2db 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
@@ -121,7 +121,10 @@ const styles = StyleSheet.create({
footerText: { fontSize: 7, color: MUTED },
});
-function DeltaText({ value }: { value: number | null }) {
+function DeltaText({ value, zeroBaseCount }: { value: number | null; zeroBaseCount?: number }) {
+ if (zeroBaseCount !== undefined) {
+ return <Text style={[styles.delta, { color: GREEN }]}>+{zeroBaseCount} new</Text>;
+ }
if (value === null) return null;
const up = value >= 0;
return (
@@ -236,47 +239,64 @@ export function ReportPdfDocument({ report }: { report: Report }) {
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,
- },
- ]
- : [];
+ const kpiEntries: {
+ label: string;
+ value: string;
+ change: number | null;
+ zeroBaseCount?: number;
+ 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,
+ zeroBaseCount:
+ Object.hasOwn(payload.insights, 'prevMentions') &&
+ payload.insights.prevMentions === 0 &&
+ payload.insights.totalMentions > 0
+ ? payload.insights.totalMentions
+ : undefined,
+ },
+ {
+ label: 'Brand Citations',
+ value: String(payload.insights.totalCitations),
+ change: payload.insights.citationsChange,
+ zeroBaseCount:
+ Object.hasOwn(payload.insights, 'prevCitations') &&
+ payload.insights.prevCitations === 0 &&
+ payload.insights.totalCitations > 0
+ ? payload.insights.totalCitations
+ : undefined,
+ },
+ {
+ 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.
@@ -311,7 +331,7 @@ export function ReportPdfDocument({ report }: { report: Report }) {
<Text style={styles.kpiLabel}>{entry.label}</Text>
<View style={styles.kpiValueRow}>
<Text style={styles.kpiValue}>{entry.value}</Text>
- <DeltaText value={entry.change} />
+ <DeltaText value={entry.change} zeroBaseCount={entry.zeroBaseCount} />
</View>
{entry.sub && <Text style={styles.kpiSub}>{entry.sub}</Text>}
</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 1a79fd00e..089119416 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx
@@ -40,8 +40,11 @@ function formatDate(iso: string) {
});
}
-/** Signed percentage delta with up/down coloring; renders nothing for null. */
-function Delta({ value }: { value: number | null }) {
+/** Signed percentage delta, or an explicit raw count for a new zero-base metric. */
+function Delta({ value, zeroBaseCount }: { value: number | null; zeroBaseCount?: number }) {
+ if (zeroBaseCount !== undefined) {
+ return <span className="text-xs font-medium text-emerald-600">+{zeroBaseCount} new</span>;
+ }
if (value === null) return null;
const up = value >= 0;
return (
@@ -56,11 +59,13 @@ function KpiCard({
label,
value,
change,
+ zeroBaseCount,
sub,
}: {
label: string;
value: string;
change: number | null;
+ zeroBaseCount?: number;
sub?: string;
}) {
return (
@@ -71,7 +76,7 @@ function KpiCard({
</p>
<div className="mt-1 flex items-baseline gap-2">
<span className="text-2xl font-bold">{value}</span>
- <Delta value={change} />
+ <Delta value={change} zeroBaseCount={zeroBaseCount} />
</div>
{sub && <p className="mt-1 text-xs text-muted-foreground">{sub}</p>}
</CardContent>
@@ -254,11 +259,25 @@ export default function ReportDetailPage() {
label={t('kpi.mentions')}
value={String(payload.insights.totalMentions)}
change={payload.insights.mentionsChange}
+ zeroBaseCount={
+ Object.hasOwn(payload.insights, 'prevMentions') &&
+ payload.insights.prevMentions === 0 &&
+ payload.insights.totalMentions > 0
+ ? payload.insights.totalMentions
+ : undefined
+ }
/>
<KpiCard
label={t('kpi.citations')}
value={String(payload.insights.totalCitations)}
change={payload.insights.citationsChange}
+ zeroBaseCount={
+ Object.hasOwn(payload.insights, 'prevCitations') &&
+ payload.insights.prevCitations === 0 &&
+ payload.insights.totalCitations > 0
+ ? payload.insights.totalCitations
+ : undefined
+ }
/>
<KpiCard
label={t('kpi.sentiment')}
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 573ca2c41..6a63b4d76 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -23,6 +23,7 @@ import { getOrgPlan } from '@/lib/guards/plan-guard';
import { getPromptVolumes } from '@/lib/actions/volumes';
import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';
import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';
+import { percentageChange } from '@/lib/metrics';
/** Round to one decimal place (keeps sub-1 averages visible instead of flooring to 0). */
function roundTo1(n: number): number {
@@ -135,8 +136,14 @@ export interface InsightsSummary {
resultCount: number;
}[];
visibilityChange: number | null;
+ /** Percentage change vs the previous period; null when the previous count is zero or unavailable. */
mentionsChange: number | null;
+ /** Percentage change vs the previous period; null when the previous count is zero or unavailable. */
citationsChange: number | null;
+ /** Raw previous-period count, used to distinguish a zero base from unavailable comparison data. */
+ prevMentions: number | null;
+ /** Raw previous-period count, used to distinguish a zero base from unavailable comparison data. */
+ prevCitations: number | null;
sentimentChange: number | null;
}
@@ -1056,6 +1063,8 @@ export async function getInsightsSummary(
visibilityChange: null,
mentionsChange: null,
citationsChange: null,
+ prevMentions: null,
+ prevCitations: null,
sentimentChange: null,
};
}
@@ -1082,6 +1091,8 @@ export async function getInsightsSummary(
let visibilityChange: number | null = null;
let mentionsChange: number | null = null;
let citationsChange: number | null = null;
+ let prevMentions: number | null = null;
+ let prevCitations: number | null = null;
let sentimentChange: number | null = null;
{
@@ -1131,19 +1142,13 @@ export async function getInsightsSummary(
const curSentimentPct = Math.round((curWin.positive_count / curWin.total_results) * 100);
const prevAvgVis = roundTo1(prevWin.sum_visibility / prevWin.total_results);
- const prevMentions = prevWin.total_mentions;
- const prevCitations = prevWin.total_citations;
+ prevMentions = prevWin.total_mentions;
+ prevCitations = prevWin.total_citations;
const prevSentimentPct = Math.round((prevWin.positive_count / prevWin.total_results) * 100);
visibilityChange = roundTo1(curAvgVis - prevAvgVis);
- mentionsChange =
- curMentions > 0 && prevMentions > 0
- ? Math.round(((curMentions - prevMentions) / prevMentions) * 100)
- : curMentions - prevMentions;
- citationsChange =
- curCitations > 0 && prevCitations > 0
- ? Math.round(((curCitations - prevCitations) / prevCitations) * 100)
- : curCitations - prevCitations;
+ mentionsChange = percentageChange(curMentions, prevMentions);
+ citationsChange = percentageChange(curCitations, prevCitations);
sentimentChange = curSentimentPct - prevSentimentPct;
}
}
@@ -1159,6 +1164,8 @@ export async function getInsightsSummary(
visibilityChange,
mentionsChange,
citationsChange,
+ prevMentions,
+ prevCitations,
sentimentChange,
};
}
diff --git a/web/src/lib/metrics.test.ts b/web/src/lib/metrics.test.ts
new file mode 100644
index 000000000..c205a75b4
--- /dev/null
+++ b/web/src/lib/metrics.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+import { percentageChange } from './metrics';
+
+describe('percentageChange', () => {
+ it('returns null when the previous period is zero', () => {
+ expect(percentageChange(354, 0)).toBeNull();
+ });
+
+ it('keeps percentage semantics when the current period drops to zero', () => {
+ expect(percentageChange(0, 25)).toBe(-100);
+ expect(percentageChange(30, 20)).toBe(50);
+ });
+});
diff --git a/web/src/lib/metrics.ts b/web/src/lib/metrics.ts
new file mode 100644
index 000000000..0a8fe21fa
--- /dev/null
+++ b/web/src/lib/metrics.ts
@@ -0,0 +1,4 @@
+/** Percentage change with one stable meaning; a zero base has no percentage delta. */
+export function percentageChange(current: number, previous: number): number | null {
+ return previous > 0 ? Math.round(((current - previous) / previous) * 100) : null;
+}