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(prompts): Top Sources card on the prompt detail page (#495)
Gökhan Geyik1af4cf78fde2
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsxindex 5e64d29f4..036c6fe7e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx@@ -2,7 +2,6 @@import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';import { useTranslations } from 'next-intl';-import Image from 'next/image';import dynamic from 'next/dynamic';const DynamicSourceTypeDonutChart = dynamic(() => import('./citations_charts').then((m) => m.SourceTypeDonutChartView),@@ -53,7 +52,13 @@ import {import { toCsv } from '@/lib/csv';import type { Topic } from '@/types';import { SOURCE_CATEGORY_LABELS, type SourceCategory } from '@/lib/citations/classify';-import { getFaviconUrl } from '@/lib/favicon';+import {+ CategoryBadge,+ DomainFavicon,+ PlatformsCell,+ UsageBar,+} from '@/components/citations/source-cells';+import { PAGE_SIZE, TablePager, usePagination } from '@/components/table-pager';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import {Dialog,@@ -85,12 +90,7 @@ import {} from '@/components/ui/table';import { Skeleton } from '@/components/ui/skeleton';import { cn } from '@/lib/utils';-import {- AIProviderAvatar,- getAIProviderDisplayName,- resolveAIProvider,- type AIProviderKey,-} from '@/components/ai-provider-avatar';+import { getAIProviderDisplayName, resolveAIProvider } from '@/components/ai-provider-avatar';// ─── Constants ───────────────────────────────────────────────────────────────@@ -107,17 +107,6 @@ const CATEGORY_COLORS: Record<SourceCategory, string> = {other: '#94a3b8',};-const CATEGORY_BADGE_CLASSES: Record<SourceCategory, string> = {- you: 'border-indigo-500/30 bg-indigo-500/10 text-indigo-700 dark:text-indigo-300',- competitor: 'border-orange-500/30 bg-orange-500/10 text-orange-700 dark:text-orange-300',- editorial: 'border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300',- forum: 'border-green-500/30 bg-green-500/10 text-green-700 dark:text-green-300',- social: 'border-purple-500/30 bg-purple-500/10 text-purple-700 dark:text-purple-300',- review: 'border-yellow-500/30 bg-yellow-500/10 text-yellow-700 dark:text-yellow-300',- institutional: 'border-teal-500/30 bg-teal-500/10 text-teal-700 dark:text-teal-300',- other: 'border-slate-400/30 bg-slate-400/10 text-slate-700 dark:text-slate-300',-};-// AI platform / model friendly names — kept in sync with the insights page.const PLATFORM_LABELS: Record<string, string> = {chatgpt: 'ChatGPT',@@ -251,78 +240,6 @@ function buildPlatformOptions(rows: CitationsOverview['rows']): PlatformOption[]// ─── Sub-components ───────────────────────────────────────────────────────────-function CategoryBadge({ category }: { category: SourceCategory }) {- return (- <Badge- variant="outline"- className={cn(- 'text-[10px] font-medium capitalize whitespace-nowrap',- CATEGORY_BADGE_CLASSES[category],- )}- >- {SOURCE_CATEGORY_LABELS[category]}- </Badge>- );-}--function ProviderDot({ provider }: { provider: AIProviderKey }) {- return <AIProviderAvatar provider={provider} />;-}--/**- * Collapse model identifiers down to their underlying provider so the column- * shows at most one dot per platform (ChatGPT, Claude, Gemini, ...). There- * are only 7 known providers, so the row width stays stable regardless of- * how many raw models fed into the domain.- */-function PlatformsCell({ models }: { models: string[] }) {- if (models.length === 0) {- return <span className="text-xs text-muted-foreground">—</span>;- }- const providers = Array.from(new Set(models.map((m) => resolveAIProvider(m)))).sort();- return (- <div className="flex items-center gap-1">- {providers.map((p) => (- <ProviderDot key={p} provider={p} />- ))}- </div>- );-}--function UsageBar({ pct }: { pct: number }) {- const clamped = Math.min(100, Math.max(0, pct));- return (- <div className="flex items-center gap-2">- <div className="h-1.5 w-20 rounded-full bg-muted overflow-hidden">- <div className="h-full rounded-full bg-primary" style={{ width: `${clamped}%` }} />- </div>- <span className="text-xs tabular-nums text-foreground">{pct.toFixed(1)}%</span>- </div>- );-}--function DomainFavicon({ domain }: { domain: string }) {- const [errored, setErrored] = useState(false);- if (errored) {- return (- <div className="flex h-6 w-6 items-center justify-center rounded border bg-muted">- <Globe className="h-3 w-3 text-muted-foreground" />- </div>- );- }- return (- <Image- src={getFaviconUrl(domain, 64)}- alt=""- width={20}- height={20}- unoptimized- className="h-5 w-5 rounded-sm border bg-white object-contain"- onError={() => setErrored(true)}- />- );-}-// ─── Donut ────────────────────────────────────────────────────────────────────function ChartContainer({@@ -1044,86 +961,6 @@ function EmptyRows({);}-// ─── Pagination ───────────────────────────────────────────────────────────────--const PAGE_SIZE = 100;--/**- * Per-table pagination state.- * resetKey — pass a JSON.stringify of the active filters so the pager- * automatically jumps back to page 0 whenever any filter changes.- */-export function usePagination(totalRows: number, resetKey: unknown) {- const [page, setPage] = useState(0);-- // eslint-disable-next-line react-hooks/exhaustive-deps- const resetKeyRef = useRef(resetKey);- if (resetKeyRef.current !== resetKey) {- resetKeyRef.current = resetKey;- setPage(0);- }-- const totalPages = Math.max(1, Math.ceil(totalRows / PAGE_SIZE));- const clampedPage = Math.min(page, totalPages - 1);-- return {- page: clampedPage,- setPage,- totalPages,- start: clampedPage * PAGE_SIZE,- end: Math.min((clampedPage + 1) * PAGE_SIZE, totalRows),- };-}--function TablePager({- page,- totalPages,- total,- start,- end,- onPage,-}: {- page: number;- totalPages: number;- total: number;- start: number;- end: number;- onPage: (p: number) => void;-}) {- if (totalPages <= 1) return null;-- return (- <div className="flex items-center justify-between border-t px-4 py-3">- <span className="text-xs text-muted-foreground tabular-nums">- {start + 1}–{end} of {total}- </span>- <div className="flex items-center gap-2">- <Button- variant="outline"- size="sm"- className="h-7 px-3 text-xs"- disabled={page === 0}- onClick={() => onPage(page - 1)}- >- Previous- </Button>- <span className="text-xs text-muted-foreground tabular-nums">- {page + 1} / {totalPages}- </span>- <Button- variant="outline"- size="sm"- className="h-7 px-3 text-xs"- disabled={page >= totalPages - 1}- onClick={() => onPage(page + 1)}- >- Next- </Button>- </div>- </div>- );-}-// ─── Competitor Gaps (#300) ───────────────────────────────────────────────────const GAP_METHODOLOGY =diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsxindex 3231570fb..643229356 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx@@ -7,14 +7,40 @@ import {getPromptDetail,type PromptDetailData,type PromptResultWithText,+ type PromptTopSource,+ type PromptTopSourceUrl,} from '@/lib/actions/tracking';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Skeleton } from '@/components/ui/skeleton';-import { ArrowLeft, ChevronDown, Clock, Eye, MessageSquareText, Quote } from 'lucide-react';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';+import {+ ArrowLeft,+ ChevronDown,+ Clock,+ ExternalLink,+ Eye,+ MessageSquareText,+ Quote,+} from 'lucide-react';import { cn } from '@/lib/utils';import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';+import {+ CategoryBadge,+ DomainFavicon,+ PlatformsCell,+ UsageBar,+} from '@/components/citations/source-cells';+import { TablePager, usePagination } from '@/components/table-pager';import { groupByPlatform, type PlatformGroup } from './grouping';const PLATFORM_LABELS: Record<string, string> = {@@ -146,6 +172,177 @@ function KpiCard({);}+function TopSourceDomainsTable({ rows }: { rows: PromptTopSource[] }) {+ const pager = usePagination(rows.length, rows.length);+ const pageRows = rows.slice(pager.start, pager.end);++ return (+ <div>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-[56px] text-xs">Rank</TableHead>+ <TableHead className="text-xs">Domain</TableHead>+ <TableHead className="text-xs">Platforms</TableHead>+ <TableHead className="text-xs">Usage</TableHead>+ <TableHead className="text-right text-xs">Citations</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {pageRows.map((row, i) => (+ <TableRow key={row.domain}>+ {/* Global rank — offset by page so rank is continuous across pages */}+ <TableCell className="text-xs text-muted-foreground tabular-nums">+ {pager.start + i + 1}+ </TableCell>+ <TableCell>+ <div className="flex min-w-0 items-center gap-2">+ <DomainFavicon domain={row.domain} />+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-sm font-medium">{row.domain}</span>+ <div className="flex items-center gap-1.5 pt-0.5">+ <CategoryBadge category={row.category} />+ <a+ href={`https://${row.domain}`}+ target="_blank"+ rel="noreferrer noopener"+ className="inline-flex items-center text-muted-foreground hover:text-foreground"+ aria-label={`Open ${row.domain} in a new tab`}+ >+ <ExternalLink className="h-3 w-3" />+ </a>+ </div>+ </div>+ </div>+ </TableCell>+ <TableCell>+ <PlatformsCell models={row.models} />+ </TableCell>+ <TableCell>+ <UsageBar pct={row.usagePct} />+ </TableCell>+ <TableCell className="text-right text-xs tabular-nums">+ {row.totalCitations}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ <TablePager+ page={pager.page}+ totalPages={pager.totalPages}+ total={rows.length}+ start={pager.start}+ end={pager.end}+ onPage={pager.setPage}+ />+ </div>+ );+}++function TopSourceUrlsTable({ rows }: { rows: PromptTopSourceUrl[] }) {+ const pager = usePagination(rows.length, rows.length);+ const pageRows = rows.slice(pager.start, pager.end);++ return (+ <div>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-[56px] text-xs">Rank</TableHead>+ <TableHead className="text-xs">URL</TableHead>+ <TableHead className="text-xs">Platforms</TableHead>+ <TableHead className="text-xs">Usage</TableHead>+ <TableHead className="text-right text-xs">Citations</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {pageRows.map((row, i) => (+ <TableRow key={row.url}>+ {/* Global rank — offset by page so rank is continuous across pages */}+ <TableCell className="text-xs text-muted-foreground tabular-nums">+ {pager.start + i + 1}+ </TableCell>+ <TableCell>+ <div className="flex min-w-0 items-start gap-2">+ <DomainFavicon domain={row.domain} />+ <div className="flex min-w-0 max-w-[480px] flex-col">+ <a+ href={row.url}+ target="_blank"+ rel="noreferrer noopener"+ className="truncate text-sm font-medium text-foreground hover:underline"+ title={row.title || row.url}+ >+ {row.title || row.url}+ </a>+ <div className="flex items-center gap-1.5 pt-0.5">+ <span className="truncate text-[11px] text-muted-foreground">+ {row.domain}+ </span>+ <CategoryBadge category={row.category} />+ </div>+ </div>+ </div>+ </TableCell>+ <TableCell>+ <PlatformsCell models={row.models} />+ </TableCell>+ <TableCell>+ <UsageBar pct={row.usagePct} />+ </TableCell>+ <TableCell className="text-right text-xs tabular-nums">+ {row.totalCitations}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ <TablePager+ page={pager.page}+ totalPages={pager.totalPages}+ total={rows.length}+ start={pager.start}+ end={pager.end}+ onPage={pager.setPage}+ />+ </div>+ );+}++function TopSourcesCard({+ sources,+ sourceUrls,+}: {+ sources: PromptTopSource[];+ sourceUrls: PromptTopSourceUrl[];+}) {+ return (+ <Card>+ <CardHeader className="pb-3">+ <CardTitle className="text-sm font-medium">Top Sources</CardTitle>+ <p className="text-xs text-muted-foreground">+ Sources AI platforms cite when answering this prompt.+ </p>+ </CardHeader>+ <CardContent>+ <Tabs defaultValue="domains">+ <TabsList>+ <TabsTrigger value="domains">Domains ({sources.length})</TabsTrigger>+ <TabsTrigger value="urls">URLs ({sourceUrls.length})</TabsTrigger>+ </TabsList>+ <TabsContent value="domains" keepMounted className="mt-4">+ <TopSourceDomainsTable rows={sources} />+ </TabsContent>+ <TabsContent value="urls" keepMounted className="mt-4">+ <TopSourceUrlsTable rows={sourceUrls} />+ </TabsContent>+ </Tabs>+ </CardContent>+ </Card>+ );+}+function PlatformResultGroup({group,expanded,@@ -439,6 +636,10 @@ export default function PromptDetailPage() {)}</CardContent></Card>++ {data.topSources.length > 0 && (+ <TopSourcesCard sources={data.topSources} sourceUrls={data.topSourceUrls} />+ )}</div>);}diff --git a/web/src/components/citations/source-cells.tsx b/web/src/components/citations/source-cells.tsxnew file mode 100644index 000000000..2aad75515--- /dev/null+++ b/web/src/components/citations/source-cells.tsx@@ -0,0 +1,103 @@+'use client';++/**+ * Shared presentational cells for citation-source tables. Used by the+ * citations page and the prompt detail Top Sources card so a domain renders+ * identically (favicon, category badge, platform dots) everywhere.+ */++import { useState } from 'react';+import Image from 'next/image';+import { Globe } from 'lucide-react';+import { Badge } from '@/components/ui/badge';+import { cn } from '@/lib/utils';+import { getFaviconUrl } from '@/lib/favicon';+import { SOURCE_CATEGORY_LABELS, type SourceCategory } from '@/lib/citations/classify';+import {+ AIProviderAvatar,+ resolveAIProvider,+ type AIProviderKey,+} from '@/components/ai-provider-avatar';++export const CATEGORY_BADGE_CLASSES: Record<SourceCategory, string> = {+ you: 'border-indigo-500/30 bg-indigo-500/10 text-indigo-700 dark:text-indigo-300',+ competitor: 'border-orange-500/30 bg-orange-500/10 text-orange-700 dark:text-orange-300',+ editorial: 'border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300',+ forum: 'border-green-500/30 bg-green-500/10 text-green-700 dark:text-green-300',+ social: 'border-purple-500/30 bg-purple-500/10 text-purple-700 dark:text-purple-300',+ review: 'border-yellow-500/30 bg-yellow-500/10 text-yellow-700 dark:text-yellow-300',+ institutional: 'border-teal-500/30 bg-teal-500/10 text-teal-700 dark:text-teal-300',+ other: 'border-slate-400/30 bg-slate-400/10 text-slate-700 dark:text-slate-300',+};++export function CategoryBadge({ category }: { category: SourceCategory }) {+ return (+ <Badge+ variant="outline"+ className={cn(+ 'text-[10px] font-medium capitalize whitespace-nowrap',+ CATEGORY_BADGE_CLASSES[category],+ )}+ >+ {SOURCE_CATEGORY_LABELS[category]}+ </Badge>+ );+}++function ProviderDot({ provider }: { provider: AIProviderKey }) {+ return <AIProviderAvatar provider={provider} />;+}++/**+ * Collapse model identifiers down to their underlying provider so the column+ * shows at most one dot per platform (ChatGPT, Claude, Gemini, ...). There+ * are only 7 known providers, so the row width stays stable regardless of+ * how many raw models fed into the domain.+ */+export function PlatformsCell({ models }: { models: string[] }) {+ if (models.length === 0) {+ return <span className="text-xs text-muted-foreground">—</span>;+ }+ const providers = Array.from(new Set(models.map((m) => resolveAIProvider(m)))).sort();+ return (+ <div className="flex items-center gap-1">+ {providers.map((p) => (+ <ProviderDot key={p} provider={p} />+ ))}+ </div>+ );+}++export function UsageBar({ pct }: { pct: number }) {+ const clamped = Math.min(100, Math.max(0, pct));+ return (+ <div className="flex items-center gap-2">+ <div className="h-1.5 w-20 rounded-full bg-muted overflow-hidden">+ <div className="h-full rounded-full bg-primary" style={{ width: `${clamped}%` }} />+ </div>+ <span className="text-xs tabular-nums text-foreground">{pct.toFixed(1)}%</span>+ </div>+ );+}++export function DomainFavicon({ domain }: { domain: string }) {+ const [errored, setErrored] = useState(false);+ if (errored) {+ return (+ <div className="flex h-6 w-6 items-center justify-center rounded border bg-muted">+ <Globe className="h-3 w-3 text-muted-foreground" />+ </div>+ );+ }+ return (+ <Image+ src={getFaviconUrl(domain, 64)}+ alt=""+ width={20}+ height={20}+ unoptimized+ className="h-5 w-5 rounded-sm border bg-white object-contain"+ onError={() => setErrored(true)}+ />+ );+}diff --git a/web/src/components/table-pager.tsx b/web/src/components/table-pager.tsxnew file mode 100644index 000000000..142da295c--- /dev/null+++ b/web/src/components/table-pager.tsx@@ -0,0 +1,88 @@+'use client';++/**+ * Client-side table pagination shared by the citations page and the prompt+ * detail Top Sources card: a fixed page size, a state hook that resets on+ * filter changes, and the Previous/Next footer row.+ */++import { useState } from 'react';+import { Button } from '@/components/ui/button';++export const PAGE_SIZE = 100;++/**+ * Per-table pagination state.+ * resetKey — pass a JSON.stringify of the active filters so the pager+ * automatically jumps back to page 0 whenever any filter changes.+ */+export function usePagination(totalRows: number, resetKey: unknown) {+ const [page, setPage] = useState(0);++ // Adjust-state-during-render pattern: jump back to page 0 when the key changes.+ const [prevResetKey, setPrevResetKey] = useState(resetKey);+ if (prevResetKey !== resetKey) {+ setPrevResetKey(resetKey);+ setPage(0);+ }++ const totalPages = Math.max(1, Math.ceil(totalRows / PAGE_SIZE));+ const clampedPage = Math.min(page, totalPages - 1);++ return {+ page: clampedPage,+ setPage,+ totalPages,+ start: clampedPage * PAGE_SIZE,+ end: Math.min((clampedPage + 1) * PAGE_SIZE, totalRows),+ };+}++export function TablePager({+ page,+ totalPages,+ total,+ start,+ end,+ onPage,+}: {+ page: number;+ totalPages: number;+ total: number;+ start: number;+ end: number;+ onPage: (p: number) => void;+}) {+ if (totalPages <= 1) return null;++ return (+ <div className="flex items-center justify-between border-t px-4 py-3">+ <span className="text-xs text-muted-foreground tabular-nums">+ {start + 1}–{end} of {total}+ </span>+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ className="h-7 px-3 text-xs"+ disabled={page === 0}+ onClick={() => onPage(page - 1)}+ >+ Previous+ </Button>+ <span className="text-xs text-muted-foreground tabular-nums">+ {page + 1} / {totalPages}+ </span>+ <Button+ variant="outline"+ size="sm"+ className="h-7 px-3 text-xs"+ disabled={page >= totalPages - 1}+ onClick={() => onPage(page + 1)}+ >+ Next+ </Button>+ </div>+ </div>+ );+}diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 52bfe9a79..31e8de7b6 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -12,6 +12,12 @@ import type {ObservedSearchQuery,} from '@/types';import { API_BASE_URL } from '@/config/api';+import {+ classifyDomain,+ extractHostname,+ normalizeDomain,+ type SourceCategory,+} from '@/lib/citations/classify';import { getTopicById } from '@/lib/actions/topic';import { getOrgPlan } from '@/lib/guards/plan-guard';import { getPromptVolumes } from '@/lib/actions/volumes';@@ -71,6 +77,28 @@ export interface PromptResultWithText extends PromptResult {topicName?: string;}+/** One row of the prompt detail "Top Sources" card — mirrors CitationDomainRow. */+export interface PromptTopSource {+ domain: string;+ category: SourceCategory;+ models: string[];+ totalCitations: number;+ resultsCiting: number;+ usagePct: number;+}++/** One URL row of the prompt detail "Top Sources" card — mirrors CitationUrlRow. */+export interface PromptTopSourceUrl {+ url: string;+ domain: string;+ category: SourceCategory;+ title: string;+ models: string[];+ totalCitations: number;+ resultsCiting: number;+ usagePct: number;+}+export interface PromptDetailData {prompt: {id: string;@@ -90,6 +118,8 @@ export interface PromptDetailData {lastCheckedAt: string | null;};results: PromptResultWithText[];+ topSources: PromptTopSource[];+ topSourceUrls: PromptTopSourceUrl[];}export interface InsightsSummary {@@ -799,6 +829,20 @@ export async function getPromptDetail(const brandId = (promptSetData?.brand_id as string | undefined) ?? '';+ // Brand + competitor domains feed classifyDomain, same as the citations page.+ const [{ data: brandDomainRows }, { data: competitorRows }] = await Promise.all([+ supabase.from('brand_domains').select('domain').eq('brand_id', brandId),+ supabase.from('competitors').select('domain').eq('brand_id', brandId),+ ]);+ const classifyCtx = {+ brandDomains: (brandDomainRows ?? [])+ .map((r) => normalizeDomain((r as { domain: string }).domain))+ .filter(Boolean),+ competitorDomains: (competitorRows ?? [])+ .map((r) => normalizeDomain((r as { domain: string }).domain))+ .filter(Boolean),+ };+let topicName: string | undefined;if (prompt.topic_id) {const { data: topic } = await supabase@@ -838,6 +882,92 @@ export async function getPromptDetail(? Math.round(results.reduce((sum, row) => sum + row.visibilityScore, 0) / totalResults): 0;+ // Aggregate citations by domain — same shape and rounding as getCitationsOverview,+ // but scoped to this prompt's already-loaded results.+ interface SourceAgg {+ domain: string;+ category: SourceCategory;+ totalCitations: number;+ resultsCiting: Set<string>;+ models: Set<string>;+ }+ interface UrlAgg extends SourceAgg {+ url: string;+ title: string;+ }+ const sourceMap = new Map<string, SourceAgg>();+ const urlMap = new Map<string, UrlAgg>();+ for (const result of results) {+ const modelKey = result.modelUsed || result.platform || '';+ for (const cite of result.citations) {+ const host = extractHostname(cite.url);+ if (!host) continue;+ const category = sourceMap.get(host)?.category ?? classifyDomain(host, classifyCtx);++ const agg = sourceMap.get(host) ?? {+ domain: host,+ category,+ totalCitations: 0,+ resultsCiting: new Set<string>(),+ models: new Set<string>(),+ };+ agg.totalCitations += 1;+ agg.resultsCiting.add(result.id);+ if (modelKey) agg.models.add(modelKey);+ sourceMap.set(host, agg);++ // URL aggregation (strip query/fragment and trailing slash for dedupe,+ // same as getCitationsOverview).+ let normalizedUrl = cite.url;+ try {+ const parsed = new URL(cite.url);+ parsed.search = '';+ parsed.hash = '';+ normalizedUrl = parsed.toString().replace(/\/$/, '');+ } catch {+ // leave as-is+ }+ const urlAgg = urlMap.get(normalizedUrl) ?? {+ url: normalizedUrl,+ domain: host,+ category,+ title: cite.title || '',+ totalCitations: 0,+ resultsCiting: new Set<string>(),+ models: new Set<string>(),+ };+ urlAgg.totalCitations += 1;+ urlAgg.resultsCiting.add(result.id);+ if (modelKey) urlAgg.models.add(modelKey);+ if (!urlAgg.title && cite.title) urlAgg.title = cite.title;+ urlMap.set(normalizedUrl, urlAgg);+ }+ }+ const usagePctOf = (resultsCiting: number) =>+ totalResults > 0 ? Math.round((resultsCiting / totalResults) * 1000) / 10 : 0;+ const topSources: PromptTopSource[] = Array.from(sourceMap.values())+ .map((agg) => ({+ domain: agg.domain,+ category: agg.category,+ models: Array.from(agg.models).sort(),+ totalCitations: agg.totalCitations,+ resultsCiting: agg.resultsCiting.size,+ usagePct: usagePctOf(agg.resultsCiting.size),+ }))+ .sort((a, b) => b.totalCitations - a.totalCitations || a.domain.localeCompare(b.domain));+ const topSourceUrls: PromptTopSourceUrl[] = Array.from(urlMap.values())+ .map((agg) => ({+ url: agg.url,+ domain: agg.domain,+ category: agg.category,+ title: agg.title,+ models: Array.from(agg.models).sort(),+ totalCitations: agg.totalCitations,+ resultsCiting: agg.resultsCiting.size,+ usagePct: usagePctOf(agg.resultsCiting.size),+ }))+ .sort((a, b) => b.totalCitations - a.totalCitations || a.url.localeCompare(b.url));+return {prompt: {id: prompt.id as string,@@ -857,6 +987,8 @@ export async function getPromptDetail(lastCheckedAt: results[0]?.createdAt ?? null,},results,+ topSources,+ topSourceUrls,};}