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): re-audit selected pages within the quota and export the Pages list (#1134)
Cihan218163d29095
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex 5702ccf53..8706dc63d 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -267,7 +267,7 @@ intent, not during exploratory queries.| Tool | What it does | Writes || --- | --- | --- |-| `get_site_audit_quota` | Monthly Site Audit allowance (`used`, `limit`, `remaining`) before starting a run. | |+| `get_site_audit_quota` | Monthly Site Audit allowance (`used`, `running`, `limit`, `remaining`) before starting a run. Audits still running are already taken out of `remaining`. | || `list_site_audits` | Recent audits for a brand (id, url, status, score) to find a past run without the id. | || `run_site_audit` | Start an AEO/GEO page audit for a URL (consumes a monthly credit; poll `get_site_audit` for results). | **yes** || `get_site_audit` | Fetch one audit by id — status, scores, signals, and fix recommendations (read-only). | |diff --git a/server/src/lib/audit/history.js b/server/src/lib/audit/history.jsindex 1ab4ca43c..03cf2fbf9 100644--- a/server/src/lib/audit/history.js+++ b/server/src/lib/audit/history.js@@ -76,6 +76,14 @@ export function pageKey(url) {}}+/**+ * How long a run may stay `running`. An audit takes a minute or two and a+ * queued bulk run waits longer; one older than this was cut short by a+ * restart (the bulk queue lives in memory) and will never complete, so it+ * reads as failed and stops holding a quota slot (plan-guard.js).+ */+export const AUDIT_RUN_TIMEOUT_MS = 2 * 60 * 60 * 1000;+const points = (score) => Math.round(score * 100);/**@@ -96,9 +104,10 @@ export function pageStatus(latestRun, current, previous) {* 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.+ * trend and its runs. A run still `running` past AUDIT_RUN_TIMEOUT_MS reads as+ * failed, so the page isn't left Running (and the hub polling) for good.*/-export function buildAuditPages(rowsNewestFirst) {+export function buildAuditPages(rowsNewestFirst, now = Date.now()) {const groups = new Map();// Rows read in slices can repeat one at a slice boundary.const seen = new Set();@@ -111,7 +120,10 @@ export function buildAuditPages(rowsNewestFirst) {groups.get(page.key).runs.push({id: r.id,url,- status: r.status,+ status:+ r.status === 'running' && now - Date.parse(r.created_at) > AUDIT_RUN_TIMEOUT_MS+ ? 'failed'+ : r.status,totalScore: r.total_score === null ? null : Number(r.total_score),createdAt: r.created_at,});diff --git a/server/src/lib/audit/history.test.js b/server/src/lib/audit/history.test.jsindex 668b5c82b..04a34ebf7 100644--- a/server/src/lib/audit/history.test.js+++ b/server/src/lib/audit/history.test.js@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import {+ AUDIT_RUN_TIMEOUT_MS,buildAuditPages,buildTrendPoints,pageKey,@@ -177,11 +178,14 @@ describe('buildAuditPages', () => {});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'),- ]);+ 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'),+ ],+ Date.parse('2026-10-15T09:05:00Z'),+ );expect(running).toMatchObject({status: 'running',score: 0.58,@@ -196,6 +200,21 @@ describe('buildAuditPages', () => {expect(failed).toMatchObject({ status: 'failed', score: null, auditId: 'b1', trend: [] });});+ it('reads a run left running past the timeout, cut short by a restart, as failed', () => {+ const rows = [+ row('a2', 'https://acme.com/pricing', '2026-10-15T09:00:00Z', null, 'running'),+ row('a1', 'https://acme.com/pricing', '2026-10-01T09:00:00Z', '0.58'),+ ];+ const start = Date.parse('2026-10-15T09:00:00Z');++ const [stillRunning] = buildAuditPages(rows, start + AUDIT_RUN_TIMEOUT_MS);+ expect(stillRunning.status).toBe('running');++ const [cutShort] = buildAuditPages(rows, start + AUDIT_RUN_TIMEOUT_MS + 1);+ expect(cutShort).toMatchObject({ status: 'needs_work', score: 0.58, auditId: 'a1' });+ expect(cutShort.runs[0]).toMatchObject({ id: 'a2', status: 'failed' });+ });+it('draws the trend from the newest completed scores, oldest first', () => {const rows = Array.from({ length: PAGE_TREND_POINTS + 3 }, (_, i) =>row(diff --git a/server/src/lib/plan-guard-site-audit.test.js b/server/src/lib/plan-guard-site-audit.test.jsnew file mode 100644index 000000000..5d3bfa249--- /dev/null+++ b/server/src/lib/plan-guard-site-audit.test.js@@ -0,0 +1,114 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The Site Audit quota counts audits still running as well as completed+ * ones (completed audits are charged when they finish), and a bulk start is+ * checked for every page it asks for at once.+ */++let used;+let running;+let runningQuery;++function query(table) {+ const filters = [];+ const builder = {+ select: () => builder,+ eq: (col, val) => {+ filters.push(['eq', col, val]);+ return builder;+ },+ gte: (col, val) => {+ filters.push(['gte', col, val]);+ return builder;+ },+ single: () => builder,+ maybeSingle: () => builder,+ then: (resolve) => {+ if (table === 'organizations') {+ return resolve({ data: { plan: 'starter', subscription_status: 'active' }, error: null });+ }+ if (table === 'site_audit_usage') return resolve({ count: used, error: null });+ if (table === 'site_audits') {+ runningQuery = filters;+ return resolve({ count: running, error: null });+ }+ return resolve({ data: null, error: null });+ },+ };+ return builder;+}++let quota;++beforeEach(async () => {+ vi.resetModules();+ process.env.IS_CLOUD = 'true';+ vi.doMock('../config/supabase.js', () => ({ default: { from: (t) => query(t) } }));+ quota = await import('./plan-guard.js');+});++afterEach(() => {+ delete process.env.IS_CLOUD;+ vi.doUnmock('../config/supabase.js');+});++describe('Site Audit quota', () => {+ it("takes running audits out of what's left", async () => {+ used = 90;+ running = 4;+ expect(await quota.getSiteAuditQuotaStatus('org-1')).toEqual({+ used: 90,+ running: 4,+ limit: 100,+ remaining: 6,+ });+ // Running audits of the org's brands, started in the last two hours.+ expect(runningQuery).toEqual(+ expect.arrayContaining([+ ['eq', 'status', 'running'],+ ['eq', 'brands.organization_id', 'org-1'],+ ['gte', 'created_at', expect.any(String)],+ ]),+ );+ });++ it('starts a bulk run only when every page fits', async () => {+ used = 90;+ running = 4;+ await expect(quota.enforceSiteAuditQuota('org-1', 6)).resolves.toMatchObject({ remaining: 6 });+ await expect(quota.enforceSiteAuditQuota('org-1', 7)).rejects.toThrow(+ 'These 7 audits need more than the 6 left this month on the Starter plan. Select up to 6.',+ );+ });++ it('refuses one more audit when completed and running ones fill the quota', async () => {+ used = 97;+ running = 3;+ await expect(quota.enforceSiteAuditQuota('org-1')).rejects.toMatchObject({+ statusCode: 429,+ message: expect.stringContaining('(100/100, 3 still running)'),+ });++ used = 100;+ running = 0;+ await expect(quota.enforceSiteAuditQuota('org-1')).rejects.toThrow(+ 'Monthly Site Audit limit reached (100/100) on the Starter plan.',+ );+ });++ it('never limits a self-hosted install', async () => {+ delete process.env.IS_CLOUD;+ used = 1000;+ running = 50;+ await expect(quota.enforceSiteAuditQuota('org-1', 50)).resolves.toMatchObject({+ remaining: -1,+ });+ expect(await quota.getSiteAuditQuotaStatus('org-1')).toEqual({+ used: 0,+ running: 0,+ limit: -1,+ remaining: -1,+ });+ });+});diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.jsindex ba617f925..3c915b424 100644--- a/server/src/lib/plan-guard.js+++ b/server/src/lib/plan-guard.js@@ -14,6 +14,7 @@ import {typicalCostUsd,} from './improve-cost.js';import { RELEVANCE_BUDGET_SHARE } from './suggestion-relevance.js';+import { AUDIT_RUN_TIMEOUT_MS } from './audit/history.js';export class PlanLimitError extends Error {constructor(message, statusCode = 403) {@@ -508,39 +509,75 @@ async function countSiteAuditUsageThisMonth(orgId) {return count || 0;}+// How long a running audit holds a quota slot (AUDIT_RUN_TIMEOUT_MS): one+// older than that was cut short by a restart and will never complete.+const SITE_AUDIT_IN_FLIGHT_MS = AUDIT_RUN_TIMEOUT_MS;+/**- * Enforce the monthly Site Audit quota for an organization. Counts completed- * audits this calendar month against plan.limits.maxSiteAudits (Starter 100,- * Growth 500, Enterprise/Self-hosted unlimited). Throws PlanLimitError (429)- * when exhausted; returns { plan, remaining } otherwise.+ * Audits of the org's brands still running. They're charged when they+ * complete, so each holds a slot until then: otherwise a run started while+ * others are in flight could take the quota past its limit.*/-export async function enforceSiteAuditQuota(orgId) {+async function countRunningSiteAudits(orgId) {+ const since = new Date(Date.now() - SITE_AUDIT_IN_FLIGHT_MS).toISOString();+ const { count } = await supabaseAdmin+ .from('site_audits')+ .select('id, brands!inner(organization_id)', { count: 'exact', head: true })+ .eq('status', 'running')+ .eq('brands.organization_id', orgId)+ .gte('created_at', since);+ return count || 0;+}++/**+ * Enforce the monthly Site Audit quota for an organization before starting+ * `count` audits. Counts completed audits this billing period, plus the ones+ * still running, against plan.limits.maxSiteAudits (Starter 100, Growth 500,+ * Enterprise/Self-hosted unlimited). Throws PlanLimitError (429) when the+ * audits don't fit, starting none; returns { plan, remaining } otherwise.+ */+export async function enforceSiteAuditQuota(orgId, count = 1) {const plan = await resolveOrgPlanByOrgId(orgId);const max = plan.limits.maxSiteAudits;if (max === -1) return { plan, remaining: -1 };- const used = await countSiteAuditUsageThisMonth(orgId);- if (used >= max) {+ const [used, running] = await Promise.all([+ countSiteAuditUsageThisMonth(orgId),+ countRunningSiteAudits(orgId),+ ]);+ const remaining = max - used - running;+ if (remaining <= 0) {+ const inFlight = running > 0 ? `, ${running} still running` : '';throw new PlanLimitError(- `Monthly Site Audit limit reached (${used}/${max}) on the ${plan.name} plan. Resets when your subscription renews — upgrade for more.`,+ `Monthly Site Audit limit reached (${used + running}/${max}${inFlight}) on the ${plan.name} plan. Resets when your subscription renews — upgrade for more.`,+ 429,+ );+ }+ if (count > remaining) {+ throw new PlanLimitError(+ `These ${count} audits need more than the ${remaining} left this month on the ${plan.name} plan. Select up to ${remaining}.`,429,);}- return { plan, remaining: max - used };+ return { plan, remaining };}/*** Get current Site Audit quota status without enforcing.- * Returns { used, limit, remaining }.+ * Returns { used, running, limit, remaining }; running audits are already+ * taken out of what remains.*/export async function getSiteAuditQuotaStatus(orgId) {const plan = await resolveOrgPlanByOrgId(orgId);const max = plan.limits.maxSiteAudits;- if (max === -1) return { used: 0, limit: -1, remaining: -1 };+ if (max === -1) return { used: 0, running: 0, limit: -1, remaining: -1 };- const used = await countSiteAuditUsageThisMonth(orgId);- return { used, limit: max, remaining: Math.max(0, max - used) };+ const [used, running] = await Promise.all([+ countSiteAuditUsageThisMonth(orgId),+ countRunningSiteAudits(orgId),+ ]);+ return { used, running, limit: max, remaining: Math.max(0, max - used - running) };}/**diff --git a/server/src/routes/audits-pages.test.js b/server/src/routes/audits-pages.test.jsindex 21ceb782a..033083109 100644--- a/server/src/routes/audits-pages.test.js+++ b/server/src/routes/audits-pages.test.js@@ -11,6 +11,9 @@ let audits;let signals;let domains;let signalQueries;+let inserted;+let enforce;+let pagesFetched;let server;let baseUrl;@@ -18,8 +21,14 @@ let baseUrl;function query(table) {const filters = { eq: {}, in: {} };let range = null;+ let insertRows = null;const builder = {+ insert: (rows) => {+ insertRows = rows;+ return builder;+ },select: () => builder,+ single: () => builder,order: () => builder,eq: (col, val) => {filters.eq[col] = val;@@ -35,6 +44,11 @@ function query(table) {},then: (resolve) => {let data = [];+ if (insertRows) {+ const rows = insertRows.map((r, i) => ({ id: `new-${inserted.length + i}`, ...r }));+ inserted.push(...rows);+ return resolve({ data: rows, error: null });+ }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);@@ -55,15 +69,21 @@ function query(table) {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/access.js', () => ({ assertBrandAccess: async () => ({ orgId: 'org-1' }) }));vi.doMock('../lib/plan-guard.js', () => ({requireFeature: () => (req, res, next) => next(),- enforceSiteAuditQuota: vi.fn(),+ enforceSiteAuditQuota: (...args) => enforce(...args),getSiteAuditQuotaStatus: vi.fn(),getOrgIdForUser: vi.fn(),PlanLimitError: class PlanLimitError extends Error {},}));- vi.doMock('../lib/audit/context.js', () => ({ buildAuditContext: vi.fn() }));+ // An audit job that never gets its page, so the queue's limit can be seen.+ vi.doMock('../lib/audit/context.js', () => ({+ buildAuditContext: (url) => {+ pagesFetched.push(url);+ return new Promise(() => {});+ },+ }));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() }));@@ -75,6 +95,7 @@ async function startApp() {const { default: router } = await import('./audits.js');const app = express();+ app.use(express.json());app.use((req, _res, next) => {req.user = { id: 'u1' };req.log = { error: vi.fn(), info: vi.fn() };@@ -99,6 +120,9 @@ const audit = (id, url, day, score, status = 'completed') => ({beforeEach(async () => {signalQueries = [];+ inserted = [];+ pagesFetched = [];+ enforce = vi.fn(async () => ({ remaining: 10 }));domains = [{ domain: 'https://www.Acme.com/', is_primary: true }];audits = [audit('p2', 'https://acme.com/pricing', 14, '0.63'),@@ -166,3 +190,64 @@ describe('GET /api/audits/pages', () => {expect(res.status).toBe(400);});});++describe('POST /api/audits/bulk', () => {+ const post = (body) =>+ fetch(`${baseUrl}/bulk`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ const brandId = '33333333-3333-3333-3333-333333333333';++ it('checks the quota for every page at once, then starts them, repeat spellings once', async () => {+ const res = await post({+ brandId,+ urls: ['https://acme.com/pricing', 'https://www.acme.com/pricing/', 'https://acme.com/blog'],+ });+ const body = await res.json();++ expect(res.status).toBe(202);+ expect(enforce).toHaveBeenCalledWith('org-1', 2);+ expect(inserted.map((r) => [r.url, r.status, r.brand_id])).toEqual([+ ['https://acme.com/pricing', 'running', brandId],+ ['https://acme.com/blog', 'running', brandId],+ ]);+ expect(body.audits.map((a) => a.status)).toEqual(['running', 'running']);+ });++ it('starts none when the quota refuses them', async () => {+ const { PlanLimitError } = await import('../lib/plan-guard.js');+ enforce = vi.fn(async () => {+ throw Object.assign(new PlanLimitError('These 2 audits need more than the 1 left'), {+ statusCode: 429,+ });+ });+ const res = await post({ brandId, urls: ['https://acme.com/a', 'https://acme.com/b'] });++ expect(res.status).toBe(429);+ expect((await res.json()).error).toBe('quota_exceeded');+ expect(inserted).toEqual([]);+ });++ it('runs a few at a time and keeps the rest waiting', async () => {+ const urls = Array.from({ length: 5 }, (_, i) => `https://acme.com/p${i}`);+ await post({ brandId, urls });+ await new Promise((resolve) => setTimeout(resolve, 20));++ // All five are running rows; three fetch their page, two wait.+ expect(inserted).toHaveLength(5);+ expect(pagesFetched).toEqual(urls.slice(0, 3));+ });++ it('refuses a request without URLs, with too many, or with something that is not a URL', async () => {+ expect((await post({ brandId, urls: [] })).status).toBe(400);+ expect(+ (await post({ brandId, urls: Array.from({ length: 51 }, (_, i) => `https://a.com/${i}`) }))+ .status,+ ).toBe(400);+ expect((await post({ brandId, urls: ['not a url'] })).status).toBe(400);+ expect((await post({ urls: ['https://acme.com/'] })).status).toBe(400);+ expect(inserted).toEqual([]);+ });+});diff --git a/server/src/routes/audits.js b/server/src/routes/audits.jsindex 4298e352b..17b86c018 100644--- a/server/src/routes/audits.js+++ b/server/src/routes/audits.js@@ -12,6 +12,7 @@*/import { Router } from 'express';+import { z } from 'zod';import supabaseAdmin from '../config/supabase.js';import logger from '../lib/logger.js';import { assertBrandAccess } from '../lib/access.js';@@ -27,6 +28,7 @@ import { normStoredDomain } from '../lib/audit/host.js';import {buildAuditPages,buildTrendPoints,+ pageKey,parseListPage,TREND_LIMIT,} from '../lib/audit/history.js';@@ -225,6 +227,75 @@ export async function createAndRunAudit(brandId, url, orgId) {return assembleAudit(created, []);}+/** Pages one bulk request may audit: the Pages list's own page size. */+export const BULK_AUDIT_MAX = 50;++/** Bulk audits run at once; the rest wait their turn, still `running`. */+export const BULK_AUDIT_CONCURRENCY = 3;++// One pool for every bulk request, so 50 re-audits don't fetch and score 50+// pages at the same time.+const bulkQueue = [];+let bulkActive = 0;++function drainBulkQueue() {+ while (bulkActive < BULK_AUDIT_CONCURRENCY && bulkQueue.length > 0) {+ const job = bulkQueue.shift();+ bulkActive += 1;+ job()+ .catch((err) => logger.error({ err }, 'bulk audit job crashed'))+ .finally(() => {+ bulkActive -= 1;+ drainBulkQueue();+ });+ }+}++/**+ * Start audits of several pages of a brand. The quota is checked for all of+ * them first, so either every page is queued or none is (PlanLimitError).+ * Repeat spellings of one page are audited once. Returns the running rows.+ */+export async function createAndQueueAudits(brandId, urls, orgId) {+ const byPage = new Map();+ for (const url of urls) {+ const key = pageKey(url)?.key;+ if (key && !byPage.has(key)) byPage.set(key, url);+ }+ const unique = [...byPage.values()];++ await enforceSiteAuditQuota(orgId, unique.length);++ const { data: created, error } = await supabaseAdmin+ .from('site_audits')+ .insert(+ unique.map((url) => ({+ brand_id: brandId,+ url,+ status: 'running',+ rubric_version: RUBRIC_VERSION,+ })),+ )+ .select('*');+ if (error) throw error;++ for (const row of created) {+ bulkQueue.push(() => runAuditJob(row.id, brandId, row.url, orgId));+ }+ drainBulkQueue();++ return created.map((row) => assembleAudit(row, []));+}++const bulkSchema = z.object({+ brandId: z.guid(),+ urls: z+ .array(z.string().trim().min(1).max(2048))+ .min(1)+ .max(BULK_AUDIT_MAX)+ .refine((urls) => urls.every((url) => pageKey(url)), 'Every URL must be a full URL'),+});+/*** Internal/MCP entry point: start an audit addressed by brand id + url.* Org-ownership is verified upstream in the web MCP layer; here we resolve the@@ -273,6 +344,38 @@ router.post('/', requireFeature('content_optimization'), async (req, res) => {}});+// POST /api/audits/bulk — re-audit several pages at once ({ brandId, urls },+// up to BULK_AUDIT_MAX). All of them must fit the monthly quota, or none+// starts. Returns 202 with the running rows; they run a few at a time.+router.post('/bulk', requireFeature('content_optimization'), async (req, res) => {+ const userId = req.user?.id;+ const parsed = bulkSchema.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({+ success: false,+ message: parsed.error.issues[0]?.message ?? 'Invalid request',+ });+ }+ const { brandId, urls } = parsed.data;++ try {+ const { orgId } = await assertBrandAccess(brandId, userId);+ const audits = await createAndQueueAudits(brandId, urls, orgId);+ return res.status(202).json({ success: true, audits });+ } catch (err) {+ if (err instanceof PlanLimitError) {+ return res+ .status(err.statusCode)+ .json({ success: false, error: 'quota_exceeded', message: err.message });+ }+ if (err.status) {+ return res.status(err.status).json({ success: false, message: err.message });+ }+ req.log.error({ err }, 'bulk audit start failed');+ return res.status(500).json({ success: false, message: err.message });+ }+});+// GET /api/audits/quota — the org's monthly audit allowance (used/limit/remaining).// Registered before /:id so "quota" isn't matched as an audit id.router.get('/quota', async (req, res) => {diff --git a/web/messages/en.json b/web/messages/en.jsonindex 2d4d1e912..40aee8cf6 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2096,6 +2096,8 @@"showHistory": "Show earlier audits of {page}","hideHistory": "Hide earlier audits of {page}","viewReport": "View report",+ "select": "Select {page}",+ "selectAll": "Select all pages shown","moreRuns": "{count, plural, one {# older audit} other {# older audits}} not shown","statuses": {"good": "Good",@@ -2105,6 +2107,26 @@"failed": "Failed"}},+ "bulk": {+ "toolbar": "Actions for the selected pages",+ "selected": "{count} selected",+ "uses": "Uses {count} of your {remaining} audits",+ "overQuota": "Uses {count} of your {remaining} audits · select up to {remaining}",+ "noneLeft": "No audits left this month",+ "reaudit": "Re-audit",+ "clear": "Clear selection",+ "started": "{count, plural, one {# audit started} other {# audits started}} · they run a few at a time"+ },+ "export": {+ "button": "Export",+ "csv": "CSV",+ "excel": "Excel",+ "sheet": "Pages",+ "previousScore": "Previous score",+ "change": "Change",+ "audits": "Audits",+ "failed": "Couldn't export the pages"+ },"loadMore": "Load more","retry": "Retry","deleteAudit": "Delete audit",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsxnew file mode 100644index 000000000..36ef1d69f--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx@@ -0,0 +1,90 @@+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 { AuditQuota } from '@/lib/actions/audits';+import { AuditBulkBar } from './_bulk-bar';++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;+const onReaudit = vi.fn();+const onExport = vi.fn();+const onClear = vi.fn();++function render(count: number, quota: AuditQuota | null, starting = false) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <AuditBulkBar+ count={count}+ quota={quota}+ starting={starting}+ onReaudit={onReaudit}+ onExport={onExport}+ onClear={onClear}+ />+ </NextIntlClientProvider>,+ );+ });+}++const button = (text: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent?.trim() === text)!;+const usage = () =>+ container.querySelectorAll('[role=toolbar] > span')[1] as HTMLElement | undefined;++beforeEach(() => {+ vi.clearAllMocks();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('AuditBulkBar', () => {+ it("says how many of the month's audits a re-audit uses, and starts it", () => {+ render(3, { used: 270, limit: 500, remaining: 225, running: 5 });++ expect(container.textContent).toContain('3 selected');+ expect(usage()?.textContent).toBe('Uses 3 of your 225 audits');+ expect(usage()?.className).not.toContain('text-destructive');+ act(() => button('Re-audit').click());+ expect(onReaudit).toHaveBeenCalledOnce();++ act(() => (container.querySelector('[aria-label="Clear selection"]') as HTMLElement).click());+ expect(onClear).toHaveBeenCalledOnce();+ });++ it('keeps Re-audit off when the selection is over what is left', () => {+ render(12, { used: 92, limit: 100, remaining: 8 });+ expect(usage()?.textContent).toBe('Uses 12 of your 8 audits · select up to 8');+ expect(usage()?.className).toContain('text-destructive');+ expect(button('Re-audit').disabled).toBe(true);++ render(1, { used: 100, limit: 100, remaining: 0 });+ expect(usage()?.textContent).toBe('No audits left this month');+ expect(button('Re-audit').disabled).toBe(true);+ });++ it('counts nothing against an unlimited plan', () => {+ render(40, { used: 0, limit: -1, remaining: -1 });+ expect(usage()).toBeUndefined();+ expect(button('Re-audit').disabled).toBe(false);+ });++ it('waits while a bulk start is on its way', () => {+ render(3, { used: 0, limit: 500, remaining: 500 }, true);+ expect(button('Re-audit').disabled).toBe(true);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsxnew file mode 100644index 000000000..953e77f1f--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx@@ -0,0 +1,127 @@+'use client';++import { useTranslations } from 'next-intl';+import { Download, FileDown, FileSpreadsheet, Loader2, RefreshCw, X } from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import type { AuditQuota } from '@/lib/actions/audits';+import { cn } from '@/lib/utils';++export type ExportFormat = 'csv' | 'xlsx';++/** Export as CSV or Excel, from the Pages header (all) or the bulk bar (selected). */+export function ExportMenu({+ disabled = false,+ busy = false,+ onExport,+}: {+ disabled?: boolean;+ busy?: boolean;+ onExport: (format: ExportFormat) => void;+}) {+ const t = useTranslations('audit.export');+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5 text-xs"+ disabled={disabled || busy}+ />+ }+ >+ {busy ? <Loader2 className="h-3 w-3 animate-spin" /> : <Download className="h-3 w-3" />}+ {t('button')}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => onExport('csv')}>+ <FileDown className="mr-2 h-4 w-4" />+ {t('csv')}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => onExport('xlsx')}>+ <FileSpreadsheet className="mr-2 h-4 w-4" />+ {t('excel')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++/**+ * The Pages table's bulk bar (SA-003), shown while pages are selected: how+ * many of the month's audits a re-audit would use, Re-audit, Export and+ * Clear. Re-audit stays off when the selection is over what's left, so a+ * bulk run never goes past the quota.+ */+export function AuditBulkBar({+ count,+ quota,+ starting,+ onReaudit,+ onExport,+ onClear,+}: {+ count: number;+ quota: AuditQuota | null;+ starting: boolean;+ onReaudit: () => void;+ onExport: (format: ExportFormat) => void;+ onClear: () => void;+}) {+ const t = useTranslations('audit.bulk');+ const limited = quota !== null && quota.limit !== -1;+ const remaining = quota?.remaining ?? 0;+ const over = limited && count > remaining;++ return (+ <div+ role="toolbar"+ aria-label={t('toolbar')}+ className="mb-3 flex flex-wrap items-center gap-2 rounded-md border bg-muted/50 px-3 py-2"+ >+ <span className="text-xs font-medium">{t('selected', { count })}</span>+ {limited && (+ <span className={cn('text-xs', over ? 'text-destructive' : 'text-muted-foreground')}>+ {remaining === 0+ ? t('noneLeft')+ : over+ ? t('overQuota', { count, remaining })+ : t('uses', { count, remaining })}+ </span>+ )}+ <div className="ml-auto flex flex-wrap items-center justify-end gap-1">+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5 text-xs"+ onClick={onReaudit}+ disabled={starting || over}+ >+ {starting ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <RefreshCw className="h-3 w-3" />+ )}+ {t('reaudit')}+ </Button>+ <ExportMenu onExport={onExport} />+ <Button+ variant="ghost"+ size="sm"+ className="h-7 w-7 p-0"+ onClick={onClear}+ aria-label={t('clear')}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>+ );+}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.tsxindex 8384786cc..f7bd79c4d 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.test.tsx@@ -64,8 +64,13 @@ let container: HTMLDivElement;let root: Root;const onLoadMore = vi.fn();const onDeleteRun = vi.fn();+const onSelect = vi.fn();-function render(pages: AuditedPage[], total = pages.length) {+function render(+ pages: AuditedPage[],+ total = pages.length,+ { selected = new Set<string>(), toolbar = null as React.ReactNode } = {},+) {act(() => {root.render(<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">@@ -76,6 +81,10 @@ function render(pages: AuditedPage[], total = pages.length) {loadingMore={false}onLoadMore={onLoadMore}onDeleteRun={onDeleteRun}+ selected={selected}+ onSelect={onSelect}+ headerAction={<button type="button">Export all</button>}+ toolbar={toolbar}/></NextIntlClientProvider>,);@@ -117,8 +126,8 @@ describe('AuditPagesTable', () => {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'],+ ['', '', '/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]');@@ -179,8 +188,8 @@ describe('AuditPagesTable', () => {]);expect(rows().map(cells)).toEqual([- ['', '/broken', '—', '—', 'Failed', 'Oct 14, 2026'],- ['', '/pricing', '63', '14', 'Running', 'Oct 14, 2026'],+ ['', '', '/broken', '—', '—', 'Failed', 'Oct 14, 2026'],+ ['', '', '/pricing', '63', '14', 'Running', 'Oct 14, 2026'],]);expect(rows()[1].querySelector('.animate-spin')).not.toBeNull();});@@ -195,6 +204,46 @@ describe('AuditPagesTable', () => {});});+describe('AuditPagesTable selection', () => {+ const blog = page({ key: 'acme.com/blog', path: '/blog', auditId: 'b1' });+ const running = page({ key: 'acme.com/run', path: '/run', status: 'running' });+ const box = (label: string) =>+ container.querySelector(`[aria-label="${label}"]`) as HTMLButtonElement;++ it('selects a page from its box without opening it, and all pages not being audited', () => {+ render([page(), blog, running]);++ act(() => box('Select /pricing').click());+ expect(onSelect).toHaveBeenLastCalledWith(['acme.com/pricing'], true);+ expect(push).not.toHaveBeenCalled();++ // A page being audited can't be selected, so Select all leaves it out.+ expect(box('Select /run').disabled).toBe(true);+ act(() => box('Select all pages shown').click());+ expect(onSelect).toHaveBeenLastCalledWith(['acme.com/pricing', 'acme.com/blog'], true);+ });++ it('marks the selection and shows the bulk bar and the header action', () => {+ render([page(), blog], 2, {+ selected: new Set(['acme.com/blog']),+ toolbar: <div role="toolbar">bulk</div>,+ });++ expect(box('Select /blog').getAttribute('data-state')).toBe('checked');+ expect(box('Select /pricing').getAttribute('data-state')).toBe('unchecked');+ expect(box('Select all pages shown').getAttribute('data-state')).toBe('indeterminate');+ expect(rows()[1].getAttribute('data-state')).toBe('selected');+ expect(container.querySelector('[role=toolbar]')?.textContent).toBe('bulk');+ expect(button('Export all')).toBeDefined();++ // Clearing every box asks for all of them off.+ render([page(), blog], 2, { selected: new Set(['acme.com/pricing', 'acme.com/blog']) });+ expect(box('Select all pages shown').getAttribute('data-state')).toBe('checked');+ act(() => box('Select all pages shown').click());+ expect(onSelect).toHaveBeenLastCalledWith(['acme.com/pricing', 'acme.com/blog'], false);+ });+});+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');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsxindex 698eab5db..c8a64c461 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx@@ -1,6 +1,6 @@'use client';-import { Fragment, useId, useState } from 'react';+import { Fragment, useId, useState, type ReactNode } from 'react';import { useTranslations } from 'next-intl';import { ChevronRight, Loader2, Trash2 } from 'lucide-react';import {@@ -16,6 +16,7 @@ import {import { Link, useRouter } from '@/i18n/navigation';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';import {Table,TableBody,@@ -139,7 +140,8 @@ function HistoryRun({ run, onDelete }: { run: AuditRun; onDelete: (id: string) =/*** The audited pages, one row per page: the row opens its latest report and- * the arrow lists its earlier audits underneath.+ * the arrow lists its earlier audits underneath. Pages not being audited can+ * be selected for the bulk bar (`toolbar`, shown above the rows).*/export function AuditPagesTable({pages,@@ -148,6 +150,10 @@ export function AuditPagesTable({loadingMore,onLoadMore,onDeleteRun,+ selected,+ onSelect,+ headerAction,+ toolbar,}: {pages: AuditedPage[];total: number;@@ -155,12 +161,22 @@ export function AuditPagesTable({loadingMore: boolean;onLoadMore: () => void;onDeleteRun: (id: string) => void;+ /** Keys of the selected pages. */+ selected: Set<string>;+ onSelect: (keys: string[], on: boolean) => void;+ /** Beside the title, e.g. Export. */+ headerAction?: ReactNode;+ toolbar?: ReactNode;}) {const t = useTranslations('audit');const router = useRouter();const idPrefix = useId();const [open, setOpen] = useState<Set<string>>(() => new Set());+ // A page being audited can't be re-audited until its run ends.+ const selectable = pages.filter((p) => p.status !== 'running').map((p) => p.key);+ const ticked = selectable.filter((key) => selected.has(key)).length;+const toggle = (key: string) =>setOpen((prev) => {const next = new Set(prev);@@ -176,11 +192,23 @@ export function AuditPagesTable({<span className="rounded-full bg-muted px-2 py-0.5 text-xs font-medium tabular-nums text-muted-foreground">{formatNumber(total)}</span>+ {headerAction && <div className="ml-auto">{headerAction}</div>}</CardHeader><CardContent className="pt-0">+ {toolbar}<Table><TableHeader><TableRow>+ <TableHead className="w-8 pr-0">+ <Checkbox+ aria-label={t('pages.selectAll')}+ disabled={selectable.length === 0}+ checked={+ ticked === 0 ? false : ticked === selectable.length ? true : 'indeterminate'+ }+ onCheckedChange={(on) => onSelect(selectable, on === true)}+ />+ </TableHead><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>@@ -199,8 +227,18 @@ export function AuditPagesTable({<Fragment key={page.key}><TableRowclassName="cursor-pointer"+ data-state={selected.has(page.key) ? 'selected' : undefined}onClick={() => router.push(`/dashboard/audit/${page.auditId}`)}>+ <TableCell className="w-8 pr-0">+ <Checkbox+ aria-label={t('pages.select', { page: label })}+ disabled={page.status === 'running'}+ checked={selected.has(page.key)}+ onClick={(e) => e.stopPropagation()}+ onCheckedChange={(on) => onSelect([page.key], on === true)}+ />+ </TableCell><TableCell className="w-9 pr-0"><Buttonvariant="ghost"@@ -258,7 +296,7 @@ export function AuditPagesTable({</TableRow>{expanded && (<TableRow id={historyId} className="hover:bg-transparent">- <TableCell />+ <TableCell colSpan={2} /><TableCell colSpan={5} className="pt-0 whitespace-normal"><ul className="divide-y rounded-md border">{page.runs.map((run) => (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_use-pages-export.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/audit/_use-pages-export.test.tsnew file mode 100644index 000000000..bb32a5977--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_use-pages-export.test.ts@@ -0,0 +1,42 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { AuditedPage } from '@/lib/actions/audits';++const getAuditPages = vi.fn();+vi.mock('@/lib/actions/audits', () => ({+ getAuditPages: (...args: unknown[]) => getAuditPages(...args),+}));++const { readAllPages } = await import('./_use-pages-export');++const page = (key: string) => ({ key }) as AuditedPage;+const keys = (from: number, to: number) =>+ Array.from({ length: to - from }, (_, i) => page(`p${from + i}`));++beforeEach(() => getAuditPages.mockReset());++describe('readAllPages', () => {+ it('reads the list 100 pages at a time and keeps a page repeated at a boundary once', async () => {+ getAuditPages+ .mockResolvedValueOnce({ pages: keys(0, 100), total: 230 })+ // A page audited meanwhile moved to the top: p99 comes again.+ .mockResolvedValueOnce({ pages: keys(99, 199), total: 230 })+ .mockResolvedValueOnce({ pages: keys(199, 230), total: 230 });++ const all = await readAllPages('b1');++ expect(getAuditPages.mock.calls.map((c) => c[1])).toEqual([0, 100, 200]);+ expect(all).toHaveLength(230);+ expect(new Set(all.map((p) => p.key)).size).toBe(230);+ });++ it('moves on even when a whole page repeats', async () => {+ getAuditPages+ .mockResolvedValueOnce({ pages: keys(0, 100), total: 300 })+ .mockResolvedValueOnce({ pages: keys(0, 100), total: 300 })+ .mockResolvedValueOnce({ pages: keys(100, 150), total: 300 });++ const all = await readAllPages('b1');+ expect(getAuditPages).toHaveBeenCalledTimes(3);+ expect(all).toHaveLength(150);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_use-pages-export.ts b/web/src/app/[locale]/(dashboard)/dashboard/audit/_use-pages-export.tsnew file mode 100644index 000000000..968cf97de--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_use-pages-export.ts@@ -0,0 +1,98 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { getAuditPages, type AuditedPage } from '@/lib/actions/audits';+import { BYTE_ORDER_MARK } from '@/lib/action-center/export';+import {+ auditPagesCsv,+ auditPagesExportFileName,+ auditPagesWorkbook,+ type AuditExportLabels,+} from '@/lib/audit-export';+import { saveBlob } from '@/lib/download';+import type { ExportFormat } from './_bulk-bar';++/** The server's largest page of the Pages list. */+const EXPORT_PAGE_SIZE = 100;++/** Every audited page of the brand, read page by page. */+export async function readAllPages(brandId: string): Promise<AuditedPage[]> {+ const all: AuditedPage[] = [];+ const seen = new Set<string>();+ for (let offset = 0; ; offset += EXPORT_PAGE_SIZE) {+ const { pages, total } = await getAuditPages(brandId, offset, EXPORT_PAGE_SIZE);+ // A page audited meanwhile moves to the top and can repeat at a boundary.+ for (const page of pages) {+ if (!seen.has(page.key)) {+ seen.add(page.key);+ all.push(page);+ }+ }+ if (pages.length < EXPORT_PAGE_SIZE || offset + EXPORT_PAGE_SIZE >= total) return all;+ }+}++/** Export CSV / Excel of the Pages table: all pages, or the ones given. */+export function usePagesExport(brandId: string | null) {+ const t = useTranslations('audit');+ const [exporting, setExporting] = useState(false);++ const labels = (): AuditExportLabels => ({+ sheet: t('export.sheet'),+ page: t('pages.page'),+ score: t('pages.score'),+ previousScore: t('export.previousScore'),+ change: t('export.change'),+ status: t('pages.status'),+ issues: t('pages.issues'),+ lastAudit: t('pages.lastAudit'),+ audits: t('export.audits'),+ statuses: {+ good: t('pages.statuses.good'),+ improving: t('pages.statuses.improving'),+ needs_work: t('pages.statuses.needs_work'),+ running: t('pages.statuses.running'),+ failed: t('pages.statuses.failed'),+ },+ });++ const download = async (pages: AuditedPage[], format: ExportFormat) => {+ if (format === 'csv') {+ saveBlob(+ new Blob([BYTE_ORDER_MARK, auditPagesCsv(pages, labels())], {+ type: 'text/csv;charset=utf-8;',+ }),+ auditPagesExportFileName('csv'),+ );+ return;+ }+ // Loaded on demand: the writer is only needed when someone asks for a file.+ const { default: writeXlsxFile } = await import('write-excel-file/browser');+ await writeXlsxFile(auditPagesWorkbook(pages, labels())).toFile(+ auditPagesExportFileName('xlsx'),+ );+ };++ const run = async (read: () => Promise<AuditedPage[]>, format: ExportFormat) => {+ setExporting(true);+ try {+ await download(await read(), format);+ } catch (err) {+ console.error('Site Audit export failed:', err);+ toast.error(t('export.failed'));+ } finally {+ setExporting(false);+ }+ };++ return {+ exporting,+ exportAll: (format: ExportFormat) => {+ if (brandId) void run(() => readAllPages(brandId), format);+ },+ exportPages: (pages: AuditedPage[], format: ExportFormat) =>+ void run(async () => pages, format),+ };+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsxindex b7fc95a27..8073460ef 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx@@ -1,6 +1,6 @@'use client';-import { useState, useEffect, useMemo } from 'react';+import { useState, useEffect, useMemo, useRef } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';import {@@ -20,6 +20,7 @@ import { Skeleton } from '@/components/ui/skeleton';import { useBrandStore } from '@/stores/use-brand-store';import {runAudit,+ runAuditsBulk,getAuditPages,getAuditQuota,getAuditTrend,@@ -32,11 +33,16 @@ 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 { AuditBulkBar, ExportMenu } from './_bulk-bar';+import { usePagesExport } from './_use-pages-export';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 };+/** While audits run, the Pages list and the quota are read again this often. */+const RUNNING_POLL_MS = 10_000;+function barClass(score: number | null): string {if (score === null) return 'bg-muted';if (score >= 0.7) return 'bg-green-600';@@ -67,6 +73,9 @@ export default function SiteAuditPage() {const [quota, setQuota] = useState<AuditQuota | null>(null);const [trend, setTrend] = useState<AuditTrend | null>(null);const [range, setRange] = useState<RangePreset>('30d');+ const [selected, setSelected] = useState<Set<string>>(() => new Set());+ const [startingBulk, setStartingBulk] = useState(false);+ const { exporting, exportAll, exportPages } = usePagesExport(activeBrandId);// Capture "now" once (impure call belongs in a lazy initializer, not render).const [nowMs] = useState(() => Date.now());@@ -78,6 +87,8 @@ export default function SiteAuditPage() {let cancelled = false;setLoading(true);setError(null);+ // A selection belongs to the brand it was made on.+ setSelected(new Set());(async () => {try {const [data, q, tr] = await Promise.all([@@ -193,26 +204,82 @@ export default function SiteAuditPage() {}};+ // Read the pages shown (up to the server's 100), the quota and the trend+ // again, in place: the table stays up with its open histories. Selected+ // pages that are gone or now running are dropped from the selection.+ const shownRef = useRef(0);+ useEffect(() => {+ shownRef.current = pages.length;+ }, [pages.length]);+ const reloadInPlace = async (brandId: string) => {+ const [data, q, tr] = await Promise.all([+ getAuditPages(brandId, 0, Math.min(Math.max(shownRef.current, 50), 100)),+ getAuditQuota(),+ getAuditTrend(brandId),+ ]);+ setPages(data.pages);+ setPagesTotal(data.total);+ setPrimaryHost(data.primaryHost);+ setQuota(q);+ setTrend(tr);+ const selectable = new Set(data.pages.filter((p) => p.status !== 'running').map((p) => p.key));+ setSelected((prev) => new Set([...prev].filter((key) => selectable.has(key))));+ };+// 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.+ // the page.const handleDelete = async (id: string) => {if (!activeBrandId) return;try {await deleteAudit(id);- 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);+ await reloadInPlace(activeBrandId);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : t('failed'));+ }+ };++ const handleSelect = (keys: string[], on: boolean) =>+ setSelected((prev) => {+ const next = new Set(prev);+ for (const key of keys) {+ if (on) next.add(key);+ else next.delete(key);+ }+ return next;+ });++ const selectedPages = pages.filter((p) => selected.has(p.key));++ const handleBulkReaudit = async () => {+ if (!activeBrandId || selectedPages.length === 0) return;+ setStartingBulk(true);+ try {+ const { started } = await runAuditsBulk(+ activeBrandId,+ selectedPages.map((p) => p.url),+ );+ toast.success(t('bulk.started', { count: started }));+ setSelected(new Set());+ await reloadInPlace(activeBrandId);} catch (err) {toast.error(err instanceof Error ? err.message : t('failed'));+ } finally {+ setStartingBulk(false);}};+ // While any page is being audited, follow it until its run ends.+ const anyRunning = pages.some((p) => p.status === 'running');+ useEffect(() => {+ if (!anyRunning || !activeBrandId) return;+ const timer = setInterval(() => {+ reloadInPlace(activeBrandId).catch((err) =>+ console.error('Failed to refresh the audited pages:', err),+ );+ }, RUNNING_POLL_MS);+ return () => clearInterval(timer);+ }, [anyRunning, activeBrandId]);+if (!activeBrandId) {return (<div className="flex items-center justify-center min-h-[400px]">@@ -416,6 +483,21 @@ export default function SiteAuditPage() {loadingMore={loadingMore}onLoadMore={handleLoadMore}onDeleteRun={handleDelete}+ selected={selected}+ onSelect={handleSelect}+ headerAction={<ExportMenu busy={exporting} onExport={exportAll} />}+ toolbar={+ selectedPages.length > 0 && (+ <AuditBulkBar+ count={selectedPages.length}+ quota={quota}+ starting={startingBulk}+ onReaudit={handleBulkReaudit}+ onExport={(format) => exportPages(selectedPages, format)}+ onClear={() => setSelected(new Set())}+ />+ )+ }/>)}</div>diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.tsindex f84fdc687..d938501cc 100644--- a/web/src/lib/actions/audits.ts+++ b/web/src/lib/actions/audits.ts@@ -58,7 +58,10 @@ export interface AuditResult {export interface AuditQuota {used: number;limit: number;+ /** What's left this month, the running audits already taken out. */remaining: number;+ /** Audits started and not finished yet: they're charged when they complete. */+ running?: number;}export interface AuditTrendPoint {@@ -205,6 +208,31 @@ export async function getAuditTrend(brandId: string): Promise<AuditTrend> {return { primaryDomain: data.primaryDomain ?? null, points: data.points ?? [] };}+/**+ * Re-audit several pages at once. Every page must fit the monthly quota, or+ * none starts; the server runs them a few at a time.+ */+export async function runAuditsBulk(brandId: string, urls: string[]): Promise<{ started: number }> {+ const session = await getSession();++ const res = await fetch(`${AEO_SERVER_URL}/api/audits/bulk`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${session.access_token}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ brandId, urls }),+ });++ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.message || `Server error: ${res.status}`);+ }++ const data = await res.json();+ return { started: (data.audits ?? []).length };+}+export interface AuditedPages {pages: AuditedPage[];/** Pages audited for the brand, across all pages of the list. */diff --git a/web/src/lib/audit-export.test.ts b/web/src/lib/audit-export.test.tsnew file mode 100644index 000000000..2391f16ff--- /dev/null+++ b/web/src/lib/audit-export.test.ts@@ -0,0 +1,90 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';+import type { AuditedPage } from '@/lib/actions/audits';+import {+ AUDIT_PAGES_CSV_HEADERS,+ auditPagesCsv,+ auditPagesExportFileName,+ auditPagesWorkbook,+ type AuditExportLabels,+} from './audit-export';++const labels: AuditExportLabels = {+ sheet: 'Pages',+ page: 'Page',+ score: 'Score',+ previousScore: 'Previous score',+ change: 'Change',+ status: 'Status',+ issues: 'Issues',+ lastAudit: 'Last audit',+ audits: 'Audits',+ statuses: {+ good: 'Good',+ improving: 'Improving',+ needs_work: 'Needs work',+ running: 'Running',+ failed: 'Failed',+ },+};++const page = (over: Partial<AuditedPage> = {}): AuditedPage => ({+ key: 'acme.com/pricing',+ host: 'acme.com',+ path: '/pricing',+ url: 'https://acme.com/pricing',+ auditId: 'a3',+ score: 0.634,+ previousScore: 0.58,+ status: 'improving',+ lastAuditedAt: '2026-10-14T23:30:00+00:00',+ trend: [0.58, 0.634],+ issues: 14,+ runs: [],+ runCount: 3,+ ...over,+});++const failed = page({+ key: 'acme.com/broken',+ url: 'https://acme.com/broken,new',+ score: null,+ previousScore: null,+ status: 'failed',+ issues: null,+ runCount: 1,+});++describe('auditPagesCsv', () => {+ it('writes a row per page, scores out of 100 with their change, and the UTC day', () => {+ expect(auditPagesCsv([page(), failed], labels).split('\n')).toEqual([+ AUDIT_PAGES_CSV_HEADERS.join(','),+ 'https://acme.com/pricing,63,58,5,Improving,14,2026-10-14,3',+ '"https://acme.com/broken,new",,,,Failed,,2026-10-14,1',+ ]);+ });+});++describe('auditPagesWorkbook', () => {+ it('is one labelled sheet a spreadsheet reader opens', async () => {+ const { default: writeXlsxFile } = await import('write-excel-file/browser');+ const { default: readXlsxFile } = await import('read-excel-file/browser');+ const blob = await writeXlsxFile(auditPagesWorkbook([page(), failed], labels)).toBlob();+ const [sheet] = await readXlsxFile(blob);++ expect(sheet.sheet).toBe('Pages');+ expect(sheet.data).toEqual([+ ['Page', 'Score', 'Previous score', 'Change', 'Status', 'Issues', 'Last audit', 'Audits'],+ ['https://acme.com/pricing', 63, 58, 5, 'Improving', 14, '2026-10-14', 3],+ ['https://acme.com/broken,new', null, null, null, 'Failed', null, '2026-10-14', 1],+ ]);+ });+});++describe('auditPagesExportFileName', () => {+ it("names the file after the day it's exported", () => {+ const now = new Date('2026-10-17T12:00:00Z');+ expect(auditPagesExportFileName('csv', now)).toBe('site-audit-pages-2026-10-17.csv');+ expect(auditPagesExportFileName('xlsx', now)).toBe('site-audit-pages-2026-10-17.xlsx');+ });+});diff --git a/web/src/lib/audit-export.ts b/web/src/lib/audit-export.tsnew file mode 100644index 000000000..79b04b37a--- /dev/null+++ b/web/src/lib/audit-export.ts@@ -0,0 +1,98 @@+import type { Sheet } from 'write-excel-file/browser';+import type { AuditedPage, AuditedPageStatus } from '@/lib/actions/audits';+import { toCsv } from '@/lib/csv';++/**+ * Site Audit's Pages export (SA-003): a row per audited page, as CSV or Excel,+ * for all pages or the selected ones.+ */++export interface AuditExportLabels {+ sheet: string;+ page: string;+ score: string;+ previousScore: string;+ change: string;+ status: string;+ issues: string;+ lastAudit: string;+ audits: string;+ statuses: Record<AuditedPageStatus, string>;+}++export const AUDIT_PAGES_CSV_HEADERS = [+ 'page_url',+ 'score',+ 'previous_score',+ 'change',+ 'status',+ 'issues',+ 'last_audit',+ 'audits',+];++const points = (score: number | null) => (score === null ? null : Math.round(score * 100));++function exportRow(page: AuditedPage, labels: AuditExportLabels) {+ const score = points(page.score);+ const previous = points(page.previousScore);+ return {+ page_url: page.url,+ score,+ previous_score: previous,+ change: score !== null && previous !== null ? score - previous : null,+ status: labels.statuses[page.status],+ issues: page.issues,+ // The UTC day, which a spreadsheet sorts and reads in any locale.+ last_audit: new Date(page.lastAuditedAt).toISOString().slice(0, 10),+ audits: page.runCount,+ };+}++/** The Pages export as CSV, without the byte order mark the download adds. */+export function auditPagesCsv(pages: AuditedPage[], labels: AuditExportLabels): string {+ return toCsv(+ pages.map((page) => exportRow(page, labels)),+ AUDIT_PAGES_CSV_HEADERS,+ );+}++const bold = (value: string) => ({ value, fontWeight: 'bold' as const });++/** The Pages export as one Excel sheet, labelled in the reader's language. */+export function auditPagesWorkbook(pages: AuditedPage[], labels: AuditExportLabels): Sheet<Blob>[] {+ return [+ {+ sheet: labels.sheet,+ stickyRowsCount: 1,+ columns: [+ { width: 60 },+ { width: 8 },+ { width: 14 },+ { width: 8 },+ { width: 12 },+ { width: 8 },+ { width: 12 },+ { width: 8 },+ ],+ data: [+ [+ labels.page,+ labels.score,+ labels.previousScore,+ labels.change,+ labels.status,+ labels.issues,+ labels.lastAudit,+ labels.audits,+ ].map(bold),+ ...pages.map((page) => Object.values(exportRow(page, labels))),+ ],+ },+ ];+}++/** "site-audit-pages-2026-10-17.csv" */+export function auditPagesExportFileName(ext: 'csv' | 'xlsx', now = new Date()): string {+ return `site-audit-pages-${now.toISOString().slice(0, 10)}.${ext}`;+}