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(reports): mention & citation evidence sections + Brand Citations naming (#444)
Gökhan Geyik3db8c2c683f7
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 555d17ee5..a7e797228 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -437,7 +437,9 @@"aiTraffic": "AI Traffic","shoppingVisibility": "Shopping","auditScore": "Audit Score",- "citations": "Citations"+ "citations": "Citations",+ "mentionEvidence": "Mention Evidence",+ "citationEvidence": "Citation Evidence"},"brandLabel": "Brand","sectionsLabel": "Sections",@@ -470,7 +472,13 @@"topic": "Topic","results": "Results","platform": "Platform",- "topPages": "Top Pages"+ "topPages": "Top Pages",+ "date": "Date",+ "mentions": "Mentions",+ "excerpt": "How you were mentioned",+ "url": "URL",+ "citations": "Citations",+ "citedIn": "Cited in"},"topicPerformance": "Topic Performance","aiTraffic": "AI Traffic",@@ -495,7 +503,7 @@"kpi": {"visibility": "Visibility","mentions": "Mentions",- "citations": "Citations",+ "citations": "Brand Citations","sentiment": "Positive Sentiment"},"shareOfVoice": "Share of Voice",@@ -503,7 +511,13 @@"topCitationSources": "Top Citation Sources","citationTotals": "{domains} domains · {citations} citations in this period","noData": "No data for this period.",- "you": "(you)"+ "you": "(you)",+ "kpiCitationsNote": "\"Brand Citations\" counts citations of your own site in AI answers.",+ "citationsSectionNote": "All sources AI answers cited around your brand — not just your own site.",+ "mentionEvidence": "Mention Evidence",+ "mentionEvidenceDescription": "The answers that mentioned you most in this period, with the passage around the mention.",+ "citationEvidence": "Citation Evidence",+ "citationEvidenceDescription": "The URLs AI answers cited most in this period, and which tracked prompts surfaced them."},"settings": {"title": "Settings",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsxindex 9ab4f1812..2abdd4159 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx@@ -267,7 +267,7 @@ export function ReportPdfDocument({ report }: { report: Report }) {payload.insights.mentionsChange,],[- 'Citations',+ 'Brand Citations',String(payload.insights.totalCitations),payload.insights.citationsChange,],@@ -288,6 +288,11 @@ export function ReportPdfDocument({ report }: { report: Report }) {))}</View>)}+ {payload.insights && (+ <Text style={{ fontSize: 7, color: MUTED, marginTop: -8, marginBottom: 12 }}>+ "Brand Citations" counts citations of your own site in AI answers.+ </Text>+ )}{/* Visibility trend */}{trend.length > 1 && (@@ -419,6 +424,27 @@ export function ReportPdfDocument({ report }: { report: Report }) {<PromptTable title="Weakest Prompts" prompts={payload.promptPerformance.worst} />)}+ {/* Mention evidence (#429) — which answers mentioned the brand, and how */}+ {payload.mentionEvidence && payload.mentionEvidence.length > 0 && (+ <View style={styles.section}>+ <Text style={styles.sectionTitle}>Mention Evidence</Text>+ <View style={styles.tableHeader}>+ <Text style={[styles.tableHeaderCell, { width: 130 }]}>Prompt</Text>+ <Text style={[styles.tableHeaderCell, { width: 60 }]}>Platform</Text>+ <Text style={[styles.tableHeaderCell, { width: 50 }]}>Date</Text>+ <Text style={[styles.tableHeaderCell, { flex: 1 }]}>How you were mentioned</Text>+ </View>+ {payload.mentionEvidence.map((m, idx) => (+ <View key={`${m.promptText}-${idx}`} style={styles.tableRow}>+ <Text style={[styles.cell, { width: 130, paddingRight: 6 }]}>{m.promptText}</Text>+ <Text style={[styles.cell, { width: 60, color: MUTED }]}>{m.platform}</Text>+ <Text style={[styles.cell, { width: 50, color: MUTED }]}>{formatDate(m.date)}</Text>+ <Text style={[styles.cell, { flex: 1, color: MUTED }]}>{m.excerpt}</Text>+ </View>+ ))}+ </View>+ )}+{/* Query fan-out */}{payload.queryFanout && payload.queryFanout.length > 0 && (<View style={styles.section} wrap={false}>@@ -573,6 +599,34 @@ export function ReportPdfDocument({ report }: { report: Report }) {</View>)}+ {/* Citation evidence (#429) — the exact URLs and the prompts that surfaced them */}+ {payload.citationEvidence && payload.citationEvidence.length > 0 && (+ <View style={styles.section}>+ <Text style={styles.sectionTitle}>Citation Evidence</Text>+ <View style={styles.tableHeader}>+ <Text style={[styles.tableHeaderCell, { flex: 1 }]}>URL</Text>+ <Text style={[styles.tableHeaderCell, { width: 55, textAlign: 'right' }]}>+ Citations+ </Text>+ <Text style={[styles.tableHeaderCell, { width: 170 }]}>Cited in</Text>+ </View>+ {payload.citationEvidence.map((c) => (+ <View key={c.url} style={styles.tableRow}>+ <View style={{ flex: 1, paddingRight: 6 }}>+ <Text style={styles.cell}>{c.title || c.url}</Text>+ <Text style={[styles.cell, { color: MUTED, fontSize: 7 }]}>{c.url}</Text>+ </View>+ <Text style={[styles.cell, { width: 55, textAlign: 'right' }]}>+ {c.totalCitations}+ </Text>+ <Text style={[styles.cell, { width: 170, color: MUTED, fontSize: 7 }]}>+ {c.sourcedPrompts.join(' · ')}+ </Text>+ </View>+ ))}+ </View>+ )}+{/* Footer */}<View style={styles.footer} fixed><Text style={styles.footerText}>Generated with Ansvisor · www.ansvisor.com</Text>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsxindex ac9e931e0..21d304b9c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/page.tsx@@ -228,6 +228,9 @@ export default function ReportDetailPage() {value={`${payload.insights.positiveSentimentPct}%`}change={payload.insights.sentimentChange}/>+ <p className="text-xs text-muted-foreground sm:col-span-2 lg:col-span-4">+ {t('kpiCitationsNote')}+ </p></div>)}{payload.visibilityTrend && payload.visibilityTrend.length > 0 && (@@ -398,6 +401,43 @@ export default function ReportDetailPage() {</div>)}+ {payload.mentionEvidence && payload.mentionEvidence.length > 0 && (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">{t('mentionEvidence')}</CardTitle>+ <p className="text-sm text-muted-foreground">{t('mentionEvidenceDescription')}</p>+ </CardHeader>+ <CardContent>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-[220px]">{t('columns.prompt')}</TableHead>+ <TableHead className="w-28">{t('columns.platform')}</TableHead>+ <TableHead className="w-24">{t('columns.date')}</TableHead>+ <TableHead>{t('columns.excerpt')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {payload.mentionEvidence.map((m, idx) => (+ <TableRow key={`${m.promptText}-${idx}`}>+ <TableCell className="max-w-[220px] truncate font-medium">+ {m.promptText}+ </TableCell>+ <TableCell className="text-muted-foreground">+ {PLATFORM_LABELS[m.platform] ?? m.platform}+ </TableCell>+ <TableCell className="text-muted-foreground">{formatDate(m.date)}</TableCell>+ <TableCell className="whitespace-normal text-sm text-muted-foreground">+ {m.excerpt}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ )}+{payload.queryFanout && payload.queryFanout.length > 0 && (<Card><CardHeader>@@ -555,7 +595,8 @@ export default function ReportDetailPage() {{t('citationTotals', {domains: payload.citations.totals.domains,citations: payload.citations.totals.citations,- })}+ })}{' '}+ {t('citationsSectionNote')}</p></CardHeader><CardContent className="space-y-4">@@ -567,7 +608,7 @@ export default function ReportDetailPage() {<TableRow><TableHead>{t('columns.domain')}</TableHead><TableHead>{t('columns.sourceType')}</TableHead>- <TableHead className="text-right">{t('kpi.citations')}</TableHead>+ <TableHead className="text-right">{t('columns.citations')}</TableHead><TableHead className="text-right">{t('columns.usage')}</TableHead></TableRow></TableHeader>@@ -588,6 +629,50 @@ export default function ReportDetailPage() {</CardContent></Card>)}++ {payload.citationEvidence && payload.citationEvidence.length > 0 && (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">{t('citationEvidence')}</CardTitle>+ <p className="text-sm text-muted-foreground">{t('citationEvidenceDescription')}</p>+ </CardHeader>+ <CardContent>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{t('columns.url')}</TableHead>+ <TableHead className="w-24 text-right">{t('columns.citations')}</TableHead>+ <TableHead className="w-[280px]">{t('columns.citedIn')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {payload.citationEvidence.map((c) => (+ <TableRow key={c.url}>+ <TableCell className="max-w-[320px]">+ <a+ href={c.url}+ target="_blank"+ rel="noopener noreferrer"+ className="block truncate font-medium hover:underline"+ title={c.title || c.url}+ >+ {c.title || c.url}+ </a>+ <span className="block truncate text-xs text-muted-foreground">+ {c.domain}+ </span>+ </TableCell>+ <TableCell className="text-right">{c.totalCitations}</TableCell>+ <TableCell className="whitespace-normal text-xs text-muted-foreground">+ {c.sourcedPrompts.join(' · ')}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ )}</div></div>);diff --git a/web/src/lib/actions/reports.ts b/web/src/lib/actions/reports.tsindex 1328e21eb..095a8e633 100644--- a/web/src/lib/actions/reports.ts+++ b/web/src/lib/actions/reports.ts@@ -16,7 +16,7 @@ import {} from '@/lib/actions/tracking';import { getCitationsOverview, type CitationsSourceBreakdown } from '@/lib/actions/citations';import { getShoppingKpis } from '@/lib/actions/shopping';-import type { SourceCategory } from '@/lib/citations/classify';+import { extractHostname, type SourceCategory } from '@/lib/citations/classify';import {getReportTemplate,ALL_REPORT_SECTIONS,@@ -57,6 +57,27 @@ export interface ReportFanoutQuery {timesSearched: number;}+/** One concrete brand mention: which prompt, where, and the passage (#429). */+export interface ReportMentionEvidence {+ promptText: string;+ /** Platform slug as stored on the result (UI maps to a label). */+ platform: string;+ date: string;+ mentionCount: number;+ /** Short passage of the answer around the brand mention. */+ excerpt: string;+}++/** One concrete cited URL and the prompts whose answers cited it (#429). */+export interface ReportCitationEvidence {+ url: string;+ domain: string;+ title: string;+ totalCitations: number;+ /** Up to a few tracked prompts whose answers cited this URL. */+ sourcedPrompts: string[];+}+export interface ReportTopicPerf {name: string;avgVisibility: number;@@ -110,6 +131,10 @@ export interface ReportPayload {best: ReportPromptPerf[];worst: ReportPromptPerf[];};+ /** The top mentioning answers, with the passage around the mention (#429). */+ mentionEvidence?: ReportMentionEvidence[];+ /** The top cited URLs with the prompts whose answers cited them (#429). */+ citationEvidence?: ReportCitationEvidence[];/** Most-run observed fan-out sub-queries in the period. */queryFanout?: ReportFanoutQuery[];/** Per-topic visibility with deltas vs the previous window. */@@ -471,6 +496,193 @@ async function getAuditSnapshot(brandId: string, dateTo: string): Promise<Report};}+/** How many evidence rows a report keeps per evidence section (#429). */+const REPORT_EVIDENCE_COUNT = 10;+/** How many sourcing prompts each cited URL lists. */+const EVIDENCE_PROMPTS_PER_URL = 3;++/** Light markdown/URL strip so excerpts read as prose. */+function stripMarkdown(text: string): string {+ return text+ .replace(/\[([^\]]*)\]\([^)]+\)/g, '$1')+ .replace(/https?:\/\/[^\s)>\]]+/g, '')+ .replace(/[*_#`]/g, '')+ .replace(/\s+/g, ' ')+ .trim();+}++/**+ * The passage of an answer around the first brand mention — the "how was I+ * mentioned" a KPI total can't convey. Falls back to the answer's opening+ * when the mention came via a domain rather than the brand name.+ */+function mentionExcerpt(response: string, brandName: string): string {+ const clean = stripMarkdown(response);+ const idx = clean.toLowerCase().indexOf(brandName.toLowerCase());+ if (idx === -1) {+ return clean.length > 180 ? `${clean.slice(0, 180).trimEnd()}…` : clean;+ }+ const start = Math.max(0, idx - 60);+ const end = Math.min(clean.length, idx + brandName.length + 140);+ const prefix = start > 0 ? '…' : '';+ const suffix = end < clean.length ? '…' : '';+ return `${prefix}${clean.slice(start, end).trim()}${suffix}`;+}++/**+ * Top mentioning answers in the window (#429): prompt, platform, date and the+ * passage around the mention. Server-side ORDER BY + LIMIT — no scan needed.+ */+async function getMentionEvidence(+ brandId: string,+ brandName: string,+ dateFrom: string,+ dateTo: string,+): Promise<ReportMentionEvidence[]> {+ const supabase = await createClient();++ const { data: rows } = await supabase+ .from('prompt_results')+ .select('prompt_id, platform, created_at, mention_count, response')+ .eq('brand_id', brandId)+ .neq('platform', 'chatgpt-shopping')+ .gt('mention_count', 0)+ .gte('created_at', dateFrom)+ .lte('created_at', dateTo)+ .order('mention_count', { ascending: false })+ .order('created_at', { ascending: false })+ .limit(REPORT_EVIDENCE_COUNT);++ const results = (rows ?? []) as Array<{+ prompt_id: string | null;+ platform: string | null;+ created_at: string;+ mention_count: number | null;+ response: string | null;+ }>;+ if (results.length === 0) return [];++ const promptIds = [...new Set(results.map((r) => r.prompt_id).filter(Boolean))] as string[];+ const promptTextById = new Map<string, string>();+ if (promptIds.length > 0) {+ const { data: promptRows } = await supabase+ .from('prompts')+ .select('id, text')+ .in('id', promptIds);+ for (const p of promptRows ?? []) promptTextById.set(p.id as string, p.text as string);+ }++ return results.map((r) => ({+ promptText: (r.prompt_id && promptTextById.get(r.prompt_id)) || '(deleted prompt)',+ platform: r.platform ?? '',+ date: r.created_at,+ mentionCount: r.mention_count ?? 0,+ excerpt: mentionExcerpt(r.response ?? '', brandName),+ }));+}++/**+ * Top cited URLs in the window with the prompts whose answers cited them+ * (#429). Needs its own paginated scan: the citations overview aggregates+ * URLs but doesn't keep the prompt attribution the evidence section is for.+ */+async function getCitationEvidence(+ brandId: string,+ dateFrom: string,+ dateTo: string,+): Promise<ReportCitationEvidence[]> {+ const supabase = await createClient();+ const PAGE_SIZE = 1000;+ const MAX_ROWS = 50_000;++ interface UrlAgg {+ url: string;+ domain: string;+ title: string;+ count: number;+ promptIds: Set<string>;+ }+ const byUrl = new Map<string, UrlAgg>();++ for (let offset = 0; offset < MAX_ROWS; offset += PAGE_SIZE) {+ const { data, error } = await supabase+ .from('prompt_results')+ .select('prompt_id, citations')+ .eq('brand_id', brandId)+ .neq('platform', 'chatgpt-shopping')+ .gte('created_at', dateFrom)+ .lte('created_at', dateTo)+ .order('created_at', { ascending: true })+ .order('id', { ascending: true })+ .range(offset, offset + PAGE_SIZE - 1);+ if (error) throw new Error(error.message);++ const batch = (data ?? []) as Array<{+ prompt_id: string | null;+ citations: Array<{ url?: string; title?: string }> | null;+ }>;++ for (const row of batch) {+ const citations = Array.isArray(row.citations) ? row.citations : [];+ for (const cite of citations) {+ if (!cite?.url) continue;+ const host = extractHostname(cite.url);+ if (!host) continue;+ // Same URL normalization the Citations page uses, so the evidence+ // list lines up with the overview's Top URLs.+ let normalized = cite.url;+ try {+ const parsed = new URL(cite.url);+ parsed.search = '';+ parsed.hash = '';+ normalized = parsed.toString().replace(/\/$/, '');+ } catch {+ // leave as-is+ }+ const agg = byUrl.get(normalized) ?? {+ url: normalized,+ domain: host,+ title: cite.title || '',+ count: 0,+ promptIds: new Set<string>(),+ };+ agg.count += 1;+ if (!agg.title && cite.title) agg.title = cite.title;+ if (row.prompt_id) agg.promptIds.add(row.prompt_id);+ byUrl.set(normalized, agg);+ }+ }++ if (batch.length < PAGE_SIZE) break;+ }++ const top = [...byUrl.values()]+ .sort((a, b) => b.count - a.count || a.url.localeCompare(b.url))+ .slice(0, REPORT_EVIDENCE_COUNT);+ if (top.length === 0) return [];++ const allPromptIds = [...new Set(top.flatMap((u) => [...u.promptIds]))];+ const promptTextById = new Map<string, string>();+ if (allPromptIds.length > 0) {+ const { data: promptRows } = await supabase+ .from('prompts')+ .select('id, text')+ .in('id', allPromptIds);+ for (const p of promptRows ?? []) promptTextById.set(p.id as string, p.text as string);+ }++ return top.map((u) => ({+ url: u.url,+ domain: u.domain,+ title: u.title,+ totalCitations: u.count,+ sourcedPrompts: [...u.promptIds]+ .map((id) => promptTextById.get(id))+ .filter((t): t is string => Boolean(t))+ .slice(0, EVIDENCE_PROMPTS_PER_URL),+ }));+}+// ─── Actions ─────────────────────────────────────────────────────────────────/** English display names used in stored (immutable) report titles. */@@ -528,6 +740,8 @@ export async function createReport(citations,trend,promptPerformance,+ mentionEvidence,+ citationEvidence,queryFanout,topicPerformance,aiTraffic,@@ -542,6 +756,8 @@ export async function createReport(: null,has('trend') ? getVisibilityTrend(brandId, range) : null,has('promptPerformance') ? getPromptPerformance(brandId, dateFrom, dateTo) : null,+ has('mentionEvidence') ? getMentionEvidence(brandId, brandName, dateFrom, dateTo) : null,+ has('citationEvidence') ? getCitationEvidence(brandId, dateFrom, dateTo) : null,has('queryFanout') ? getFanoutSnapshot(brandId, dateFrom, dateTo) : null,has('topicPerformance') ? getTopicPerformance(brandId, dateFrom, dateTo) : null,has('aiTraffic') ? getTrafficSnapshot(brandId, dateFrom, dateTo) : null,@@ -554,6 +770,8 @@ export async function createReport(...(insights ? { insights } : {}),...(trend ? { visibilityTrend: trend } : {}),...(promptPerformance ? { promptPerformance } : {}),+ ...(mentionEvidence && mentionEvidence.length > 0 ? { mentionEvidence } : {}),+ ...(citationEvidence && citationEvidence.length > 0 ? { citationEvidence } : {}),...(queryFanout ? { queryFanout } : {}),...(topicPerformance && topicPerformance.length > 0 ? { topicPerformance } : {}),...(aiTraffic ? { aiTraffic } : {}),diff --git a/web/src/lib/reports/templates.ts b/web/src/lib/reports/templates.tsindex 222154b4f..104db6474 100644--- a/web/src/lib/reports/templates.ts+++ b/web/src/lib/reports/templates.ts@@ -25,11 +25,13 @@ export type ReportSection =| 'competitors'| 'topicPerformance'| 'promptPerformance'+ | 'mentionEvidence'| 'queryFanout'| 'aiTraffic'| 'shoppingVisibility'| 'auditScore'- | 'citations';+ | 'citations'+ | 'citationEvidence';/*** Every pickable section, in report render order — drives the section@@ -44,11 +46,13 @@ export const ALL_REPORT_SECTIONS: ReportSection[] = ['competitors','topicPerformance','promptPerformance',+ 'mentionEvidence','queryFanout','aiTraffic','shoppingVisibility','auditScore','citations',+ 'citationEvidence',];export interface ReportTemplateDef {@@ -74,11 +78,13 @@ export const REPORT_TEMPLATES: ReportTemplateDef[] = ['competitors','topicPerformance','promptPerformance',+ 'mentionEvidence','queryFanout','aiTraffic','shoppingVisibility','auditScore','citations',+ 'citationEvidence',],defaultPreset: '30d',},@@ -89,7 +95,7 @@ export const REPORT_TEMPLATES: ReportTemplateDef[] = [},{id: 'citation_sources',- sections: ['citations'],+ sections: ['citations', 'citationEvidence'],defaultPreset: '30d',},];