Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(audit): primary-domain score trend + category breakdown on the hub (#264)

Gökhan Geyik56c0131bb139
diff --git a/server/src/routes/audits.js b/server/src/routes/audits.js
index 2552c58de..fe2c6109f 100644
--- a/server/src/routes/audits.js
+++ b/server/src/routes/audits.js
@@ -211,6 +211,73 @@ router.get('/quota', async (req, res) => {
}
});
+/** Lowercased host of a URL with a leading www. stripped (null on failure). */
+function normHost(u) {
+ try {
+ return new URL(u).host.replace(/^www\./i, '').toLowerCase();
+ } catch {
+ return null;
+ }
+}
+
+// GET /api/audits/trend?brandId=… — completed audits of the brand's PRIMARY
+// domain over time (score + category scores), for the hub trend chart.
+// Registered before /:id so "trend" isn't matched as an audit id.
+router.get('/trend', async (req, res) => {
+ const userId = req.user?.id;
+ const { brandId } = req.query;
+ if (!brandId) {
+ return res.status(400).json({ success: false, message: 'brandId is required' });
+ }
+
+ try {
+ await assertBrandAccess(brandId, userId);
+
+ const { data: domainRows } = await supabaseAdmin
+ .from('brand_domains')
+ .select('domain, is_primary')
+ .eq('brand_id', brandId);
+ const primary =
+ (domainRows ?? []).find((d) => d.is_primary)?.domain ?? (domainRows ?? [])[0]?.domain ?? null;
+ const primaryHost = primary
+ ? primary
+ .replace(/^https?:\/\//, '')
+ .replace(/^www\./i, '')
+ .toLowerCase()
+ : null;
+
+ const { data: rows } = await supabaseAdmin
+ .from('site_audits')
+ .select('id, url, final_url, total_score, category_scores, created_at')
+ .eq('brand_id', brandId)
+ .eq('status', 'completed')
+ .order('created_at', { ascending: true })
+ .limit(500);
+
+ // Keep only audits of the primary domain (match on host of url / final_url).
+ const points = (rows ?? [])
+ .filter((r) => {
+ if (!primaryHost) return false;
+ const h = normHost(r.final_url) ?? normHost(r.url);
+ return h === primaryHost;
+ })
+ .map((r) => ({
+ id: r.id,
+ createdAt: r.created_at,
+ totalScore: r.total_score === null ? null : Number(r.total_score),
+ categoryScores: r.category_scores ?? {},
+ }));
+
+ return res.json({ success: true, primaryDomain: primary, points });
+ } catch (err) {
+ if (err.status) {
+ return res.status(err.status).json({ success: false, message: err.message });
+ }
+ console.error('[audit] trend failed:', err.message);
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
// GET /api/audits/:id — fetch one stored audit with its signals
router.get('/:id', async (req, res) => {
const userId = req.user?.id;
diff --git a/web/messages/en.json b/web/messages/en.json
index 1a4df911f..02abfc049 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -38,6 +38,10 @@
"recent": "Recent Audits",
"deleteAudit": "Delete audit",
"auditsLeft": "audits left this month",
+ "scoreOverTime": "Score over time",
+ "categoryBreakdown": "Category breakdown",
+ "inRange": "in range",
+ "trendNeedsMore": "Run at least two audits of your homepage to see the trend.",
"noBrand": "Select a brand first.",
"urlRequired": "Enter a URL to audit.",
"failed": "Audit failed. Please try again.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_charts.tsx
new file mode 100644
index 000000000..ef5d98845
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_charts.tsx
@@ -0,0 +1,98 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { AreaChart, Area, CartesianGrid, XAxis, YAxis, Tooltip } from 'recharts';
+
+export type TrendDatum = { date: string; score: number };
+
+// Chart color follows the same score bands as the rest of Site Audit
+// (green ≥70 / amber 40–69 / red <40). Driven by the overall (latest) score.
+function scoreHex(score: number | null): string {
+ if (score === null) return '#6366f1';
+ if (score >= 0.7) return '#16a34a'; // green-600
+ if (score >= 0.4) return '#f59e0b'; // amber-500
+ return '#dc2626'; // red-600
+}
+
+// Width-tracking wrapper — ResponsiveContainer has React 19 quirks, so we
+// measure with a ResizeObserver (same approach as insights/_charts.tsx).
+function ChartContainer({
+ height,
+ children,
+}: {
+ height: number;
+ children: (width: number) => React.ReactNode;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [width, setWidth] = useState(0);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const update = () => setWidth(el.clientWidth);
+ update();
+ const ro = new ResizeObserver(update);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+ return (
+ <div ref={ref} style={{ width: '100%', height }}>
+ {width > 0 && children(width)}
+ </div>
+ );
+}
+
+function ScoreTooltip({
+ active,
+ payload,
+ label,
+}: {
+ active?: boolean;
+ payload?: { value: number }[];
+ label?: string;
+}) {
+ if (!active || !payload?.length) return null;
+ return (
+ <div className="rounded-lg border bg-background px-3 py-2 text-xs shadow-md">
+ <p className="mb-1 font-medium text-foreground">{label}</p>
+ <p>
+ Score: <span className="font-medium">{payload[0].value}</span>/100
+ </p>
+ </div>
+ );
+}
+
+export function ScoreTrendChart({ data, score }: { data: TrendDatum[]; score: number | null }) {
+ const color = scoreHex(score);
+ return (
+ <ChartContainer height={200}>
+ {(width) => (
+ <AreaChart
+ width={width}
+ height={200}
+ data={data}
+ margin={{ top: 8, right: 8, left: -20, bottom: 0 }}
+ >
+ <defs>
+ <linearGradient id="auditScoreGrad" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={color} stopOpacity={0.25} />
+ <stop offset="95%" stopColor={color} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid strokeDasharray="3 3" className="stroke-border" vertical={false} />
+ <XAxis dataKey="date" tick={{ fontSize: 11 }} tickLine={false} axisLine={false} />
+ <YAxis domain={[0, 100]} tick={{ fontSize: 11 }} tickLine={false} axisLine={false} />
+ <Tooltip content={<ScoreTooltip />} />
+ <Area
+ type="monotone"
+ dataKey="score"
+ stroke={color}
+ strokeWidth={2}
+ fill="url(#auditScoreGrad)"
+ dot={{ r: 3, fill: color }}
+ activeDot={{ r: 4 }}
+ />
+ </AreaChart>
+ )}
+ </ChartContainer>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
index 399140fea..f38a38b6b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
@@ -1,9 +1,9 @@
'use client';
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useMemo } from 'react';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
-import { Search, Loader2, Trash2, Sparkles } from 'lucide-react';
+import { Search, Loader2, Trash2, Sparkles, TrendingUp, TrendingDown } from 'lucide-react';
import { Link, useRouter } from '@/i18n/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
@@ -13,13 +13,26 @@ import {
runAudit,
getAudits,
getAuditQuota,
+ getAuditTrend,
deleteAudit,
type AuditSummary,
type AuditQuota,
+ type AuditTrend,
} from '@/lib/actions/audits';
-import { pct, scoreColor } from '@/components/audit/audit-report';
+import { pct, scoreColor, CATEGORY_META } from '@/components/audit/audit-report';
+import { ScoreTrendChart } from './_charts';
import { cn } from '@/lib/utils';
+type RangePreset = '7d' | '30d' | '90d' | 'all';
+const RANGE_DAYS: Record<RangePreset, number | null> = { '7d': 7, '30d': 30, '90d': 90, all: null };
+
+function barClass(score: number | null): string {
+ if (score === null) return 'bg-muted';
+ if (score >= 0.7) return 'bg-green-600';
+ if (score >= 0.4) return 'bg-amber-500';
+ return 'bg-destructive';
+}
+
export default function SiteAuditPage() {
const t = useTranslations('audit');
const router = useRouter();
@@ -35,20 +48,29 @@ export default function SiteAuditPage() {
const [running, setRunning] = useState(false);
const [history, setHistory] = useState<AuditSummary[]>([]);
const [quota, setQuota] = useState<AuditQuota | null>(null);
+ const [trend, setTrend] = useState<AuditTrend | null>(null);
+ const [range, setRange] = useState<RangePreset>('30d');
+ // Capture "now" once (impure call belongs in a lazy initializer, not render).
+ const [nowMs] = useState(() => Date.now());
- // Load recent audits + the monthly quota for the active brand.
+ // Load recent audits + the monthly quota + the primary-domain trend.
useEffect(() => {
if (!activeBrandId) return;
let cancelled = false;
(async () => {
try {
- const [data, q] = await Promise.all([getAudits(activeBrandId), getAuditQuota()]);
+ const [data, q, tr] = await Promise.all([
+ getAudits(activeBrandId),
+ getAuditQuota(),
+ getAuditTrend(activeBrandId),
+ ]);
if (!cancelled) {
setHistory(data);
setQuota(q);
+ setTrend(tr);
}
} catch (err) {
- console.error('Failed to load audit history:', err);
+ console.error('Failed to load audit hub data:', err);
}
})();
return () => {
@@ -58,6 +80,29 @@ export default function SiteAuditPage() {
const quotaExhausted = quota !== null && quota.limit !== -1 && quota.remaining <= 0;
+ // Trend points within the selected range (oldest → newest).
+ const rangePoints = useMemo(() => {
+ const points = trend?.points ?? [];
+ const days = RANGE_DAYS[range];
+ if (days === null) return points;
+ const cutoff = nowMs - days * 24 * 60 * 60 * 1000;
+ return points.filter((p) => new Date(p.createdAt).getTime() >= cutoff);
+ }, [trend, range, nowMs]);
+
+ const chartData = rangePoints
+ .filter((p) => p.totalScore !== null)
+ .map((p) => ({
+ date: new Date(p.createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }),
+ score: pct(p.totalScore) ?? 0,
+ }));
+
+ const latestPoint = rangePoints[rangePoints.length - 1] ?? null;
+ const delta =
+ rangePoints.length >= 2
+ ? (pct(rangePoints[rangePoints.length - 1].totalScore) ?? 0) -
+ (pct(rangePoints[0].totalScore) ?? 0)
+ : null;
+
const handleRun = async () => {
if (!activeBrandId) {
toast.error(t('noBrand'));
@@ -97,6 +142,108 @@ export default function SiteAuditPage() {
<p className="text-sm text-muted-foreground">{t('description')}</p>
</div>
+ {/* Primary-domain score trend + category breakdown */}
+ {trend && trend.points.length > 0 && (
+ <Card>
+ <CardHeader className="flex flex-row items-start justify-between gap-3 space-y-0">
+ <div>
+ <CardTitle className="text-base">{t('scoreOverTime')}</CardTitle>
+ {trend.primaryDomain && (
+ <p className="mt-0.5 text-xs text-muted-foreground">{trend.primaryDomain}</p>
+ )}
+ </div>
+ <div className="flex shrink-0 overflow-hidden rounded-md border">
+ {(['7d', '30d', '90d', 'all'] as RangePreset[]).map((p) => (
+ <button
+ key={p}
+ type="button"
+ onClick={() => setRange(p)}
+ className={cn(
+ 'px-2.5 py-1 text-xs font-medium transition-colors',
+ range === p
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-card text-foreground hover:bg-muted',
+ )}
+ >
+ {p === 'all' ? 'All' : p}
+ </button>
+ ))}
+ </div>
+ </CardHeader>
+ <CardContent className="grid grid-cols-1 gap-6 lg:grid-cols-3">
+ {/* Chart + delta */}
+ <div className="lg:col-span-2">
+ <div className="mb-2 flex items-baseline gap-2">
+ <span
+ className={cn(
+ 'text-3xl font-bold tabular-nums',
+ scoreColor(latestPoint?.totalScore ?? null),
+ )}
+ >
+ {latestPoint ? (pct(latestPoint.totalScore) ?? '—') : '—'}
+ </span>
+ <span className="text-sm text-muted-foreground">/100</span>
+ {delta !== null && (
+ <span
+ className={cn(
+ 'inline-flex items-center gap-0.5 text-xs font-medium',
+ delta > 0
+ ? 'text-green-600'
+ : delta < 0
+ ? 'text-destructive'
+ : 'text-muted-foreground',
+ )}
+ >
+ {delta > 0 ? (
+ <TrendingUp className="h-3.5 w-3.5" />
+ ) : delta < 0 ? (
+ <TrendingDown className="h-3.5 w-3.5" />
+ ) : null}
+ {delta > 0 ? '+' : ''}
+ {delta} {t('inRange')}
+ </span>
+ )}
+ </div>
+ {chartData.length >= 2 ? (
+ <ScoreTrendChart data={chartData} score={latestPoint?.totalScore ?? null} />
+ ) : (
+ <div className="flex h-[200px] items-center justify-center text-center text-sm text-muted-foreground">
+ {t('trendNeedsMore')}
+ </div>
+ )}
+ </div>
+
+ {/* Category breakdown grid (latest audit in range) */}
+ <div className="space-y-3">
+ <div className="text-xs font-medium text-muted-foreground">
+ {t('categoryBreakdown')}
+ </div>
+ {CATEGORY_META.map((cat) => {
+ const cs = latestPoint?.categoryScores?.[cat.key];
+ const score = cs?.score ?? null;
+ const p = pct(score);
+ return (
+ <div key={cat.key}>
+ <div className="mb-1 flex items-center justify-between text-xs">
+ <span className="font-medium">{cat.label}</span>
+ <span className="text-muted-foreground tabular-nums">
+ {p === null ? 'n/a' : `${p}/100`}
+ </span>
+ </div>
+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
+ <div
+ className={cn('h-full rounded-full', barClass(score))}
+ style={{ width: `${p ?? 0}%` }}
+ />
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </CardContent>
+ </Card>
+ )}
+
{/* Run bar */}
<Card>
<CardContent className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center">
diff --git a/web/src/components/audit/audit-report.tsx b/web/src/components/audit/audit-report.tsx
index 5580bac4a..f7ae4e6e2 100644
--- a/web/src/components/audit/audit-report.tsx
+++ b/web/src/components/audit/audit-report.tsx
@@ -20,7 +20,7 @@ import { cn } from '@/lib/utils';
// Display order + labels for the five rubric categories (keys come from the
// server's categoryScores). Mirrors the rubric category weights.
-const CATEGORY_META: { key: string; label: string; weight: number }[] = [
+export const CATEGORY_META: { key: string; label: string; weight: number }[] = [
{ key: 'structure', label: 'Structure', weight: 0.25 },
{ key: 'content', label: 'Content', weight: 0.25 },
{ key: 'authority', label: 'Authority', weight: 0.2 },
diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.ts
index 077fa4ffe..c99f85bfd 100644
--- a/web/src/lib/actions/audits.ts
+++ b/web/src/lib/actions/audits.ts
@@ -58,6 +58,18 @@ export interface AuditQuota {
remaining: number;
}
+export interface AuditTrendPoint {
+ id: string;
+ createdAt: string;
+ totalScore: number | null;
+ categoryScores: Record<string, CategoryScore>;
+}
+
+export interface AuditTrend {
+ primaryDomain: string | null;
+ points: AuditTrendPoint[];
+}
+
export interface AuditSummary {
id: string;
url: string;
@@ -148,6 +160,26 @@ export async function getAuditQuota(): Promise<AuditQuota> {
return data.quota;
}
+/** Score + category-score time series for the brand's primary domain. */
+export async function getAuditTrend(brandId: string): Promise<AuditTrend> {
+ const session = await getSession();
+
+ const res = await fetch(
+ `${AEO_SERVER_URL}/api/audits/trend?brandId=${encodeURIComponent(brandId)}`,
+ {
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ },
+ );
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.message || `Server error: ${res.status}`);
+ }
+
+ const data = await res.json();
+ return { primaryDomain: data.primaryDomain ?? null, points: data.points ?? [] };
+}
+
/** List recent audits for a brand (summaries, no signal detail). */
export async function getAudits(brandId: string): Promise<AuditSummary[]> {
const session = await getSession();