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(audit): list audited pages one row per URL with their history (#1133)
Cihan848e1da40505
diff --git a/server/src/lib/audit/history.js b/server/src/lib/audit/history.jsindex 356e4c6bf..1ab4ca43c 100644--- a/server/src/lib/audit/history.js+++ b/server/src/lib/audit/history.js@@ -1,6 +1,7 @@/**- * 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.+ * Pure helpers for the Site Audit history reads (hub trend chart, the Pages+ * list and the raw audit list), kept out of the route so they can be unit+ * tested.*/import { normHost } from './host.js';@@ -49,3 +50,94 @@ export function buildTrendPoints(rowsNewestFirst, primaryHost) {})).reverse();}++/** Score at or above which a page reads as Good (70/100). */+export const GOOD_SCORE = 0.7;++/** Completed scores drawn in a page's trend line, newest last. */+export const PAGE_TREND_POINTS = 10;++/** Runs listed under a page's history. */+export const PAGE_HISTORY_LIMIT = 50;++/**+ * One key per page, so repeat audits of it share a row: the host without+ * www. and the path without a trailing slash. Query and fragment are ignored.+ * Null for something that isn't a URL.+ */+export function pageKey(url) {+ try {+ const u = new URL(url);+ const host = u.hostname.replace(/^www\./i, '').toLowerCase();+ const path = u.pathname.replace(/\/+$/, '') || '/';+ return { key: `${host}${path}`, host, path };+ } catch {+ return null;+ }+}++const points = (score) => Math.round(score * 100);++/**+ * A page's status from its runs (newest first) and its two latest completed+ * audits: Running while a run is in progress, Failed when none ever+ * completed, Good from 70, Improving below 70 when at least a point above the+ * previous audit, and Needs work otherwise.+ */+export function pageStatus(latestRun, current, previous) {+ if (latestRun?.status === 'running') return 'running';+ if (!current) return 'failed';+ if (current.totalScore >= GOOD_SCORE) return 'good';+ if (previous && points(current.totalScore) > points(previous.totalScore)) return 'improving';+ return 'needs_work';+}++/**+ * Group audit rows read NEWEST first into one entry per page (pageKey of+ * final_url, else url), most recently audited page first. Each page carries+ * its latest completed score and audit, the one before it, a status, its+ * trend and its runs.+ */+export function buildAuditPages(rowsNewestFirst) {+ const groups = new Map();+ // Rows read in slices can repeat one at a slice boundary.+ const seen = new Set();+ for (const r of rowsNewestFirst ?? []) {+ if (seen.has(r.id)) continue;+ seen.add(r.id);+ const url = r.final_url ?? r.url;+ const page = pageKey(url) ?? { key: url, host: null, path: url };+ if (!groups.has(page.key)) groups.set(page.key, { ...page, runs: [] });+ groups.get(page.key).runs.push({+ id: r.id,+ url,+ status: r.status,+ totalScore: r.total_score === null ? null : Number(r.total_score),+ createdAt: r.created_at,+ });+ }++ return [...groups.values()].map(({ key, host, path, runs }) => {+ const completed = runs.filter((r) => r.status === 'completed' && r.totalScore !== null);+ const latest = runs[0];+ const current = completed[0] ?? null;+ const previous = completed[1] ?? null;+ return {+ key,+ host,+ path,+ url: (current ?? latest).url,+ auditId: (current ?? latest).id,+ score: current?.totalScore ?? null,+ previousScore: previous?.totalScore ?? null,+ status: pageStatus(latest, current, previous),+ lastAuditedAt: (current ?? latest).createdAt,+ trend: completed+ .slice(0, PAGE_TREND_POINTS)+ .map((r) => r.totalScore)+ .reverse(),+ runs: runs.slice(0, PAGE_HISTORY_LIMIT),+ runCount: runs.length,+ };+ });+}diff --git a/server/src/lib/audit/history.test.js b/server/src/lib/audit/history.test.jsindex c24e52a40..668b5c82b 100644--- a/server/src/lib/audit/history.test.js+++ b/server/src/lib/audit/history.test.js@@ -1,5 +1,14 @@import { describe, expect, it } from 'vitest';-import { buildTrendPoints, parseListPage, LIST_DEFAULT_LIMIT, LIST_MAX_LIMIT } from './history.js';+import {+ buildAuditPages,+ buildTrendPoints,+ pageKey,+ pageStatus,+ parseListPage,+ LIST_DEFAULT_LIMIT,+ LIST_MAX_LIMIT,+ PAGE_TREND_POINTS,+} from './history.js';describe('parseListPage', () => {it('defaults to the first page of the default size', () => {@@ -66,3 +75,139 @@ describe('buildTrendPoints', () => {expect(buildTrendPoints(null, 'example.com')).toEqual([]);});});++describe('pageKey', () => {+ it('reads repeat audits of a page as the same page', () => {+ const keys = [+ 'https://acme.com/pricing',+ 'https://www.acme.com/pricing/',+ 'http://ACME.com/pricing?utm_source=x#plans',+ ].map((u) => pageKey(u).key);+ expect(new Set(keys)).toEqual(new Set(['acme.com/pricing']));+ });++ it('keeps the root, path case and other hosts apart', () => {+ expect(pageKey('https://acme.com')).toEqual({ key: 'acme.com/', host: 'acme.com', path: '/' });+ expect(pageKey('https://acme.com/Blog').key).not.toBe(pageKey('https://acme.com/blog').key);+ expect(pageKey('https://blog.acme.com/pricing').key).toBe('blog.acme.com/pricing');+ expect(pageKey('not a url')).toBeNull();+ });+});++describe('pageStatus', () => {+ const run = (status) => ({ status });+ const audit = (totalScore) => ({ totalScore });++ it('is Good from 70, whatever the previous audit was', () => {+ expect(pageStatus(run('completed'), audit(0.7), audit(0.9))).toBe('good');+ });++ it('is Improving below 70 when at least a point up on the previous audit', () => {+ expect(pageStatus(run('completed'), audit(0.65), audit(0.6))).toBe('improving');+ expect(pageStatus(run('completed'), audit(0.654), audit(0.646))).toBe('needs_work');+ expect(pageStatus(run('completed'), audit(0.6), audit(0.65))).toBe('needs_work');+ expect(pageStatus(run('completed'), audit(0.3), null)).toBe('needs_work');+ });++ it('is Running while a run is in progress, and Failed when none ever completed', () => {+ expect(pageStatus(run('running'), audit(0.8), null)).toBe('running');+ expect(pageStatus(run('failed'), null, null)).toBe('failed');+ // A failed retry doesn't hide the last completed score.+ expect(pageStatus(run('failed'), audit(0.8), null)).toBe('good');+ });+});++describe('buildAuditPages', () => {+ const row = (id, url, created_at, total_score, status = 'completed', final_url = url) => ({+ id,+ url,+ final_url: status === 'completed' ? final_url : null,+ status,+ total_score,+ created_at,+ });++ it('gives each page one row with its latest score, the previous one and its runs', () => {+ const pages = buildAuditPages([+ row('a3', 'https://acme.com/pricing/', '2026-10-14T09:00:00Z', '0.63'),+ row('b1', 'https://acme.com/blog', '2026-10-12T09:00:00Z', '0.74'),+ row('a2', 'https://www.acme.com/pricing', '2026-10-01T09:00:00Z', '0.58'),+ row('a1', 'https://acme.com/pricing', '2026-09-20T09:00:00Z', '0.5'),+ ]);++ expect(pages.map((p) => p.key)).toEqual(['acme.com/pricing', 'acme.com/blog']);+ expect(pages[0]).toMatchObject({+ host: 'acme.com',+ path: '/pricing',+ url: 'https://acme.com/pricing/',+ auditId: 'a3',+ score: 0.63,+ previousScore: 0.58,+ status: 'improving',+ lastAuditedAt: '2026-10-14T09:00:00Z',+ trend: [0.5, 0.58, 0.63],+ runCount: 3,+ });+ expect(pages[0].runs.map((r) => r.id)).toEqual(['a3', 'a2', 'a1']);+ expect(pages[1]).toMatchObject({ score: 0.74, previousScore: null, status: 'good' });+ });++ it('counts a run repeated at a read boundary once', () => {+ const a2 = row('a2', 'https://acme.com/pricing', '2026-10-14T09:00:00Z', '0.6');+ const a1 = row('a1', 'https://acme.com/pricing', '2026-10-01T09:00:00Z', '0.5');+ const [page] = buildAuditPages([a2, a1, a1]);+ expect(page.runCount).toBe(2);+ expect(page.trend).toEqual([0.5, 0.6]);+ });++ it('groups by the final URL after a redirect', () => {+ const pages = buildAuditPages([+ row(+ 'a2',+ 'http://acme.com/old',+ '2026-10-14T09:00:00Z',+ '0.6',+ 'completed',+ 'https://acme.com/new',+ ),+ row('a1', 'https://acme.com/new', '2026-10-01T09:00:00Z', '0.5'),+ ]);+ expect(pages).toHaveLength(1);+ expect(pages[0].runCount).toBe(2);+ });++ it('keeps the last completed score while a re-audit runs or after one fails', () => {+ const [running] = buildAuditPages([+ row('a3', 'https://acme.com/pricing', '2026-10-15T09:00:00Z', null, 'running'),+ row('a2', 'https://acme.com/pricing', '2026-10-14T09:00:00Z', null, 'failed'),+ row('a1', 'https://acme.com/pricing', '2026-10-01T09:00:00Z', '0.58'),+ ]);+ expect(running).toMatchObject({+ status: 'running',+ score: 0.58,+ auditId: 'a1',+ lastAuditedAt: '2026-10-01T09:00:00Z',+ runCount: 3,+ });++ const [failed] = buildAuditPages([+ row('b1', 'https://acme.com/blog', '2026-10-15T09:00:00Z', null, 'failed'),+ ]);+ expect(failed).toMatchObject({ status: 'failed', score: null, auditId: 'b1', trend: [] });+ });++ it('draws the trend from the newest completed scores, oldest first', () => {+ const rows = Array.from({ length: PAGE_TREND_POINTS + 3 }, (_, i) =>+ row(+ `a${i}`,+ 'https://acme.com/',+ `2026-10-${String(20 - i).padStart(2, '0')}T09:00:00Z`,+ String(0.9 - i / 100),+ ),+ );+ const [page] = buildAuditPages(rows);+ expect(page.trend).toHaveLength(PAGE_TREND_POINTS);+ expect(page.trend.at(-1)).toBe(0.9);+ expect(page.trend[0]).toBeCloseTo(0.81);+ });+});diff --git a/server/src/routes/audits-pages.test.js b/server/src/routes/audits-pages.test.jsnew file mode 100644index 000000000..21ceb782a--- /dev/null+++ b/server/src/routes/audits-pages.test.js@@ -0,0 +1,168 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for GET /api/audits/pages: the brand's audits read in+ * full (past PostgREST's 1000-row page), grouped into one row per page,+ * paged, and the open issues counted for the rows returned.+ */++let audits;+let signals;+let domains;+let signalQueries;+let server;+let baseUrl;++// A query builder that answers from the arrays above.+function query(table) {+ const filters = { eq: {}, in: {} };+ let range = null;+ const builder = {+ select: () => builder,+ order: () => builder,+ eq: (col, val) => {+ filters.eq[col] = val;+ return builder;+ },+ in: (col, vals) => {+ filters.in[col] = vals;+ return builder;+ },+ range: (from, to) => {+ range = [from, to];+ return builder;+ },+ then: (resolve) => {+ let data = [];+ if (table === 'site_audits') {+ data = audits.filter((a) => a.brand_id === filters.eq.brand_id);+ if (range) data = data.slice(range[0], range[1] + 1);+ } else if (table === 'brand_domains') {+ data = domains;+ } else if (table === 'audit_signal_results') {+ signalQueries.push(filters.in.audit_id);+ data = signals.filter(+ (s) => filters.in.audit_id.includes(s.audit_id) && filters.in.status.includes(s.status),+ );+ }+ return resolve({ data, error: null });+ },+ };+ return builder;+}++async function startApp() {+ vi.resetModules();+ vi.doMock('../config/supabase.js', () => ({ default: { from: (t) => query(t) } }));+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess: vi.fn() }));+ vi.doMock('../lib/plan-guard.js', () => ({+ requireFeature: () => (req, res, next) => next(),+ enforceSiteAuditQuota: vi.fn(),+ getSiteAuditQuotaStatus: vi.fn(),+ getOrgIdForUser: vi.fn(),+ PlanLimitError: class PlanLimitError extends Error {},+ }));+ vi.doMock('../lib/audit/context.js', () => ({ buildAuditContext: vi.fn() }));+ vi.doMock('../lib/audit/engine.js', () => ({ runSignals: vi.fn() }));+ vi.doMock('../lib/audit/llm-signals.js', () => ({ evaluateLlmSignals: vi.fn() }));+ vi.doMock('../lib/audit/external-signals.js', () => ({ evaluateBrandEntity: vi.fn() }));+ vi.doMock('../lib/audit/recommendations.js', () => ({ generateRecommendations: vi.fn() }));+ vi.doMock('../lib/logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ return { default: logger, logger };+ });++ const { default: router } = await import('./audits.js');+ const app = express();+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/audits', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/audits`;+}++const audit = (id, url, day, score, status = 'completed') => ({+ id,+ brand_id: 'b1',+ url,+ final_url: status === 'completed' ? url : null,+ status,+ total_score: score,+ created_at: `2026-10-${String(day).padStart(2, '0')}T09:00:00Z`,+});++beforeEach(async () => {+ signalQueries = [];+ domains = [{ domain: 'https://www.Acme.com/', is_primary: true }];+ audits = [+ audit('p2', 'https://acme.com/pricing', 14, '0.63'),+ audit('x1', 'https://other.com/', 13, '0.8'),+ audit('p1', 'https://acme.com/pricing/', 1, '0.58'),+ audit('f1', 'https://acme.com/broken', 1, null, 'failed'),+ ];+ signals = [+ { audit_id: 'p2', status: 'fail' },+ { audit_id: 'p2', status: 'warn' },+ { audit_id: 'p1', status: 'fail' },+ ];+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+ vi.doUnmock('../config/supabase.js');+});++describe('GET /api/audits/pages', () => {+ it('returns one row per page with its issues, the total and the primary host', async () => {+ const res = await fetch(`${baseUrl}/pages?brandId=b1`);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.total).toBe(3);+ expect(body.primaryHost).toBe('acme.com');+ expect(body.pages.map((p) => [p.path, p.status, p.issues])).toEqual([+ ['/pricing', 'improving', 2],+ ['/', 'good', 0],+ ['/broken', 'failed', null],+ ]);+ expect(body.pages[0]).toMatchObject({ auditId: 'p2', score: 0.63, previousScore: 0.58 });+ // Issues are counted for the latest completed audit of each row only.+ expect(signalQueries).toEqual([['p2', 'x1']]);+ });++ it('pages over pages, not audits', async () => {+ const res = await fetch(`${baseUrl}/pages?brandId=b1&limit=1&offset=1`);+ const body = await res.json();+ expect(body.total).toBe(3);+ expect(body.pages.map((p) => p.host)).toEqual(['other.com']);+ });++ it('reads past the first 1000 audits', async () => {+ audits = Array.from({ length: 1200 }, (_, i) =>+ audit(`a${i}`, `https://acme.com/p${i % 600}`, 1, '0.5'),+ );+ const body = await (await fetch(`${baseUrl}/pages?brandId=b1&limit=1`)).json();+ expect(body.total).toBe(600);+ expect(body.pages[0].runCount).toBe(2);+ });++ it('counts issues in chunks that stay under the 1000-row page', async () => {+ audits = Array.from({ length: 45 }, (_, i) =>+ audit(`a${i}`, `https://acme.com/p${i}`, 1, '0.5'),+ );+ await fetch(`${baseUrl}/pages?brandId=b1&limit=45`);+ expect(signalQueries.map((ids) => ids.length)).toEqual([20, 20, 5]);+ });++ it('needs a brand', async () => {+ const res = await fetch(`${baseUrl}/pages`);+ expect(res.status).toBe(400);+ });+});diff --git a/server/src/routes/audits.js b/server/src/routes/audits.jsindex bf649e7ec..4298e352b 100644--- a/server/src/routes/audits.js+++ b/server/src/routes/audits.js@@ -24,7 +24,13 @@ import {} from '../lib/plan-guard.js';import { buildAuditContext } from '../lib/audit/context.js';import { normStoredDomain } from '../lib/audit/host.js';-import { buildTrendPoints, parseListPage, TREND_LIMIT } from '../lib/audit/history.js';+import {+ buildAuditPages,+ buildTrendPoints,+ parseListPage,+ TREND_LIMIT,+} from '../lib/audit/history.js';+import { readAllRpcRows } from '../lib/rpc-pages.js';import { runSignals } from '../lib/audit/engine.js';import { evaluateLlmSignals } from '../lib/audit/llm-signals.js';import { evaluateBrandEntity } from '../lib/audit/external-signals.js';@@ -74,6 +80,43 @@ function assembleAudit(audit, signalRows) {};}+/** The brand's primary domain as stored (else its first domain), or null. */+async function primaryDomainOf(brandId) {+ const { data: domainRows } = await supabaseAdmin+ .from('brand_domains')+ .select('domain, is_primary')+ .eq('brand_id', brandId);+ return (+ (domainRows ?? []).find((d) => d.is_primary)?.domain ?? (domainRows ?? [])[0]?.domain ?? null+ );+}++// 20 audits × 47 signals stays under PostgREST's 1000-row page.+const ISSUE_COUNT_CHUNK = 20;++/** Failed and warning signals per audit id. */+async function countIssues(auditIds) {+ const counts = new Map();+ const chunks = [];+ for (let i = 0; i < auditIds.length; i += ISSUE_COUNT_CHUNK) {+ chunks.push(auditIds.slice(i, i + ISSUE_COUNT_CHUNK));+ }+ const results = await Promise.all(+ chunks.map((ids) =>+ supabaseAdmin+ .from('audit_signal_results')+ .select('audit_id')+ .in('audit_id', ids)+ .in('status', ['fail', 'warn']),+ ),+ );+ for (const { data, error } of results) {+ if (error) throw error;+ for (const row of data ?? []) counts.set(row.audit_id, (counts.get(row.audit_id) ?? 0) + 1);+ }+ return counts;+}+/*** Run the full audit (fetch → deterministic + LLM + Wikidata → score →* persist) for an already-created `running` row. Runs detached from the@@ -263,12 +306,7 @@ router.get('/trend', async (req, res) => {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 primary = await primaryDomainOf(brandId);const primaryHost = normStoredDomain(primary);const { data: rows } = await supabaseAdmin@@ -291,6 +329,58 @@ router.get('/trend', async (req, res) => {}});+// GET /api/audits/pages?brandId=…&limit=50&offset=0 — one row per audited+// page (repeat audits of a URL share it), most recently audited first, with+// its latest score, the previous one, a status, its trend, its open issues+// and its runs. `total` is the number of pages, for paging.+// Registered before /:id so "pages" isn't matched as an audit id.+router.get('/pages', 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' });+ }++ try {+ await assertBrandAccess(brandId, userId);++ const [primary, { data: rows, error }] = await Promise.all([+ primaryDomainOf(brandId),+ readAllRpcRows('site_audits', (from, to) =>+ supabaseAdmin+ .from('site_audits')+ .select('id, url, final_url, status, total_score, created_at')+ .eq('brand_id', brandId)+ .order('created_at', { ascending: false })+ .order('id', { ascending: false })+ .range(from, to),+ ),+ ]);+ if (error) throw error;++ const all = buildAuditPages(rows);+ const pages = all.slice(offset, offset + limit);+ const issues = await countIssues(pages.filter((p) => p.score !== null).map((p) => p.auditId));++ return res.json({+ success: true,+ pages: pages.map((p) => ({+ ...p,+ issues: p.score === null ? null : (issues.get(p.auditId) ?? 0),+ })),+ total: all.length,+ primaryHost: normStoredDomain(primary),+ });+ } catch (err) {+ if (err.status) {+ return res.status(err.status).json({ success: false, message: err.message });+ }+ req.log.error({ err }, 'audit pages failed');+ return res.status(500).json({ success: false, message: err.message });+ }+});+// GET /api/audits/:id — fetch one stored audit with its signalsrouter.get('/:id', async (req, res) => {const userId = req.user?.id;diff --git a/web/messages/en.json b/web/messages/en.jsonindex ec6ff5abb..925ef758a 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2080,7 +2080,26 @@"description": "Score any page against the 47-signal AEO/GEO","runAudit": "Run Audit","running": "Auditing…",- "recent": "Recent Audits",+ "pages": {+ "title": "Pages",+ "page": "Page",+ "score": "Score",+ "issues": "Issues",+ "status": "Status",+ "lastAudit": "Last audit",+ "trend": "Score trend: {scores}",+ "showHistory": "Show earlier audits of {page}",+ "hideHistory": "Hide earlier audits of {page}",+ "viewReport": "View report",+ "moreRuns": "{count, plural, one {# older audit} other {# older audits}} not shown",+ "statuses": {+ "good": "Good",+ "improving": "Improving",+ "needs_work": "Needs work",+ "running": "Running",+ "failed": "Failed"+ }+ },"loadMore": "Load more","retry": "Retry","deleteAudit": "Delete audit",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.test.tsxnew file mode 100644index 000000000..8384786cc--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.test.tsx@@ -0,0 +1,206 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { AuditedPage } from '@/lib/actions/audits';+import { AuditPagesTable, pageLabel } from './_pages-table';++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const push = vi.fn();+vi.mock('@/i18n/navigation', () => ({+ Link: ({ children, ...props }: React.ComponentProps<'a'>) => <a {...props}>{children}</a>,+ useRouter: () => ({ push }),+}));++// Midday UTC, so the dates read the same in any timezone.+const at = (day: number) => `2026-10-${String(day).padStart(2, '0')}T12:00:00.000Z`;++const page = (over: Partial<AuditedPage> = {}): AuditedPage => ({+ key: 'acme.com/pricing',+ host: 'acme.com',+ path: '/pricing',+ url: 'https://acme.com/pricing',+ auditId: 'a3',+ score: 0.63,+ previousScore: 0.58,+ status: 'improving',+ lastAuditedAt: at(14),+ trend: [0.5, 0.58, 0.63],+ issues: 14,+ runs: [+ {+ id: 'a3',+ url: 'https://acme.com/pricing',+ status: 'completed',+ totalScore: 0.63,+ createdAt: at(14),+ },+ {+ id: 'a2',+ url: 'https://acme.com/pricing',+ status: 'failed',+ totalScore: null,+ createdAt: at(10),+ },+ {+ id: 'a1',+ url: 'https://acme.com/pricing',+ status: 'completed',+ totalScore: 0.58,+ createdAt: at(1),+ },+ ],+ runCount: 3,+ ...over,+});++let container: HTMLDivElement;+let root: Root;+const onLoadMore = vi.fn();+const onDeleteRun = vi.fn();++function render(pages: AuditedPage[], total = pages.length) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <AuditPagesTable+ pages={pages}+ total={total}+ primaryHost="acme.com"+ loadingMore={false}+ onLoadMore={onLoadMore}+ onDeleteRun={onDeleteRun}+ />+ </NextIntlClientProvider>,+ );+ });+}++const rows = () => [...container.querySelectorAll('tbody > tr')];+const cells = (row: Element) => [...row.querySelectorAll('td')].map((td) => td.textContent?.trim());+const button = (text: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent?.trim() === text)!;++beforeEach(() => {+ vi.clearAllMocks();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('AuditPagesTable', () => {+ it('shows one row per page with its score, issues, status and last audit', () => {+ render([+ page(),+ page({+ key: 'acme.com/blog',+ path: '/blog',+ auditId: 'b1',+ score: 0.74,+ status: 'good',+ issues: 7,+ lastAuditedAt: at(2),+ trend: [0.74],+ }),+ ]);++ expect(container.querySelector('[data-slot=card-title]')?.textContent).toBe('Pages');+ expect(rows().map(cells)).toEqual([+ ['', '/pricing', '63', '14', 'Improving', 'Oct 14, 2026'],+ ['', '/blog', '74', '7', 'Good', 'Oct 2, 2026'],+ ]);+ // A trend needs two scores to draw.+ const lines = container.querySelectorAll('svg[role=img]');+ expect(lines).toHaveLength(1);+ expect(lines[0].getAttribute('aria-label')).toBe('Score trend: 50, 58, 63');+ });++ it('opens the latest report from the row, and the earlier audits from the arrow', () => {+ render([page()]);++ act(() => (rows()[0] as HTMLElement).click());+ expect(push).toHaveBeenCalledWith('/dashboard/audit/a3');+ expect(container.querySelector('a')?.getAttribute('href')).toBe('/dashboard/audit/a3');++ push.mockClear();+ const arrow = container.querySelector('button[aria-expanded]') as HTMLButtonElement;+ expect(arrow.getAttribute('aria-label')).toBe('Show earlier audits of /pricing');+ act(() => arrow.click());+ expect(push).not.toHaveBeenCalled();+ expect(arrow.getAttribute('aria-expanded')).toBe('true');++ const history = document.getElementById(arrow.getAttribute('aria-controls')!)!;+ const runs = [...history.querySelectorAll('li')];+ expect(runs.map((li) => li.querySelectorAll('span')[1].textContent)).toEqual([+ '63',+ 'Failed',+ '58',+ ]);+ expect(runs[0].textContent).toContain('Oct 14, 2026');+ expect(runs.map((li) => li.querySelector('a')?.getAttribute('href'))).toEqual([+ '/dashboard/audit/a3',+ '/dashboard/audit/a2',+ '/dashboard/audit/a1',+ ]);++ act(() => arrow.click());+ expect(document.getElementById(arrow.getAttribute('aria-controls')!)).toBeNull();+ });++ it('says how many older audits the history leaves out', () => {+ render([page({ runCount: 53 })]);+ act(() => (container.querySelector('button[aria-expanded]') as HTMLButtonElement).click());+ expect(container.textContent).toContain('50 older audits not shown');+ });++ it('shows a page that never completed, and one being re-audited', () => {+ render([+ page({+ key: 'acme.com/broken',+ path: '/broken',+ score: null,+ previousScore: null,+ status: 'failed',+ issues: null,+ trend: [],+ }),+ page({ status: 'running' }),+ ]);++ expect(rows().map(cells)).toEqual([+ ['', '/broken', '—', '—', 'Failed', 'Oct 14, 2026'],+ ['', '/pricing', '63', '14', 'Running', 'Oct 14, 2026'],+ ]);+ expect(rows()[1].querySelector('.animate-spin')).not.toBeNull();+ });++ it('loads more pages while some are left', () => {+ render([page()], 2);+ act(() => button('Load more').click());+ expect(onLoadMore).toHaveBeenCalledOnce();++ render([page()], 1);+ expect(button('Load more')).toBeUndefined();+ });+});++describe('pageLabel', () => {+ it("lists the brand's own pages by path and other sites by host", () => {+ expect(pageLabel({ host: 'acme.com', path: '/pricing' }, 'acme.com')).toBe('/pricing');+ expect(pageLabel({ host: 'acme.com', path: '/' }, 'acme.com')).toBe('/');+ expect(pageLabel({ host: 'other.com', path: '/' }, 'acme.com')).toBe('other.com');+ expect(pageLabel({ host: 'other.com', path: '/blog' }, 'acme.com')).toBe('other.com/blog');+ expect(pageLabel({ host: 'acme.com', path: '/blog' }, null)).toBe('acme.com/blog');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsxnew file mode 100644index 000000000..698eab5db--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx@@ -0,0 +1,292 @@+'use client';++import { Fragment, useId, useState } from 'react';+import { useTranslations } from 'next-intl';+import { ChevronRight, Loader2, Trash2 } from 'lucide-react';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@/components/ui/dialog';+import { Link, useRouter } from '@/i18n/navigation';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Button } from '@/components/ui/button';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { pct, scoreColor } from '@/components/audit/audit-report';+import type { AuditedPage, AuditedPageStatus, AuditRun } from '@/lib/actions/audits';+import { formatDate, formatDateTime, formatNumber } from '@/lib/format';+import { cn } from '@/lib/utils';++const STATUS_CLASS: Record<AuditedPageStatus, string> = {+ good: 'bg-green-600/10 text-green-700 dark:bg-green-500/15 dark:text-green-400',+ needs_work: 'bg-amber-500/10 text-amber-700 dark:bg-amber-500/15 dark:text-amber-400',+ improving: 'bg-muted text-muted-foreground',+ running: 'bg-muted text-muted-foreground',+ failed: 'bg-destructive/10 text-destructive',+};++/** A page's label: its path on the brand's primary host, else host and path. */+export function pageLabel(page: Pick<AuditedPage, 'host' | 'path'>, primaryHost: string | null) {+ if (!page.host || page.host === primaryHost) return page.path;+ return page.path === '/' ? page.host : `${page.host}${page.path}`;+}++/** A small line of a page's latest scores (0–1), oldest first. */+export function ScoreSparkline({ points, label }: { points: number[]; label: string }) {+ if (points.length < 2) return null;+ const width = 48;+ const height = 16;+ const min = Math.min(...points);+ const max = Math.max(...points);+ const y = (p: number) =>+ max === min ? height / 2 : height - 1 - ((p - min) / (max - min)) * (height - 2);+ const coords = points+ .map((p, i) => `${((i / (points.length - 1)) * width).toFixed(1)},${y(p).toFixed(1)}`)+ .join(' ');+ return (+ <svg+ viewBox={`0 0 ${width} ${height}`}+ width={width}+ height={height}+ role="img"+ aria-label={label}+ className="shrink-0 text-muted-foreground"+ >+ <polyline+ points={coords}+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ );+}++function StatusPill({ status }: { status: AuditedPageStatus }) {+ const t = useTranslations('audit.pages');+ return (+ <span+ className={cn(+ 'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium',+ STATUS_CLASS[status],+ )}+ >+ {status === 'running' && <Loader2 className="h-3 w-3 animate-spin" />}+ {t(`statuses.${status}`)}+ </span>+ );+}++function HistoryRun({ run, onDelete }: { run: AuditRun; onDelete: (id: string) => void }) {+ const t = useTranslations('audit');+ return (+ <li className="flex items-center gap-3 px-3 py-1.5 text-sm">+ <span className="w-48 shrink-0 text-muted-foreground">{formatDateTime(run.createdAt)}</span>+ <span+ className={cn(+ 'w-20 shrink-0 font-semibold tabular-nums',+ run.status === 'completed' ? scoreColor(run.totalScore) : 'text-muted-foreground',+ )}+ >+ {run.status === 'completed' ? (pct(run.totalScore) ?? '—') : t(`status.${run.status}`)}+ </span>+ <Link href={`/dashboard/audit/${run.id}`} className="text-primary hover:underline">+ {t('pages.viewReport')}+ </Link>+ <Dialog>+ <DialogTrigger+ render={+ <Button+ variant="ghost"+ size="icon"+ className="ml-auto h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive"+ aria-label={t('deleteAudit')}+ />+ }+ >+ <Trash2 className="h-3.5 w-3.5" />+ </DialogTrigger>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>{t('deleteAudit')}</DialogTitle>+ <DialogDescription>{t('deleteConfirm')}</DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>{t('cancel')}</DialogClose>+ <DialogClose render={<Button variant="destructive" onClick={() => onDelete(run.id)} />}>+ {t('deleteAudit')}+ </DialogClose>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </li>+ );+}++/**+ * The audited pages, one row per page: the row opens its latest report and+ * the arrow lists its earlier audits underneath.+ */+export function AuditPagesTable({+ pages,+ total,+ primaryHost,+ loadingMore,+ onLoadMore,+ onDeleteRun,+}: {+ pages: AuditedPage[];+ total: number;+ primaryHost: string | null;+ loadingMore: boolean;+ onLoadMore: () => void;+ onDeleteRun: (id: string) => void;+}) {+ const t = useTranslations('audit');+ const router = useRouter();+ const idPrefix = useId();+ const [open, setOpen] = useState<Set<string>>(() => new Set());++ const toggle = (key: string) =>+ setOpen((prev) => {+ const next = new Set(prev);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ return next;+ });++ return (+ <Card>+ <CardHeader className="flex flex-row items-center gap-2 space-y-0">+ <CardTitle className="text-base">{t('pages.title')}</CardTitle>+ <span className="rounded-full bg-muted px-2 py-0.5 text-xs font-medium tabular-nums text-muted-foreground">+ {formatNumber(total)}+ </span>+ </CardHeader>+ <CardContent className="pt-0">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-9" />+ {/* The page column takes the room left, and long URLs truncate in it. */}+ <TableHead className="w-full">{t('pages.page')}</TableHead>+ <TableHead>{t('pages.score')}</TableHead>+ <TableHead className="text-right">{t('pages.issues')}</TableHead>+ <TableHead>{t('pages.status')}</TableHead>+ <TableHead>{t('pages.lastAudit')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {pages.map((page, i) => {+ const label = pageLabel(page, primaryHost);+ const historyId = `${idPrefix}-history-${i}`;+ const expanded = open.has(page.key);+ return (+ <Fragment key={page.key}>+ <TableRow+ className="cursor-pointer"+ onClick={() => router.push(`/dashboard/audit/${page.auditId}`)}+ >+ <TableCell className="w-9 pr-0">+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ aria-expanded={expanded}+ aria-controls={historyId}+ aria-label={t(expanded ? 'pages.hideHistory' : 'pages.showHistory', {+ page: label,+ })}+ onClick={(e) => {+ e.stopPropagation();+ toggle(page.key);+ }}+ >+ <ChevronRight+ className={cn('h-4 w-4 transition-transform', expanded && 'rotate-90')}+ />+ </Button>+ </TableCell>+ <TableCell className="max-w-0">+ <Link+ href={`/dashboard/audit/${page.auditId}`}+ onClick={(e) => e.stopPropagation()}+ title={page.url}+ className="block truncate font-medium hover:underline"+ >+ {label}+ </Link>+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-2">+ <span+ className={cn('w-7 font-semibold tabular-nums', scoreColor(page.score))}+ >+ {pct(page.score) ?? '—'}+ </span>+ <ScoreSparkline+ points={page.trend}+ label={t('pages.trend', {+ scores: page.trend.map((s) => pct(s)).join(', '),+ })}+ />+ </div>+ </TableCell>+ <TableCell className="text-right tabular-nums">+ {page.issues === null ? '—' : formatNumber(page.issues)}+ </TableCell>+ <TableCell>+ <StatusPill status={page.status} />+ </TableCell>+ <TableCell className="text-muted-foreground">+ {formatDate(page.lastAuditedAt)}+ </TableCell>+ </TableRow>+ {expanded && (+ <TableRow id={historyId} className="hover:bg-transparent">+ <TableCell />+ <TableCell colSpan={5} className="pt-0 whitespace-normal">+ <ul className="divide-y rounded-md border">+ {page.runs.map((run) => (+ <HistoryRun key={run.id} run={run} onDelete={onDeleteRun} />+ ))}+ </ul>+ {page.runCount > page.runs.length && (+ <p className="mt-1.5 text-xs text-muted-foreground">+ {t('pages.moreRuns', { count: page.runCount - page.runs.length })}+ </p>+ )}+ </TableCell>+ </TableRow>+ )}+ </Fragment>+ );+ })}+ </TableBody>+ </Table>+ {pages.length < total && (+ <div className="flex justify-center pt-3">+ <Button variant="outline" size="sm" onClick={onLoadMore} disabled={loadingMore}>+ {loadingMore && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}+ {t('loadMore')}+ </Button>+ </div>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsxindex 7be4bd585..b7fc95a27 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx@@ -6,24 +6,13 @@ import { toast } from 'sonner';import {Search,Loader2,- Trash2,Sparkles,TrendingUp,TrendingDown,AlertCircle,RefreshCw,} from 'lucide-react';-import {- Dialog,- DialogClose,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from '@/components/ui/dialog';-import { Link, useRouter } from '@/i18n/navigation';+import { useRouter } from '@/i18n/navigation';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';@@ -31,16 +20,18 @@ import { Skeleton } from '@/components/ui/skeleton';import { useBrandStore } from '@/stores/use-brand-store';import {runAudit,- getAudits,+ getAuditPages,getAuditQuota,getAuditTrend,deleteAudit,- type AuditSummary,+ type AuditedPage,type AuditQuota,type AuditTrend,} from '@/lib/actions/audits';import { pct, scoreColor, CATEGORY_META } from '@/components/audit/audit-report';+import { formatMonthDay } from '@/lib/format';import { ScoreTrendChart } from './_charts';+import { AuditPagesTable } from './_pages-table';import { cn } from '@/lib/utils';type RangePreset = '7d' | '30d' | '90d' | 'all';@@ -69,8 +60,9 @@ export default function SiteAuditPage() {const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);const [refreshKey, setRefreshKey] = useState(0);- const [history, setHistory] = useState<AuditSummary[]>([]);- const [historyTotal, setHistoryTotal] = useState(0);+ const [pages, setPages] = useState<AuditedPage[]>([]);+ const [pagesTotal, setPagesTotal] = useState(0);+ const [primaryHost, setPrimaryHost] = useState<string | null>(null);const [loadingMore, setLoadingMore] = useState(false);const [quota, setQuota] = useState<AuditQuota | null>(null);const [trend, setTrend] = useState<AuditTrend | null>(null);@@ -80,7 +72,7 @@ export default function SiteAuditPage() {const refetch = () => setRefreshKey((k: number) => k + 1);- // Load recent audits + the monthly quota + the primary-domain trend.+ // Load the audited pages + the monthly quota + the primary-domain trend.useEffect(() => {if (!activeBrandId) return;let cancelled = false;@@ -89,13 +81,14 @@ export default function SiteAuditPage() {(async () => {try {const [data, q, tr] = await Promise.all([- getAudits(activeBrandId),+ getAuditPages(activeBrandId),getAuditQuota(),getAuditTrend(activeBrandId),]);if (!cancelled) {- setHistory(data.audits);- setHistoryTotal(data.total);+ setPages(data.pages);+ setPagesTotal(data.total);+ setPrimaryHost(data.primaryHost);setQuota(q);setTrend(tr);}@@ -149,7 +142,7 @@ export default function SiteAuditPage() {const chartData = dailyPoints.filter((p) => p.totalScore !== null).map((p) => ({- date: new Date(p.createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }),+ date: formatMonthDay(p.createdAt),score: pct(p.totalScore) ?? 0,}));@@ -181,18 +174,18 @@ 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.+ // Append the next page of the Pages list. Dedupe by page: a page audited+ // since the first read moves to the top and 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))];+ const next = await getAuditPages(activeBrandId, pages.length);+ setPages((current) => {+ const seen = new Set(current.map((p) => p.key));+ return [...current, ...next.pages.filter((p) => !seen.has(p.key))];});- setHistoryTotal(next.total);+ setPagesTotal(next.total);} catch (err) {toast.error(err instanceof Error ? err.message : t('failed'));} finally {@@ -200,14 +193,22 @@ export default function SiteAuditPage() {}};+ // Deleting a run can change its page's score, status or trend, or remove+ // the page, so the pages shown and the trend are read again, in place: the+ // table stays up with its open histories.const handleDelete = async (id: string) => {- const prev = history;- setHistory((h) => h.filter((a) => a.id !== id));+ if (!activeBrandId) return;try {await deleteAudit(id);- refetch();+ const [data, tr] = await Promise.all([+ getAuditPages(activeBrandId, 0, Math.min(Math.max(pages.length, 50), 100)),+ getAuditTrend(activeBrandId),+ ]);+ setPages(data.pages);+ setPagesTotal(data.total);+ setPrimaryHost(data.primaryHost);+ setTrend(tr);} catch (err) {- setHistory(prev);toast.error(err instanceof Error ? err.message : t('failed'));}};@@ -399,7 +400,7 @@ export default function SiteAuditPage() {</Button></CardContent></Card>- ) : history.length === 0 ? (+ ) : pages.length === 0 ? (<Card><CardContent className="flex flex-col items-center gap-2 py-12 text-center"><Sparkles className="h-7 w-7 text-primary" />@@ -408,75 +409,14 @@ export default function SiteAuditPage() {</CardContent></Card>) : (- <Card>- <CardHeader>- <CardTitle className="text-base">{t('recent')}</CardTitle>- </CardHeader>- <CardContent className="pt-0">- {history.map((h) => (- <div- key={h.id}- className="flex items-center gap-3 border-b py-1 last:border-b-0 hover:bg-muted/40"- >- <Link- href={`/dashboard/audit/${h.id}`}- className="flex flex-1 items-center gap-3 py-2 text-left"- >- <span className="flex-1 truncate text-sm">{h.url}</span>- <span className="text-xs text-muted-foreground">- {new Date(h.created_at).toLocaleDateString()}- </span>- <span- className={cn(- 'w-12 text-right text-sm font-semibold tabular-nums',- scoreColor(h.total_score),- )}- >- {h.status === 'completed'- ? (pct(h.total_score) ?? '—')- : t(`status.${h.status}`)}- </span>- </Link>- <Dialog>- <DialogTrigger- render={- <Button- variant="ghost"- size="icon"- className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"- aria-label={t('deleteAudit')}- />- }- >- <Trash2 className="h-3.5 w-3.5" />- </DialogTrigger>- <DialogContent className="sm:max-w-sm">- <DialogHeader>- <DialogTitle>{t('deleteAudit')}</DialogTitle>- <DialogDescription>{t('deleteConfirm')}</DialogDescription>- </DialogHeader>- <DialogFooter>- <DialogClose render={<Button variant="outline" />}>{t('cancel')}</DialogClose>- <DialogClose- render={<Button variant="destructive" onClick={() => handleDelete(h.id)} />}- >- {t('deleteAudit')}- </DialogClose>- </DialogFooter>- </DialogContent>- </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>+ <AuditPagesTable+ pages={pages}+ total={pagesTotal}+ primaryHost={primaryHost}+ loadingMore={loadingMore}+ onLoadMore={handleLoadMore}+ onDeleteRun={handleDelete}+ />)}</div>);diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.tsindex 864e56a2c..f84fdc687 100644--- a/web/src/lib/actions/audits.ts+++ b/web/src/lib/actions/audits.ts@@ -73,14 +73,36 @@ export interface AuditTrend {points: AuditTrendPoint[];}-export interface AuditSummary {+/** One audit run of a page, in its history. */+export interface AuditRun {id: string;url: string;status: 'running' | 'completed' | 'failed';- total_score: number | null;- signals_evaluated: number | null;- signals_total: number;- created_at: string;+ totalScore: number | null;+ createdAt: string;+}++export type AuditedPageStatus = 'good' | 'improving' | 'needs_work' | 'running' | 'failed';++/** One audited page: its repeat audits share the row. */+export interface AuditedPage {+ key: string;+ host: string | null;+ path: string;+ url: string;+ /** The latest completed audit (else the latest run), which the row opens. */+ auditId: string;+ score: number | null;+ previousScore: number | null;+ status: AuditedPageStatus;+ lastAuditedAt: string;+ /** Latest completed scores, oldest first. */+ trend: number[];+ /** Failed and warning signals in the latest completed audit. */+ issues: number | null;+ /** Runs, newest first. */+ runs: AuditRun[];+ runCount: number;}async function getSession() {@@ -183,14 +205,20 @@ export async function getAuditTrend(brandId: string): Promise<AuditTrend> {return { primaryDomain: data.primaryDomain ?? null, points: data.points ?? [] };}-export interface AuditPage {- audits: AuditSummary[];- /** Total audits for the brand, across all pages. */+export interface AuditedPages {+ pages: AuditedPage[];+ /** Pages audited for the brand, across all pages of the list. */total: number;+ /** The brand's primary host, whose pages are listed by path alone. */+ primaryHost: string | null;}-/** 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> {+/** List a page of the brand's audited pages, most recently audited first. */+export async function getAuditPages(+ brandId: string,+ offset = 0,+ limit = 50,+): Promise<AuditedPages> {const session = await getSession();const params = new URLSearchParams({@@ -198,7 +226,7 @@ export async function getAudits(brandId: string, offset = 0, limit = 50): Promislimit: String(limit),offset: String(offset),});- const res = await fetch(`${AEO_SERVER_URL}/api/audits?${params}`, {+ const res = await fetch(`${AEO_SERVER_URL}/api/audits/pages?${params}`, {headers: { Authorization: `Bearer ${session.access_token}` },});@@ -208,6 +236,6 @@ export async function getAudits(brandId: string, offset = 0, limit = 50): Promis}const data = await res.json();- const audits: AuditSummary[] = data.audits ?? [];- return { audits, total: data.total ?? audits.length };+ const pages: AuditedPage[] = data.pages ?? [];+ return { pages, total: data.total ?? pages.length, primaryHost: data.primaryHost ?? null };}diff --git a/web/src/lib/format.test.ts b/web/src/lib/format.test.tsindex 51c36752a..bd0fb1615 100644--- a/web/src/lib/format.test.ts+++ b/web/src/lib/format.test.ts@@ -7,7 +7,13 @@*/import { afterEach, beforeEach, expect, test, vi } from 'vitest';-import { formatCompactNumber, formatNumber } from './format.js';+import {+ formatCompactNumber,+ formatDate,+ formatDateTime,+ formatMonthDay,+ formatNumber,+} from './format.js';const toLocaleString = Number.prototype.toLocaleString;@@ -46,3 +52,29 @@ test('formatCompactNumber abbreviates from 1,000 up', () => {expect(formatCompactNumber(2_500_000)).toBe('2.5M');expect(formatCompactNumber(3_000_000_000)).toBe('3B');});++test('dates read in English whatever the browser locale is', () => {+ const toLocaleDateString = Date.prototype.toLocaleDateString;+ const toLocaleStringDate = Date.prototype.toLocaleString;+ vi.spyOn(Date.prototype, 'toLocaleDateString').mockImplementation(function (+ this: Date,+ locales?: Intl.LocalesArgument,+ options?: Intl.DateTimeFormatOptions,+ ) {+ return toLocaleDateString.call(this, locales ?? 'tr-TR', options);+ });+ vi.spyOn(Date.prototype, 'toLocaleString').mockImplementation(function (+ this: Date,+ locales?: Intl.LocalesArgument,+ options?: Intl.DateTimeFormatOptions,+ ) {+ return toLocaleStringDate.call(this, locales ?? 'tr-TR', options);+ });+ // Midday UTC, so the day is the same in any timezone the tests run in.+ const iso = '2026-10-17T11:05:00.000Z';++ expect(new Date(iso).toLocaleDateString()).toBe('17.10.2026');+ expect(formatMonthDay(iso)).toBe('Oct 17');+ expect(formatDate(iso)).toBe('Oct 17, 2026');+ expect(formatDateTime(iso)).toMatch(/^Oct 17, 2026, \d{1,2}:05\s(AM|PM)$/);+});diff --git a/web/src/lib/format.ts b/web/src/lib/format.tsindex 6e0dcb80b..f657e9376 100644--- a/web/src/lib/format.ts+++ b/web/src/lib/format.ts@@ -30,3 +30,19 @@ export function formatDate(iso: string | null): string {day: 'numeric',});}++/** "Oct 17": a short day label, e.g. for a chart axis. */+export function formatMonthDay(iso: string): string {+ return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });+}++/** "Oct 17, 2026, 2:05 PM": a date with its time, for runs on the same day. */+export function formatDateTime(iso: string): string {+ return new Date(iso).toLocaleString('en-US', {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ hour: 'numeric',+ minute: '2-digit',+ });+}