Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(insights): explain the visibility change beside the platform table
Cihan26e857a52e66
diff --git a/supabase/migrations/00135_insights_change_drivers.sql b/supabase/migrations/00135_insights_change_drivers.sqlnew file mode 100644index 000000000..4a2a00d83--- /dev/null+++ b/supabase/migrations/00135_insights_change_drivers.sql@@ -0,0 +1,275 @@+-- Insights "Why it changed" (VIS-009).+--+-- The v2 mockup explains the Visibility change beside the By AI platform+-- table: the platforms, topics and prompts that moved it most, each with its+-- own score before → after and its effect on the overall score, plus a line+-- for the prompts added this period ("509 new prompts · Sep 29 · own+-- baseline, not counted").+--+-- These return the Visibility components per prompt and per (model,+-- platform) in both comparison windows, over the prompts answered in both+-- when p_same_prompts (00130), with each prompt's text and topic; the app+-- folds engines into platforms and prompts into topics, and scores every+-- slice with the card's formula. They also count the prompts answered this+-- period but not the one before, and when the ones created this period were+-- added. The rollups serve whole days, so the box costs what the cards cost;+-- prompt_results serves the 24h and topic views, like+-- insights_platform_compare (00132).+-- `complete` is false while the prompt-grain rollups behind the window are+-- not backfilled (00130).++create or replace function public.insights_change_drivers_daily(+ p_brand_id uuid,+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_models text[] default null,+ p_region text default null,+ p_same_prompts boolean default true+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with prompt_rows as (+ select d.*,+ case when d.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (d.day between p_cur_from and p_cur_to or d.day between p_prev_from and p_prev_to)+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur') as in_cur,+ bool_or(win = 'prev') as in_prev+ from prompt_rows+ group by prompt_id+ ),+ scoped as (+ select r.* from prompt_rows r join presence p using (prompt_id)+ where not p_same_prompts or (p.in_cur and p.in_prev)+ ),+ by_prompt as (+ select prompt_id, win,+ sum(answer_count) as answers,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count+ from scoped+ group by prompt_id, win+ ),+ by_engine as (+ select model_used, platform, win,+ sum(answer_count) as answers,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count+ from scoped+ group by model_used, platform, win+ ),+ added as (+ select p.created_at+ from presence pr+ join public.prompts p on p.id = pr.prompt_id+ where pr.in_cur and not pr.in_prev+ )+ select jsonb_build_object(+ 'complete', not exists (select 1 from prompt_rows where mention_answers is null),+ 'prompts', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'prompt_id', b.prompt_id,+ 'win', b.win,+ 'answers', b.answers,+ 'mention_answers', b.mention_answers,+ 'citation_answers', b.citation_answers,+ 'sum_inv_position', b.sum_inv_position,+ 'position_count', b.position_count))+ from by_prompt b),+ '[]'::jsonb),+ 'engines', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', e.model_used,+ 'platform', e.platform,+ 'win', e.win,+ 'answers', e.answers,+ 'mention_answers', e.mention_answers,+ 'citation_answers', e.citation_answers,+ 'sum_inv_position', e.sum_inv_position,+ 'position_count', e.position_count))+ from by_engine e),+ '[]'::jsonb),+ 'prompt_info', 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 prompt_id from by_prompt)),+ '[]'::jsonb),+ -- Dates only for prompts created this period: one answered again after+ -- a pause is new to the comparison, not newly added.+ 'new_prompts', (select jsonb_build_object(+ 'count', count(*),+ 'first_added', min(created_at) filter (+ where created_at >= (p_cur_from::timestamp at time zone 'utc')),+ 'last_added', max(created_at) filter (+ where created_at >= (p_cur_from::timestamp at time zone 'utc')))+ from added)+ );+$$;++create or replace function public.insights_change_drivers(+ p_brand_id uuid,+ p_cur_from timestamptz,+ p_cur_to timestamptz,+ p_prev_from timestamptz,+ p_prev_to timestamptz,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null,+ p_same_prompts boolean default true+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with filtered as (+ select pr.prompt_id, pr.model_used, pr.platform, pr.created_at,+ pr.mention_count, pr.citation_count, pr.mention_position+ 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 pr.created_at >= p_prev_from+ and pr.created_at <= p_cur_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))+ ),+ -- Each window selected on its own, inclusive at both ends like the card.+ windowed as (+ select 'cur' as win, f.* from filtered f+ where f.created_at >= p_cur_from and f.created_at <= p_cur_to+ union all+ select 'prev' as win, f.* from filtered f+ where f.created_at >= p_prev_from and f.created_at <= p_prev_to+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur') as in_cur,+ bool_or(win = 'prev') as in_prev+ from windowed+ group by prompt_id+ ),+ scoped as (+ select w.* from windowed w join presence p using (prompt_id)+ where not p_same_prompts or (p.in_cur and p.in_prev)+ ),+ by_prompt as (+ select prompt_id, win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ sum(1.0 / mention_position) filter (where mention_position is not null)+ as sum_inv_position,+ count(*) filter (where mention_position is not null) as position_count+ from scoped+ group by prompt_id, win+ ),+ by_engine as (+ select model_used, platform, win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ sum(1.0 / mention_position) filter (where mention_position is not null)+ as sum_inv_position,+ count(*) filter (where mention_position is not null) as position_count+ from scoped+ group by model_used, platform, win+ ),+ added as (+ select p.created_at+ from presence pr+ join public.prompts p on p.id = pr.prompt_id+ where pr.in_cur and not pr.in_prev+ )+ select jsonb_build_object(+ 'complete', true,+ 'prompts', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'prompt_id', b.prompt_id,+ 'win', b.win,+ 'answers', b.answers,+ 'mention_answers', b.mention_answers,+ 'citation_answers', b.citation_answers,+ 'sum_inv_position', b.sum_inv_position,+ 'position_count', b.position_count))+ from by_prompt b),+ '[]'::jsonb),+ 'engines', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', e.model_used,+ 'platform', e.platform,+ 'win', e.win,+ 'answers', e.answers,+ 'mention_answers', e.mention_answers,+ 'citation_answers', e.citation_answers,+ 'sum_inv_position', e.sum_inv_position,+ 'position_count', e.position_count))+ from by_engine e),+ '[]'::jsonb),+ 'prompt_info', 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 prompt_id from by_prompt)),+ '[]'::jsonb),+ -- Dates only for prompts created this period: one answered again after+ -- a pause is new to the comparison, not newly added.+ 'new_prompts', (select jsonb_build_object(+ 'count', count(*),+ 'first_added', min(created_at) filter (where created_at >= p_cur_from),+ 'last_added', max(created_at) filter (where created_at >= p_cur_from))+ from added)+ );+$$;++revoke all on function public.insights_change_drivers_daily(+ uuid, date, date, date, date, text[], text, boolean+) from public;+grant execute on function public.insights_change_drivers_daily(+ uuid, date, date, date, date, text[], text, boolean+) to authenticated, service_role;++revoke all on function public.insights_change_drivers(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean+) from public;+grant execute on function public.insights_change_drivers(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean+) to authenticated, service_role;++comment on function public.insights_change_drivers_daily(+ uuid, date, date, date, date, text[], text, boolean+) is+ 'Insights "Why it changed" (VIS-009, 00135): Visibility components per prompt and per (model, platform) in both comparison windows, over the prompts answered in both when p_same_prompts, with prompt text and topic, and the prompts new this period, from the prompt-grain rollups. complete=false until they are backfilled (00130).';++comment on function public.insights_change_drivers(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean+) is+ 'Insights "Why it changed" (VIS-009, 00135) for timestamp windows (24h, topic views), from prompt_results. Same output as insights_change_drivers_daily.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 561f57fc3..8b729cf66 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -16256,3 +16256,282 @@ as $$);$$;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00135_insights_change_drivers.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Insights "Why it changed" (VIS-009).+--+-- The v2 mockup explains the Visibility change beside the By AI platform+-- table: the platforms, topics and prompts that moved it most, each with its+-- own score before → after and its effect on the overall score, plus a line+-- for the prompts added this period ("509 new prompts · Sep 29 · own+-- baseline, not counted").+--+-- These return the Visibility components per prompt and per (model,+-- platform) in both comparison windows, over the prompts answered in both+-- when p_same_prompts (00130), with each prompt's text and topic; the app+-- folds engines into platforms and prompts into topics, and scores every+-- slice with the card's formula. They also count the prompts answered this+-- period but not the one before, and when the ones created this period were+-- added. The rollups serve whole days, so the box costs what the cards cost;+-- prompt_results serves the 24h and topic views, like+-- insights_platform_compare (00132).+-- `complete` is false while the prompt-grain rollups behind the window are+-- not backfilled (00130).++create or replace function public.insights_change_drivers_daily(+ p_brand_id uuid,+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_models text[] default null,+ p_region text default null,+ p_same_prompts boolean default true+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with prompt_rows as (+ select d.*,+ case when d.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (d.day between p_cur_from and p_cur_to or d.day between p_prev_from and p_prev_to)+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur') as in_cur,+ bool_or(win = 'prev') as in_prev+ from prompt_rows+ group by prompt_id+ ),+ scoped as (+ select r.* from prompt_rows r join presence p using (prompt_id)+ where not p_same_prompts or (p.in_cur and p.in_prev)+ ),+ by_prompt as (+ select prompt_id, win,+ sum(answer_count) as answers,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count+ from scoped+ group by prompt_id, win+ ),+ by_engine as (+ select model_used, platform, win,+ sum(answer_count) as answers,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count+ from scoped+ group by model_used, platform, win+ ),+ added as (+ select p.created_at+ from presence pr+ join public.prompts p on p.id = pr.prompt_id+ where pr.in_cur and not pr.in_prev+ )+ select jsonb_build_object(+ 'complete', not exists (select 1 from prompt_rows where mention_answers is null),+ 'prompts', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'prompt_id', b.prompt_id,+ 'win', b.win,+ 'answers', b.answers,+ 'mention_answers', b.mention_answers,+ 'citation_answers', b.citation_answers,+ 'sum_inv_position', b.sum_inv_position,+ 'position_count', b.position_count))+ from by_prompt b),+ '[]'::jsonb),+ 'engines', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', e.model_used,+ 'platform', e.platform,+ 'win', e.win,+ 'answers', e.answers,+ 'mention_answers', e.mention_answers,+ 'citation_answers', e.citation_answers,+ 'sum_inv_position', e.sum_inv_position,+ 'position_count', e.position_count))+ from by_engine e),+ '[]'::jsonb),+ 'prompt_info', 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 prompt_id from by_prompt)),+ '[]'::jsonb),+ -- Dates only for prompts created this period: one answered again after+ -- a pause is new to the comparison, not newly added.+ 'new_prompts', (select jsonb_build_object(+ 'count', count(*),+ 'first_added', min(created_at) filter (+ where created_at >= (p_cur_from::timestamp at time zone 'utc')),+ 'last_added', max(created_at) filter (+ where created_at >= (p_cur_from::timestamp at time zone 'utc')))+ from added)+ );+$$;++create or replace function public.insights_change_drivers(+ p_brand_id uuid,+ p_cur_from timestamptz,+ p_cur_to timestamptz,+ p_prev_from timestamptz,+ p_prev_to timestamptz,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null,+ p_same_prompts boolean default true+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with filtered as (+ select pr.prompt_id, pr.model_used, pr.platform, pr.created_at,+ pr.mention_count, pr.citation_count, pr.mention_position+ 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 pr.created_at >= p_prev_from+ and pr.created_at <= p_cur_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))+ ),+ -- Each window selected on its own, inclusive at both ends like the card.+ windowed as (+ select 'cur' as win, f.* from filtered f+ where f.created_at >= p_cur_from and f.created_at <= p_cur_to+ union all+ select 'prev' as win, f.* from filtered f+ where f.created_at >= p_prev_from and f.created_at <= p_prev_to+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur') as in_cur,+ bool_or(win = 'prev') as in_prev+ from windowed+ group by prompt_id+ ),+ scoped as (+ select w.* from windowed w join presence p using (prompt_id)+ where not p_same_prompts or (p.in_cur and p.in_prev)+ ),+ by_prompt as (+ select prompt_id, win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ sum(1.0 / mention_position) filter (where mention_position is not null)+ as sum_inv_position,+ count(*) filter (where mention_position is not null) as position_count+ from scoped+ group by prompt_id, win+ ),+ by_engine as (+ select model_used, platform, win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ sum(1.0 / mention_position) filter (where mention_position is not null)+ as sum_inv_position,+ count(*) filter (where mention_position is not null) as position_count+ from scoped+ group by model_used, platform, win+ ),+ added as (+ select p.created_at+ from presence pr+ join public.prompts p on p.id = pr.prompt_id+ where pr.in_cur and not pr.in_prev+ )+ select jsonb_build_object(+ 'complete', true,+ 'prompts', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'prompt_id', b.prompt_id,+ 'win', b.win,+ 'answers', b.answers,+ 'mention_answers', b.mention_answers,+ 'citation_answers', b.citation_answers,+ 'sum_inv_position', b.sum_inv_position,+ 'position_count', b.position_count))+ from by_prompt b),+ '[]'::jsonb),+ 'engines', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', e.model_used,+ 'platform', e.platform,+ 'win', e.win,+ 'answers', e.answers,+ 'mention_answers', e.mention_answers,+ 'citation_answers', e.citation_answers,+ 'sum_inv_position', e.sum_inv_position,+ 'position_count', e.position_count))+ from by_engine e),+ '[]'::jsonb),+ 'prompt_info', 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 prompt_id from by_prompt)),+ '[]'::jsonb),+ -- Dates only for prompts created this period: one answered again after+ -- a pause is new to the comparison, not newly added.+ 'new_prompts', (select jsonb_build_object(+ 'count', count(*),+ 'first_added', min(created_at) filter (where created_at >= p_cur_from),+ 'last_added', max(created_at) filter (where created_at >= p_cur_from))+ from added)+ );+$$;++revoke all on function public.insights_change_drivers_daily(+ uuid, date, date, date, date, text[], text, boolean+) from public;+grant execute on function public.insights_change_drivers_daily(+ uuid, date, date, date, date, text[], text, boolean+) to authenticated, service_role;++revoke all on function public.insights_change_drivers(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean+) from public;+grant execute on function public.insights_change_drivers(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean+) to authenticated, service_role;++comment on function public.insights_change_drivers_daily(+ uuid, date, date, date, date, text[], text, boolean+) is+ 'Insights "Why it changed" (VIS-009, 00135): Visibility components per prompt and per (model, platform) in both comparison windows, over the prompts answered in both when p_same_prompts, with prompt text and topic, and the prompts new this period, from the prompt-grain rollups. complete=false until they are backfilled (00130).';++comment on function public.insights_change_drivers(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean+) is+ 'Insights "Why it changed" (VIS-009, 00135) for timestamp windows (24h, topic views), from prompt_results. Same output as insights_change_drivers_daily.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 3b03e1690..da9b63989 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1741,6 +1741,25 @@"gapTo": "{gap} pts to #{rank}","tiedWith": "Level with #{rank}","lever": "lever: {platform}"+ },+ "whyChanged": {+ "title": "Why it changed",+ "fullBreakdown": "Full breakdown",+ "gains": "Gains",+ "drops": "Drops",+ "kind": {+ "platform": "Platform",+ "topic": "Topic",+ "prompt": "Prompt"+ },+ "uncategorized": "Uncategorized",+ "deletedPrompt": "Deleted prompt",+ "range": "{prev} → {cur}",+ "open": "Open {name} in the breakdown",+ "lowSample": "Too few answers compared to explain the change: {cur} this period, {prev} before.",+ "steady": "Nothing moved the score by 0.1 pts or more.",+ "newExcluded": "{count, plural, one {# new prompt} other {# new prompts}}{hasDate, select, yes { · {date}} other {}} · own baseline, not counted",+ "newIncluded": "{count, plural, one {# new prompt} other {# new prompts}}{hasDate, select, yes { · {date}} other {}} · counted in the change"}},"topics": {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.tsxindex 1538cf1c1..6f3d8118a 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@@ -24,6 +24,9 @@ import {} from '@/lib/insights-breakdown';import { sortBreakdownRowsForDisplay } from './breakdown-display';+/** The panel's tabs: each kind of slice it lists. */+export type BreakdownTab = 'prompts' | 'platforms' | 'topics';+const METRIC_TITLE: Record<BreakdownMetric, string> = {mentions: 'Mentions',visibility: 'Visibility',@@ -40,9 +43,17 @@ interface Props {onOpenChange: (open: boolean) => void;/** The window and filters the cards were loaded with, so the panel explains their numbers. */filters?: BreakdownFilters;+ /** The tab to open on, e.g. the one a "Why it changed" row belongs to; Prompts by default. */+ initialTab?: BreakdownTab;}-export function MetricBreakdownSheet({ brandId, metric, onOpenChange, filters }: Props) {+export function MetricBreakdownSheet({+ brandId,+ metric,+ onOpenChange,+ filters,+ initialTab,+}: Props) {const open = Boolean(brandId && metric);const [data, setData] = useState<InsightsBreakdown | null>(null);const [loading, setLoading] = useState(false);@@ -109,7 +120,9 @@ export function MetricBreakdownSheet({ brandId, metric, onOpenChange, filters }:</div>)}- {!loading && !error && data && metric && <BreakdownBody data={data} metric={metric} />}+ {!loading && !error && data && metric && (+ <BreakdownBody data={data} metric={metric} initialTab={initialTab} />+ )}</div></SheetContent></Sheet>@@ -129,8 +142,16 @@ function BreakdownSkeleton() {);}-function BreakdownBody({ data, metric }: { data: InsightsBreakdown; metric: BreakdownMetric }) {- const [tab, setTab] = useState<'prompts' | 'platforms' | 'topics'>('prompts');+function BreakdownBody({+ data,+ metric,+ initialTab,+}: {+ data: InsightsBreakdown;+ metric: BreakdownMetric;+ initialTab?: BreakdownTab;+}) {+ const [tab, setTab] = useState<BreakdownTab>(initialTab ?? 'prompts');const samePrompts = data.comparison?.basis === 'same';const newCount = data.comparison?.newPrompts ?? 0;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsxindex 2439b4889..3cf15daad 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsx@@ -12,13 +12,19 @@ import { TONE_TEXT, upIsGood } from './kpi-format';* enough answers shows why instead of numbers; the row with the biggest drop* is tinted. Replaces the Share of Voice donut and trend charts.*/-export function PlatformTable({ rows }: { rows: PlatformTableRow[] }) {+export function PlatformTable({+ rows,+ className,+}: {+ rows: PlatformTableRow[];+ className?: string;+}) {const t = useTranslations('insights.platforms');// Share-of-voice bars are scaled to the largest share in the table.const maxSov = Math.max(0, ...rows.map((r) => r.shareOfVoice ?? 0));return (- <Card>+ <Card className={className}><CardHeader className="pb-2"><CardTitle className="text-sm font-medium">{t('title')}</CardTitle></CardHeader>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_why-changed.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_why-changed.tsxnew file mode 100644index 000000000..d6bd8ead8--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_why-changed.tsx@@ -0,0 +1,128 @@+'use client';++import { useTranslations } from 'next-intl';+import { ArrowRight } from 'lucide-react';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { cn } from '@/lib/utils';+import type { Driver, DriverKind, WhyChanged as WhyChangedData } from '@/lib/insights-drivers';+import { signedChange, TONE_TEXT } from './kpi-format';+import type { BreakdownTab } from './_metric-breakdown-sheet';++const TAB_OF: Record<DriverKind, BreakdownTab> = {+ platform: 'platforms',+ topic: 'topics',+ prompt: 'prompts',+};++/** "Oct 12", or "Sep 29 – Oct 12" when the prompts were added over several days. */+function addedOn(first: string | null, last: string | null): string | null {+ const day = (ts: string) =>+ new Date(ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });+ if (!first || !last) return first ? day(first) : last ? day(last) : null;+ return day(first) === day(last) ? day(last) : `${day(first)} – ${day(last)}`;+}++/**+ * "Why it changed" (VIS-009), as in the v2 mockup: the platforms, topics and+ * prompts that moved Visibility most, each with its own score before → after+ * and its effect on the overall score, and the prompts added this period.+ * A row, or "Full breakdown", opens the breakdown panel.+ */+export function WhyChanged({+ data,+ onOpenBreakdown,+ className,+}: {+ data: WhyChangedData;+ onOpenBreakdown: (tab?: BreakdownTab) => void;+ className?: string;+}) {+ const t = useTranslations('insights.whyChanged');+ const date = addedOn(data.newPrompts.firstAdded, data.newPrompts.lastAdded);++ const nameOf = (d: Driver) =>+ d.name ?? (d.kind === 'topic' ? t('uncategorized') : t('deletedPrompt'));++ const section = (label: string, drivers: Driver[]) =>+ drivers.length > 0 && (+ <div className="space-y-1.5">+ <h3 className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">+ {label}+ </h3>+ <ul className="space-y-0.5">+ {drivers.map((d) => {+ const name = nameOf(d);+ return (+ <li key={`${d.kind}:${d.id}`}>+ <button+ type="button"+ onClick={() => onOpenBreakdown(TAB_OF[d.kind])}+ title={t('open', { name })}+ className="-mx-1.5 flex w-[calc(100%+0.75rem)] items-center gap-2.5 rounded-md px-1.5 py-1 text-left transition-colors hover:bg-muted/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <span className="w-[58px] shrink-0 rounded bg-muted py-0.5 text-center text-[10.5px] font-medium text-muted-foreground">+ {t(`kind.${d.kind}`)}+ </span>+ <span className="min-w-0 flex-1 truncate text-[13px]" title={name}>+ {name}+ </span>+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">+ {t('range', { prev: d.prev.toFixed(1), cur: d.cur.toFixed(1) })}+ </span>+ <span+ className={cn(+ 'w-11 shrink-0 text-right text-[12.5px] font-semibold tabular-nums',+ TONE_TEXT[d.impact > 0 ? 'good' : 'bad'],+ )}+ >+ {signedChange(d.impact)}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ </div>+ );++ return (+ <Card className={cn('flex flex-col', className)}>+ <CardHeader className="pb-2">+ <div className="flex items-center justify-between gap-3">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ <button+ type="button"+ onClick={() => onOpenBreakdown()}+ className="flex shrink-0 items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"+ >+ {t('fullBreakdown')}+ <ArrowRight className="h-3 w-3" />+ </button>+ </div>+ </CardHeader>+ <CardContent className="flex flex-1 flex-col gap-3">+ {data.status === 'lowSample' ? (+ <p className="text-sm text-muted-foreground">+ {t('lowSample', { cur: data.answers.cur, prev: data.answers.prev })}+ </p>+ ) : data.gains.length === 0 && data.drops.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('steady')}</p>+ ) : (+ <>+ {section(t('gains'), data.gains)}+ {section(t('drops'), data.drops)}+ </>+ )}+ {data.newPrompts.count > 0 && (+ <p className="mt-auto rounded-lg border border-dashed px-2.5 py-2 text-xs text-muted-foreground">+ {t(data.samePrompts ? 'newExcluded' : 'newIncluded', {+ count: data.newPrompts.count,+ hasDate: date ? 'yes' : 'no',+ date: date ?? '',+ })}+ </p>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex 6bd1cb5c6..e8c55ab8a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -14,7 +14,7 @@ const VisibilityRateTrendChart = dynamic(},);-import { MetricBreakdownSheet } from './_metric-breakdown-sheet';+import { MetricBreakdownSheet, type BreakdownTab } from './_metric-breakdown-sheet';import { FormulaDialog } from './_formula-dialog';import { useBrandStore } from '@/stores/use-brand-store';import {@@ -88,6 +88,8 @@ import { KpiRows } from './_kpi-cards';import { SummaryLine } from './_summary-line';import { PlatformTable } from './_platform-table';import { Leaderboard } from './_leaderboard';+import { WhyChanged } from './_why-changed';+import type { WhyChanged as WhyChangedData } from '@/lib/insights-drivers';// ─── Filter Types ─────────────────────────────────────────────────────────────@@ -858,7 +860,9 @@ export default function InsightsPage() {const [kpiSeries, setKpiSeries] = useState<KpiSeriesDay[] | null>(null);const [platformChanges, setPlatformChanges] = useState<PlatformChange[] | null>(null);const [platforms, setPlatforms] = useState<PlatformTableRow[] | null>(null);+ const [whyChanged, setWhyChanged] = useState<WhyChangedData | null>(null);const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);+ const [breakdownTab, setBreakdownTab] = useState<BreakdownTab | undefined>(undefined);// 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).@@ -948,6 +952,7 @@ export default function InsightsPage() {setKpiSeries(insights.kpiSeries);setPlatformChanges(insights.platformChanges);setPlatforms(insights.platforms);+ setWhyChanged(insights.whyChanged);setHasAnyData(insights.hasAnyData);// Group raw model slugs by their resolved display name so different@@ -1412,7 +1417,10 @@ export default function InsightsPage() {competitors={competitorData}comparison={comparison}series={kpiSeries}- onBreakdown={setBreakdownMetric}+ onBreakdown={(metric) => {+ setBreakdownTab(undefined);+ setBreakdownMetric(metric);+ }}onNavigate={(path) => router.push(path)}/>@@ -1476,8 +1484,24 @@ export default function InsightsPage() {<NoCompetitorsTeaser />)}- {/* By AI platform (VIS-008): replaces the Share of Voice charts. */}- {platforms && platforms.length > 0 && <PlatformTable rows={platforms} />}+ {/* By AI platform (VIS-008) and Why it changed (VIS-009), side by side as in the mockup. */}+ {((platforms && platforms.length > 0) || whyChanged) && (+ <div className="flex flex-wrap gap-4">+ {platforms && platforms.length > 0 && (+ <PlatformTable className="min-w-0 flex-[1_1_520px]" rows={platforms} />+ )}+ {whyChanged && (+ <WhyChanged+ className="min-w-0 flex-[1_1_420px]"+ data={whyChanged}+ onOpenBreakdown={(tab) => {+ setBreakdownTab(tab);+ setBreakdownMetric('visibility');+ }}+ />+ )}+ </div>+ )}{/* Recommendations (#459) — stored data, not period-scoped */}{recommendations && <RecommendationsSection data={recommendations} />}@@ -1502,6 +1526,7 @@ export default function InsightsPage() {if (!open) setBreakdownMetric(null);}}filters={loadedFilters}+ initialTab={breakdownTab}/></div>);diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 86356385c..f18799b13 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -45,6 +45,7 @@ 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 { parseChangeDrivers, whyChanged, type WhyChanged } from '@/lib/insights-drivers';import {parsePlatformRows,platformChanges,@@ -736,6 +737,11 @@ export interface InsightsData {platformChanges: PlatformChange[] | null;/** The "By AI platform" table (VIS-008); null under the same conditions. */platforms: PlatformTableRow[] | null;+ /**+ * "Why it changed" (VIS-009): what moved the change and the prompts new this+ * period. Null for All time, before the backfill, or when the read failed.+ */+ whyChanged: WhyChanged | null;/** The run ledger, when the 24h window was anchored to it (`anchor24h`). */trackingWindow: TrackingWindow | null;}@@ -832,6 +838,7 @@ type WindowedInsights = Pick<| 'kpiSeries'| 'platformChanges'| 'platforms'+ | 'whyChanged'>;type InsightsFilterArgs = {@@ -873,27 +880,38 @@ async function loadWindowedInsights(return fallback;});- const [summary, competitors, sov, filterOptions, trend, same, coverage, kpiSeries, platformData] =- await Promise.all([- getInsightsSummary(brandId, filterOpts),- lenient(- getCompetitorComparison(brandId, filterOpts),- EMPTY_COMPETITORS,- 'competitor comparison',- ),- lenient(getShareOfVoiceData(brandId, filterOpts), EMPTY_SOV, 'share of voice'),- getInsightsFilterOptions(brandId),- // The chart follows the same window as every other number on the page.- lenient<VisibilityRateTrendData | null>(- getVisibilityRateTrend(brandId, filterOpts),- null,- 'visibility trend',- ),- getSamePromptComparison(brandId, filterOpts),- lenient(getCoverageKpi(brandId, filterOpts), null, 'coverage'),- lenient(getKpiSeries(brandId, filterOpts), null, 'KPI sparklines'),- lenient(getPlatformData(brandId, filterOpts), null, 'platforms'),- ]);+ const [+ summary,+ competitors,+ sov,+ filterOptions,+ trend,+ same,+ coverage,+ kpiSeries,+ platformData,+ drivers,+ ] = await Promise.all([+ getInsightsSummary(brandId, filterOpts),+ lenient(+ getCompetitorComparison(brandId, filterOpts),+ EMPTY_COMPETITORS,+ 'competitor comparison',+ ),+ lenient(getShareOfVoiceData(brandId, filterOpts), EMPTY_SOV, 'share of voice'),+ getInsightsFilterOptions(brandId),+ // The chart follows the same window as every other number on the page.+ lenient<VisibilityRateTrendData | null>(+ getVisibilityRateTrend(brandId, filterOpts),+ null,+ 'visibility trend',+ ),+ getSamePromptComparison(brandId, filterOpts),+ lenient(getCoverageKpi(brandId, filterOpts), null, 'coverage'),+ lenient(getKpiSeries(brandId, filterOpts), null, 'KPI sparklines'),+ lenient(getPlatformData(brandId, filterOpts), null, 'platforms'),+ lenient(getChangeDrivers(brandId, filterOpts), null, 'why it changed'),+ ]);const windowed = {...(comparisonWindows(filterOpts).prev ? { summary, sov } : withoutChanges(summary, sov)),competitors,@@ -910,6 +928,9 @@ async function loadWindowedInsights(resolveProvider,): null,+ whyChanged:+ drivers &&+ whyChanged(drivers, resolveProvider, { samePrompts: filterOpts.samePrompts !== false }),};return withPromptComparison(windowed, same, filterOpts.samePrompts !== false);}@@ -1004,6 +1025,51 @@ async function getKpiSeries(return parseKpiSeries(data);}+/**+ * The inputs of "Why it changed" (VIS-009): each prompt's and engine's+ * Visibility components in both comparison windows, over the same prompts as+ * the card's change, and the prompts new this period. Null for All time.+ */+async function getChangeDrivers(+ brandId: string,+ opts?: InsightsFilterArgs,+): Promise<ReturnType<typeof parseChangeDrivers>> {+ const windows = comparisonWindows(opts);+ if (!windows.prev) return null;+ const supabase = await dbClient();+ const base = {+ p_brand_id: brandId,+ p_models: modelFilterArray(opts?.model),+ p_region: opts?.region ?? undefined,+ p_same_prompts: opts?.samePrompts !== false,+ };++ let res;+ if (windows.cur.kind === 'days') {+ const { cur, prev } = deltaDayWindows(windows.cur.days);+ res = await supabase.rpc('insights_change_drivers_daily', {+ ...base,+ p_cur_from: cur.dayFrom,+ p_cur_to: cur.dayTo,+ p_prev_from: prev.dayFrom,+ p_prev_to: prev.dayTo,+ });+ } else {+ const cur = windowBounds(windows.cur);+ const prev = windowBounds(windows.prev);+ res = await supabase.rpc('insights_change_drivers', {+ ...base,+ p_cur_from: cur.from,+ p_cur_to: cur.to,+ p_prev_from: prev.from,+ p_prev_to: prev.to,+ p_topic_id: opts?.topicId ?? undefined,+ });+ }+ if (res.error) throw new Error(res.error.message);+ return parseChangeDrivers(res.data);+}+/*** Each platform in the comparison windows (VIS-006, VIS-008): the rows over* every prompt, for the "By AI platform" table's values, and each platform'sdiff --git a/web/src/lib/insights-drivers.test.ts b/web/src/lib/insights-drivers.test.tsnew file mode 100644index 000000000..a4bd4020a--- /dev/null+++ b/web/src/lib/insights-drivers.test.ts@@ -0,0 +1,214 @@+import { describe, expect, it } from 'vitest';+import { computeAiVisibilityScore } from './visibility-score';+import { parseChangeDrivers, whyChanged, type ChangeDriversPayload } from './insights-drivers';++const sums = (answers: number, mentions: number) => ({+ answers,+ mentionAnswers: mentions,+ citationAnswers: 0,+ sumInvPosition: 0,+ positionCount: 0,+});++const engine = (model: string, win: 'cur' | 'prev', answers: number, mentions: number) => ({+ modelUsed: model,+ platform: null,+ win,+ sums: sums(answers, mentions),+});++const prompt = (id: string, win: 'cur' | 'prev', answers: number, mentions: number) => ({+ promptId: id,+ win,+ sums: sums(answers, mentions),+});++const payload = (p: Partial<ChangeDriversPayload>): ChangeDriversPayload => ({+ prompts: [],+ engines: [],+ promptInfo: [],+ newPrompts: { count: 0, firstAdded: null, lastAdded: null },+ ...p,+});++// Model slugs fold into platform names, as resolveProvider does.+const platformOf = (model: string | null) =>+ model?.startsWith('gpt-') ? 'ChatGPT' : model?.startsWith('gemini') ? 'Gemini' : 'Other';++const same = { samePrompts: true };++const score = (answers: number, mentions: number) =>+ computeAiVisibilityScore({+ answers,+ mentionAnswers: mentions,+ citationAnswers: 0,+ positionFactor: null,+ })!;++describe('parseChangeDrivers', () => {+ it('reads the RPC payload and refuses rollups not yet backfilled', () => {+ const parsed = parseChangeDrivers({+ complete: true,+ prompts: [{ prompt_id: 'p1', win: 'prev', answers: '4', mention_answers: 2 }],+ engines: [{ model_used: 'gpt-4o', platform: null, win: 'cur', answers: 3 }],+ prompt_info: [{ id: 'p1', text: 'best crm', topic_id: 't1', topic_name: 'CRM' }],+ new_prompts: { count: 6, first_added: '2026-10-12T19:28:41Z', last_added: null },+ });++ expect(parsed?.prompts[0]).toEqual({ promptId: 'p1', win: 'prev', sums: sums(4, 2) });+ expect(parsed?.engines[0]).toMatchObject({ modelUsed: 'gpt-4o', platform: null, win: 'cur' });+ expect(parsed?.promptInfo[0]).toEqual({+ id: 'p1',+ text: 'best crm',+ topicId: 't1',+ topicName: 'CRM',+ });+ expect(parsed?.newPrompts).toEqual({+ count: 6,+ firstAdded: '2026-10-12T19:28:41Z',+ lastAdded: null,+ });+ expect(parseChangeDrivers({ complete: false })).toBeNull();+ });+});++describe('whyChanged', () => {+ it('credits the one platform that moved with the whole change', () => {+ const result = whyChanged(+ payload({+ engines: [+ engine('gpt-4o', 'cur', 100, 60),+ engine('gpt-4o', 'prev', 100, 30),+ engine('gemini-2.5-pro', 'cur', 100, 40),+ engine('gemini-2.5-pro', 'prev', 100, 40),+ ],+ }),+ platformOf,+ same,+ );++ const change = Math.round((score(200, 100) - score(200, 70)) * 10) / 10;+ expect(result.status).toBe('ok');+ expect(result.gains).toEqual([+ {+ kind: 'platform',+ id: 'ChatGPT',+ name: 'ChatGPT',+ prev: Math.round(score(100, 30) * 10) / 10,+ cur: Math.round(score(100, 60) * 10) / 10,+ impact: change,+ },+ ]);+ expect(result.drops).toEqual([]);+ });++ it('weighs a slice by its answers, so a small swing ranks below a big one', () => {+ const result = whyChanged(+ payload({+ prompts: [+ prompt('big', 'cur', 90, 50),+ prompt('big', 'prev', 90, 30),+ prompt('small', 'cur', 10, 10),+ prompt('small', 'prev', 10, 0),+ ],+ engines: [engine('gpt-4o', 'cur', 100, 60), engine('gpt-4o', 'prev', 100, 30)],+ promptInfo: [+ { id: 'big', text: 'Big prompt', topicId: 't1', topicName: 'Topic' },+ { id: 'small', text: 'Small prompt', topicId: 't1', topicName: 'Topic' },+ ],+ }),+ platformOf,+ { samePrompts: true, limit: 5 },+ );++ const prompts = result.gains.filter((d) => d.kind === 'prompt');+ expect(prompts.map((d) => d.id)).toEqual(['big', 'small']);+ // The small prompt went 0 → 100 on its own but moved the total less.+ expect(prompts[1].cur - prompts[1].prev).toBeGreaterThan(prompts[0].cur - prompts[0].prev);+ expect(prompts[1].impact).toBeLessThan(prompts[0].impact);+ // Its topic carries both prompts.+ expect(result.gains.find((d) => d.kind === 'topic')).toMatchObject({ id: 't1', name: 'Topic' });+ });++ it('lists gains and drops apart, largest first, up to the limit', () => {+ const result = whyChanged(+ payload({+ prompts: [+ prompt('a', 'cur', 50, 40),+ prompt('a', 'prev', 50, 10),+ prompt('b', 'cur', 50, 5),+ prompt('b', 'prev', 50, 20),+ prompt('c', 'cur', 50, 25),+ prompt('c', 'prev', 50, 20),+ ],+ engines: [engine('gpt-4o', 'cur', 150, 70), engine('gpt-4o', 'prev', 150, 50)],+ promptInfo: [],+ }),+ platformOf,+ { samePrompts: true, limit: 1 },+ );++ expect(result.gains).toHaveLength(1);+ expect(result.gains[0]).toMatchObject({ kind: 'prompt', id: 'a', name: null });+ expect(result.drops).toHaveLength(1);+ expect(result.drops[0]).toMatchObject({ kind: 'prompt', id: 'b' });+ expect(result.drops[0].impact).toBeLessThan(0);+ });++ it('credits nothing to a slice whose answers grew at the same rates', () => {+ const result = whyChanged(+ payload({+ engines: [+ engine('gpt-4o', 'cur', 100, 50),+ engine('gpt-4o', 'prev', 50, 25),+ engine('gemini-2.5-pro', 'cur', 50, 10),+ engine('gemini-2.5-pro', 'prev', 50, 10),+ ],+ }),+ platformOf,+ same,+ );++ // The overall score rose with ChatGPT's larger share, but neither+ // platform did better or worse than before.+ expect(result.status).toBe('ok');+ expect(result.gains).toEqual([]);+ expect(result.drops).toEqual([]);+ });++ it('skips a slice answered in only one window', () => {+ const result = whyChanged(+ payload({+ engines: [+ engine('gpt-4o', 'cur', 50, 30),+ engine('gpt-4o', 'prev', 50, 30),+ engine('gemini-2.5-pro', 'cur', 30, 30),+ ],+ }),+ platformOf,+ same,+ );++ expect([...result.gains, ...result.drops].map((d) => d.id)).not.toContain('Gemini');+ });++ it('explains nothing on fewer than 20 compared answers in a window', () => {+ const result = whyChanged(+ payload({+ engines: [engine('gpt-4o', 'cur', 2, 2), engine('gpt-4o', 'prev', 16, 4)],+ newPrompts: { count: 6, firstAdded: null, lastAdded: null },+ }),+ platformOf,+ same,+ );++ expect(result).toEqual({+ status: 'lowSample',+ answers: { cur: 2, prev: 16 },+ samePrompts: true,+ gains: [],+ drops: [],+ newPrompts: { count: 6, firstAdded: null, lastAdded: null },+ });+ });+});diff --git a/web/src/lib/insights-drivers.ts b/web/src/lib/insights-drivers.tsnew file mode 100644index 000000000..86f2398d0--- /dev/null+++ b/web/src/lib/insights-drivers.ts@@ -0,0 +1,211 @@+import { computeAiVisibilityScore } from '@/lib/visibility-score';+import { LOW_SAMPLE_ANSWERS } from '@/lib/insights-summary';++/**+ * "Why it changed" (VIS-009), as in the v2 mockup: the platforms, topics and+ * prompts that moved the Visibility change most, each with its own score+ * before → after and its effect on the overall score, and the prompts added+ * this period. Built from insights_change_drivers[_daily] (00135), over the+ * same prompts as the change on the card.+ */++/** Visibility components of one slice in one window. */+interface Sums {+ answers: number;+ mentionAnswers: number;+ citationAnswers: number;+ sumInvPosition: number;+ positionCount: number;+}++interface ComponentRow {+ win: 'cur' | 'prev';+ sums: Sums;+}++export interface ChangeDriversPayload {+ prompts: (ComponentRow & { promptId: string })[];+ engines: (ComponentRow & { modelUsed: string | null; platform: string | null })[];+ promptInfo: { id: string; text: string; topicId: string | null; topicName: string | null }[];+ newPrompts: { count: number; firstAdded: string | null; lastAdded: string | null };+}++const num = (v: unknown): number => Number(v ?? 0);+const str = (v: unknown): string | null => (typeof v === 'string' ? v : null);++const sumsOf = (r: Record<string, unknown>): Sums => ({+ answers: num(r.answers),+ mentionAnswers: num(r.mention_answers),+ citationAnswers: num(r.citation_answers),+ sumInvPosition: num(r.sum_inv_position),+ positionCount: num(r.position_count),+});++/** The RPC payload, or null when it can't be used: missing, or rollups not yet backfilled. */+export function parseChangeDrivers(raw: unknown): ChangeDriversPayload | null {+ const r = raw as Record<string, unknown> | null;+ if (!r || r.complete !== true) return null;+ const rows = (v: unknown) => (Array.isArray(v) ? (v as Record<string, unknown>[]) : []);+ const win = (v: unknown): 'cur' | 'prev' => (v === 'prev' ? 'prev' : 'cur');+ const added = (r.new_prompts ?? {}) as Record<string, unknown>;+ return {+ prompts: rows(r.prompts).map((p) => ({+ promptId: String(p.prompt_id),+ win: win(p.win),+ sums: sumsOf(p),+ })),+ engines: rows(r.engines).map((e) => ({+ modelUsed: str(e.model_used),+ platform: str(e.platform),+ win: win(e.win),+ sums: sumsOf(e),+ })),+ promptInfo: rows(r.prompt_info).map((p) => ({+ id: String(p.id),+ text: String(p.text ?? ''),+ topicId: str(p.topic_id),+ topicName: str(p.topic_name),+ })),+ newPrompts: {+ count: num(added.count),+ firstAdded: str(added.first_added),+ lastAdded: str(added.last_added),+ },+ };+}++export type DriverKind = 'platform' | 'topic' | 'prompt';++export interface Driver {+ kind: DriverKind;+ id: string;+ /** Platform, topic or prompt text; null for prompts without a topic or a deleted prompt. */+ name: string | null;+ /** The slice's own Visibility in each window, as the breakdown panel scores it. */+ prev: number;+ cur: number;+ /** Points the overall score moved because of this slice. */+ impact: number;+}++export interface WhyChanged {+ /** 'lowSample': too few compared answers in a window to explain the change. */+ status: 'ok' | 'lowSample';+ /** Answers compared in each window. */+ answers: { cur: number; prev: number };+ /** "Compare: Same prompts": new prompts are left out of the change. */+ samePrompts: boolean;+ gains: Driver[];+ drops: Driver[];+ newPrompts: ChangeDriversPayload['newPrompts'];+}++const empty = (): Sums => ({+ answers: 0,+ mentionAnswers: 0,+ citationAnswers: 0,+ sumInvPosition: 0,+ positionCount: 0,+});++const add = (a: Sums, b: Sums, k = 1): Sums => ({+ answers: a.answers + b.answers * k,+ mentionAnswers: a.mentionAnswers + b.mentionAnswers * k,+ citationAnswers: a.citationAnswers + b.citationAnswers * k,+ sumInvPosition: a.sumInvPosition + b.sumInvPosition * k,+ positionCount: a.positionCount + b.positionCount * k,+});++/** The card's formula over a slice; 0 for a slice without answers. */+const score = (s: Sums) =>+ computeAiVisibilityScore({+ answers: s.answers,+ mentionAnswers: s.mentionAnswers,+ citationAnswers: s.citationAnswers,+ positionFactor: s.positionCount > 0 ? s.sumInvPosition / s.positionCount : null,+ }) ?? 0;++const round1 = (n: number) => Math.round(n * 10) / 10;++/**+ * What moved the change. A slice's effect is how much higher the overall+ * score is than it would be had the slice kept last period's rates at this+ * period's volume: big slices weigh more, and a handful of answers can't top+ * the list. Slices answered in only one window aren't compared. Up to+ * `limit` gains and drops, largest first; an effect under 0.1 points is+ * left out. Too few compared answers in either window explain nothing.+ */+export function whyChanged(+ payload: ChangeDriversPayload,+ platformOf: (modelUsed: string | null, platform: string | null) => string,+ { samePrompts, limit = 3 }: { samePrompts: boolean; limit?: number },+): WhyChanged {+ const total = { cur: empty(), prev: empty() };+ for (const e of payload.engines) total[e.win] = add(total[e.win], e.sums);+ const answers = { cur: total.cur.answers, prev: total.prev.answers };+ const base = { answers, samePrompts, newPrompts: payload.newPrompts };+ if (answers.cur < LOW_SAMPLE_ANSWERS || answers.prev < LOW_SAMPLE_ANSWERS) {+ return { ...base, status: 'lowSample', gains: [], drops: [] };+ }++ const slices = new Map<+ string,+ { kind: DriverKind; id: string; name: string | null; cur: Sums; prev: Sums }+ >();+ const fold = (+ kind: DriverKind,+ id: string,+ name: string | null,+ win: 'cur' | 'prev',+ s: Sums,+ ) => {+ const key = `${kind}:${id}`;+ const slice = slices.get(key) ?? { kind, id, name, cur: empty(), prev: empty() };+ slice[win] = add(slice[win], s);+ slices.set(key, slice);+ };++ for (const e of payload.engines) {+ const name = platformOf(e.modelUsed, e.platform);+ fold('platform', name, name, e.win, e.sums);+ }+ const info = new Map(payload.promptInfo.map((p) => [p.id, p]));+ for (const p of payload.prompts) {+ const prompt = info.get(p.promptId);+ fold('prompt', p.promptId, prompt?.text ?? null, p.win, p.sums);+ // A deleted prompt's topic is unknown: it isn't put under "Uncategorized".+ if (prompt) fold('topic', prompt.topicId ?? '', prompt.topicName, p.win, p.sums);+ }++ const overall = score(total.cur);+ const drivers: Driver[] = [];+ for (const s of slices.values()) {+ if (s.cur.answers === 0 || s.prev.answers === 0) continue;+ // This period, with the slice at last period's rates.+ const without = add(add(total.cur, s.cur, -1), s.prev, s.cur.answers / s.prev.answers);+ const impact = round1(overall - score(without));+ if (impact === 0) continue;+ drivers.push({+ kind: s.kind,+ id: s.id,+ name: s.name,+ prev: round1(score(s.prev)),+ cur: round1(score(s.cur)),+ impact,+ });+ }++ const byImpact = (a: Driver, b: Driver) => Math.abs(b.impact) - Math.abs(a.impact);+ return {+ ...base,+ status: 'ok',+ gains: drivers+ .filter((d) => d.impact > 0)+ .sort(byImpact)+ .slice(0, limit),+ drops: drivers+ .filter((d) => d.impact < 0)+ .sort(byImpact)+ .slice(0, limit),+ };+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 5d2798998..a37e17da6 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3087,6 +3087,33 @@ export type Database = {}Returns: Json}+ insights_change_drivers: {+ Args: {+ p_brand_id: string+ p_cur_from: string+ p_cur_to: string+ p_models?: string[]+ p_prev_from: string+ p_prev_to: string+ p_region?: string+ p_same_prompts?: boolean+ p_topic_id?: string+ }+ Returns: Json+ }+ insights_change_drivers_daily: {+ Args: {+ p_brand_id: string+ p_cur_from: string+ p_cur_to: string+ p_models?: string[]+ p_prev_from: string+ p_prev_to: string+ p_region?: string+ p_same_prompts?: boolean+ }+ Returns: Json+ }insights_filter_options: {Args: { p_brand_id: string }Returns: {