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.

fix(audit): end the score trend at the latest audit and page through Recent audits (#975)

Gökhan Geyikf1019bbc8a63
diff --git a/server/src/lib/audit/history.js b/server/src/lib/audit/history.js
new file mode 100644
index 000000000..356e4c6bf
--- /dev/null
+++ b/server/src/lib/audit/history.js
@@ -0,0 +1,51 @@
+/**
+ * Pure helpers for the Site Audit history reads (hub trend chart and the
+ * Recent audits list), kept out of the route so they can be unit tested.
+ */
+
+import { normHost } from './host.js';
+
+/** How many recent completed audits the trend endpoint reads. */
+export const TREND_LIMIT = 500;
+
+/** Default / maximum page size of the Recent audits list. */
+export const LIST_DEFAULT_LIMIT = 50;
+export const LIST_MAX_LIMIT = 100;
+
+function toInt(value) {
+ if (value === undefined || value === null || value === '') return null;
+ const n = Number(value);
+ return Number.isInteger(n) ? n : null;
+}
+
+/**
+ * Parse `limit` / `offset` query params for the audit list. Missing or invalid
+ * values fall back to the first page of LIST_DEFAULT_LIMIT, so callers that
+ * pass neither keep the old "newest 50" behaviour.
+ */
+export function parseListPage(query = {}) {
+ const limit = toInt(query.limit);
+ const offset = toInt(query.offset);
+ return {
+ limit: limit !== null && limit > 0 ? Math.min(limit, LIST_MAX_LIMIT) : LIST_DEFAULT_LIMIT,
+ offset: offset !== null && offset > 0 ? offset : 0,
+ };
+}
+
+/**
+ * Turn completed audit rows read NEWEST first into the chart's points: keep
+ * only audits of the primary domain (host of final_url, else url) and return
+ * them oldest → newest so the chart ends at the latest audit.
+ */
+export function buildTrendPoints(rowsNewestFirst, primaryHost) {
+ if (!primaryHost) return [];
+ return (rowsNewestFirst ?? [])
+ .filter((r) => (normHost(r.final_url) ?? normHost(r.url)) === primaryHost)
+ .map((r) => ({
+ id: r.id,
+ createdAt: r.created_at,
+ totalScore: r.total_score === null ? null : Number(r.total_score),
+ categoryScores: r.category_scores ?? {},
+ }))
+ .reverse();
+}
diff --git a/server/src/lib/audit/history.test.js b/server/src/lib/audit/history.test.js
new file mode 100644
index 000000000..c24e52a40
--- /dev/null
+++ b/server/src/lib/audit/history.test.js
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest';
+import { buildTrendPoints, parseListPage, LIST_DEFAULT_LIMIT, LIST_MAX_LIMIT } from './history.js';
+
+describe('parseListPage', () => {
+ it('defaults to the first page of the default size', () => {
+ expect(parseListPage({})).toEqual({ limit: LIST_DEFAULT_LIMIT, offset: 0 });
+ expect(parseListPage()).toEqual({ limit: LIST_DEFAULT_LIMIT, offset: 0 });
+ });
+
+ it('reads limit and offset from query strings', () => {
+ expect(parseListPage({ limit: '20', offset: '40' })).toEqual({ limit: 20, offset: 40 });
+ });
+
+ it('caps the limit', () => {
+ expect(parseListPage({ limit: '10000' }).limit).toBe(LIST_MAX_LIMIT);
+ });
+
+ it('falls back on invalid values', () => {
+ expect(parseListPage({ limit: '0', offset: '-5' })).toEqual({
+ limit: LIST_DEFAULT_LIMIT,
+ offset: 0,
+ });
+ expect(parseListPage({ limit: 'abc', offset: '1.5' })).toEqual({
+ limit: LIST_DEFAULT_LIMIT,
+ offset: 0,
+ });
+ });
+});
+
+describe('buildTrendPoints', () => {
+ const row = (id, url, createdAt, score = '0.5') => ({
+ id,
+ url,
+ final_url: null,
+ total_score: score,
+ category_scores: null,
+ created_at: createdAt,
+ });
+
+ it('keeps primary-domain audits and returns them oldest first', () => {
+ const newestFirst = [
+ row('c', 'https://www.example.com/', '2026-03-03T00:00:00Z'),
+ row('x', 'https://other.com/', '2026-03-02T12:00:00Z'),
+ row('b', 'https://example.com/a', '2026-03-02T00:00:00Z'),
+ row('a', 'https://example.com/', '2026-03-01T00:00:00Z', null),
+ ];
+ const points = buildTrendPoints(newestFirst, 'example.com');
+ expect(points.map((p) => p.id)).toEqual(['a', 'b', 'c']);
+ expect(points[0]).toEqual({
+ id: 'a',
+ createdAt: '2026-03-01T00:00:00Z',
+ totalScore: null,
+ categoryScores: {},
+ });
+ expect(points[2].totalScore).toBe(0.5);
+ });
+
+ it('matches on final_url before url', () => {
+ const r = { ...row('a', 'https://old.com/', '2026-03-01T00:00:00Z') };
+ r.final_url = 'https://example.com/';
+ expect(buildTrendPoints([r], 'example.com')).toHaveLength(1);
+ });
+
+ it('returns nothing without a primary domain', () => {
+ expect(buildTrendPoints([row('a', 'https://example.com/', 'x')], null)).toEqual([]);
+ expect(buildTrendPoints(null, 'example.com')).toEqual([]);
+ });
+});
diff --git a/server/src/routes/audits.js b/server/src/routes/audits.js
index a0e66e235..04d17707b 100644
--- a/server/src/routes/audits.js
+++ b/server/src/routes/audits.js
@@ -4,7 +4,7 @@
*
* POST /api/audits { url, brandId } → run a single-page audit
* GET /api/audits/:id → fetch a stored audit + signals
- * GET /api/audits?brandId=… → recent audits for a brand
+ * GET /api/audits?brandId=…&limit=&offset= → recent audits for a brand (paged)
*
* The audit runs synchronously: one Scrape.do fetch, the deterministic signal
* engine, one batched LLM round-trip for the semantic signals, and a Wikidata
@@ -23,7 +23,8 @@ import {
PlanLimitError,
} from '../lib/plan-guard.js';
import { buildAuditContext } from '../lib/audit/context.js';
-import { normHost, normStoredDomain } from '../lib/audit/host.js';
+import { normStoredDomain } from '../lib/audit/host.js';
+import { buildTrendPoints, parseListPage, TREND_LIMIT } from '../lib/audit/history.js';
import { runSignals } from '../lib/audit/engine.js';
import { evaluateLlmSignals } from '../lib/audit/llm-signals.js';
import { evaluateBrandEntity } from '../lib/audit/external-signals.js';
@@ -244,7 +245,9 @@ router.get('/quota', async (req, res) => {
});
// GET /api/audits/trend?brandId=… — completed audits of the brand's PRIMARY
-// domain over time (score + category scores), for the hub trend chart.
+// domain over time (score + category scores), for the hub trend chart. Reads
+// the newest TREND_LIMIT completed audits so the chart always ends at the
+// latest one, then returns the points oldest → newest.
// Registered before /:id so "trend" isn't matched as an audit id.
router.get('/trend', async (req, res) => {
const userId = req.user?.id;
@@ -269,22 +272,10 @@ router.get('/trend', async (req, res) => {
.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 ?? {},
- }));
+ .order('created_at', { ascending: false })
+ .limit(TREND_LIMIT);
+
+ const points = buildTrendPoints(rows, primaryHost);
return res.json({ success: true, primaryDomain: primary, points });
} catch (err) {
@@ -328,10 +319,13 @@ router.get('/:id', async (req, res) => {
}
});
-// GET /api/audits?brandId=… — recent audits for a brand (list, no signals)
+// GET /api/audits?brandId=…&limit=50&offset=0 — recent audits for a brand,
+// newest first (list, no signals). `total` is the brand's full audit count so
+// the client can page; omitting limit/offset returns the newest 50 as before.
router.get('/', async (req, res) => {
const userId = req.user?.id;
const { brandId } = req.query;
+ const { limit, offset } = parseListPage(req.query);
if (!brandId) {
return res.status(400).json({ success: false, message: 'brandId is required' });
@@ -340,14 +334,17 @@ router.get('/', async (req, res) => {
try {
await assertBrandAccess(brandId, userId);
- const { data: audits } = await supabaseAdmin
+ const { data: audits, count } = await supabaseAdmin
.from('site_audits')
- .select('id, url, status, total_score, signals_evaluated, signals_total, created_at')
+ .select('id, url, status, total_score, signals_evaluated, signals_total, created_at', {
+ count: 'exact',
+ })
.eq('brand_id', brandId)
.order('created_at', { ascending: false })
- .limit(50);
+ .order('id', { ascending: false })
+ .range(offset, offset + limit - 1);
- return res.json({ success: true, audits: audits ?? [] });
+ return res.json({ success: true, audits: audits ?? [], total: count ?? 0 });
} catch (err) {
if (err.status) {
return res.status(err.status).json({ success: false, message: err.message });
diff --git a/web/messages/en.json b/web/messages/en.json
index c0ffa8a01..7e08f48eb 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1455,6 +1455,7 @@
"runAudit": "Run Audit",
"running": "Auditing…",
"recent": "Recent Audits",
+ "loadMore": "Load more",
"retry": "Retry",
"deleteAudit": "Delete audit",
"loadFailed": "Couldn't load this audit",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
index 84bec476e..7be4bd585 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
@@ -70,6 +70,8 @@ export default function SiteAuditPage() {
const [error, setError] = useState<string | null>(null);
const [refreshKey, setRefreshKey] = useState(0);
const [history, setHistory] = useState<AuditSummary[]>([]);
+ const [historyTotal, setHistoryTotal] = useState(0);
+ const [loadingMore, setLoadingMore] = useState(false);
const [quota, setQuota] = useState<AuditQuota | null>(null);
const [trend, setTrend] = useState<AuditTrend | null>(null);
const [range, setRange] = useState<RangePreset>('30d');
@@ -92,7 +94,8 @@ export default function SiteAuditPage() {
getAuditTrend(activeBrandId),
]);
if (!cancelled) {
- setHistory(data);
+ setHistory(data.audits);
+ setHistoryTotal(data.total);
setQuota(q);
setTrend(tr);
}
@@ -178,6 +181,25 @@ export default function SiteAuditPage() {
}
};
+ // Append the next page of Recent audits. Dedupe by id: an audit started
+ // since the first page shifts offsets by one.
+ const handleLoadMore = async () => {
+ if (!activeBrandId) return;
+ setLoadingMore(true);
+ try {
+ const next = await getAudits(activeBrandId, history.length);
+ setHistory((h) => {
+ const seen = new Set(h.map((a) => a.id));
+ return [...h, ...next.audits.filter((a) => !seen.has(a.id))];
+ });
+ setHistoryTotal(next.total);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : t('failed'));
+ } finally {
+ setLoadingMore(false);
+ }
+ };
+
const handleDelete = async (id: string) => {
const prev = history;
setHistory((h) => h.filter((a) => a.id !== id));
@@ -445,6 +467,14 @@ export default function SiteAuditPage() {
</Dialog>
</div>
))}
+ {history.length < historyTotal && (
+ <div className="flex justify-center pt-3">
+ <Button variant="outline" size="sm" onClick={handleLoadMore} disabled={loadingMore}>
+ {loadingMore && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+ {t('loadMore')}
+ </Button>
+ </div>
+ )}
</CardContent>
</Card>
)}
diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.ts
index 69b4b6fd5..a80a1fb21 100644
--- a/web/src/lib/actions/audits.ts
+++ b/web/src/lib/actions/audits.ts
@@ -181,11 +181,22 @@ export async function getAuditTrend(brandId: string): Promise<AuditTrend> {
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[]> {
+export interface AuditPage {
+ audits: AuditSummary[];
+ /** Total audits for the brand, across all pages. */
+ total: number;
+}
+
+/** List a page of a brand's audits, newest first (summaries, no signal detail). */
+export async function getAudits(brandId: string, offset = 0, limit = 50): Promise<AuditPage> {
const session = await getSession();
- const res = await fetch(`${AEO_SERVER_URL}/api/audits?brandId=${encodeURIComponent(brandId)}`, {
+ const params = new URLSearchParams({
+ brandId,
+ limit: String(limit),
+ offset: String(offset),
+ });
+ const res = await fetch(`${AEO_SERVER_URL}/api/audits?${params}`, {
headers: { Authorization: `Bearer ${session.access_token}` },
});
@@ -195,5 +206,6 @@ export async function getAudits(brandId: string): Promise<AuditSummary[]> {
}
const data = await res.json();
- return data.audits ?? [];
+ const audits: AuditSummary[] = data.audits ?? [];
+ return { audits, total: data.total ?? audits.length };
}