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
fix(insights): trend chart plots the rolling selected window so it always matches the headline (#576)
Gökhan Geyik56d638d1e18f
diff --git a/supabase/migrations/00042_visibility_rate_trend_position_n.sql b/supabase/migrations/00042_visibility_rate_trend_position_n.sqlnew file mode 100644index 000000000..2c7446c66--- /dev/null+++ b/supabase/migrations/00042_visibility_rate_trend_position_n.sql@@ -0,0 +1,115 @@+-- Add position_n (answers carrying a mention_position) to the per-day+-- buckets of visibility_rate_trend, for the brand and each competitor.+--+-- The trend chart is switching from "that day's score" points to a rolling+-- window (each day's point = the score over the trailing selected window),+-- so the line's last point always equals the headline card exactly. Rolling+-- position factors need the weighted average across days:+-- rolling_pf = Σ(position_factor_d × position_n_d) / Σ(position_n_d)+-- which requires the per-day weight. Purely additive JSON keys — existing+-- consumers are unaffected.++CREATE OR REPLACE FUNCTION public.visibility_rate_trend(+ p_brand_id uuid,+ p_platform text DEFAULT NULL,+ p_models text[] DEFAULT NULL,+ p_region text DEFAULT NULL,+ p_date_from timestamptz DEFAULT NULL,+ p_date_to timestamptz DEFAULT NULL,+ p_topic_id uuid DEFAULT NULL+)+RETURNS jsonb+LANGUAGE sql+STABLE+SECURITY INVOKER+SET search_path = public+AS $$+ WITH filtered AS (+ SELECT pr.prompt_id, pr.mention_count, pr.citation_count, pr.mention_position,+ pr.competitor_mentions,+ (pr.created_at AT TIME ZONE 'UTC')::date AS day+ FROM public.prompt_results pr+ WHERE pr.brand_id = p_brand_id+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights+ AND (p_platform IS NULL OR pr.platform = p_platform)+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))+ AND (p_region IS NULL OR pr.region = p_region)+ 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))+ ),+ brand_daily AS (+ SELECT day,+ COUNT(DISTINCT prompt_id) AS prompt_count,+ COUNT(DISTINCT prompt_id)+ FILTER (WHERE mention_count > 0 OR citation_count > 0)+ AS visible_prompts,+ COUNT(*) AS answers,+ COUNT(*) FILTER (WHERE mention_count > 0) AS mention_answers,+ COUNT(*) FILTER (WHERE citation_count > 0) AS citation_answers,+ AVG(1.0 / mention_position)+ FILTER (WHERE mention_position IS NOT NULL) AS position_factor,+ COUNT(*) FILTER (WHERE mention_position IS NOT NULL)+ AS position_n+ FROM filtered+ GROUP BY day+ ),+ comp_daily AS (+ SELECT f.day,+ cm.value->>'competitor_id' AS competitor_id,+ COUNT(DISTINCT f.prompt_id)+ FILTER (WHERE COALESCE((cm.value->>'mention_count')::int, 0) > 0+ OR COALESCE((cm.value->>'citation_count')::int, 0) > 0+ OR COALESCE((cm.value->>'visibility_score')::numeric, 0) > 0)+ AS visible_prompts,+ COUNT(*) FILTER (+ WHERE COALESCE((cm.value->>'mention_count')::int, 0) > 0)+ AS mention_answers,+ COUNT(*) FILTER (+ WHERE COALESCE((cm.value->>'citation_count')::int, 0) > 0)+ AS citation_answers,+ AVG(1.0 / (cm.value->>'mention_position')::numeric)+ FILTER (WHERE (cm.value->>'mention_position') IS NOT NULL)+ AS position_factor,+ COUNT(*) FILTER (WHERE (cm.value->>'mention_position') IS NOT NULL)+ AS position_n+ FROM filtered f,+ LATERAL jsonb_array_elements(+ COALESCE(f.competitor_mentions, '[]'::jsonb)) cm+ WHERE cm.value ? 'competitor_id'+ AND EXISTS (+ SELECT 1 FROM public.competitors c+ WHERE c.id::text = cm.value->>'competitor_id'+ AND c.brand_id = p_brand_id+ )+ GROUP BY f.day, cm.value->>'competitor_id'+ )+ SELECT COALESCE(+ jsonb_agg(jsonb_build_object(+ 'day', bd.day,+ 'prompt_count', bd.prompt_count,+ 'visible_prompts', bd.visible_prompts,+ 'answers', bd.answers,+ 'mention_answers', bd.mention_answers,+ 'citation_answers', bd.citation_answers,+ 'position_factor', bd.position_factor,+ 'position_n', bd.position_n,+ 'competitors', COALESCE(+ (SELECT jsonb_agg(jsonb_build_object(+ 'competitor_id', cd.competitor_id,+ 'visible_prompts', cd.visible_prompts,+ 'mention_answers', cd.mention_answers,+ 'citation_answers', cd.citation_answers,+ 'position_factor', cd.position_factor,+ 'position_n', cd.position_n))+ FROM comp_daily cd WHERE cd.day = bd.day),+ '[]'::jsonb)+ ) ORDER BY bd.day),+ '[]'::jsonb)+ FROM brand_daily bd;+$$;++GRANT EXECUTE ON FUNCTION public.visibility_rate_trend(uuid, text, text[], text, timestamptz, timestamptz, uuid)+ TO authenticated;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 08ff3cdd6..fe642069c 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -4707,3 +4707,122 @@ $$;GRANT EXECUTE ON FUNCTION public.prompt_visibility_summaries(uuid, timestamptz, timestamptz)TO authenticated;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00042_visibility_rate_trend_position_n.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Add position_n (answers carrying a mention_position) to the per-day+-- buckets of visibility_rate_trend, for the brand and each competitor.+--+-- The trend chart is switching from "that day's score" points to a rolling+-- window (each day's point = the score over the trailing selected window),+-- so the line's last point always equals the headline card exactly. Rolling+-- position factors need the weighted average across days:+-- rolling_pf = Σ(position_factor_d × position_n_d) / Σ(position_n_d)+-- which requires the per-day weight. Purely additive JSON keys — existing+-- consumers are unaffected.++CREATE OR REPLACE FUNCTION public.visibility_rate_trend(+ p_brand_id uuid,+ p_platform text DEFAULT NULL,+ p_models text[] DEFAULT NULL,+ p_region text DEFAULT NULL,+ p_date_from timestamptz DEFAULT NULL,+ p_date_to timestamptz DEFAULT NULL,+ p_topic_id uuid DEFAULT NULL+)+RETURNS jsonb+LANGUAGE sql+STABLE+SECURITY INVOKER+SET search_path = public+AS $$+ WITH filtered AS (+ SELECT pr.prompt_id, pr.mention_count, pr.citation_count, pr.mention_position,+ pr.competitor_mentions,+ (pr.created_at AT TIME ZONE 'UTC')::date AS day+ FROM public.prompt_results pr+ WHERE pr.brand_id = p_brand_id+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights+ AND (p_platform IS NULL OR pr.platform = p_platform)+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))+ AND (p_region IS NULL OR pr.region = p_region)+ 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))+ ),+ brand_daily AS (+ SELECT day,+ COUNT(DISTINCT prompt_id) AS prompt_count,+ COUNT(DISTINCT prompt_id)+ FILTER (WHERE mention_count > 0 OR citation_count > 0)+ AS visible_prompts,+ COUNT(*) AS answers,+ COUNT(*) FILTER (WHERE mention_count > 0) AS mention_answers,+ COUNT(*) FILTER (WHERE citation_count > 0) AS citation_answers,+ AVG(1.0 / mention_position)+ FILTER (WHERE mention_position IS NOT NULL) AS position_factor,+ COUNT(*) FILTER (WHERE mention_position IS NOT NULL)+ AS position_n+ FROM filtered+ GROUP BY day+ ),+ comp_daily AS (+ SELECT f.day,+ cm.value->>'competitor_id' AS competitor_id,+ COUNT(DISTINCT f.prompt_id)+ FILTER (WHERE COALESCE((cm.value->>'mention_count')::int, 0) > 0+ OR COALESCE((cm.value->>'citation_count')::int, 0) > 0+ OR COALESCE((cm.value->>'visibility_score')::numeric, 0) > 0)+ AS visible_prompts,+ COUNT(*) FILTER (+ WHERE COALESCE((cm.value->>'mention_count')::int, 0) > 0)+ AS mention_answers,+ COUNT(*) FILTER (+ WHERE COALESCE((cm.value->>'citation_count')::int, 0) > 0)+ AS citation_answers,+ AVG(1.0 / (cm.value->>'mention_position')::numeric)+ FILTER (WHERE (cm.value->>'mention_position') IS NOT NULL)+ AS position_factor,+ COUNT(*) FILTER (WHERE (cm.value->>'mention_position') IS NOT NULL)+ AS position_n+ FROM filtered f,+ LATERAL jsonb_array_elements(+ COALESCE(f.competitor_mentions, '[]'::jsonb)) cm+ WHERE cm.value ? 'competitor_id'+ AND EXISTS (+ SELECT 1 FROM public.competitors c+ WHERE c.id::text = cm.value->>'competitor_id'+ AND c.brand_id = p_brand_id+ )+ GROUP BY f.day, cm.value->>'competitor_id'+ )+ SELECT COALESCE(+ jsonb_agg(jsonb_build_object(+ 'day', bd.day,+ 'prompt_count', bd.prompt_count,+ 'visible_prompts', bd.visible_prompts,+ 'answers', bd.answers,+ 'mention_answers', bd.mention_answers,+ 'citation_answers', bd.citation_answers,+ 'position_factor', bd.position_factor,+ 'position_n', bd.position_n,+ 'competitors', COALESCE(+ (SELECT jsonb_agg(jsonb_build_object(+ 'competitor_id', cd.competitor_id,+ 'visible_prompts', cd.visible_prompts,+ 'mention_answers', cd.mention_answers,+ 'citation_answers', cd.citation_answers,+ 'position_factor', cd.position_factor,+ 'position_n', cd.position_n))+ FROM comp_daily cd WHERE cd.day = bd.day),+ '[]'::jsonb)+ ) ORDER BY bd.day),+ '[]'::jsonb)+ FROM brand_daily bd;+$$;++GRANT EXECUTE ON FUNCTION public.visibility_rate_trend(uuid, text, text[], text, timestamptz, timestamptz, uuid)+ TO authenticated;+diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex ccef6a0f9..e2b2a099a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -1525,20 +1525,22 @@ export default function InsightsPage() {{rateTrend.summary.change} pts</span>)}- <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',- })}- </span>+ {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',+ })}+ </span>+ )}</div></div>) : (diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex b9de11d90..3a122da5d 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -2162,12 +2162,14 @@ interface VisibilityRateTrendRow {mention_answers: number;citation_answers: number;position_factor: number | null;+ position_n: number;competitors: {competitor_id: string;visible_prompts: number;mention_answers: number;citation_answers: number;position_factor: number | null;+ position_n: number;}[];}@@ -2189,15 +2191,24 @@ export async function getVisibilityRateTrend(},): Promise<VisibilityRateTrendData> {const supabase = await createClient();- const dateFrom = opts?.dateFrom ?? new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();+ // 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.+ const boundedFrom = opts?.dateFrom ?? null;const dateTo = expandDateToEndOfDay(opts?.dateTo) ?? new Date().toISOString();- // Equal-length window immediately before, for the headline delta.- const windowMs = new Date(dateTo).getTime() - new Date(dateFrom).getTime();- const prevFrom = new Date(new Date(dateFrom).getTime() - windowMs).toISOString();- const prevTo = dateFrom;+ // Equal-length window immediately before, for the headline delta+ // (undefined for all-time — there is no comparable previous window).+ const windowMs = boundedFrom+ ? new Date(dateTo).getTime() - new Date(boundedFrom).getTime()+ : null;+ const prevFrom =+ boundedFrom && windowMs !== null+ ? new Date(new Date(boundedFrom).getTime() - windowMs).toISOString()+ : null;+ const prevTo = boundedFrom;- const rateArgs = (from: string, to: string) => ({+ const rateArgs = (from: string | null, to: string) => ({p_brand_id: brandId,p_platform: null as string | null,p_models: modelFilterArray(opts?.model),@@ -2218,9 +2229,14 @@ export async function getVisibilityRateTrend(supabase.from('brands').select('name, logo_url').eq('id', brandId).single(),supabase.from('brand_domains').select('domain, is_primary').eq('brand_id', brandId),supabase.from('competitors').select('id, name, domain').eq('brand_id', brandId),- supabase.rpc('visibility_rate_trend', rateArgs(dateFrom, dateTo)),- supabase.rpc('ai_visibility_aggregates', rateArgs(dateFrom, dateTo)),- supabase.rpc('ai_visibility_aggregates', rateArgs(prevFrom, prevTo)),+ // The chart plots a rolling window per day, so the earliest displayed+ // days need trailing data from before the display range (all-time needs+ // no warm-up — the window expands from the first row).+ supabase.rpc('visibility_rate_trend', rateArgs(prevFrom, dateTo)),+ supabase.rpc('ai_visibility_aggregates', rateArgs(boundedFrom, dateTo)),+ prevFrom && prevTo+ ? supabase.rpc('ai_visibility_aggregates', rateArgs(prevFrom, prevTo))+ : 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);@@ -2247,37 +2263,98 @@ export async function getVisibilityRateTrend(})),];- // Each day's value is the AI Visibility Score computed over that day's- // answers — same blend as every other surface, shared denominator.- const points: VisibilityRateTrendPoint[] = rows.map((row) => {- const values: Record<string, number> = {- you:- computeAiVisibilityScore({- answers: row.answers,- mentionAnswers: row.mention_answers,- citationAnswers: row.citation_answers,- positionFactor: row.position_factor,- }) ?? 0,+ // Each day's point is the score over the TRAILING window of the selected+ // length ending that day (rolling window). This makes the line's last+ // 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;+ const dayMs = (day: string) => new Date(day + 'T00:00:00Z').getTime();+ const displayFromMs = boundedFrom ? new Date(boundedFrom).getTime() : Number.NEGATIVE_INFINITY;++ interface RollingSums {+ answers: number;+ mention: number;+ citation: number;+ posSum: number;+ posN: number;+ }+ const emptySums = (): RollingSums => ({+ answers: 0,+ mention: 0,+ citation: 0,+ posSum: 0,+ posN: 0,+ });+ const entityKeys = ['you', ...(competitors ?? []).map((c) => c.id)];+ const sums = new Map<string, RollingSums>(entityKeys.map((k) => [k, emptySums()]));++ const dayComponents = (row: VisibilityRateTrendRow, key: string): RollingSums => {+ if (key === 'you') {+ return {+ answers: row.answers,+ mention: row.mention_answers,+ citation: row.citation_answers,+ posSum: (row.position_factor ?? 0) * (row.position_n ?? 0),+ posN: row.position_n ?? 0,+ };+ }+ const entry = row.competitors.find((c) => c.competitor_id === key);+ return {+ answers: 0,+ mention: entry?.mention_answers ?? 0,+ citation: entry?.citation_answers ?? 0,+ posSum: (entry?.position_factor ?? 0) * (entry?.position_n ?? 0),+ posN: entry?.position_n ?? 0,};- const byId = new Map(row.competitors.map((c) => [c.competitor_id, c]));- for (const c of competitors ?? []) {- const entry = byId.get(c.id);- values[c.id] =+ };+ const apply = (key: string, comp: RollingSums, sign: 1 | -1) => {+ const s = sums.get(key)!;+ s.answers += sign * comp.answers;+ s.mention += sign * comp.mention;+ s.citation += sign * comp.citation;+ s.posSum += sign * comp.posSum;+ s.posN += sign * comp.posN;+ };++ const points: VisibilityRateTrendPoint[] = [];+ let start = 0;+ for (let i = 0; i < rows.length; i++) {+ const row = rows[i];+ for (const key of entityKeys) apply(key, dayComponents(row, key), 1);+ // Evict day-buckets that fell out of the trailing window (all-time+ // keeps everything — the window expands cumulatively).+ while (+ windowDays !== null &&+ dayMs(row.day) - dayMs(rows[start].day) >= windowDays * 86_400_000+ ) {+ for (const key of entityKeys) apply(key, dayComponents(rows[start], key), -1);+ start++;+ }+ // Only emit points inside the display range; earlier rows exist purely+ // to warm up the trailing window.+ if (dayMs(row.day) + 86_400_000 <= displayFromMs) continue;++ const brandSums = sums.get('you')!;+ const values: Record<string, number> = {};+ for (const key of entityKeys) {+ const s = sums.get(key)!;+ values[key] =computeAiVisibilityScore({- answers: row.answers,- mentionAnswers: entry?.mention_answers ?? 0,- citationAnswers: entry?.citation_answers ?? 0,- positionFactor: entry?.position_factor ?? null,+ answers: brandSums.answers,+ mentionAnswers: s.mention,+ citationAnswers: s.citation,+ positionFactor: s.posN > 0 ? s.posSum / s.posN : null,}) ?? 0;}- return {+ points.push({date: new Date(row.day + 'T00:00:00').toLocaleDateString('en-US', {month: 'short',day: 'numeric',}),values,- };- });+ });+ }// Headline: overall window score (components over the whole window — not// an average of the daily points) plus the delta vs the previous@@ -2291,8 +2368,8 @@ export async function getVisibilityRateTrend(rate: headlineScore,prevRate: prevScore,change: prevScore === null ? null : Math.round((headlineScore - prevScore) * 10) / 10,- prevFrom,- prevTo,+ prevFrom: prevFrom ?? '',+ prevTo: prevTo ?? '',};return { entities, points, summary };