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): show when auto-audit runs, what it audited and what failed (#1201)
Cihan8d43edcdd52d
diff --git a/server/src/lib/audit/history.js b/server/src/lib/audit/history.jsindex 03cf2fbf9..c4bb6152c 100644--- a/server/src/lib/audit/history.js+++ b/server/src/lib/audit/history.js@@ -106,6 +106,8 @@ export function pageStatus(latestRun, current, previous) {* its latest completed score and audit, the one before it, a status, its* 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.+ * lastAuditSource says whether the audit the row opens was an auto-audit+ * run's (SA-006) or a user's; rows read without `source` count as the user's.*/export function buildAuditPages(rowsNewestFirst, now = Date.now()) {const groups = new Map();@@ -126,6 +128,7 @@ export function buildAuditPages(rowsNewestFirst, now = Date.now()) {: r.status,totalScore: r.total_score === null ? null : Number(r.total_score),createdAt: r.created_at,+ source: r.source === 'auto' ? 'auto' : 'user',});}@@ -144,6 +147,7 @@ export function buildAuditPages(rowsNewestFirst, now = Date.now()) {previousScore: previous?.totalScore ?? null,status: pageStatus(latest, current, previous),lastAuditedAt: (current ?? latest).createdAt,+ lastAuditSource: (current ?? latest).source,trend: completed.slice(0, PAGE_TREND_POINTS).map((r) => r.totalScore)diff --git a/server/src/lib/audit/history.test.js b/server/src/lib/audit/history.test.jsindex 04a34ebf7..71d9c70ab 100644--- a/server/src/lib/audit/history.test.js+++ b/server/src/lib/audit/history.test.js@@ -153,6 +153,19 @@ describe('buildAuditPages', () => {expect(pages[1]).toMatchObject({ score: 0.74, previousScore: null, status: 'good' });});+ it("says whether the audit a row opens was an auto-audit run's", () => {+ const pages = buildAuditPages([+ { ...row('a2', 'https://acme.com/pricing', '2026-10-19T06:00:00Z', '0.6'), source: 'auto' },+ row('a1', 'https://acme.com/pricing', '2026-10-01T09:00:00Z', '0.5'),+ row('b2', 'https://acme.com/blog', '2026-10-18T09:00:00Z', null, 'running'),+ { ...row('b1', 'https://acme.com/blog', '2026-10-01T09:00:00Z', '0.7'), source: 'auto' },+ ]);+ expect(pages[0]).toMatchObject({ auditId: 'a2', lastAuditSource: 'auto' });+ expect(pages[0].runs.map((r) => r.source)).toEqual(['auto', 'user']);+ // A row opens its latest completed audit, a run's here, while a user's re-audit runs.+ expect(pages[1]).toMatchObject({ auditId: 'b1', lastAuditSource: 'auto' });+ });+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');diff --git a/server/src/routes/audits.js b/server/src/routes/audits.jsindex 427f51e85..c063924bd 100644--- a/server/src/routes/audits.js+++ b/server/src/routes/audits.js@@ -116,7 +116,7 @@ function readBrandAudits(brandId) {return readAllRpcRows('site_audits', (from, to) =>supabaseAdmin.from('site_audits')- .select('id, url, final_url, status, total_score, created_at')+ .select('id, url, final_url, status, total_score, created_at, source').eq('brand_id', brandId).order('created_at', { ascending: false }).order('id', { ascending: false })diff --git a/web/messages/en.json b/web/messages/en.jsonindex a44db9e8a..1ec775acb 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2134,6 +2134,8 @@"issues": "Issues","status": "Status","lastAudit": "Last audit",+ "auto": "Auto",+ "autoTitle": "Audited by an auto-audit run","showHistory": "Show earlier audits of {page}","hideHistory": "Hide earlier audits of {page}","viewReport": "View report",@@ -2236,6 +2238,8 @@"run_done": "done","run_next": "next run","run_upcoming": "upcoming",+ "run_missed": "skipped",+ "runTitle": "Day {day} of your billing month · {date}","autoShare": "Auto {share}%","autoOff": "Auto-audit off","autoPerRun": "Auto · {perRun} pages a run",@@ -2256,6 +2260,7 @@"nextAuto": "Next auto-audit <b>{when}</b> · {count, plural, one {# page} other {# pages}}","today": "today","tomorrow": "tomorrow",+ "withinADay": "within a day","onDate": "on {date}","autoOff": "Auto-audit off"},@@ -2268,6 +2273,11 @@"autoAuditOff": "Off: all {limit} audits a month are yours.","autoAuditUnlimited": "{perRun} pages on days 1, 7, 14, 21 and 28 of the month.","orgWide": "Applies to every brand in your organization.",+ "lastRun": "Last run {date}",+ "runningNow": "Running now",+ "nextRun": "Next run {date}",+ "firstRun": "First run {date}",+ "withinADay": "within a day","emailLabel": "E-mail the team after each run","excludeTitle": "Excluded pages","excludeHelp": "One path per line, * for anything. These pages stay out of Opportunities and auto-audits.",@@ -2288,6 +2298,9 @@"done": "{pages, plural, one {# page} other {# pages}} audited · {issues, plural, one {# critical issue} other {# critical issues}}","running": "Auditing {pages, plural, one {# page} other {# pages}} · {completed} done","nextRun": "next run {date}",+ "nextRunSoon": "next run within a day",+ "failed": "{count, plural, one {# page} other {# pages}} couldn't be audited",+ "viewPages": "View pages","dismiss": "Dismiss"},"bulk": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.test.tsxindex eff7b1650..25ccfefb7 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.test.tsx@@ -1,9 +1,10 @@import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { NextIntlClientProvider } from 'next-intl';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../messages/en.json';import type { AutoAuditRun } from '@/lib/actions/audits';+import type { NextAutoRun } from '@/lib/audit-auto-runs';import { AutoRunNotice } from './_auto-run-notice';(@@ -30,11 +31,15 @@ const run = (over: Partial<AutoAuditRun> = {}): AutoAuditRun => ({let container: HTMLDivElement;let root: Root;-function render(value: AutoAuditRun | null, nextRunAt: string | null = '2026-10-14T12:00:00.000Z') {+function render(+ value: AutoAuditRun | null,+ nextRun: NextAutoRun | null = { at: '2026-10-14T00:00:00.000Z', soon: false },+ onViewPages?: () => void,+) {act(() => {root.render(<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">- <AutoRunNotice brandId={BRAND} run={value} nextRunAt={nextRunAt} />+ <AutoRunNotice brandId={BRAND} run={value} nextRun={nextRun} onViewPages={onViewPages} /></NextIntlClientProvider>,);});@@ -66,12 +71,34 @@ afterEach(() => {describe('AutoRunNotice', () => {it('sums up the run with the next run date', () => {- render(run());+ render(run({ pages: 2 }));expect(container.textContent).toBe('Auto-audit · Oct 7 · 2 pages audited · 3 critical issues · next run Oct 14',);});+ it("counts the audits that failed, so they don't go missing", () => {+ render(run());+ expect(container.textContent).toBe(+ "Auto-audit · Oct 7 · 2 pages audited · 3 critical issues · 1 page couldn't be audited · next run Oct 14",+ );+ });++ it("says within a day when the next run's turn has started without it", () => {+ render(run({ pages: 2 }), { at: '2026-10-14T00:00:00.000Z', soon: true });+ expect(container.textContent).toContain('next run within a day');+ });++ it('leads to the pages the run audited', () => {+ const onViewPages = vi.fn();+ render(run(), null, onViewPages);+ const view = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'View pages',+ )!;+ act(() => view.click());+ expect(onViewPages).toHaveBeenCalled();+ });+it('shows a run still going, and no next run when there is none', () => {render(run({ status: 'running', pages: 3, completed: 1, running: 2, criticalIssues: 0 }), null);expect(container.textContent).toBe('Auto-audit · Oct 7 · Auditing 3 pages · 1 done');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.tsxindex 8b8abe5e7..b5fbe80fa 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.tsx@@ -5,6 +5,7 @@ import { useTranslations } from 'next-intl';import { CalendarClock, X } from 'lucide-react';import { Button } from '@/components/ui/button';import type { AutoAuditRun } from '@/lib/actions/audits';+import type { NextAutoRun } from '@/lib/audit-auto-runs';import { formatMonthDay } from '@/lib/format';const dismissKey = (brandId: string) => `audit-auto-run-dismissed:${brandId}`;@@ -20,16 +21,21 @@ function readDismissed(brandId: string): string | null {/*** The in-app notice after an auto-audit run (SA-006): "Auto-audit · Oct 21 ·* 25 pages audited · 6 critical issues · next run Oct 28", for the brand's- * pages the run audited. Dismissed per run, in this browser.+ * pages the run audited, with the audits that failed and a way to the pages+ * (View pages). Dismissed per run, in this browser.*/export function AutoRunNotice({brandId,run,- nextRunAt,+ nextRun,+ onViewPages,}: {brandId: string;run: AutoAuditRun | null;- nextRunAt: string | null;+ /** Null while auto-audit is off. */+ nextRun: NextAutoRun | null;+ /** Shows the Pages list, where the run's audits are, latest first. */+ onViewPages?: () => void;}) {const t = useTranslations('audit.autoRun');const [dismissed, setDismissed] = useState(() => readDismissed(brandId));@@ -45,13 +51,18 @@ export function AutoRunNotice({setDismissed(run.id);};+ // Audits neither completed nor running: they failed, e.g. on a page that blocks bots.+ const failed = Math.max(0, run.pages - run.completed - run.running);const parts = [t('label'),formatMonthDay(run.startedAt),run.status === 'running'? t('running', { pages: run.pages, completed: run.completed }): t('done', { pages: run.completed, issues: run.criticalIssues }),- ...(nextRunAt ? [t('nextRun', { date: formatMonthDay(nextRunAt) })] : []),+ ...(failed > 0 ? [t('failed', { count: failed })] : []),+ ...(nextRun+ ? [nextRun.soon ? t('nextRunSoon') : t('nextRun', { date: formatMonthDay(nextRun.at) })]+ : []),];return (@@ -60,7 +71,8 @@ export function AutoRunNotice({className="flex items-center gap-2 rounded-lg border bg-card py-1.5 pr-1.5 pl-3 text-sm"><CalendarClock className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />- <p className="min-w-0 flex-1 truncate">+ {/* Wraps rather than cut off the next run on a narrow screen. */}+ <p className="min-w-0 flex-1">{parts.map((part, i) => (<span key={i}>{i > 0 && <span className="text-muted-foreground"> · </span>}@@ -68,6 +80,11 @@ export function AutoRunNotice({</span>))}</p>+ {onViewPages && (+ <Button variant="ghost" size="sm" className="h-7 shrink-0 text-xs" onClick={onViewPages}>+ {t('viewPages')}+ </Button>+ )}<Button variant="ghost" size="icon-sm" onClick={dismiss} aria-label={t('dismiss')}><X className="h-4 w-4" /></Button>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsxindex 00a986af0..99390bd81 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx@@ -58,15 +58,22 @@ const growthAuto: AuditQuota = {auto: auto(),};const onOpenSettings = vi.fn();+/** The day before day 28's run. */+const NOW = new Date('2026-10-27T12:00:00Z');let container: HTMLDivElement;let root: Root;-function render(data: AuditOverview | null, quota: AuditQuota | null = growth) {+function render(data: AuditOverview | null, quota: AuditQuota | null = growth, now = NOW) {act(() => {root.render(<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">- <AuditOverviewCards overview={data} quota={quota} onOpenSettings={onOpenSettings} />+ <AuditOverviewCards+ overview={data}+ quota={quota}+ now={now}+ onOpenSettings={onOpenSettings}+ /></NextIntlClientProvider>,);});@@ -157,16 +164,34 @@ describe('AuditOverviewCards', () => {]);expect(audits).toContain('Auto 25% · How it works');- // The five runs: done, done, done, done, next.+ // The five runs by date: done, done, done, done, next.const runs = [...container.querySelectorAll('ol[aria-label] li')];expect(runs.map((li) => li.textContent)).toEqual([- '1done',- '7done',- '14done',- '21done',- '28next run',+ 'Oct 1done',+ 'Oct 7done',+ 'Oct 14done',+ 'Oct 21done',+ 'Oct 28next run',]);expect(runs[4].className).toContain('font-semibold');+ expect(runs[4].getAttribute('title')).toBe('Day 28 of your billing month · Oct 28');+ });++ it('marks a run whose turn passed without running as skipped, not upcoming', () => {+ // Auto-audit came out on day 25: only day 28 ran.+ const late = auto({+ runs: [1, 7, 14, 21, 28].map((day) => ({+ day,+ at: `2026-10-${String(day).padStart(2, '0')}T00:00:00.000Z`,+ done: day === 28,+ })),+ nextRun: null,+ });+ // Seen on day 28, after the run.+ render(overview(), { ...growthAuto, auto: late }, new Date('2026-10-28T12:00:00Z'));+ expect(+ [...container.querySelectorAll('ol[aria-label] li .sr-only')].map((s) => s.textContent),+ ).toEqual(['skipped', 'skipped', 'skipped', 'skipped', 'done']);});it("counts a run's running audits as auto, not the user's", () => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsxindex 1c3b2695c..7df4be48a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx@@ -87,10 +87,13 @@ const GRID = 'grid grid-cols-1 gap-3 sm:grid-cols-2 min-[75rem]:grid-cols-4';export function AuditOverviewCards({overview,quota,+ now,onOpenSettings,}: {overview: AuditOverview | null;quota: AuditQuota | null;+ /** For the runs' states (done, skipped, next). */+ now: Date;/** Opens the Site Audit settings, from How it works. */onOpenSettings?: () => void;}) {@@ -133,7 +136,7 @@ export function AuditOverviewCards({const quotaFooter = !quota ? null : shares ? (<div className="space-y-2 pb-0.5"><QuotaSegments quota={quota} />- {auto?.enabled && <RunDots auto={auto} />}+ {auto?.enabled && <RunDots auto={auto} now={now} />}<div className="truncate text-xs text-muted-foreground">{auto?.enabled? tq('autoShare', { share: autoSharePct(auto, quota.limit) })@@ -144,7 +147,7 @@ export function AuditOverviewCards({</div>) : auto?.enabled ? (<div className="space-y-2 pb-0.5">- <RunDots auto={auto} />+ <RunDots auto={auto} now={now} /><div className="truncate text-xs text-muted-foreground">{tq('autoPerRun', { perRun: auto.perRun })}</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 196e5e1f0..0d800800a 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@@ -138,6 +138,11 @@ describe('AuditPagesTable', () => {expect(container.querySelectorAll('tbody svg[role=img]')).toHaveLength(0);});+ it("tags a page whose last audit was an auto-audit run's", () => {+ render([page({ lastAuditSource: 'auto' }), page({ key: 'acme.com/blog', path: '/blog' })]);+ expect(rows().map((row) => cells(row).at(-1))).toEqual(['Oct 14, 2026Auto', 'Oct 14, 2026']);+ });+it('opens the latest report from the row, and the earlier audits from the arrow', () => {render([page()]);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsxindex 75bf210e6..af458c04c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx@@ -14,6 +14,7 @@ import {DialogTrigger,} from '@/components/ui/dialog';import { Link, useRouter } from '@/i18n/navigation';+import { Badge } from '@/components/ui/badge';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Button } from '@/components/ui/button';import { Checkbox } from '@/components/ui/checkbox';@@ -327,6 +328,15 @@ export function AuditPagesTable({</TableCell><TableCell className="text-muted-foreground">{formatDate(page.lastAuditedAt)}+ {page.lastAuditSource === 'auto' && (+ <Badge+ variant="outline"+ className="ml-1.5 text-[10px]"+ title={t('pages.autoTitle')}+ >+ {t('pages.auto')}+ </Badge>+ )}</TableCell></TableRow>{expanded && (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.tsxindex 597f67c93..0ab44a2d7 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_quota-meter.tsx@@ -2,7 +2,8 @@import { useTranslations } from 'next-intl';import type { AuditAutoStatus, AuditQuota } from '@/lib/actions/audits';-import { formatNumber } from '@/lib/format';+import { autoRunStates } from '@/lib/audit-auto-runs';+import { formatMonthDay, formatNumber } from '@/lib/format';import { cn } from '@/lib/utils';/** Auto-audit's runs a month (days 1, 7, 14, 21 and 28). */@@ -64,18 +65,21 @@ export function QuotaSegments({ quota }: { quota: AuditQuota }) {}/**- * The five runs on one line: 1 · 7 · 14 · 21 · 28. Done filled, the next one- * outlined and bold, the rest empty.+ * The five runs on one line, by date (days 1, 7, 14, 21 and 28 of the+ * billing month): done filled, the next one outlined and bold, one whose turn+ * passed without a run dashed, the rest empty.*/-export function RunDots({ auto }: { auto: AuditAutoStatus }) {+export function RunDots({ auto, now }: { auto: AuditAutoStatus; now: Date }) {const t = useTranslations('audit.quota');return (<ol aria-label={t('runs')} className="flex items-start">- {auto.runs.map((run) => {- const state = run.done ? 'done' : run.day === auto.nextRun?.day ? 'next' : 'upcoming';+ {autoRunStates(auto, now).map(({ day, at, state }) => {+ // Run days are UTC days (auto-audit.js), so their dates are too.+ const date = formatMonthDay(at, 'UTC');return (<li- key={run.day}+ key={day}+ title={t('runTitle', { day, date })}className={cn('relative flex flex-1 flex-col items-center gap-[3px] text-[11px] leading-none whitespace-nowrap',// The line to the next run.@@ -90,9 +94,10 @@ export function RunDots({ auto }: { auto: AuditAutoStatus }) {state === 'done' && 'border-foreground bg-foreground',state === 'next' && 'border-foreground bg-card',state === 'upcoming' && 'border-muted-foreground/40 bg-card',+ state === 'missed' && 'border-dashed border-muted-foreground/40 bg-transparent',)}/>- {run.day}+ {date}<span className="sr-only">{t(`run_${state}`)}</span></li>);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsxindex 0ba6eeff8..7184a93fd 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsx@@ -3,7 +3,7 @@ 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 { AuditSettings } from '@/lib/actions/audits';+import type { AuditAutoStatus, AuditSettings, AutoAuditRun } from '@/lib/actions/audits';import { AuditSettingsDialog, parsePatterns } from './_settings-dialog';(@@ -36,7 +36,42 @@ let root: Root;const onSaved = vi.fn();const onOpenChange = vi.fn();-async function render(canManage = true) {+/** A billing month from Sep 22 to Oct 22 whose last run (day 28, Oct 19) is done. */+const schedule = (enabled = true): AuditAutoStatus => ({+ enabled,+ setting: null,+ emailAfterRun: false,+ perRun: 5,+ reserved: 0,+ used: 5,+ running: 0,+ periodStart: '2026-09-22T00:00:00.000Z',+ periodEnd: '2026-10-22T00:00:00.000Z',+ runs: [+ { day: 1, at: '2026-09-22T00:00:00.000Z', done: false },+ { day: 7, at: '2026-09-28T00:00:00.000Z', done: false },+ { day: 14, at: '2026-10-05T00:00:00.000Z', done: false },+ { day: 21, at: '2026-10-12T00:00:00.000Z', done: false },+ { day: 28, at: '2026-10-19T00:00:00.000Z', done: enabled },+ ],+ nextRun: null,+});+const latestRun: AutoAuditRun = {+ id: 'run-1',+ day: 28,+ status: 'completed',+ startedAt: '2026-10-19T06:00:00.000Z',+ finishedAt: '2026-10-19T06:40:00.000Z',+ pages: 5,+ completed: 5,+ running: 0,+ criticalIssues: 12,+};++async function render(+ canManage = true,+ timing?: { schedule: AuditAutoStatus; latestRun: AutoAuditRun | null },+) {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">@@ -46,6 +81,9 @@ async function render(canManage = true) {onOpenChange={onOpenChange}canManage={canManage}onSaved={onSaved}+ schedule={timing?.schedule}+ latestRun={timing?.latestRun}+ now={new Date('2026-10-19T12:00:00Z')}/></NextIntlClientProvider>,);@@ -145,6 +183,22 @@ describe('AuditSettingsDialog', () => {expect(dialog().textContent).toContain('No pinned pages. Pin them from Opportunities.');});+ it('says when the last run was and when the next one is', async () => {+ await render(true, { schedule: schedule(), latestRun });+ expect(dialog().textContent).toContain('Last run Oct 19 · Next run Oct 22');+ });++ it('says when the first run is once auto-audit is turned on, and nothing while off', async () => {+ actions.getAuditSettings.mockResolvedValue(+ settings({ autoAudit: { enabled: false, setting: false, perRun: 5, limit: 100 } }),+ );+ await render(true, { schedule: schedule(false), latestRun: null });+ expect(dialog().textContent).not.toContain('run Oct');+ act(() => (dialog().querySelector('#audit-auto') as HTMLElement).click());+ // Day 28's turn has started without it: the next daily sweep takes it.+ expect(dialog().textContent).toContain('First run within a day');+ });+it('says what a plan without a monthly limit runs', async () => {actions.getAuditSettings.mockResolvedValue(settings({ autoAudit: { enabled: false, setting: null, perRun: 25, limit: -1 } }),diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsxindex 8fa8c97ec..439614c20 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsx@@ -20,10 +20,13 @@ import {getAuditSettings,saveAuditSettings,setOpportunityPrefs,+ type AuditAutoStatus,type AuditSettings,type AuditSettingsChanges,+ type AutoAuditRun,} from '@/lib/actions/audits';-import { formatNumber } from '@/lib/format';+import { nextAutoRun } from '@/lib/audit-auto-runs';+import { formatMonthDay, formatNumber } from '@/lib/format';/** One pattern per line, blank lines dropped. */export function parsePatterns(text: string): string[] {@@ -53,7 +56,9 @@ function Section({ title, children }: { title: string; children: React.ReactNode/*** Site Audit › Settings (SA-006): the organization's auto-audit switch and* e-mail, the brand's exclude patterns and its pinned pages. Admins and- * managers change them; everyone else reads them.+ * managers change them; everyone else reads them. With the page's quota, the+ * switch also says when the runs happen: the last one and the next (the+ * first, when it was just turned on).*/export function AuditSettingsDialog({brandId,@@ -61,6 +66,9 @@ export function AuditSettingsDialog({onOpenChange,canManage,onSaved,+ schedule,+ latestRun,+ now,}: {brandId: string;open: boolean;@@ -68,6 +76,11 @@ export function AuditSettingsDialog({canManage: boolean;/** Read the page's quota and inbox again: the reserved share or the inbox may change. */onSaved: () => void;+ /** Where auto-audit stands this billing month (the quota's). */+ schedule?: AuditAutoStatus | null;+ /** The latest run on this brand's pages. */+ latestRun?: AutoAuditRun | null;+ now?: Date;}) {const t = useTranslations('audit.settings');const [settings, setSettings] = useState<AuditSettings | null>(null);@@ -159,6 +172,20 @@ export function AuditSettingsDialog({}): t('autoAuditOff', { limit: formatNumber(auto.limit) });+ const timing: string[] = [];+ if (auto && autoAudit && schedule && now) {+ if (latestRun) {+ timing.push(+ latestRun.status === 'running'+ ? t('runningNow')+ : t('lastRun', { date: formatMonthDay(latestRun.startedAt) }),+ );+ }+ const next = nextAutoRun(schedule, now);+ const date = next.soon ? t('withinADay') : formatMonthDay(next.at);+ timing.push(auto.enabled ? t('nextRun', { date }) : t('firstRun', { date }));+ }+return (<Dialog open={open} onOpenChange={onOpenChange}><DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg">@@ -185,6 +212,9 @@ export function AuditSettingsDialog({<div className="space-y-0.5"><Label htmlFor="audit-auto">{t('autoAuditLabel')}</Label><p className="text-xs text-muted-foreground">{autoLine}</p>+ {timing.length > 0 && (+ <p className="text-xs font-medium text-foreground">{timing.join(' · ')}</p>+ )}<p className="text-xs text-muted-foreground">{t('orgWide')}</p></div></div>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_summary-strip.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_summary-strip.test.tsxindex adafa8ace..eb4f6de06 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_summary-strip.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_summary-strip.test.tsx@@ -37,10 +37,21 @@ const auto = (over: Partial<AuditAutoStatus> = {}): AuditAutoStatus => ({running: 0,periodStart: '2026-10-01T00:00:00.000Z',periodEnd: '2026-11-01T00:00:00.000Z',- runs: [],- nextRun: { day: 28, at: new Date(2026, 9, 28, 0, 0).toISOString() },+ // Four runs done, day 28's still to come.+ runs: [1, 7, 14, 21, 28].map((day) => ({+ day,+ at: `2026-10-${String(day).padStart(2, '0')}T00:00:00.000Z`,+ done: day < 28,+ })),+ nextRun: { day: 28, at: '2026-10-28T00:00:00.000Z' },...over,});+const runs = (done: (day: number) => boolean) =>+ [1, 7, 14, 21, 28].map((day) => ({+ day,+ at: `2026-10-${String(day).padStart(2, '0')}T00:00:00.000Z`,+ done: done(day),+ }));const quota = (a: AuditAutoStatus | undefined): AuditQuota => ({used: 250,@@ -97,13 +108,14 @@ describe('AuditSummaryStrip', () => {expect(container.textContent).toContain('ansvisor.com');});- it('says today, or the date further out, and when auto-audit is off', () => {- render(overview(), quota(auto({ nextRun: { day: 21, at: NOW.toISOString() } })));- expect(items()[3]).toBe('Next auto-audit today · 25 pages');- render(- overview(),- quota(auto({ nextRun: { day: 1, at: new Date(2026, 10, 1, 0, 0).toISOString() } })),- );+ it("says within a day while a run's turn has started without it, not today", () => {+ // Day 21's turn lasts until day 28, and it hasn't run (turned on after the sweep).+ render(overview(), quota(auto({ runs: runs((day) => day < 21) })));+ expect(items()[3]).toBe('Next auto-audit within a day · 25 pages');+ });++ it("gives next month's first run once this month's runs are over, and says when it's off", () => {+ render(overview(), quota(auto({ runs: runs(() => true), nextRun: null })));expect(items()[3]).toBe('Next auto-audit on Nov 1 · 25 pages');render(overview(), quota(auto({ enabled: false })));expect(items()[3]).toBe('Auto-audit off');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_summary-strip.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_summary-strip.tsxindex 60ba08534..4c6eebd69 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_summary-strip.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_summary-strip.tsx@@ -4,6 +4,7 @@ import { Fragment } from 'react';import { useTranslations } from 'next-intl';import { CATEGORY_META, pct } from '@/components/audit/audit-report';import type { AuditOverview, AuditQuota } from '@/lib/actions/audits';+import { nextAutoRun } from '@/lib/audit-auto-runs';import { formatMonthDay } from '@/lib/format';import { cn } from '@/lib/utils';@@ -63,14 +64,18 @@ export function AuditSummaryStrip({);}const auto = quota?.auto;- if (auto?.enabled && auto.nextRun) {- const days = daysUntil(auto.nextRun.at, now);- const when =- days <= 0+ if (auto?.enabled) {+ // This month's next run, else next month's first; within a day when its+ // turn has started without it (the next daily sweep takes it).+ const next = nextAutoRun(auto, now);+ const days = daysUntil(next.at, now);+ const when = next.soon+ ? t('withinADay')+ : days <= 0? t('today'): days === 1? t('tomorrow')- : t('onDate', { date: formatMonthDay(auto.nextRun.at) });+ : t('onDate', { date: formatMonthDay(next.at) });items.push(t.rich('nextAuto', { b, when, count: auto.perRun }));} else if (auto && !auto.enabled) {items.push(t('autoOff'));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsxindex 2bc1e19d7..baecf32d3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx@@ -58,6 +58,7 @@ import { AutoRunNotice } from './_auto-run-notice';import { AuditSummaryStrip } from './_summary-strip';import { EmptyPoolMessage } from './_quota-meter';import { usePagesExport } from './_use-pages-export';+import { nextAutoRun } from '@/lib/audit-auto-runs';import { cn } from '@/lib/utils';type RangePreset = '7d' | '30d' | '90d' | 'all';@@ -159,6 +160,14 @@ export default function SiteAuditPage() {const refetch = () => setRefreshKey((k: number) => k + 1);+ // The run notice's View pages: the Pages list, latest audits first, so the+ // run's pages lead it (tagged Auto).+ const listsRef = useRef<HTMLDivElement>(null);+ const showPages = () => {+ setTab('pages');+ listsRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });+ };+// Load the audited pages + the monthly quota + the primary-domain trend.useEffect(() => {if (!activeBrandId) return;@@ -550,6 +559,9 @@ export default function SiteAuditPage() {console.error('Failed to refresh after saving the settings:', err),)}+ schedule={quota?.auto ?? null}+ latestRun={latestRun}+ now={new Date(nowMs)}/>{/* Summary strip, as in the v2 mockup (SA-019) */}@@ -600,7 +612,8 @@ export default function SiteAuditPage() {key={activeBrandId}brandId={activeBrandId}run={latestRun}- nextRunAt={quota?.auto?.enabled ? (quota.auto.nextRun?.at ?? null) : null}+ nextRun={quota?.auto?.enabled ? nextAutoRun(quota.auto, new Date(nowMs)) : null}+ onViewPages={showPages}/>{/* KPI cards, as in the v2 mockup (SA-018) */}@@ -608,6 +621,7 @@ export default function SiteAuditPage() {<AuditOverviewCardsoverview={loading ? null : overview}quota={quota}+ now={new Date(nowMs)}onOpenSettings={() => setSettingsOpen(true)}/>)}@@ -755,7 +769,7 @@ export default function SiteAuditPage() {</CardContent></Card>) : (- <Tabs value={tab ?? 'pages'} onValueChange={(v) => setTab(v as ListTab)}>+ <Tabs ref={listsRef} value={tab ?? 'pages'} onValueChange={(v) => setTab(v as ListTab)}><TabsList variant="line" aria-label={t('lists.label')}>{opps && (<TabsTrigger value="opportunities">diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.tsindex be31afd9e..56285d905 100644--- a/web/src/lib/actions/audits.ts+++ b/web/src/lib/actions/audits.ts@@ -161,6 +161,8 @@ export interface AuditedPage {previousScore: number | null;status: AuditedPageStatus;lastAuditedAt: string;+ /** Whether the audit the row opens was an auto-audit run's (SA-006) or a user's. */+ lastAuditSource?: 'user' | 'auto';/** Latest completed scores, oldest first. */trend: number[];/** Failed and warning signals in the latest completed audit. */diff --git a/web/src/lib/audit-auto-runs.test.ts b/web/src/lib/audit-auto-runs.test.tsnew file mode 100644index 000000000..0a27e26d4--- /dev/null+++ b/web/src/lib/audit-auto-runs.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest';+import { autoRunStates, nextAutoRun } from './audit-auto-runs';++// A billing month from Sep 22 to Oct 22: runs on its days 1, 7, 14, 21 and 28.+const schedule = (done: number[] = []) => ({+ periodEnd: '2026-10-22T00:00:00.000Z',+ runs: [+ { day: 1, at: '2026-09-22T00:00:00.000Z' },+ { day: 7, at: '2026-09-28T00:00:00.000Z' },+ { day: 14, at: '2026-10-05T00:00:00.000Z' },+ { day: 21, at: '2026-10-12T00:00:00.000Z' },+ { day: 28, at: '2026-10-19T00:00:00.000Z' },+ ].map((run) => ({ ...run, done: done.includes(run.day) })),+});++describe('autoRunStates', () => {+ it('marks the runs whose turn ended without a run as missed, not upcoming', () => {+ const states = autoRunStates(schedule([28]), new Date('2026-10-19T12:00:00Z'));+ expect(states.map((r) => r.state)).toEqual(['missed', 'missed', 'missed', 'missed', 'done']);+ });++ it('marks the first run still to come as next and the rest as upcoming', () => {+ const states = autoRunStates(schedule([1]), new Date('2026-09-25T12:00:00Z'));+ expect(states.map((r) => r.state)).toEqual([+ 'done',+ 'next',+ 'upcoming',+ 'upcoming',+ 'upcoming',+ ]);+ });++ it('keeps a run next while its turn lasts, before the sweep records it', () => {+ const states = autoRunStates(schedule([1]), new Date('2026-09-30T12:00:00Z'));+ expect(states.map((r) => r.state)).toEqual([+ 'done',+ 'next',+ 'upcoming',+ 'upcoming',+ 'upcoming',+ ]);+ });+});++describe('nextAutoRun', () => {+ it("is the next billing month's first run once this month's runs are over", () => {+ expect(nextAutoRun(schedule([28]), new Date('2026-10-19T12:00:00Z'))).toEqual({+ at: '2026-10-22T00:00:00.000Z',+ soon: false,+ });+ });++ it('is the next run of this month when one is still to come', () => {+ expect(nextAutoRun(schedule([1]), new Date('2026-09-25T12:00:00Z'))).toEqual({+ at: '2026-09-28T00:00:00.000Z',+ soon: false,+ });+ });++ it("is soon, not today, while a run's turn has started but it hasn't run", () => {+ // Turned on after day 7's morning sweep: the next sweep takes it.+ expect(nextAutoRun(schedule([1]), new Date('2026-09-30T12:00:00Z'))).toEqual({+ at: '2026-09-28T00:00:00.000Z',+ soon: true,+ });+ });+});diff --git a/web/src/lib/audit-auto-runs.ts b/web/src/lib/audit-auto-runs.tsnew file mode 100644index 000000000..9b3c261ad--- /dev/null+++ b/web/src/lib/audit-auto-runs.ts@@ -0,0 +1,58 @@+import type { AuditAutoStatus } from '@/lib/actions/audits';++/**+ * Where an auto-audit run of the billing month stands (SA-006): done once+ * recorded; missed when its turn ended without a run (auto-audit was off+ * then, or not out yet); next for the first one still to come; upcoming+ * after it.+ */+export type AutoRunState = 'done' | 'missed' | 'next' | 'upcoming';++type AutoSchedule = Pick<AuditAutoStatus, 'runs' | 'periodEnd'>;++/** A run's turn lasts until the next one starts, the last one's until the month ends (auto-audit.js). */+const turnEnds = (auto: AutoSchedule) =>+ auto.runs.map((_, i) => Date.parse(auto.runs[i + 1]?.at ?? auto.periodEnd));++/** The month's five runs with their state at `now`, for the quota card's dots. */+export function autoRunStates(+ auto: AutoSchedule,+ now: Date,+): { day: number; at: string; state: AutoRunState }[] {+ const ends = turnEnds(auto);+ let nextFound = false;+ return auto.runs.map((run, i) => {+ let state: AutoRunState = 'upcoming';+ if (run.done) state = 'done';+ else if (ends[i] <= now.getTime()) state = 'missed';+ else if (!nextFound) {+ state = 'next';+ nextFound = true;+ }+ return { day: run.day, at: run.at, state };+ });+}++export interface NextAutoRun {+ /** The day its turn starts: this month's next run, or next month's first. */+ at: string;+ /**+ * Its turn has started but it hasn't run: auto-audit was turned on after+ * that morning's sweep, say. The next daily sweep takes it, within a day,+ * so it isn't "today".+ */+ soon: boolean;+}++/**+ * The next run: the first of this month still to come, else the next+ * billing month's first, on the day this one ends. Counted whether or not+ * auto-audit is on, so turning it on can say when it starts.+ */+export function nextAutoRun(auto: AutoSchedule, now: Date): NextAutoRun {+ const ends = turnEnds(auto);+ const i = auto.runs.findIndex((run, j) => !run.done && ends[j] > now.getTime());+ if (i === -1) return { at: auto.periodEnd, soon: false };+ const { at } = auto.runs[i];+ return { at, soon: Date.parse(at) <= now.getTime() };+}diff --git a/web/src/lib/format.ts b/web/src/lib/format.tsindex f657e9376..1688154a6 100644--- a/web/src/lib/format.ts+++ b/web/src/lib/format.ts@@ -32,8 +32,8 @@ export function formatDate(iso: string | null): string {}/** "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' });+export function formatMonthDay(iso: string, timeZone?: string): string {+ return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone });}/** "Oct 17, 2026, 2:05 PM": a date with its time, for runs on the same day. */