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(insights): show the same visibility on the card, breakdown and leaderboard

Cihan11c0a46fa106
diff --git a/supabase/migrations/00129_insights_breakdown_groups.sql b/supabase/migrations/00129_insights_breakdown_groups.sql
new file mode 100644
index 000000000..e9c5ad484
--- /dev/null
+++ b/supabase/migrations/00129_insights_breakdown_groups.sql
@@ -0,0 +1,102 @@
+-- Insights breakdown panel: aggregate in Postgres instead of fetching rows.
+--
+-- The "View breakdown" panel (Visibility and Mentions) selected the raw
+-- prompt_results rows of both comparison windows and grouped them in JS.
+-- PostgREST caps an un-paginated select at 1,000 rows, in no fixed order, so
+-- on any brand with more answers than that the panel scored an arbitrary
+-- sample: 24.1 pts in the panel against 17.4 on the Visibility card for the
+-- same 30 days (VIS-001).
+--
+-- This returns the panel's inputs already grouped, one entry per
+-- (prompt, platform) — a few thousand at most, inside one jsonb value, so no
+-- row cap applies. The components are the ones the Visibility score is built
+-- from (web/src/lib/visibility-score.ts), counted exactly as
+-- refresh_insights_daily counts them for the rollups the card reads.
+--
+-- The window is either whole UTC days (p_day_from/p_day_to, the rollups' own
+-- day boundaries, so the panel and the card cover the same answers) or a
+-- timestamp range for the 24h and topic-filtered views, which the card also
+-- answers from the raw rows. The prompts behind the groups come back
+-- alongside with their text and topic, so the caller needs no second read.
+--
+-- SECURITY INVOKER like ai_visibility_aggregates (00040): RLS on
+-- prompt_results, prompts and topics scopes everything to the caller's org.
+-- chatgpt-shopping stays excluded (#155).
+create or replace function public.insights_breakdown_groups(
+ p_brand_id uuid,
+ p_models text[] default null,
+ p_region text default null,
+ p_topic_id uuid default null,
+ p_day_from date default null,
+ p_day_to date default null,
+ p_date_from timestamptz default null,
+ p_date_to timestamptz default null
+)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with groups as (
+ select
+ pr.prompt_id,
+ pr.platform,
+ count(*) as answers,
+ count(*) filter (where pr.mention_count > 0) as mention_answers,
+ count(*) filter (where pr.citation_count > 0) as citation_answers,
+ sum(1.0 / pr.mention_position)
+ filter (where pr.mention_position is not null) as sum_inv_position,
+ count(*) filter (where pr.mention_position is not null) as position_count,
+ coalesce(sum(pr.mention_count), 0) as mentions
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and (p_models is null or pr.model_used = any (p_models))
+ and (p_region is null or pr.region = p_region)
+ and (p_day_from is null or pr.created_at >= (p_day_from::timestamp at time zone 'utc'))
+ and (p_day_to is null or pr.created_at < ((p_day_to + 1)::timestamp at time zone 'utc'))
+ and (p_date_from is null or pr.created_at >= p_date_from)
+ and (p_date_to is null or pr.created_at <= p_date_to)
+ and (p_topic_id is null or exists (
+ select 1 from public.prompts p
+ where p.id = pr.prompt_id and p.topic_id = p_topic_id))
+ group by pr.prompt_id, pr.platform
+ )
+ select jsonb_build_object(
+ 'groups', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'prompt_id', g.prompt_id,
+ 'platform', g.platform,
+ 'answers', g.answers,
+ 'mention_answers', g.mention_answers,
+ 'citation_answers', g.citation_answers,
+ 'sum_inv_position', g.sum_inv_position,
+ 'position_count', g.position_count,
+ 'mentions', g.mentions))
+ from groups g),
+ '[]'::jsonb),
+ 'prompts', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'id', p.id,
+ 'text', p.text,
+ 'topic_id', p.topic_id,
+ 'topic_name', t.name))
+ from public.prompts p
+ left join public.topics t on t.id = p.topic_id
+ where p.id in (select distinct g.prompt_id from groups g)),
+ '[]'::jsonb)
+ );
+$$;
+
+revoke all on function public.insights_breakdown_groups(
+ uuid, text[], text, uuid, date, date, timestamptz, timestamptz
+) from public;
+grant execute on function public.insights_breakdown_groups(
+ uuid, text[], text, uuid, date, date, timestamptz, timestamptz
+) to authenticated, service_role;
+
+comment on function public.insights_breakdown_groups(
+ uuid, text[], text, uuid, date, date, timestamptz, timestamptz
+) is
+ 'Insights breakdown panel inputs (VIS-001, 00129): Visibility-score components and mention totals per (prompt, platform) for one window, plus the prompts behind them. Whole UTC days or a timestamp range. Security invoker.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 01bf15e8a..05c1d3296 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -14619,3 +14619,109 @@ grant execute on function public.content_opportunity_aggregates(
timestamptz
) to authenticated;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00129_insights_breakdown_groups.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Insights breakdown panel: aggregate in Postgres instead of fetching rows.
+--
+-- The "View breakdown" panel (Visibility and Mentions) selected the raw
+-- prompt_results rows of both comparison windows and grouped them in JS.
+-- PostgREST caps an un-paginated select at 1,000 rows, in no fixed order, so
+-- on any brand with more answers than that the panel scored an arbitrary
+-- sample: 24.1 pts in the panel against 17.4 on the Visibility card for the
+-- same 30 days (VIS-001).
+--
+-- This returns the panel's inputs already grouped, one entry per
+-- (prompt, platform) — a few thousand at most, inside one jsonb value, so no
+-- row cap applies. The components are the ones the Visibility score is built
+-- from (web/src/lib/visibility-score.ts), counted exactly as
+-- refresh_insights_daily counts them for the rollups the card reads.
+--
+-- The window is either whole UTC days (p_day_from/p_day_to, the rollups' own
+-- day boundaries, so the panel and the card cover the same answers) or a
+-- timestamp range for the 24h and topic-filtered views, which the card also
+-- answers from the raw rows. The prompts behind the groups come back
+-- alongside with their text and topic, so the caller needs no second read.
+--
+-- SECURITY INVOKER like ai_visibility_aggregates (00040): RLS on
+-- prompt_results, prompts and topics scopes everything to the caller's org.
+-- chatgpt-shopping stays excluded (#155).
+create or replace function public.insights_breakdown_groups(
+ p_brand_id uuid,
+ p_models text[] default null,
+ p_region text default null,
+ p_topic_id uuid default null,
+ p_day_from date default null,
+ p_day_to date default null,
+ p_date_from timestamptz default null,
+ p_date_to timestamptz default null
+)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with groups as (
+ select
+ pr.prompt_id,
+ pr.platform,
+ count(*) as answers,
+ count(*) filter (where pr.mention_count > 0) as mention_answers,
+ count(*) filter (where pr.citation_count > 0) as citation_answers,
+ sum(1.0 / pr.mention_position)
+ filter (where pr.mention_position is not null) as sum_inv_position,
+ count(*) filter (where pr.mention_position is not null) as position_count,
+ coalesce(sum(pr.mention_count), 0) as mentions
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and (p_models is null or pr.model_used = any (p_models))
+ and (p_region is null or pr.region = p_region)
+ and (p_day_from is null or pr.created_at >= (p_day_from::timestamp at time zone 'utc'))
+ and (p_day_to is null or pr.created_at < ((p_day_to + 1)::timestamp at time zone 'utc'))
+ and (p_date_from is null or pr.created_at >= p_date_from)
+ and (p_date_to is null or pr.created_at <= p_date_to)
+ and (p_topic_id is null or exists (
+ select 1 from public.prompts p
+ where p.id = pr.prompt_id and p.topic_id = p_topic_id))
+ group by pr.prompt_id, pr.platform
+ )
+ select jsonb_build_object(
+ 'groups', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'prompt_id', g.prompt_id,
+ 'platform', g.platform,
+ 'answers', g.answers,
+ 'mention_answers', g.mention_answers,
+ 'citation_answers', g.citation_answers,
+ 'sum_inv_position', g.sum_inv_position,
+ 'position_count', g.position_count,
+ 'mentions', g.mentions))
+ from groups g),
+ '[]'::jsonb),
+ 'prompts', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'id', p.id,
+ 'text', p.text,
+ 'topic_id', p.topic_id,
+ 'topic_name', t.name))
+ from public.prompts p
+ left join public.topics t on t.id = p.topic_id
+ where p.id in (select distinct g.prompt_id from groups g)),
+ '[]'::jsonb)
+ );
+$$;
+
+revoke all on function public.insights_breakdown_groups(
+ uuid, text[], text, uuid, date, date, timestamptz, timestamptz
+) from public;
+grant execute on function public.insights_breakdown_groups(
+ uuid, text[], text, uuid, date, date, timestamptz, timestamptz
+) to authenticated, service_role;
+
+comment on function public.insights_breakdown_groups(
+ uuid, text[], text, uuid, date, date, timestamptz, timestamptz
+) is
+ 'Insights breakdown panel inputs (VIS-001, 00129): Visibility-score components and mention totals per (prompt, platform) for one window, plus the prompts behind them. Whole UTC days or a timestamp range. Security invoker.';
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx
index 2df33316b..6cf2df8d5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx
@@ -14,12 +14,14 @@ import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Link } from '@/i18n/navigation';
import { cn } from '@/lib/utils';
+import { getInsightsBreakdown } from '@/lib/actions/tracking';
import {
- getInsightsBreakdown,
+ pickDriver,
+ type BreakdownFilters,
type BreakdownMetric,
type BreakdownRow,
type InsightsBreakdown,
-} from '@/lib/actions/tracking';
+} from '@/lib/insights-breakdown';
import { sortBreakdownRowsForDisplay } from './breakdown-display';
const METRIC_TITLE: Record<BreakdownMetric, string> = {
@@ -36,13 +38,8 @@ interface Props {
brandId: string | null;
metric: BreakdownMetric | null;
onOpenChange: (open: boolean) => void;
- filters?: {
- dateFrom?: string;
- dateTo?: string;
- region?: string;
- model?: string;
- topicId?: string;
- };
+ /** The window and filters the cards were loaded with, so the panel explains their numbers. */
+ filters?: BreakdownFilters;
}
export function MetricBreakdownSheet({ brandId, metric, onOpenChange, filters }: Props) {
@@ -94,9 +91,11 @@ export function MetricBreakdownSheet({ brandId, metric, onOpenChange, filters }:
<SheetHeader className="border-b px-5 py-4">
<SheetTitle className="text-base">{title} Breakdown</SheetTitle>
<SheetDescription className="text-xs">
- {data
- ? `Last ${data.windowDays} day${data.windowDays !== 1 ? 's' : ''} vs previous ${data.windowDays} day${data.windowDays !== 1 ? 's' : ''}`
- : 'Comparing the selected window with the previous equal-length window.'}
+ {!data
+ ? 'Comparing the selected window with the previous equal-length window.'
+ : data.windowDays === null
+ ? 'All time. There is no earlier period of the same length to compare.'
+ : `Last ${data.windowDays} day${data.windowDays !== 1 ? 's' : ''} vs previous ${data.windowDays} day${data.windowDays !== 1 ? 's' : ''}`}
</SheetDescription>
</SheetHeader>
@@ -143,7 +142,7 @@ function BreakdownBody({ data, metric }: { data: InsightsBreakdown; metric: Brea
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="text-xs uppercase tracking-wide text-muted-foreground">
- Current {data.windowDays}d
+ {data.windowDays === null ? 'All time' : `Current ${data.windowDays}d`}
</div>
<div className="text-2xl font-semibold tabular-nums">
{formatValue(data.curTotal, metric)}
@@ -151,15 +150,23 @@ function BreakdownBody({ data, metric }: { data: InsightsBreakdown; metric: Brea
{METRIC_UNIT[metric]}
</span>
</div>
- <div className="text-xs text-muted-foreground">
- vs previous{' '}
- <span className="tabular-nums">
- {formatValue(data.prevTotal, metric)}
- {METRIC_UNIT[metric]}
- </span>
- </div>
+ {data.windowDays !== null && (
+ <div className="text-xs text-muted-foreground">
+ vs previous{' '}
+ {data.prevTotal === null ? (
+ 'no data'
+ ) : (
+ <span className="tabular-nums">
+ {formatValue(data.prevTotal, metric)}
+ {METRIC_UNIT[metric]}
+ </span>
+ )}
+ </div>
+ )}
</div>
- <DeltaPill delta={data.delta} deltaPct={data.deltaPct} metric={metric} big />
+ {data.delta !== null && (
+ <DeltaPill delta={data.delta} deltaPct={data.deltaPct} metric={metric} big />
+ )}
</div>
<RootCauseSummary data={data} metric={metric} />
</div>
@@ -188,7 +195,12 @@ function BreakdownBody({ data, metric }: { data: InsightsBreakdown; metric: Brea
</TabsList>
<TabsContent value={tab} className="mt-3">
- <BreakdownTable rows={pickRows()} metric={metric} kind={tab} />
+ <BreakdownTable
+ rows={pickRows()}
+ metric={metric}
+ kind={tab}
+ comparable={data.windowDays !== null}
+ />
</TabsContent>
</Tabs>
</div>
@@ -196,15 +208,11 @@ function BreakdownBody({ data, metric }: { data: InsightsBreakdown; metric: Brea
}
function RootCauseSummary({ data, metric }: { data: InsightsBreakdown; metric: BreakdownMetric }) {
- const isDrop = data.delta < 0;
- const isFlat = data.delta === 0;
- const topPrompt = isDrop ? data.byPrompt[0] : data.byPrompt[data.byPrompt.length - 1];
- const topPlatform = isDrop ? data.byPlatform[0] : data.byPlatform[data.byPlatform.length - 1];
- const promptContributes = !!topPrompt && (isDrop ? topPrompt.delta < 0 : topPrompt.delta > 0);
- const platformContributes =
- !!topPlatform && (isDrop ? topPlatform.delta < 0 : topPlatform.delta > 0);
-
- if (isFlat || !promptContributes || !topPrompt) {
+ const isDrop = (data.delta ?? 0) < 0;
+ const topPrompt = pickDriver(data.byPrompt, data.delta);
+ const topPlatform = pickDriver(data.byPlatform, data.delta);
+
+ if (!topPrompt) {
return (
<div className="mt-2 text-xs text-muted-foreground leading-relaxed">{data.rootCause}</div>
);
@@ -220,7 +228,7 @@ function RootCauseSummary({ data, metric }: { data: InsightsBreakdown; metric: B
&quot;{truncate(topPrompt.label, 60)}&quot;
</Link>{' '}
{formatContribution(topPrompt, metric)}.
- {platformContributes && topPlatform && (
+ {topPlatform && (
<>
{' '}
Top platform {isDrop ? 'drop' : 'gain'}: {topPlatform.label}{' '}
@@ -235,10 +243,13 @@ function BreakdownTable({
rows,
metric,
kind,
+ comparable,
}: {
rows: BreakdownRow[];
metric: BreakdownMetric;
kind: 'prompts' | 'platforms' | 'topics';
+ /** False for All time: no previous window, so no Prev or Change column. */
+ comparable: boolean;
}) {
if (rows.length === 0) {
return (
@@ -254,9 +265,9 @@ function BreakdownTable({
<thead>
<tr className="border-b bg-muted/40 text-[11px] uppercase tracking-wide text-muted-foreground">
<th className="text-left font-medium px-3 py-2">Name</th>
- <th className="text-right font-medium px-2 py-2 w-16">Prev</th>
+ {comparable && <th className="text-right font-medium px-2 py-2 w-16">Prev</th>}
<th className="text-right font-medium px-2 py-2 w-16">Cur</th>
- <th className="text-right font-medium px-2 py-2 w-24">Change</th>
+ {comparable && <th className="text-right font-medium px-2 py-2 w-24">Change</th>}
</tr>
</thead>
<tbody>
@@ -277,13 +288,17 @@ function BreakdownTable({
<div className="mt-0.5 text-[11px] text-muted-foreground">{r.sublabel}</div>
)}
</td>
- <td className="px-2 py-2 text-right tabular-nums text-muted-foreground">
- {formatValue(r.prev, metric)}
- </td>
+ {comparable && (
+ <td className="px-2 py-2 text-right tabular-nums text-muted-foreground">
+ {r.prev === null ? '—' : formatValue(r.prev, metric)}
+ </td>
+ )}
<td className="px-2 py-2 text-right tabular-nums">{formatValue(r.cur, metric)}</td>
- <td className="px-2 py-2 text-right">
- <DeltaPill delta={r.delta} deltaPct={r.deltaPct} metric={metric} />
- </td>
+ {comparable && (
+ <td className="px-2 py-2 text-right">
+ <DeltaPill delta={r.delta ?? 0} deltaPct={r.deltaPct} metric={metric} />
+ </td>
+ )}
</tr>
))}
</tbody>
@@ -358,8 +373,9 @@ function formatValue(value: number, metric: BreakdownMetric): string {
}
function formatContribution(row: BreakdownRow, metric: BreakdownMetric): string {
- const isLoss = row.delta < 0;
- const abs = Math.abs(row.delta);
+ const delta = row.delta ?? 0;
+ const isLoss = delta < 0;
+ const abs = Math.abs(delta);
if (metric === 'visibility') {
const verb = isLoss ? 'dropped' : 'rose';
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/breakdown-display.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/breakdown-display.ts
index 7e4c91f61..7bcf495c5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/breakdown-display.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/breakdown-display.ts
@@ -5,7 +5,7 @@ export function sortBreakdownRowsForDisplay(rows: BreakdownRow[]): BreakdownRow[
const currentDiff = b.cur - a.cur;
if (currentDiff !== 0) return currentDiff;
- const deltaDiff = b.delta - a.delta;
+ const deltaDiff = (b.delta ?? 0) - (a.delta ?? 0);
if (deltaDiff !== 0) return deltaDiff;
return a.label.localeCompare(b.label);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 566456ea9..4abbdf595 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -58,6 +58,7 @@ import {
type ShareOfVoiceData,
type InsightsRecommendations,
type TrackingJobStatus,
+ type BreakdownFilters,
type BreakdownMetric,
} from '@/lib/actions/tracking';
import { getTopics } from '@/lib/actions/topic';
@@ -227,6 +228,21 @@ function getDateRange(
return { dateFrom: `${dayFrom}T00:00:00.000Z`, dateTo: undefined, days: { dayFrom, dayTo } };
}
+/**
+ * A comparison-window bound for the "vs <range>" label. Whole-day windows
+ * come as 'YYYY-MM-DD' UTC days and are shown as those days; the 24h and
+ * topic views come as timestamps and are shown in local time.
+ */
+function formatWindowBound(value: string): string {
+ const dayOnly = /^\d{4}-\d{2}-\d{2}$/.test(value);
+ return new Date(dayOnly ? `${value}T00:00:00Z` : value).toLocaleDateString('en-US', {
+ month: 'short',
+ day: '2-digit',
+ year: 'numeric',
+ ...(dayOnly ? { timeZone: 'UTC' } : {}),
+ });
+}
+
// ─── Info Tooltip ─────────────────────────────────────────────────────────────
function InfoTip({ content }: { content: string }) {
@@ -1019,6 +1035,10 @@ export default function InsightsPage() {
const [sovData, setSovData] = useState<ShareOfVoiceData | null>(null);
const [recommendations, setRecommendations] = useState<InsightsRecommendations | null>(null);
const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);
+ // The window and filters the cards were last loaded with (the 24h view
+ // anchored to its tracking run): the breakdown panel explains those exact
+ // numbers rather than recomputing "now" on every render (VIS-001).
+ const [loadedFilters, setLoadedFilters] = useState<BreakdownFilters>();
const [isExporting, setIsExporting] = useState(false);
const [cronRun, setCronRun] = useState<TrackingWindow['activeRun']>(null);
const cronRunRef = useRef<TrackingWindow['activeRun']>(null);
@@ -1085,6 +1105,12 @@ export default function InsightsPage() {
cronRunRef.current = insights.trackingWindow.activeRun;
setCronRun(insights.trackingWindow.activeRun);
}
+ const anchored = insights.trackingWindow?.anchored;
+ setLoadedFilters({
+ ...filterOpts,
+ dateFrom: anchored?.dateFrom ?? filterOpts.dateFrom,
+ dateTo: anchored?.dateTo ?? filterOpts.dateTo,
+ });
const trend = insights.trend;
setRateTrend(trend && trend.points.length > 0 ? trend : null);
setSummary(insights.summary);
@@ -1683,18 +1709,8 @@ export default function InsightsPage() {
)}
{rateTrend.summary.change !== null && rateTrend.summary.prevFrom && (
<span className="text-muted-foreground">
- vs{' '}
- {new Date(rateTrend.summary.prevFrom).toLocaleDateString('en-US', {
- month: 'short',
- day: '2-digit',
- year: 'numeric',
- })}{' '}
- –{' '}
- {new Date(rateTrend.summary.prevTo).toLocaleDateString('en-US', {
- month: 'short',
- day: '2-digit',
- year: 'numeric',
- })}
+ vs {formatWindowBound(rateTrend.summary.prevFrom)} –{' '}
+ {formatWindowBound(rateTrend.summary.prevTo)}
</span>
)}
</div>
@@ -1796,19 +1812,7 @@ export default function InsightsPage() {
onOpenChange={(open) => {
if (!open) setBreakdownMetric(null);
}}
- filters={(() => {
- const { dateFrom, dateTo } = getDateRange(filters.datePreset, {
- from: filters.dateFrom,
- to: filters.dateTo,
- });
- return {
- dateFrom,
- dateTo,
- region: filters.region || undefined,
- model: filters.model || undefined,
- topicId: filters.topic || undefined,
- };
- })()}
+ filters={loadedFilters}
/>
</div>
);
diff --git a/web/src/lib/actions/tracking-visibility-parity.test.ts b/web/src/lib/actions/tracking-visibility-parity.test.ts
new file mode 100644
index 000000000..09fd99796
--- /dev/null
+++ b/web/src/lib/actions/tracking-visibility-parity.test.ts
@@ -0,0 +1,216 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * VIS-001: the Visibility card, the "View breakdown" panel and the
+ * leaderboard's own row must show the same number and the same change for
+ * the same filters. All three are fed the same aggregate payloads here; they
+ * used to disagree because the panel scored a 1,000-row sample over its own
+ * windows, and the leaderboard compared All time with a 7-day window.
+ */
+
+type Call = { name: string; args: Record<string, unknown> };
+let calls: Call[] = [];
+
+// Current window: 1,800 answers; previous window: 1,600.
+const visibilityPayload = (answers: number, mentions: number, citations: number) => ({
+ answers,
+ mention_answers: mentions,
+ citation_answers: citations,
+ position_factor: 0.5,
+ by_competitor: [],
+});
+const CUR = visibilityPayload(1800, 540, 180);
+let PREV = visibilityPayload(1600, 400, 176);
+
+// The Mentions card's aggregates: insights_aggregates(_daily).
+const summaryPayload = (results: number, mentions: number) => ({
+ total_results: results,
+ sum_visibility: 0,
+ total_mentions: mentions,
+ total_citations: 0,
+ positive_count: 0,
+ mentioning_results: 0,
+ last_checked_at: null,
+ by_model: [],
+});
+const SUMMARY_CUR = summaryPayload(1800, 710);
+let SUMMARY_PREV = summaryPayload(1600, 500);
+
+const groups = {
+ groups: [
+ {
+ prompt_id: 'p1',
+ platform: 'chatgpt',
+ answers: 900,
+ mention_answers: 300,
+ citation_answers: 100,
+ sum_inv_position: 150,
+ position_count: 300,
+ mentions: 410,
+ },
+ {
+ prompt_id: 'p2',
+ platform: 'gemini',
+ answers: 900,
+ mention_answers: 240,
+ citation_answers: 80,
+ sum_inv_position: 120,
+ position_count: 240,
+ mentions: 300,
+ },
+ ],
+ prompts: [
+ { id: 'p1', text: 'best rank tracker', topic_id: null, topic_name: null },
+ { id: 'p2', text: 'geo tools', topic_id: null, topic_name: null },
+ ],
+};
+
+const competitorAgg = {
+ brand_row_count: 1800,
+ brand_sum_visibility: 0,
+ brand_total_mentions: 710,
+ brand_total_citations: 180,
+ brand_prompt_count: 2,
+ brand_visible_prompts: 2,
+ by_competitor: [],
+ by_brand_provider: [],
+ by_competitor_provider: [],
+};
+
+/** Which window a call reads: the previous one starts before the current one. */
+const isPrev = (args: Record<string, unknown>) =>
+ args.p_day_from === '2026-08-16' || args.p_date_from === '2026-10-12T06:00:00.000Z';
+
+function rpc(name: string, args: Record<string, unknown>) {
+ calls.push({ name, args });
+ let data: unknown = null;
+ if (name.startsWith('ai_visibility_aggregates')) data = isPrev(args) ? PREV : CUR;
+ else if (name === 'insights_breakdown_groups') data = groups;
+ else if (name.startsWith('visibility_rate_trend')) data = [];
+ else if (name.startsWith('competitor_aggregates')) data = competitorAgg;
+ else if (name.startsWith('insights_aggregates')) data = isPrev(args) ? SUMMARY_PREV : SUMMARY_CUR;
+ return Promise.resolve({ data, error: null });
+}
+
+function table() {
+ const result = { data: [] as unknown[], error: null };
+ const builder: Record<string, unknown> = {
+ select: () => builder,
+ eq: () => builder,
+ single: async () => ({ data: { name: 'Ansvisor', logo_url: null }, error: null }),
+ then: (resolve: (v: typeof result) => unknown) => resolve(result),
+ };
+ return builder;
+}
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({ from: () => table(), rpc }),
+}));
+vi.mock('@/lib/actions/topic', () => ({ getTopicById: vi.fn() }));
+
+const {
+ getVisibilityRateTrend,
+ getInsightsBreakdown,
+ getCompetitorComparison,
+ getInsightsSummary,
+} = await import('./tracking');
+
+const thirtyDays = {
+ dateFrom: '2026-09-15T00:00:00.000Z',
+ days: { dayFrom: '2026-09-15', dayTo: '2026-10-14' },
+};
+
+describe('Visibility parity (VIS-001)', () => {
+ beforeEach(() => {
+ calls = [];
+ PREV = visibilityPayload(1600, 400, 176);
+ SUMMARY_PREV = summaryPayload(1600, 500);
+ });
+
+ it('shows the same number and change on the card, the panel and the leaderboard', async () => {
+ const card = (await getVisibilityRateTrend('b1', thirtyDays)).summary;
+ const panel = await getInsightsBreakdown('b1', 'visibility', thirtyDays);
+ const own = (await getCompetitorComparison('b1', thirtyDays)).brands.find((e) => e.isOwnBrand)!;
+
+ expect(card.change).not.toBeNull();
+ expect(panel.curTotal).toBe(card.rate);
+ expect(panel.prevTotal).toBe(card.prevRate);
+ expect(panel.delta).toBe(card.change);
+ expect(own.score).toBe(card.rate);
+ expect(own.scoreChange).toBe(card.change);
+ expect(panel.windowDays).toBe(30);
+ });
+
+ it('labels the change with the whole days it was measured against', async () => {
+ const card = (await getVisibilityRateTrend('b1', thirtyDays)).summary;
+
+ expect(card.prevFrom).toBe('2026-08-16');
+ expect(card.prevTo).toBe('2026-09-14');
+ });
+
+ it('reads the panel slices in Postgres over the card’s whole days', async () => {
+ await getInsightsBreakdown('b1', 'visibility', thirtyDays);
+
+ const groupCalls = calls.filter((c) => c.name === 'insights_breakdown_groups');
+ expect(groupCalls.map((c) => [c.args.p_day_from, c.args.p_day_to])).toEqual([
+ ['2026-09-15', '2026-10-14'],
+ ['2026-08-16', '2026-09-14'],
+ ]);
+ });
+
+ it('shows no change anywhere for All time', async () => {
+ const allTime = { days: {} };
+ const card = (await getVisibilityRateTrend('b1', allTime)).summary;
+ const panel = await getInsightsBreakdown('b1', 'visibility', allTime);
+ const own = (await getCompetitorComparison('b1', allTime)).brands.find((e) => e.isOwnBrand)!;
+
+ expect(card.change).toBeNull();
+ expect(panel).toMatchObject({ prevTotal: null, delta: null, windowDays: null });
+ expect(panel.curTotal).toBe(card.rate);
+ // The leaderboard used to compare all time with the trailing 7 days.
+ expect(own.scoreChange).toBeNull();
+ expect(calls.filter((c) => c.name === 'insights_breakdown_groups')).toHaveLength(1);
+ });
+
+ it('uses the anchored 24h window and the topic on the raw path', async () => {
+ const anchored = {
+ dateFrom: '2026-10-13T06:00:00.000Z',
+ dateTo: '2026-10-14T06:00:00.000Z',
+ topicId: 'topic-1',
+ };
+ const card = (await getVisibilityRateTrend('b1', anchored)).summary;
+ const panel = await getInsightsBreakdown('b1', 'visibility', anchored);
+
+ expect(panel.delta).toBe(card.change);
+ const groupCalls = calls.filter((c) => c.name === 'insights_breakdown_groups');
+ expect(
+ groupCalls.map((c) => [c.args.p_date_from, c.args.p_date_to, c.args.p_topic_id]),
+ ).toEqual([
+ ['2026-10-13T06:00:00.000Z', '2026-10-14T06:00:00.000Z', 'topic-1'],
+ ['2026-10-12T06:00:00.000Z', '2026-10-13T06:00:00.000Z', 'topic-1'],
+ ]);
+ });
+
+ it('says there is nothing to compare when the previous window had no answers', async () => {
+ PREV = visibilityPayload(0, 0, 0);
+ const card = (await getVisibilityRateTrend('b1', thirtyDays)).summary;
+ const panel = await getInsightsBreakdown('b1', 'visibility', thirtyDays);
+
+ expect(card.change).toBeNull();
+ expect(panel).toMatchObject({ prevTotal: null, delta: null, windowDays: 30 });
+ expect(panel.rootCause).toContain('No answers in one of the two 30-day windows');
+ });
+
+ it('matches the Mentions card, which shows no change without previous answers', async () => {
+ const withPrev = await getInsightsBreakdown('b1', 'mentions', thirtyDays);
+ const cardWithPrev = await getInsightsSummary('b1', thirtyDays);
+ expect(withPrev).toMatchObject({ curTotal: 710, prevTotal: 500, delta: 210 });
+ expect(withPrev.deltaPct).toBe(cardWithPrev.mentionsChange);
+
+ SUMMARY_PREV = summaryPayload(0, 0);
+ const panel = await getInsightsBreakdown('b1', 'mentions', thirtyDays);
+ const card = await getInsightsSummary('b1', thirtyDays);
+ expect(card.mentionsChange).toBeNull();
+ expect(panel).toMatchObject({ curTotal: 710, prevTotal: null, delta: null, deltaPct: null });
+ });
+});
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index bad4f32fa..635641b26 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -3,6 +3,15 @@
import { unstable_cache } from 'next/cache';
import { dbClient, withDbClient } from '@/lib/supabase/scoped';
import { expandDateToEndOfDay } from '@/lib/dates';
+import {
+ comparisonWindows,
+ dailyWindow,
+ deltaDayWindows,
+ visibilityChange,
+ windowBounds,
+ type DayWindow,
+ type MetricWindow,
+} from '@/lib/insights-windows';
import { computeAiVisibilityScore } from '@/lib/visibility-score';
import type {
PromptResult,
@@ -28,6 +37,16 @@ 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';
+import {
+ breakdownDelta,
+ buildBreakdownRows,
+ parseBreakdownGroups,
+ pickDriver,
+ type BreakdownFilters,
+ type BreakdownMetric,
+ type BreakdownRow,
+ type InsightsBreakdown,
+} from '@/lib/insights-breakdown';
import { PLATFORM_LABELS } from '@/config/platform-labels';
import {
aggregateHeadToHead,
@@ -184,70 +203,9 @@ function modelFilterArray(model: string | undefined): string[] | undefined {
return list.length > 0 ? list : undefined;
}
-// ── Daily-rollup routing (00066) ────────────────────────────────────────────
-//
-// The aggregate RPCs used to rescan a brand's whole history per page load;
-// past ~55k results that exceeds the authenticated role's 8s statement
-// timeout and the wide presets die. Every preset except 24h now describes its
-// window as whole UTC days, and calls that carry one are answered from the
-// pre-aggregated daily tables instead — cost scales with days in the window,
-// never with accumulated results.
-//
-// Topic-filtered calls deliberately stay on the raw RPCs: topic is a live
-// prompt attribute (reassigning a prompt must move its history), the rollups
-// have no prompt dimension at brand grain, and a topic slice is a small
-// fraction of the scan that made the raw path unaffordable.
-
-/**
- * Whole-day UTC window, 'YYYY-MM-DD' inclusive on both ends. Its presence in
- * an action's opts marks the call as servable from the daily rollups; either
- * bound may be absent (the All-time preset carries an empty window).
- */
-export interface DayWindow {
- dayFrom?: string;
- dayTo?: string;
-}
-
-interface WindowedOpts {
- topicId?: string;
- days?: DayWindow;
-}
-
-/** The day window to serve from rollups, or null when the raw path must answer. */
-function dailyWindow(opts?: WindowedOpts): DayWindow | null {
- return opts?.days && !opts.topicId ? opts.days : null;
-}
-
-const DAY_MS = 86_400_000;
-
-function utcToday(): string {
- return new Date().toISOString().slice(0, 10);
-}
-
-function addDays(day: string, n: number): string {
- return new Date(Date.parse(`${day}T00:00:00Z`) + n * DAY_MS).toISOString().slice(0, 10);
-}
-
-/**
- * Current + previous equal-length day windows for the ↑/↓ delta math. An
- * unbounded window anchors to the trailing 7 days, mirroring what the raw
- * path's `now() - 7d` default has always compared against. The previous
- * window ends the day BEFORE the current one starts — the raw path's
- * timestamp arithmetic let the two windows share their boundary instant.
- */
-function deltaDayWindows(days: DayWindow): {
- cur: { dayFrom: string; dayTo: string };
- prev: { dayFrom: string; dayTo: string };
-} {
- const curTo = days.dayTo ?? utcToday();
- const curFrom = days.dayFrom ?? addDays(curTo, -6);
- const len = Math.round((Date.parse(curTo) - Date.parse(curFrom)) / DAY_MS) + 1;
- const prevTo = addDays(curFrom, -1);
- return {
- cur: { dayFrom: curFrom, dayTo: curTo },
- prev: { dayFrom: addDays(prevTo, -(len - 1)), dayTo: prevTo },
- };
-}
+// Daily-rollup routing and the comparison windows live in
+// @/lib/insights-windows, shared with the breakdown panel (VIS-001).
+export type { DayWindow } from '@/lib/insights-windows';
// ── RPC return shapes (mirror supabase/migrations/00031_insights_sentiment_denominator.sql) ─
@@ -1917,6 +1875,38 @@ function foldAiVisibility(raw: unknown): AiVisibilityWindow {
};
}
+/**
+ * ai_visibility_aggregates over one comparison window (VIS-001): the daily
+ * rollups for whole days, the raw rows for a timestamp range. The card, the
+ * breakdown panel and the leaderboard read their Visibility through this, so
+ * the same window always yields the same number.
+ */
+function aiVisibilityWindow(
+ supabase: Awaited<ReturnType<typeof dbClient>>,
+ brandId: string,
+ opts: { model?: string; region?: string; topicId?: string } | undefined,
+ win: MetricWindow,
+) {
+ const base = {
+ p_brand_id: brandId,
+ p_platform: undefined as string | undefined,
+ p_models: modelFilterArray(opts?.model),
+ p_region: opts?.region ?? undefined,
+ };
+ return win.kind === 'days'
+ ? supabase.rpc('ai_visibility_aggregates_daily', {
+ ...base,
+ p_day_from: win.days.dayFrom,
+ p_day_to: win.days.dayTo,
+ })
+ : supabase.rpc('ai_visibility_aggregates', {
+ ...base,
+ p_date_from: win.from,
+ p_date_to: win.to,
+ p_topic_id: opts?.topicId ?? undefined,
+ });
+}
+
export interface CompetitorComparisonEntry {
name: string;
avgVisibilityScore: number;
@@ -2057,25 +2047,16 @@ export async function getCompetitorComparison(
p_date_from: from,
p_date_to: to,
});
- const visRpc = (win: { dayFrom?: string; dayTo?: string } | null, from?: string, to?: string) =>
- win
- ? supabase.rpc('ai_visibility_aggregates_daily', {
- ...dailyArgs,
- p_day_from: win.dayFrom,
- p_day_to: win.dayTo,
- })
- : supabase.rpc('ai_visibility_aggregates', {
- ...baseArgs,
- p_date_from: from,
- p_date_to: to,
- });
+ // Scores and their change use the card's windows (VIS-001), so the
+ // brand's own row always matches the Visibility card.
+ const visWindows = comparisonWindows(opts);
// 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 }, visDisplayRes] = await Promise.all([
supabase.from('brands').select('name').eq('id', brandId).single(),
compRpc(daily, opts?.dateFrom ?? undefined, expandDateToEndOfDay(opts?.dateTo) ?? undefined),
- visRpc(daily, opts?.dateFrom ?? undefined, expandDateToEndOfDay(opts?.dateTo) ?? undefined),
+ aiVisibilityWindow(supabase, brandId, opts, visWindows.cur),
]);
if (aggErr) throw new Error(aggErr.message);
if (visDisplayRes.error) throw new Error(visDisplayRes.error.message);
@@ -2116,14 +2097,15 @@ export async function getCompetitorComparison(
deltaDays
? compRpc(deltaDays.prev)
: compRpc(null, prevFrom.toISOString(), currentFrom.toISOString()),
- deltaDays
- ? visRpc(deltaDays.prev)
- : visRpc(null, prevFrom.toISOString(), currentFrom.toISOString()),
+ visWindows.prev
+ ? aiVisibilityWindow(supabase, brandId, opts, visWindows.prev)
+ : Promise.resolve({ data: null, error: new Error('no previous window') }),
]);
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.
+ // before it (none for All time); 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;
@@ -2487,7 +2469,11 @@ export interface VisibilityRateTrendSummary {
prevRate: number | null;
/** rate − prevRate in points, one decimal; null when prevRate is null. */
change: number | null;
- /** ISO bounds of the previous window, for the "vs <range>" label. */
+ /**
+ * Inclusive bounds of the previous window, for the "vs <range>" label:
+ * 'YYYY-MM-DD' UTC days for whole-day windows, ISO timestamps for the 24h
+ * and topic views. Empty when there is no previous window (All time).
+ */
prevFrom: string;
prevTo: string;
}
@@ -2537,6 +2523,9 @@ export async function getVisibilityRateTrend(
): Promise<VisibilityRateTrendData> {
const supabase = await dbClient();
const daily = dailyWindow(opts);
+ // The headline and its change: the same windows the breakdown panel and
+ // the leaderboard use (VIS-001).
+ const windows = comparisonWindows(opts);
// No explicit lower bound = the "All time" preset: the summary covers
// everything (matching the leaderboard) and the chart plots an expanding
// cumulative window instead of a fixed-length rolling one.
@@ -2546,8 +2535,8 @@ export async function getVisibilityRateTrend(
const boundedFrom = opts?.dateFrom ?? undefined;
const dateTo = expandDateToEndOfDay(opts?.dateTo) ?? new Date().toISOString();
- // Equal-length window immediately before, for the headline delta
- // (undefined for all-time — there is no comparable previous window).
+ // On the raw path the chart reads one window further back, to warm up the
+ // rolling window of its earliest points (all-time needs none).
const windowMs = boundedFrom
? new Date(dateTo).getTime() - new Date(boundedFrom).getTime()
: null;
@@ -2555,7 +2544,6 @@ export async function getVisibilityRateTrend(
boundedFrom && windowMs !== null
? new Date(new Date(boundedFrom).getTime() - windowMs).toISOString()
: undefined;
- const prevTo = boundedFrom;
const rateArgs = (from: string | undefined, to: string) => ({
p_brand_id: brandId,
@@ -2574,8 +2562,8 @@ export async function getVisibilityRateTrend(
p_day_from: dayFrom,
p_day_to: dayTo,
});
- // Day-window equivalents of the three timestamp windows above: display,
- // warm-up-extended fetch range, and the previous window for the delta.
+ // The chart's warm-up range on the rollup path starts at the previous
+ // window's first day.
const deltaDays = daily?.dayFrom ? deltaDayWindows(daily) : null;
const [
@@ -2595,19 +2583,10 @@ export async function getVisibilityRateTrend(
daily
? supabase.rpc('visibility_rate_trend_daily', dayArgs(deltaDays?.prev.dayFrom, daily.dayTo))
: supabase.rpc('visibility_rate_trend', rateArgs(prevFrom, dateTo)),
- daily
- ? supabase.rpc('ai_visibility_aggregates_daily', dayArgs(daily.dayFrom, daily.dayTo))
- : supabase.rpc('ai_visibility_aggregates', rateArgs(boundedFrom, dateTo)),
- daily
- ? deltaDays
- ? supabase.rpc(
- 'ai_visibility_aggregates_daily',
- dayArgs(deltaDays.prev.dayFrom, deltaDays.prev.dayTo),
- )
- : Promise.resolve({ data: null, error: new Error('no previous window') })
- : prevFrom && prevTo
- ? supabase.rpc('ai_visibility_aggregates', rateArgs(prevFrom, prevTo))
- : Promise.resolve({ data: null, error: new Error('no previous window') }),
+ aiVisibilityWindow(supabase, brandId, opts, windows.cur),
+ windows.prev
+ ? aiVisibilityWindow(supabase, brandId, opts, windows.prev)
+ : Promise.resolve({ data: null, error: new Error('no previous window') }),
]);
if (rpcRes.error) throw new Error(rpcRes.error.message);
if (visCurRes.error) throw new Error(visCurRes.error.message);
@@ -2639,7 +2618,9 @@ export async function getVisibilityRateTrend(
// point equal the headline card exactly — the chart's inside and outside
// can never disagree — and every earlier point answers "what would the
// headline have shown that day".
- const windowDays = windowMs !== null ? Math.max(1, Math.round(windowMs / 86_400_000)) : null;
+ // Whole-day windows count their days: rounding the elapsed time made the
+ // 30d chart's newest point cover 29 days before noon UTC.
+ const windowDays = windows.windowDays;
const dayMs = (day: string) => new Date(day + 'T00:00:00Z').getTime();
const displayFromMs = boundedFrom ? new Date(boundedFrom).getTime() : Number.NEGATIVE_INFINITY;
@@ -2732,15 +2713,17 @@ export async function getVisibilityRateTrend(
// 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 headline = visibilityChange(visCur.brandScore, visPrev?.brandScore ?? null);
+ // The window the change was measured against: 'YYYY-MM-DD' days for the
+ // rollup presets, ISO timestamps for the 24h and topic views.
+ const prevWin = windows.prev;
const summary: VisibilityRateTrendSummary = {
- rate: headlineScore,
- prevRate: prevScore,
- change: prevScore === null ? null : Math.round((headlineScore - prevScore) * 10) / 10,
- prevFrom: prevFrom ?? '',
- prevTo: prevTo ?? '',
+ rate: headline.value,
+ prevRate: headline.prev,
+ change: headline.change,
+ prevFrom: prevWin ? windowBounds(prevWin).from : '',
+ prevTo: prevWin ? windowBounds(prevWin).to : '',
};
return { entities, points, summary };
@@ -2839,334 +2822,149 @@ export async function getHeadToHeadRuns(
// ─── Insights Metric Breakdown (Root-Cause Drilldown) ─────────────────────────
-export type BreakdownMetric = 'mentions' | 'visibility';
+export type {
+ BreakdownFilters,
+ BreakdownMetric,
+ BreakdownRow,
+ InsightsBreakdown,
+} from '@/lib/insights-breakdown';
function formatPlatformLabel(slug: string): string {
return PLATFORM_LABELS[slug] ?? slug;
}
-export interface BreakdownRow {
- /** Unique identifier for the row: prompt_id / platform name / topic_id. */
- id: string;
- /** Display label: prompt text / platform name / topic name. */
- label: string;
- /** Optional secondary label (e.g. topic name for a prompt). */
- sublabel?: string;
- /** Metric value in the current window. */
- cur: number;
- /** Metric value in the previous window. */
- prev: number;
- /** Absolute change (cur - prev). */
- delta: number;
- /** Percentage change. Null when previous is zero (use delta instead). */
- deltaPct: number | null;
- /** Number of result rows that contributed in the current window. */
- curRuns: number;
- /** Number of result rows that contributed in the previous window. */
- prevRuns: number;
-}
-
-export interface InsightsBreakdown {
- metric: BreakdownMetric;
- curTotal: number;
- prevTotal: number;
- delta: number;
- deltaPct: number | null;
- /** Number of full calendar days covered by each comparison window. */
- windowDays: number;
- byPrompt: BreakdownRow[];
- byPlatform: BreakdownRow[];
- byTopic: BreakdownRow[];
- /** One-line rule-based root-cause summary for the drop/rise. */
- rootCause: string;
-}
-
-/** Aggregate a metric over a set of raw prompt_results rows. */
-function aggregateMetric(
- rows: Array<{
- mention_count: number;
- citation_count?: number;
- visibility_score: number;
- mention_position?: number | null;
- }>,
- metric: BreakdownMetric,
-): { value: number; runs: number } {
- if (metric === 'visibility') {
- if (rows.length === 0) return { value: 0, runs: 0 };
- // AI Visibility Score over the group's answers — the drill-down explains
- // the same number the KPI card shows, per prompt/platform/topic.
- let mentionAnswers = 0;
- let citationAnswers = 0;
- let posSum = 0;
- let posN = 0;
- for (const r of rows) {
- if ((r.mention_count ?? 0) > 0) mentionAnswers++;
- if ((r.citation_count ?? 0) > 0) citationAnswers++;
- const pos = r.mention_position;
- if (pos !== null && pos !== undefined && pos > 0) {
- posSum += 1 / pos;
- posN++;
- }
- }
- return {
- value:
- computeAiVisibilityScore({
- answers: rows.length,
- mentionAnswers,
- citationAnswers,
- positionFactor: posN > 0 ? posSum / posN : null,
- }) ?? 0,
- runs: rows.length,
- };
- }
- const value = rows.reduce((s, r) => s + (r.mention_count ?? 0), 0);
- return { value, runs: rows.length };
-}
-
-function computeDelta(
- cur: number,
- prev: number,
- metric: BreakdownMetric,
-): { delta: number; deltaPct: number | null } {
- if (metric === 'visibility') {
- return {
- delta: Math.round((cur - prev) * 10) / 10,
- deltaPct: null,
- };
- }
- const delta = cur - prev;
- const deltaPct = prev > 0 ? Math.round((delta / prev) * 100) : null;
- return { delta, deltaPct };
-}
-
/**
- * Returns a per-prompt / per-platform / per-topic breakdown comparing the
- * current window with the previous window of equal duration.
+ * Per-prompt / per-platform / per-topic breakdown of the Visibility or
+ * Mentions card, comparing the window on screen with the one before it.
*
* Used by the Insights KPI drill-down Sheet to surface which entities drove a
* metric change (e.g. "Mentions dropped 12% because prompt X lost 84 mentions
- * on ChatGPT"). Windows mirror `getInsightsSummary` — when `dateFrom` is
- * provided the current window spans [dateFrom, dateTo ?? now] and the previous
- * window has the same length immediately before; otherwise both are 7 days.
+ * on ChatGPT"). VIS-001: the windows are the card's own (comparisonWindows),
+ * the totals come from the card's own aggregates, and the slices are
+ * aggregated in Postgres (insights_breakdown_groups, 00129) — the rows used
+ * to be fetched raw, capped at 1,000 per window, which scored an arbitrary
+ * sample instead of the card's answers.
*/
export async function getInsightsBreakdown(
brandId: string,
metric: BreakdownMetric,
- opts?: {
- model?: string;
- region?: string;
- dateFrom?: string;
- dateTo?: string;
- topicId?: string;
- },
+ opts?: BreakdownFilters,
): Promise<InsightsBreakdown> {
const supabase = await dbClient();
-
- let currentFrom: Date;
- let currentTo: Date;
-
- if (opts?.dateFrom) {
- currentFrom = new Date(opts.dateFrom);
- currentTo = opts.dateTo ? new Date(opts.dateTo) : new Date();
- } else {
- currentTo = new Date();
- currentFrom = new Date();
- currentFrom.setDate(currentFrom.getDate() - 7);
- }
-
- const duration = currentTo.getTime() - currentFrom.getTime();
- const prevFrom = new Date(currentFrom.getTime() - duration);
- const prevTo = currentFrom;
- const windowDays = Math.max(1, Math.round(duration / (24 * 60 * 60 * 1000)));
-
- const { query: curQuery } = await buildResultsQuery(brandId, {
- ...opts,
- dateFrom: currentFrom.toISOString(),
- dateTo: currentTo.toISOString(),
- });
- const { query: prevQuery } = await buildResultsQuery(brandId, {
- ...opts,
- dateFrom: prevFrom.toISOString(),
- dateTo: prevTo.toISOString(),
- });
-
- const [curRes, prevRes] = await Promise.all([curQuery, prevQuery]);
- if (curRes.error) throw new Error(curRes.error.message);
- if (prevRes.error) throw new Error(prevRes.error.message);
-
- type Row = {
- prompt_id: string;
- platform: string;
- mention_count: number;
- citation_count: number;
- visibility_score: number;
- mention_position: number | null;
- };
- const curRows = (curRes.data ?? []) as unknown as Row[];
- const prevRows = (prevRes.data ?? []) as unknown as Row[];
-
- const allPromptIds = new Set<string>();
- for (const r of curRows) allPromptIds.add(r.prompt_id);
- for (const r of prevRows) allPromptIds.add(r.prompt_id);
-
- // Resolve prompt text + topic for every participating prompt.
- const { data: promptRowsRaw } =
- allPromptIds.size > 0
- ? await supabase
- .from('prompts')
- .select('id, text, topic_id')
- .in('id', [...allPromptIds])
- : { data: [] as unknown[] };
-
- const promptInfo = new Map<string, { text: string; topicId: string | null }>();
- const topicIds = new Set<string>();
- for (const p of (promptRowsRaw ?? []) as Array<{
- id: string;
- text: string;
- topic_id: string | null;
- }>) {
- promptInfo.set(p.id, { text: p.text, topicId: p.topic_id });
- if (p.topic_id) topicIds.add(p.topic_id);
- }
-
- const { data: topicRowsRaw } =
- topicIds.size > 0
- ? await supabase
- .from('topics')
- .select('id, name')
- .in('id', [...topicIds])
- : { data: [] as unknown[] };
-
- const topicNameById = new Map<string, string>();
- for (const t of (topicRowsRaw ?? []) as Array<{ id: string; name: string }>) {
- topicNameById.set(t.id, t.name);
- }
-
- // ─── Group rows by prompt / platform / topic ────────────────────────────────
- function groupBy<K extends string>(rows: Row[], keyFn: (r: Row) => K) {
- const m = new Map<K, Row[]>();
- for (const r of rows) {
- const k = keyFn(r);
- const arr = m.get(k) ?? [];
- arr.push(r);
- m.set(k, arr);
- }
- return m;
- }
-
- function mergeKeys<K>(a: Map<K, unknown>, b: Map<K, unknown>): K[] {
- const s = new Set<K>();
- for (const k of a.keys()) s.add(k);
- for (const k of b.keys()) s.add(k);
- return [...s];
- }
-
- function buildRows(
- curMap: Map<string, Row[]>,
- prevMap: Map<string, Row[]>,
- resolver: (key: string) => { id: string; label: string; sublabel?: string },
- ): BreakdownRow[] {
- const keys = mergeKeys(curMap, prevMap);
- const rows: BreakdownRow[] = keys.map((key) => {
- const curAgg = aggregateMetric(curMap.get(key) ?? [], metric);
- const prevAgg = aggregateMetric(prevMap.get(key) ?? [], metric);
- const { delta, deltaPct } = computeDelta(curAgg.value, prevAgg.value, metric);
- const { id, label, sublabel } = resolver(key);
- return {
- id,
- label,
- sublabel,
- cur: curAgg.value,
- prev: prevAgg.value,
- delta,
- deltaPct,
- curRuns: curAgg.runs,
- prevRuns: prevAgg.runs,
- };
+ const windows = comparisonWindows(opts);
+ const p_models = modelFilterArray(opts?.model);
+ const p_region = opts?.region ?? undefined;
+
+ const groupsFor = (win: MetricWindow) =>
+ supabase.rpc('insights_breakdown_groups', {
+ p_brand_id: brandId,
+ p_models,
+ p_region,
+ p_topic_id: opts?.topicId ?? undefined,
+ ...(win.kind === 'days'
+ ? { p_day_from: win.days.dayFrom, p_day_to: win.days.dayTo }
+ : { p_date_from: win.from, p_date_to: win.to }),
});
- // Sort: biggest drops first, then biggest gains, untouched rows last.
- rows.sort((a, b) => a.delta - b.delta);
- return rows;
- }
-
- const curByPrompt = groupBy(curRows, (r) => r.prompt_id);
- const prevByPrompt = groupBy(prevRows, (r) => r.prompt_id);
- const byPrompt = buildRows(curByPrompt, prevByPrompt, (pid) => {
- const info = promptInfo.get(pid);
- const topicName = info?.topicId ? topicNameById.get(info.topicId) : undefined;
- return {
- id: pid,
- label: info?.text ?? 'Unknown prompt',
- sublabel: topicName,
- };
- });
-
- const curByPlatform = groupBy(curRows, (r) => r.platform);
- const prevByPlatform = groupBy(prevRows, (r) => r.platform);
- const byPlatform = buildRows(curByPlatform, prevByPlatform, (plat) => ({
- id: plat,
- label: formatPlatformLabel(plat),
- }));
+ // The headline numbers: exactly what the Visibility and Mentions cards read.
+ const totalFor = async (win: MetricWindow): Promise<number | null> => {
+ if (metric === 'visibility') {
+ const { data, error } = await aiVisibilityWindow(supabase, brandId, opts, win);
+ if (error) throw new Error(error.message);
+ return foldAiVisibility(data).brandScore;
+ }
+ const { data, error } =
+ win.kind === 'days'
+ ? await supabase.rpc('insights_aggregates_daily', {
+ p_brand_id: brandId,
+ p_platform: undefined,
+ p_models,
+ p_region,
+ p_day_from: win.days.dayFrom,
+ p_day_to: win.days.dayTo,
+ })
+ : await supabase.rpc('insights_aggregates', {
+ p_brand_id: brandId,
+ p_platform: undefined,
+ p_models,
+ p_region,
+ p_date_from: win.from,
+ p_date_to: win.to,
+ p_prompt_id: undefined,
+ p_topic_id: opts?.topicId ?? undefined,
+ });
+ if (error) throw new Error(error.message);
+ // Null for a window with no answers: the Mentions card shows no change
+ // unless both windows have some.
+ const agg = data as unknown as InsightsAggregates | null;
+ return agg && agg.total_results > 0 ? agg.total_mentions : null;
+ };
- const curByTopic = groupBy(curRows, (r) => {
- const info = promptInfo.get(r.prompt_id);
- return info?.topicId ?? '__uncategorized__';
- });
- const prevByTopic = groupBy(prevRows, (r) => {
- const info = promptInfo.get(r.prompt_id);
- return info?.topicId ?? '__uncategorized__';
- });
- const byTopic = buildRows(curByTopic, prevByTopic, (tid) => ({
- id: tid,
- label:
- tid === '__uncategorized__' ? 'Uncategorized' : (topicNameById.get(tid) ?? 'Unknown topic'),
- }));
+ const [curGroupsRes, prevGroupsRes, curScore, prevScore] = await Promise.all([
+ groupsFor(windows.cur),
+ windows.prev ? groupsFor(windows.prev) : Promise.resolve(null),
+ totalFor(windows.cur),
+ windows.prev ? totalFor(windows.prev) : Promise.resolve(null),
+ ]);
+ if (curGroupsRes.error) throw new Error(curGroupsRes.error.message);
+ if (prevGroupsRes?.error) throw new Error(prevGroupsRes.error.message);
- // ─── Totals + root-cause summary ────────────────────────────────────────────
- const curTotalAgg = aggregateMetric(curRows, metric);
- const prevTotalAgg = aggregateMetric(prevRows, metric);
- const { delta: totalDelta, deltaPct: totalDeltaPct } = computeDelta(
- curTotalAgg.value,
- prevTotalAgg.value,
+ const { byPrompt, byPlatform, byTopic } = buildBreakdownRows(
metric,
+ parseBreakdownGroups(curGroupsRes.data),
+ prevGroupsRes ? parseBreakdownGroups(prevGroupsRes.data) : null,
+ formatPlatformLabel,
);
- const metricLabel =
- metric === 'visibility' ? 'Visibility' : metric === 'mentions' ? 'Mentions' : 'Citations';
-
- const isDrop = totalDelta < 0;
- const isFlat = totalDelta === 0;
-
- // Select the biggest contributor in the same direction as the overall change.
- // `buildRows` sorts ascending by delta so byPrompt[0] is the largest drop and
- // byPrompt[last] is the largest gain.
- const topPrompt = isDrop ? byPrompt[0] : byPrompt[byPrompt.length - 1];
- const topPlatform = isDrop ? byPlatform[0] : byPlatform[byPlatform.length - 1];
+ // Totals and their change, worked out the way each card does.
+ let curTotal: number;
+ let prevTotal: number | null;
+ let totalDelta: number | null;
+ let totalDeltaPct: number | null;
+ if (metric === 'visibility') {
+ const v = visibilityChange(curScore, prevScore);
+ curTotal = v.value;
+ prevTotal = v.prev;
+ totalDelta = v.change;
+ totalDeltaPct = null;
+ } else {
+ curTotal = curScore ?? 0;
+ prevTotal = prevScore;
+ ({ delta: totalDelta, deltaPct: totalDeltaPct } =
+ curScore === null
+ ? { delta: null, deltaPct: null }
+ : breakdownDelta(curTotal, prevTotal, metric));
+ }
- const promptContributes = !!topPrompt && (isDrop ? topPrompt.delta < 0 : topPrompt.delta > 0);
- const platformContributes =
- !!topPlatform && (isDrop ? topPlatform.delta < 0 : topPlatform.delta > 0);
+ // ─── Root-cause summary ─────────────────────────────────────────────────────
+ const metricLabel = metric === 'visibility' ? 'Visibility' : 'Mentions';
+ const windowDays = windows.windowDays;
+ const topPrompt = pickDriver(byPrompt, totalDelta);
+ const topPlatform = pickDriver(byPlatform, totalDelta);
let rootCause: string;
- if (isFlat) {
+ if (!windows.prev) {
+ rootCause = `${metricLabel} over all time; there is no earlier period of the same length to compare.`;
+ } else if (totalDelta === null) {
+ rootCause = `No answers in one of the two ${windowDays}-day windows, so there is no change to explain yet.`;
+ } else if (totalDelta === 0) {
rootCause = `${metricLabel} held steady vs the previous ${windowDays}-day window.`;
- } else if (!promptContributes) {
+ } else if (!topPrompt) {
const dir = totalDelta > 0 ? 'rose' : 'fell';
const magnitude = formatTotalMagnitude(totalDelta, totalDeltaPct, metric);
rootCause = `${metricLabel} ${dir} ${magnitude} vs the previous ${windowDays}d — the change is spread evenly across prompts, no single driver.`;
} else {
- const headline = isDrop ? 'Biggest drop' : 'Biggest gain';
- const promptClause = `"${truncate(topPrompt!.label, 60)}" ${formatContribution(topPrompt!, metric)}`;
- const platformClause = platformContributes
- ? ` Top platform ${isDrop ? 'drop' : 'gain'}: ${topPlatform!.label} ${formatContribution(topPlatform!, metric)}.`
+ const headline = totalDelta < 0 ? 'Biggest drop' : 'Biggest gain';
+ const promptClause = `"${truncate(topPrompt.label, 60)}" ${formatContribution(topPrompt, metric)}`;
+ const platformClause = topPlatform
+ ? ` Top platform ${totalDelta < 0 ? 'drop' : 'gain'}: ${topPlatform.label} ${formatContribution(topPlatform, metric)}.`
: '';
rootCause = `${headline}: ${promptClause}.${platformClause}`;
}
return {
metric,
- curTotal: curTotalAgg.value,
- prevTotal: prevTotalAgg.value,
+ curTotal,
+ prevTotal,
delta: totalDelta,
deltaPct: totalDeltaPct,
windowDays,
@@ -3184,12 +2982,12 @@ function truncate(s: string, max: number): string {
/**
* Format a single contributor's delta as a human sentence fragment, e.g.:
* - mentions: "lost 84 mentions (−38%)" or "gained 12 mentions"
- * - citations: "lost 7 citations (−15%)"
* - visibility: "dropped 2.1 pts" or "rose 2.1 pts"
*/
function formatContribution(row: BreakdownRow, metric: BreakdownMetric): string {
- const isLoss = row.delta < 0;
- const abs = Math.abs(row.delta);
+ const delta = row.delta ?? 0;
+ const isLoss = delta < 0;
+ const abs = Math.abs(delta);
if (metric === 'visibility') {
const verb = isLoss ? 'dropped' : 'rose';
diff --git a/web/src/lib/insights-breakdown.test.ts b/web/src/lib/insights-breakdown.test.ts
new file mode 100644
index 000000000..2be68d29c
--- /dev/null
+++ b/web/src/lib/insights-breakdown.test.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it } from 'vitest';
+import { computeAiVisibilityScore } from './visibility-score';
+import {
+ buildBreakdownRows,
+ parseBreakdownGroups,
+ pickDriver,
+ type BreakdownGroup,
+ type BreakdownGroupsPayload,
+ type BreakdownRow,
+} from './insights-breakdown';
+
+const group = (
+ prompt_id: string,
+ platform: string,
+ answers: number,
+ mention_answers: number,
+ citation_answers: number,
+ mentions = mention_answers,
+ position: [number, number] = [mention_answers * 0.5, mention_answers],
+): BreakdownGroup => ({
+ prompt_id,
+ platform,
+ answers,
+ mention_answers,
+ citation_answers,
+ sum_inv_position: position[0],
+ position_count: position[1],
+ mentions,
+});
+
+const prompts = [
+ { id: 'p1', text: 'best rank tracker', topic_id: 't1', topic_name: 'Rank tracking' },
+ { id: 'p2', text: 'geo tools', topic_id: 't1', topic_name: 'Rank tracking' },
+ { id: 'p3', text: 'aeo audit', topic_id: null, topic_name: null },
+];
+
+const cur: BreakdownGroupsPayload = {
+ groups: [
+ group('p1', 'chatgpt', 40, 10, 4),
+ group('p1', 'gemini', 40, 30, 12),
+ group('p2', 'chatgpt', 20, 0, 0, 0, [0, 0]),
+ group('p3', 'gemini', 20, 8, 2),
+ ],
+ prompts,
+};
+
+const prev: BreakdownGroupsPayload = {
+ groups: [group('p1', 'chatgpt', 40, 20, 8), group('p1', 'gemini', 40, 30, 12)],
+ prompts,
+};
+
+const label = (slug: string) => ({ chatgpt: 'ChatGPT', gemini: 'Gemini' })[slug] ?? slug;
+
+/** The card's formula over a set of groups, pooled like the rollups pool answers. */
+function pooled(groups: BreakdownGroup[]): number {
+ const s = groups.reduce(
+ (acc, g) => ({
+ answers: acc.answers + g.answers,
+ mentionAnswers: acc.mentionAnswers + g.mention_answers,
+ citationAnswers: acc.citationAnswers + g.citation_answers,
+ inv: acc.inv + (g.sum_inv_position ?? 0),
+ n: acc.n + g.position_count,
+ }),
+ { answers: 0, mentionAnswers: 0, citationAnswers: 0, inv: 0, n: 0 },
+ );
+ return (
+ computeAiVisibilityScore({
+ answers: s.answers,
+ mentionAnswers: s.mentionAnswers,
+ citationAnswers: s.citationAnswers,
+ positionFactor: s.n > 0 ? s.inv / s.n : null,
+ }) ?? 0
+ );
+}
+
+describe('buildBreakdownRows', () => {
+ it('scores each slice with the card formula over all of its answers', () => {
+ const rows = buildBreakdownRows('visibility', cur, prev, label);
+
+ const p1 = rows.byPrompt.find((r) => r.id === 'p1')!;
+ expect(p1.cur).toBe(pooled(cur.groups.filter((g) => g.prompt_id === 'p1')));
+ expect(p1.curRuns).toBe(80);
+
+ const gemini = rows.byPlatform.find((r) => r.id === 'gemini')!;
+ expect(gemini.label).toBe('Gemini');
+ expect(gemini.cur).toBe(pooled(cur.groups.filter((g) => g.platform === 'gemini')));
+ });
+
+ it('groups prompts into their topics, and the rest into Uncategorized', () => {
+ const rows = buildBreakdownRows('visibility', cur, prev, label);
+
+ expect(rows.byTopic.map((r) => r.label).sort()).toEqual(['Rank tracking', 'Uncategorized']);
+ const topic = rows.byTopic.find((r) => r.id === 't1')!;
+ expect(topic.cur).toBe(pooled(cur.groups.filter((g) => g.prompt_id !== 'p3')));
+ expect(rows.byPrompt.find((r) => r.id === 'p1')!.sublabel).toBe('Rank tracking');
+ });
+
+ it('measures the change against the previous window and sorts drops first', () => {
+ const rows = buildBreakdownRows('visibility', cur, prev, label);
+
+ const chatgpt = rows.byPlatform.find((r) => r.id === 'chatgpt')!;
+ expect(chatgpt.prev).toBe(pooled(prev.groups.filter((g) => g.platform === 'chatgpt')));
+ expect(chatgpt.delta).toBe(Math.round((chatgpt.cur - chatgpt.prev!) * 10) / 10);
+ expect(rows.byPlatform[0].id).toBe('chatgpt');
+ // A slice with no answers in the previous window counts as 0 there.
+ expect(rows.byPrompt.find((r) => r.id === 'p3')!.prev).toBe(0);
+ });
+
+ it('carries no previous value or change without a previous window (All time)', () => {
+ const rows = buildBreakdownRows('visibility', cur, null, label);
+
+ for (const r of [...rows.byPrompt, ...rows.byPlatform, ...rows.byTopic]) {
+ expect(r.prev).toBeNull();
+ expect(r.delta).toBeNull();
+ }
+ });
+
+ it('sums mentions and gives their percentage change', () => {
+ const rows = buildBreakdownRows('mentions', cur, prev, label);
+
+ const p1 = rows.byPrompt.find((r) => r.id === 'p1')!;
+ expect(p1).toMatchObject({ cur: 40, prev: 50, delta: -10, deltaPct: -20 });
+ });
+});
+
+describe('pickDriver', () => {
+ const row = (id: string, delta: number | null): BreakdownRow => ({
+ id,
+ label: id,
+ cur: 0,
+ prev: delta === null ? null : 0,
+ delta,
+ deltaPct: null,
+ curRuns: 0,
+ prevRuns: 0,
+ });
+
+ it('picks the biggest drop when the total fell, and the biggest gain when it rose', () => {
+ const rows = [row('a', -4), row('b', -1), row('c', 3)];
+
+ expect(pickDriver(rows, -2)?.id).toBe('a');
+ expect(pickDriver(rows, 2)?.id).toBe('c');
+ });
+
+ it('has no driver when nothing moved that way, or nothing to compare', () => {
+ expect(pickDriver([row('a', -1)], 2)).toBeNull();
+ expect(pickDriver([row('a', 5)], 0)).toBeNull();
+ expect(pickDriver([row('a', null)], null)).toBeNull();
+ });
+});
+
+describe('parseBreakdownGroups', () => {
+ it('reads the RPC payload, numeric strings and missing parts included', () => {
+ const parsed = parseBreakdownGroups({
+ groups: [
+ {
+ prompt_id: 'p1',
+ platform: 'chatgpt',
+ answers: '3',
+ mention_answers: 1,
+ citation_answers: 0,
+ sum_inv_position: null,
+ position_count: 0,
+ mentions: 2,
+ },
+ ],
+ });
+
+ expect(parsed.groups[0]).toMatchObject({ answers: 3, sum_inv_position: null, mentions: 2 });
+ expect(parsed.prompts).toEqual([]);
+ expect(parseBreakdownGroups(null)).toEqual({ groups: [], prompts: [] });
+ });
+});
diff --git a/web/src/lib/insights-breakdown.ts b/web/src/lib/insights-breakdown.ts
new file mode 100644
index 000000000..dd8ede7aa
--- /dev/null
+++ b/web/src/lib/insights-breakdown.ts
@@ -0,0 +1,257 @@
+import { computeAiVisibilityScore } from '@/lib/visibility-score';
+import { percentageChange } from '@/lib/metrics';
+import type { DayWindow } from '@/lib/insights-windows';
+
+/**
+ * The Insights "View breakdown" panel (VIS-001): which prompts, platforms and
+ * topics moved a metric between two windows. The rows are built here from
+ * the grouped components `insights_breakdown_groups` (00129) returns; the
+ * totals come from the same aggregates as the KPI card, so the panel's
+ * headline is the card's number.
+ */
+
+export type BreakdownMetric = 'mentions' | 'visibility';
+
+/** The window and filters a breakdown explains: the ones the cards were loaded with. */
+export interface BreakdownFilters {
+ model?: string;
+ region?: string;
+ topicId?: string;
+ dateFrom?: string;
+ dateTo?: string;
+ days?: DayWindow;
+}
+
+export interface BreakdownRow {
+ /** Unique identifier for the row: prompt_id / platform name / topic_id. */
+ id: string;
+ /** Display label: prompt text / platform name / topic name. */
+ label: string;
+ /** Optional secondary label (e.g. topic name for a prompt). */
+ sublabel?: string;
+ /** Metric value in the current window. */
+ cur: number;
+ /** Metric value in the previous window; null when there is none (All time). */
+ prev: number | null;
+ /** Absolute change (cur - prev); null without a previous window. */
+ delta: number | null;
+ /** Percentage change. Null when previous is zero or absent (use delta instead). */
+ deltaPct: number | null;
+ /** Answers that contributed in the current window. */
+ curRuns: number;
+ /** Answers that contributed in the previous window. */
+ prevRuns: number;
+}
+
+export interface InsightsBreakdown {
+ metric: BreakdownMetric;
+ curTotal: number;
+ /** Null when there is no previous window (All time). */
+ prevTotal: number | null;
+ delta: number | null;
+ deltaPct: number | null;
+ /** Days in each comparison window (24h is 1); null for All time. */
+ windowDays: number | null;
+ byPrompt: BreakdownRow[];
+ byPlatform: BreakdownRow[];
+ byTopic: BreakdownRow[];
+ /** One-line rule-based root-cause summary for the drop/rise. */
+ rootCause: string;
+}
+
+/** One (prompt, platform) entry of `insights_breakdown_groups`. */
+export interface BreakdownGroup {
+ prompt_id: string;
+ platform: string;
+ answers: number;
+ mention_answers: number;
+ citation_answers: number;
+ sum_inv_position: number | null;
+ position_count: number;
+ mentions: number;
+}
+
+export interface BreakdownPrompt {
+ id: string;
+ text: string;
+ topic_id: string | null;
+ topic_name: string | null;
+}
+
+/** The payload of `insights_breakdown_groups` for one window. */
+export interface BreakdownGroupsPayload {
+ groups: BreakdownGroup[];
+ prompts: BreakdownPrompt[];
+}
+
+export function parseBreakdownGroups(raw: unknown): BreakdownGroupsPayload {
+ const payload = (raw ?? {}) as Partial<BreakdownGroupsPayload>;
+ return {
+ groups: (payload.groups ?? []).map((g) => ({
+ prompt_id: String(g.prompt_id),
+ platform: String(g.platform),
+ answers: Number(g.answers ?? 0),
+ mention_answers: Number(g.mention_answers ?? 0),
+ citation_answers: Number(g.citation_answers ?? 0),
+ sum_inv_position: g.sum_inv_position === null ? null : Number(g.sum_inv_position ?? 0),
+ position_count: Number(g.position_count ?? 0),
+ mentions: Number(g.mentions ?? 0),
+ })),
+ prompts: payload.prompts ?? [],
+ };
+}
+
+interface Sums {
+ answers: number;
+ mentionAnswers: number;
+ citationAnswers: number;
+ sumInvPosition: number;
+ positionCount: number;
+ mentions: number;
+}
+
+const emptySums = (): Sums => ({
+ answers: 0,
+ mentionAnswers: 0,
+ citationAnswers: 0,
+ sumInvPosition: 0,
+ positionCount: 0,
+ mentions: 0,
+});
+
+function addGroup(s: Sums, g: BreakdownGroup) {
+ s.answers += g.answers;
+ s.mentionAnswers += g.mention_answers;
+ s.citationAnswers += g.citation_answers;
+ s.sumInvPosition += g.sum_inv_position ?? 0;
+ s.positionCount += g.position_count;
+ s.mentions += g.mentions;
+}
+
+/**
+ * A group's value. Visibility is the card's formula over the group's own
+ * answers, so a row reads exactly like the card would for that slice; a
+ * group with no answers in the window scores 0.
+ */
+function valueOf(s: Sums, metric: BreakdownMetric): number {
+ if (metric === 'mentions') return s.mentions;
+ return (
+ computeAiVisibilityScore({
+ answers: s.answers,
+ mentionAnswers: s.mentionAnswers,
+ citationAnswers: s.citationAnswers,
+ positionFactor: s.positionCount > 0 ? s.sumInvPosition / s.positionCount : null,
+ }) ?? 0
+ );
+}
+
+/**
+ * Change between two values: points with one decimal for Visibility, a
+ * count plus a percentage for Mentions. Null without a previous value.
+ */
+export function breakdownDelta(
+ cur: number,
+ prev: number | null,
+ metric: BreakdownMetric,
+): { delta: number | null; deltaPct: number | null } {
+ if (prev === null) return { delta: null, deltaPct: null };
+ if (metric === 'visibility') {
+ return { delta: Math.round((cur - prev) * 10) / 10, deltaPct: null };
+ }
+ return { delta: cur - prev, deltaPct: percentageChange(cur, prev) };
+}
+
+function sumBy(groups: BreakdownGroup[], keyOf: (g: BreakdownGroup) => string): Map<string, Sums> {
+ const out = new Map<string, Sums>();
+ for (const g of groups) {
+ const key = keyOf(g);
+ const sums = out.get(key) ?? emptySums();
+ addGroup(sums, g);
+ out.set(key, sums);
+ }
+ return out;
+}
+
+const UNCATEGORIZED = '__uncategorized__';
+
+/**
+ * Per-prompt, per-platform and per-topic rows for one comparison. `prev` is
+ * null when there is no previous window (All time): rows then carry no
+ * previous value and no change. A slice missing from one window counts as 0
+ * there. Rows come sorted by change, biggest drop first.
+ */
+export function buildBreakdownRows(
+ metric: BreakdownMetric,
+ cur: BreakdownGroupsPayload,
+ prev: BreakdownGroupsPayload | null,
+ platformLabel: (slug: string) => string,
+): { byPrompt: BreakdownRow[]; byPlatform: BreakdownRow[]; byTopic: BreakdownRow[] } {
+ const prompts = new Map<string, BreakdownPrompt>();
+ for (const p of [...(prev?.prompts ?? []), ...cur.prompts]) prompts.set(p.id, p);
+ const topicOf = (g: BreakdownGroup) => prompts.get(g.prompt_id)?.topic_id ?? UNCATEGORIZED;
+ const topicNames = new Map<string, string>();
+ for (const p of prompts.values()) {
+ if (p.topic_id && p.topic_name) topicNames.set(p.topic_id, p.topic_name);
+ }
+
+ const rows = (
+ keyOf: (g: BreakdownGroup) => string,
+ describe: (key: string) => { label: string; sublabel?: string },
+ ): BreakdownRow[] => {
+ const curSums = sumBy(cur.groups, keyOf);
+ const prevSums = prev ? sumBy(prev.groups, keyOf) : new Map<string, Sums>();
+ const keys = new Set([...curSums.keys(), ...prevSums.keys()]);
+ const out = [...keys].map((key): BreakdownRow => {
+ const c = curSums.get(key) ?? emptySums();
+ const p = prevSums.get(key) ?? emptySums();
+ const curValue = valueOf(c, metric);
+ const prevValue = prev ? valueOf(p, metric) : null;
+ return {
+ id: key,
+ ...describe(key),
+ cur: curValue,
+ prev: prevValue,
+ ...breakdownDelta(curValue, prevValue, metric),
+ curRuns: c.answers,
+ prevRuns: p.answers,
+ };
+ });
+ out.sort((a, b) => (a.delta ?? 0) - (b.delta ?? 0));
+ return out;
+ };
+
+ return {
+ byPrompt: rows(
+ (g) => g.prompt_id,
+ (id) => {
+ const info = prompts.get(id);
+ return {
+ label: info?.text ?? 'Unknown prompt',
+ sublabel: info?.topic_name ?? undefined,
+ };
+ },
+ ),
+ byPlatform: rows(
+ (g) => g.platform,
+ (slug) => ({ label: platformLabel(slug) }),
+ ),
+ byTopic: rows(topicOf, (id) => ({
+ label: id === UNCATEGORIZED ? 'Uncategorized' : (topicNames.get(id) ?? 'Unknown topic'),
+ })),
+ };
+}
+
+/**
+ * The row that did the most in the direction of the overall change: the
+ * biggest drop when the total fell, the biggest gain when it rose. Null when
+ * nothing moved that way, or when there is no previous window.
+ */
+export function pickDriver(rows: BreakdownRow[], totalDelta: number | null): BreakdownRow | null {
+ if (totalDelta === null || totalDelta === 0) return null;
+ let best: BreakdownRow | null = null;
+ for (const r of rows) {
+ if (r.delta === null) continue;
+ if (totalDelta < 0 ? r.delta < (best?.delta ?? 0) : r.delta > (best?.delta ?? 0)) best = r;
+ }
+ return best;
+}
diff --git a/web/src/lib/insights-windows.test.ts b/web/src/lib/insights-windows.test.ts
new file mode 100644
index 000000000..995065062
--- /dev/null
+++ b/web/src/lib/insights-windows.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, it } from 'vitest';
+import {
+ comparisonWindows,
+ deltaDayWindows,
+ visibilityChange,
+ windowBounds,
+} from './insights-windows';
+
+describe('comparisonWindows', () => {
+ it('compares a 30-day preset with the 30 whole days before it', () => {
+ const w = comparisonWindows({
+ dateFrom: '2026-09-15T00:00:00.000Z',
+ days: { dayFrom: '2026-09-15', dayTo: '2026-10-14' },
+ });
+
+ expect(w.cur).toEqual({ kind: 'days', days: { dayFrom: '2026-09-15', dayTo: '2026-10-14' } });
+ expect(w.prev).toEqual({ kind: 'days', days: { dayFrom: '2026-08-16', dayTo: '2026-09-14' } });
+ // Counted in days, not rounded from elapsed time: 30, whatever the hour.
+ expect(w.windowDays).toBe(30);
+ });
+
+ it('has no previous window for All time', () => {
+ const w = comparisonWindows({ days: {} });
+
+ expect(w.cur).toEqual({ kind: 'days', days: {} });
+ expect(w.prev).toBeNull();
+ expect(w.windowDays).toBeNull();
+ });
+
+ it('uses raw timestamps when a topic is selected, like the card', () => {
+ const now = new Date('2026-10-14T12:00:00.000Z');
+ const w = comparisonWindows(
+ {
+ topicId: 'topic-1',
+ dateFrom: '2026-10-08T00:00:00.000Z',
+ days: { dayFrom: '2026-10-08', dayTo: '2026-10-14' },
+ },
+ now,
+ );
+
+ expect(w.cur).toEqual({
+ kind: 'range',
+ from: '2026-10-08T00:00:00.000Z',
+ to: '2026-10-14T12:00:00.000Z',
+ });
+ expect(w.prev).toEqual({
+ kind: 'range',
+ from: '2026-10-01T12:00:00.000Z',
+ to: '2026-10-08T00:00:00.000Z',
+ });
+ });
+
+ it('counts whole days on the raw path too, so a topic-filtered 30d view is 30 days', () => {
+ // 09:00 UTC: the elapsed time since the first day's midnight rounds to 29.
+ const now = new Date('2026-10-14T09:00:00.000Z');
+ const w = comparisonWindows(
+ {
+ topicId: 'topic-1',
+ dateFrom: '2026-09-15T00:00:00.000Z',
+ days: { dayFrom: '2026-09-15', dayTo: '2026-10-14' },
+ },
+ now,
+ );
+
+ expect(w.cur.kind).toBe('range');
+ expect(w.windowDays).toBe(30);
+ });
+
+ it('compares an anchored 24h window with the 24 hours before it', () => {
+ const w = comparisonWindows({
+ dateFrom: '2026-10-13T06:00:00.000Z',
+ dateTo: '2026-10-14T06:00:00.000Z',
+ });
+
+ expect(w.prev).toEqual({
+ kind: 'range',
+ from: '2026-10-12T06:00:00.000Z',
+ to: '2026-10-13T06:00:00.000Z',
+ });
+ expect(w.windowDays).toBe(1);
+ });
+
+ it('has no previous window on the raw path without a start', () => {
+ const now = new Date('2026-10-14T12:00:00.000Z');
+ const w = comparisonWindows({ topicId: 'topic-1', days: {} }, now);
+
+ expect(w.cur).toEqual({ kind: 'range', from: undefined, to: '2026-10-14T12:00:00.000Z' });
+ expect(w.prev).toBeNull();
+ });
+
+ it('agrees with deltaDayWindows, which the other cards use', () => {
+ const days = { dayFrom: '2026-10-08', dayTo: '2026-10-14' };
+ const w = comparisonWindows({ days });
+
+ expect(w.prev).toEqual({ kind: 'days', days: deltaDayWindows(days).prev });
+ });
+});
+
+describe('visibilityChange', () => {
+ it('rounds the change to one decimal', () => {
+ expect(visibilityChange(17.4, 15.9)).toEqual({ value: 17.4, prev: 15.9, change: 1.5 });
+ });
+
+ it('has no change without a previous score', () => {
+ expect(visibilityChange(17.4, null)).toEqual({ value: 17.4, prev: null, change: null });
+ });
+
+ it('reads an empty current window as 0', () => {
+ expect(visibilityChange(null, 3)).toEqual({ value: 0, prev: 3, change: -3 });
+ });
+});
+
+describe('windowBounds', () => {
+ it('gives days for whole-day windows and timestamps otherwise', () => {
+ expect(
+ windowBounds({ kind: 'days', days: { dayFrom: '2026-08-16', dayTo: '2026-09-14' } }),
+ ).toEqual({ from: '2026-08-16', to: '2026-09-14' });
+ expect(
+ windowBounds({ kind: 'range', from: undefined, to: '2026-10-14T06:00:00.000Z' }),
+ ).toEqual({
+ from: '',
+ to: '2026-10-14T06:00:00.000Z',
+ });
+ });
+});
diff --git a/web/src/lib/insights-windows.ts b/web/src/lib/insights-windows.ts
new file mode 100644
index 000000000..eac1cdfd0
--- /dev/null
+++ b/web/src/lib/insights-windows.ts
@@ -0,0 +1,159 @@
+import { expandDateToEndOfDay } from '@/lib/dates';
+
+// ── Daily-rollup routing (00066) ────────────────────────────────────────────
+//
+// The aggregate RPCs used to rescan a brand's whole history per page load;
+// past ~55k results that exceeds the authenticated role's 8s statement
+// timeout and the wide presets die. Every preset except 24h now describes its
+// window as whole UTC days, and calls that carry one are answered from the
+// pre-aggregated daily tables instead — cost scales with days in the window,
+// never with accumulated results.
+//
+// Topic-filtered calls deliberately stay on the raw RPCs: topic is a live
+// prompt attribute (reassigning a prompt must move its history), the rollups
+// have no prompt dimension at brand grain, and a topic slice is a small
+// fraction of the scan that made the raw path unaffordable.
+
+/**
+ * Whole-day UTC window, 'YYYY-MM-DD' inclusive on both ends. Its presence in
+ * an action's opts marks the call as servable from the daily rollups; either
+ * bound may be absent (the All-time preset carries an empty window).
+ */
+export interface DayWindow {
+ dayFrom?: string;
+ dayTo?: string;
+}
+
+export interface WindowedOpts {
+ topicId?: string;
+ days?: DayWindow;
+}
+
+/** The day window to serve from rollups, or null when the raw path must answer. */
+export function dailyWindow(opts?: WindowedOpts): DayWindow | null {
+ return opts?.days && !opts.topicId ? opts.days : null;
+}
+
+export const DAY_MS = 86_400_000;
+
+export function utcToday(): string {
+ return new Date().toISOString().slice(0, 10);
+}
+
+export function addDays(day: string, n: number): string {
+ return new Date(Date.parse(`${day}T00:00:00Z`) + n * DAY_MS).toISOString().slice(0, 10);
+}
+
+/**
+ * Current + previous equal-length day windows for the ↑/↓ delta math. An
+ * unbounded window anchors to the trailing 7 days, mirroring what the raw
+ * path's `now() - 7d` default has always compared against. The previous
+ * window ends the day BEFORE the current one starts — the raw path's
+ * timestamp arithmetic let the two windows share their boundary instant.
+ */
+export function deltaDayWindows(days: DayWindow): {
+ cur: { dayFrom: string; dayTo: string };
+ prev: { dayFrom: string; dayTo: string };
+} {
+ const curTo = days.dayTo ?? utcToday();
+ const curFrom = days.dayFrom ?? addDays(curTo, -6);
+ const len = Math.round((Date.parse(curTo) - Date.parse(curFrom)) / DAY_MS) + 1;
+ const prevTo = addDays(curFrom, -1);
+ return {
+ cur: { dayFrom: curFrom, dayTo: curTo },
+ prev: { dayFrom: addDays(prevTo, -(len - 1)), dayTo: prevTo },
+ };
+}
+
+// ── Comparison windows (VIS-001) ────────────────────────────────────────────
+
+/**
+ * One window an Insights number is computed over: whole UTC days, answered
+ * from the daily rollups, or a timestamp range, answered from the raw rows
+ * (the 24h view and any topic filter). An absent bound is open.
+ */
+export type MetricWindow =
+ | { kind: 'days'; days: DayWindow }
+ | { kind: 'range'; from?: string; to?: string };
+
+export interface ComparisonWindows {
+ /** The window the number on screen covers. */
+ cur: MetricWindow;
+ /** The equal-length window right before it; null for All time, which has none. */
+ prev: MetricWindow | null;
+ /** Length of `cur` in days (24h is 1); null for All time. */
+ windowDays: number | null;
+}
+
+/**
+ * The windows behind the Visibility number and its change. The card, the
+ * breakdown panel and the leaderboard all take their windows from here, so
+ * the same filters always compare the same answers (VIS-001).
+ *
+ * - Whole-day windows compare against the equal run of whole days ending
+ * the day before (deltaDayWindows).
+ * - Timestamp windows compare against the equal span ending where the
+ * current one starts.
+ * - All time has no previous window: there is no earlier period of the same
+ * length to compare with, so it shows no change at all.
+ */
+export function comparisonWindows(
+ opts?: WindowedOpts & { dateFrom?: string; dateTo?: string },
+ now: Date = new Date(),
+): ComparisonWindows {
+ const daily = dailyWindow(opts);
+ if (daily) {
+ if (!daily.dayFrom) return { cur: { kind: 'days', days: daily }, prev: null, windowDays: null };
+ const { cur, prev } = deltaDayWindows(daily);
+ return {
+ cur: { kind: 'days', days: daily },
+ prev: { kind: 'days', days: prev },
+ windowDays: dayCount(cur),
+ };
+ }
+
+ const from = opts?.dateFrom || undefined;
+ const to = expandDateToEndOfDay(opts?.dateTo) ?? now.toISOString();
+ if (!from) return { cur: { kind: 'range', from: undefined, to }, prev: null, windowDays: null };
+ const span = Date.parse(to) - Date.parse(from);
+ return {
+ cur: { kind: 'range', from, to },
+ prev: { kind: 'range', from: new Date(Date.parse(from) - span).toISOString(), to: from },
+ // A day preset read raw (a topic is selected) still covers whole days:
+ // count them, as on the rollup path, rather than rounding elapsed time.
+ windowDays: opts?.days?.dayFrom
+ ? dayCount(deltaDayWindows(opts.days).cur)
+ : Math.max(1, Math.round(span / DAY_MS)),
+ };
+}
+
+function dayCount(days: { dayFrom: string; dayTo: string }): number {
+ return Math.round((Date.parse(days.dayTo) - Date.parse(days.dayFrom)) / DAY_MS) + 1;
+}
+
+/**
+ * A window's bounds for display: 'YYYY-MM-DD' UTC days for whole-day
+ * windows, ISO timestamps otherwise; '' for an open bound.
+ */
+export function windowBounds(win: MetricWindow): { from: string; to: string } {
+ return win.kind === 'days'
+ ? { from: win.days.dayFrom ?? '', to: win.days.dayTo ?? '' }
+ : { from: win.from ?? '', to: win.to ?? '' };
+}
+
+/**
+ * The Visibility number and its change, from the scores of the two windows.
+ * An empty current window reads as 0 (the card has always shown a number);
+ * the change is null when there is nothing to compare with.
+ */
+export function visibilityChange(
+ curScore: number | null,
+ prevScore: number | null,
+): { value: number; prev: number | null; change: number | null } {
+ const value = curScore ?? 0;
+ return {
+ value,
+ prev: prevScore,
+ change: prevScore === null ? null : Math.round((value - prevScore) * 10) / 10,
+ };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 8e4f1346c..1dcae1de1 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3074,6 +3074,19 @@ export type Database = {
}
Returns: Json
}
+ insights_breakdown_groups: {
+ Args: {
+ p_brand_id: string
+ p_date_from?: string
+ p_date_to?: string
+ p_day_from?: string
+ p_day_to?: string
+ p_models?: string[]
+ p_region?: string
+ p_topic_id?: string
+ }
+ Returns: Json
+ }
insights_filter_options: {
Args: { p_brand_id: string }
Returns: {