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
perf(traffic): read the AI Traffic page's data side by side, behind one spinner (#1216)
Cihanf0940eb74563
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 5d795f490..35ac8e091 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3376,6 +3376,7 @@"newSignalGainLost": "Completed earlier, but the gain did not hold: visibility on these prompts was {after}% after the work and is {now}% now."},"traffic": {+ "loadingRange": "Loading the selected range","title": "AI Traffic Analytics","description": "Track which AI bots are crawling your website.","totalCrawls": "Total Crawls",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.test.tsxindex 45cd14081..b85c49b17 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.test.tsx@@ -15,10 +15,12 @@ const getBotConnections = vi.fn();const createBotConnection = vi.fn();const revokeBotConnection = vi.fn();vi.mock('@/lib/actions/ai-bots', () => ({- getBotConnections: (...a: unknown[]) => getBotConnections(...a),createBotConnection: (...a: unknown[]) => createBotConnection(...a),revokeBotConnection: (...a: unknown[]) => revokeBotConnection(...a),}));+vi.mock('@/lib/traffic-reads', () => ({+ getBotConnections: (...a: unknown[]) => getBotConnections(...a),+}));vi.mock('@/i18n/navigation', () => ({Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,}));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.tsxindex 5b580cfa5..7840631e3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-connect.tsx@@ -26,13 +26,13 @@ import {} from '@/lib/ai-bots';import {createBotConnection,- getBotConnections,revokeBotConnection,type BotConnectionKind,type BotConnections,type NewBotConnection,} from '@/lib/actions/ai-bots';import { SourceCard } from './_source-card';+import { getBotConnections } from '@/lib/traffic-reads';const KINDS: BotConnectionKind[] = ['cloudflare_worker', 'cloudflare_logpush', 'vercel_drain'];diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.test.tsxindex f6e3784a0..e040933ce 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.test.tsx@@ -15,12 +15,13 @@ import type { TrafficBots, TrafficDateWindow } from '@/lib/actions/traffic';const getBotConnections = vi.fn();const createBotConnection = vi.fn();vi.mock('@/lib/actions/ai-bots', () => ({- getBotConnections: (...a: unknown[]) => getBotConnections(...a),createBotConnection: (...a: unknown[]) => createBotConnection(...a),revokeBotConnection: vi.fn(),}));const getTrafficBots = vi.fn();-vi.mock('@/lib/actions/traffic', () => ({+vi.mock('@/lib/actions/traffic', () => ({}));+vi.mock('@/lib/traffic-reads', () => ({+ getBotConnections: (...a: unknown[]) => getBotConnections(...a),getTrafficBots: (...a: unknown[]) => getTrafficBots(...a),}));vi.mock('@/i18n/navigation', () => ({diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.tsxindex 4090d9286..6b90e31cb 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_bots-report.tsx@@ -22,15 +22,12 @@ import { formatNumber } from '@/lib/format';import { formatRelative } from '@/lib/format-relative';import { botName } from '@/lib/ai-bot-names';import { botReportState, logsPausedUntil, rowsPausedUntil, sampleBotTypes } from '@/lib/ai-bots';-import { getBotConnections, type BotConnections } from '@/lib/actions/ai-bots';-import {- getTrafficBots,- type BotTypeRow,- type TrafficBots,- type TrafficDateWindow,-} from '@/lib/actions/traffic';+import { type BotConnections } from '@/lib/actions/ai-bots';+import { type BotTypeRow, type TrafficBots, type TrafficDateWindow } from '@/lib/actions/traffic';import { formatTrafficBucketDate } from './_charts';import { BotsDialog } from './_bots-connect';+import { getBotConnections, getTrafficBots } from '@/lib/traffic-reads';+import { useRangeReady } from './_range-ready';/** Where Upgrade goes, as on the Prompts page's usage cards. */const PLAN_PAGE = '/dashboard/settings?tab=billing';@@ -223,10 +220,12 @@ export function BotsReportSection({const t = useTranslations('traffic.botReport');const tBots = useTranslations('traffic.bots');const key = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}|${revision}`;- const [loaded, setLoaded] = useState<{+ // The connections don't depend on the range: read again only on a change.+ const infoKey = `${brandId}|${revision}`;+ const [loaded, setLoaded] = useState<{ key: string; report: TrafficBots | null } | null>(null);+ const [connections, setConnections] = useState<{key: string;info: BotConnections | null;- report: TrafficBots | null;/** The last connections read without an error, for the dialog. */lastInfo: BotConnections | null;} | null>(null);@@ -235,31 +234,47 @@ export function BotsReportSection({useEffect(() => {let cancelled = false;- Promise.all([- getBotConnections(brandId).catch(() => ({ error: 'failed' })),- getTrafficBots(brandId, dateWindow).catch((err) => {+ getBotConnections(brandId)+ .catch(() => ({ error: 'failed' }))+ .then((result) => {+ if (cancelled) return;+ const info = 'error' in result ? null : result;+ setConnections((prev) => ({+ key: infoKey,+ info,+ lastInfo: info ?? prev?.lastInfo ?? null,+ }));+ });+ return () => {+ cancelled = true;+ };+ }, [brandId, infoKey]);++ useEffect(() => {+ let cancelled = false;+ getTrafficBots(brandId, dateWindow)+ .catch((err) => {// Best effort: the rest of the page doesn't depend on this section.console.error('Failed to load the AI bot report:', err);return null;- }),- ]).then(([result, report]) => {- if (cancelled) return;- const info = 'error' in result ? null : result;- setLoaded((prev) => ({ key, info, report, lastInfo: info ?? prev?.lastInfo ?? null }));- });+ })+ .then((report) => {+ if (!cancelled) setLoaded({ key, report });+ });return () => {cancelled = true;};}, [brandId, dateWindow, key]);- const current = loaded?.key === key ? loaded : null;- const info = current?.info ?? null;- const report = current?.report ?? null;+ const ready = loaded?.key === key && connections?.key === infoKey;+ useRangeReady('botsReport', ready);+ const info = ready ? (connections?.info ?? null) : null;+ const report = ready ? (loaded?.report ?? null) : null;// The dialog keeps the connections it was opened with while the section// reads again after a change it made (the page bumps `revision`), and when// that read fails: taken down, it would lose the new connection's secret// and settings.- const dialogInfo = info ?? loaded?.lastInfo ?? null;+ const dialogInfo = info ?? connections?.lastInfo ?? null;const state = info ? botReportState(info, report) : null;const pausedUntil = info ? rowsPausedUntil(info.usage) : null;// Past the raw cap log files aren't read: the report stops mid-month.@@ -311,7 +326,7 @@ export function BotsReportSection({</div>);- const body = !current ? (+ const body = !ready ? (<div className="px-6 py-4"><Skeleton className="h-4 w-56" /></div>@@ -347,7 +362,7 @@ export function BotsReportSection({</div><div className={cn('grid grid-cols-1 gap-4', state === 'data' && 'xl:grid-cols-2')}>- <Card className={cn(!current && 'opacity-80')} aria-busy={!current}>+ <Card className={cn(!ready && 'opacity-80')} aria-busy={!ready}><CardHeader className="pb-2"><div className="flex items-center justify-between gap-2"><CardTitle className="text-sm font-medium">{t('typesTitle')}</CardTitle>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.test.tsxindex 490373c51..0c372b4f2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.test.tsx@@ -14,7 +14,8 @@ import type { TrafficConversions, TrafficDateWindow } from '@/lib/actions/traffi*/const getTrafficConversions = vi.fn();-vi.mock('@/lib/actions/traffic', () => ({+vi.mock('@/lib/actions/traffic', () => ({}));+vi.mock('@/lib/traffic-reads', () => ({getTrafficConversions: (...args: unknown[]) => getTrafficConversions(...args),}));vi.mock('@/hooks/use-integration-connect', () => ({diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.tsxindex b587942a1..3a470212d 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_conversions.tsx@@ -20,12 +20,10 @@ import { getPlatformName } from '@/lib/traffic-platforms';import { conversionRate, type ConversionFigures } from '@/lib/traffic-conversions';import { googleSourceStatus } from '@/lib/traffic-sources';import type { SourceState } from '@/lib/actions/integrations';-import {- getTrafficConversions,- type TrafficConversions,- type TrafficDateWindow,-} from '@/lib/actions/traffic';+import { type TrafficConversions, type TrafficDateWindow } from '@/lib/actions/traffic';import { NeedsTag, SourceUnavailable } from './_source-gate';+import { getTrafficConversions } from '@/lib/traffic-reads';+import { useRangeReady } from './_range-ready';/*** Where AI visitors convert (AT-014, spec §3.4b): which landing pages turn@@ -139,6 +137,7 @@ export function ConversionsSection({cancelled = true;};}, [brandId, dateWindow, key, gaReady]);+ useRangeReady('conversions', !gaReady || loaded?.key === key);const current = loaded?.key === key ? loaded : null;const result = current?.result ?? null;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsxindex 28a4a9639..75b1faca2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsx@@ -14,7 +14,8 @@ import type { TrafficDateWindow, TrafficGooglePages } from '@/lib/actions/traffi*/const getTrafficGooglePages = vi.fn();-vi.mock('@/lib/actions/traffic', () => ({+vi.mock('@/lib/actions/traffic', () => ({}));+vi.mock('@/lib/traffic-reads', () => ({getTrafficGooglePages: (...args: unknown[]) => getTrafficGooglePages(...args),}));vi.mock('@/hooks/use-integration-connect', () => ({diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsxindex 21d704eb7..b2e5d19b9 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsx@@ -22,15 +22,13 @@ import { formatNumber } from '@/lib/format';import { googleSourceStatus } from '@/lib/traffic-sources';import type { SourceState } from '@/lib/actions/integrations';import { GOOGLE_PAGES_MIN_IMPRESSIONS, ctrPct, impressionsRise } from '@/lib/traffic-google-pages';-import {- getTrafficGooglePages,- type TrafficDateWindow,- type TrafficGooglePages,-} from '@/lib/actions/traffic';+import { type TrafficDateWindow, type TrafficGooglePages } from '@/lib/actions/traffic';import { formatTrafficBucketDate } from './_charts';import { PagePromptsDialog } from './_page-prompts-dialog';import { NeedsTag, SourceUnavailable } from './_source-gate';import { UntrackedQueriesCard } from './_untracked-queries';+import { getTrafficGooglePages } from '@/lib/traffic-reads';+import { useRangeReady } from './_range-ready';/** CTR as the table shows it: "3.1%". */function ctr(clicks: number, impressions: number): string {@@ -118,6 +116,7 @@ export function GoogleSection({};}, [brandId, dateWindow, key, gscReady, reloads]);+ useRangeReady('googleSection', !gscReady || loaded?.key === key);const current = loaded?.key === key ? loaded : null;const result = current?.result ?? null;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.test.tsxindex 58af33ecf..c4860d1bf 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.test.tsx@@ -13,7 +13,8 @@ import type { GoogleTrendPoint } from '@/lib/traffic-google-trend';*/const getTrafficGoogleTrend = vi.fn();-vi.mock('@/lib/actions/traffic', () => ({+vi.mock('@/lib/actions/traffic', () => ({}));+vi.mock('@/lib/traffic-reads', () => ({getTrafficGoogleTrend: (...args: unknown[]) => getTrafficGoogleTrend(...args),}));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.tsxindex 148ff58d6..1e756d458 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-trend.tsx@@ -6,11 +6,9 @@ import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';import { formatTrafficBucketDate, GoogleTrendChart } from './_charts';import { googleTrend, googleTrendDays } from '@/lib/traffic-google-trend';-import {- getTrafficGoogleTrend,- type TrafficGoogleTrend,- type TrafficTrendPoint,-} from '@/lib/actions/traffic';+import { type TrafficGoogleTrend, type TrafficTrendPoint } from '@/lib/actions/traffic';+import { getTrafficGoogleTrend } from '@/lib/traffic-reads';+import { useRangeReady } from './_range-ready';/** Search Console's part when it isn't connected: no clicks, no days. */const NO_GOOGLE = { clicks: [], firstDay: null, lastDay: null };@@ -69,6 +67,7 @@ export function GoogleTrendView({cancelled = true;};}, [brandId, since, until, key]);+ useRangeReady('googleTrend', !since || !until || loaded?.key === key);if (days === null) {return (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsxindex 71793d5ab..2f1301134 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx@@ -24,11 +24,13 @@ const getTrafficPages = vi.fn(async () => ({counts: { noAiTraffic: 0, citedNotClicked: 0, trafficNoPrompt: 0, all: 0 },rows: [],}));-vi.mock('@/lib/actions/traffic', () => ({+vi.mock('@/lib/actions/traffic', () => ({}));+vi.mock('@/lib/traffic-reads', () => ({getTrafficGoogleTotals: (...args: unknown[]) => getTrafficGoogleTotals(...args),- getTrafficPages: (...args: unknown[]) => getTrafficPages(...(args as [])),+ getTrafficPageCounts: async (...args: unknown[]) =>+ (await getTrafficPages(...(args as []))).counts,// The summary line's untracked Google queries (AT-009): tested with the line.- getUntrackedGoogleQueries: async () => ({ count: 0, capped: false, rows: [] }),+ getUntrackedQueryCount: async () => ({ count: 0, capped: false }),}));const connect = vi.fn();vi.mock('@/hooks/use-integration-connect', () => ({diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsxindex 5ec76f798..92e6ccea8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx@@ -14,7 +14,6 @@ import {} from 'lucide-react';import type { DateRangePreset } from '@/components/filters/date-range-filter';import {- getTrafficGoogleTotals,type TrafficDateWindow,type TrafficGoogleTotals,type TrafficSources,@@ -37,6 +36,8 @@ import { MetricCard } from '../insights/_kpi-cards';import { SummaryLine } from './_summary-line';import type { Change } from '../insights/kpi-format';import { SourceKpiCard } from './_source-gate';+import { getTrafficGoogleTotals } from '@/lib/traffic-reads';+import { useRangeReady } from './_range-ready';// Four in a row from 1,100px, two below (spec §3.2), one on a phone. In rem,// so Tailwind orders it after sm: (a px breakpoint would sort before it).@@ -161,6 +162,7 @@ export function TrafficKpis({cancelled = true;};}, [brandId, dateWindow, gaReady, gscReady, latestDays, key]);+ useRangeReady('kpis', (!gaReady && !gscReady) || loaded?.key === key);const totalVisits = summary?.totalVisits ?? 0;const totalVisitsPrev = summary?.totalVisitsPrev ?? 0;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsxindex cc585a4f8..cbd45a7e8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsx@@ -32,9 +32,11 @@ const toast = vi.hoisted(() => ({info: vi.fn(),}));vi.mock('@/lib/actions/traffic', () => ({- getTrafficPages: (...args: unknown[]) => getTrafficPages(...args),sendTrafficPagesToActionCenter: (...args: unknown[]) => sendTrafficPagesToActionCenter(...args),}));+vi.mock('@/lib/traffic-reads', () => ({+ getTrafficPages: (...args: unknown[]) => getTrafficPages(...args),+}));vi.mock('@/lib/actions/audits', () => ({runAudit: (...args: unknown[]) => runAudit(...args),runAuditsBulk: (...args: unknown[]) => runAuditsBulk(...args),diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsxindex 7c09c3faa..0e22cea84 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx@@ -30,7 +30,6 @@ import { formatRelative } from '@/lib/format-relative';import { getPlatformName } from '@/lib/traffic-platforms';import { citationState, pageStatuses, pageUrl } from '@/lib/traffic-pages';import {- getTrafficPages,type TrafficBrokenLink,type TrafficDateWindow,type TrafficPageRow,@@ -41,6 +40,8 @@ import {import { runAudit } from '@/lib/actions/audits';import { PAGE_ACTION_MAX, auditBlock, usePageActions } from './_use-page-actions';import { PagePromptsDialog } from './_page-prompts-dialog';+import { getTrafficPages } from '@/lib/traffic-reads';+import { useRangeReady } from './_range-ready';/*** Pages: which answers send visitors (AT-006, spec §3.5, "the@@ -231,6 +232,7 @@ export function PagesCard({cancelled = true;};}, [brandId, dateWindow, tab, limit, key]);+ useRangeReady('pagesCard', loaded?.key === key);const result = loaded?.result ?? null;const stale = loaded !== null && loaded.key !== key;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_range-ready.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_range-ready.test.tsxnew file mode 100644index 000000000..ec021371b--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_range-ready.test.tsx@@ -0,0 +1,110 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { RangeReadyProvider, rangeKeyOf, useRangeGate, useRangeReady } from './_range-ready';++/**+ * A new range on the AI Traffic page shows only a spinner until the page and+ * every section have its data; a settled range stays shown.+ */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++function Section({ id, ready }: { id: string; ready: boolean }) {+ useRangeReady(id, ready);+ return null;+}++function Page({+ range,+ own,+ sections,+}: {+ range: string;+ own: boolean;+ sections: Record<string, boolean>;+}) {+ const gate = useRangeGate(range, own);+ return (+ <RangeReadyProvider value={gate.value}>+ <p>{gate.settled ? 'shown' : 'spinner'}</p>+ {Object.entries(sections).map(([id, ready]) => (+ <Section key={id} id={id} ready={ready} />+ ))}+ </RangeReadyProvider>+ );+}++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ vi.useFakeTimers();+ container = document.createElement('div');+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ vi.useRealTimers();+});++const render = async (props: Parameters<typeof Page>[0]) => {+ await act(async () => root.render(<Page {...props} />));+ await act(async () => vi.advanceTimersByTime(1));+ return container.textContent;+};++describe('the range gate', () => {+ it('waits for the page and every section, then shows the range', async () => {+ expect(await render({ range: 'a', own: false, sections: { pages: true } })).toBe('spinner');+ expect(await render({ range: 'a', own: true, sections: { pages: false, bots: true } })).toBe(+ 'spinner',+ );+ expect(await render({ range: 'a', own: true, sections: { pages: true, bots: true } })).toBe(+ 'shown',+ );+ });++ it("doesn't hide a settled range when a section reads again for a tab", async () => {+ await render({ range: 'a', own: true, sections: { pages: true } });+ expect(await render({ range: 'a', own: true, sections: { pages: false } })).toBe('shown');+ });++ it('hides the page again for a new range, until its sections have it', async () => {+ await render({ range: 'a', own: true, sections: { pages: true } });+ // The same render the range changes in: the section still holds range a.+ expect(await render({ range: 'b', own: true, sections: { pages: true } })).toBe('shown');+ // ...because it hadn't said otherwise: a section that has nothing to read+ // for b is ready for b straight away. One still reading keeps it hidden.+ expect(await render({ range: 'c', own: true, sections: { pages: false } })).toBe('spinner');+ expect(await render({ range: 'c', own: true, sections: { pages: true } })).toBe('shown');+ });++ it("shows the page after 10 s even if a read hangs, about the reads' statement timeout", async () => {+ expect(await render({ range: 'a', own: true, sections: { pages: false } })).toBe('spinner');+ await act(async () => vi.advanceTimersByTime(9_000));+ expect(container.textContent).toBe('spinner');+ await act(async () => vi.advanceTimersByTime(1_000));+ expect(container.textContent).toBe('shown');+ });++ // gkhngyk on #1216: All time → 7d → All time while 7d loads showed the old+ // All time state as settled at once, with 7d's data if it had landed.+ it('waits again when the range comes back to one that settled before', async () => {+ await render({ range: 'all', own: true, sections: { pages: true } });+ await render({ range: '7d', own: false, sections: { pages: false } });+ expect(await render({ range: 'all', own: false, sections: { pages: false } })).toBe('spinner');+ expect(await render({ range: 'all', own: true, sections: { pages: true } })).toBe('shown');+ });+});++describe('rangeKeyOf', () => {+ it('names a window by its two ends; all time has none', () => {+ expect(rangeKeyOf({ dateFrom: '2026-10-12T00:00:00Z', dateTo: '2026-10-19T00:00:00Z' })).toBe(+ '2026-10-12T00:00:00Z|2026-10-19T00:00:00Z',+ );+ expect(rangeKeyOf({})).toBe('|');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_range-ready.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_range-ready.tsxnew file mode 100644index 000000000..a857fdac5--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_range-ready.tsx@@ -0,0 +1,98 @@+'use client';++import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import type { TrafficDateWindow } from '@/lib/actions/traffic';++/**+ * Whether the AI Traffic page has every section's data for the range on+ * screen. A new range shows only a spinner until then, rather than one+ * range's numbers beside another's while the sections fill in.+ *+ * Each section says whether it has its data for the current range+ * (useRangeReady); the page (useRangeGate) waits for all of them and its own+ * reads. Once a range has settled it stays settled: a section reading again+ * for a tab or a Track doesn't hide the page.+ */++type Report = (id: string, range: string | null) => void;++const RangeReadyContext = createContext<{+ rangeKey: string;+ report: Report;+ unregister: (id: string) => void;+} | null>(null);++export const RangeReadyProvider = RangeReadyContext.Provider;++/** The range a page's data answers, for comparing one with another. */+export function rangeKeyOf(window: TrafficDateWindow): string {+ return `${window.dateFrom ?? ''}|${window.dateTo ?? ''}`;+}++/**+ * A section says whether it has its data for the page's current range — or+ * has none to read (a source not connected), which is ready too.+ */+export function useRangeReady(id: string, ready: boolean) {+ const ctx = useContext(RangeReadyContext);+ const rangeKey = ctx?.rangeKey ?? null;+ useEffect(() => {+ ctx?.report(id, ready ? rangeKey : null);+ }, [ctx, id, ready, rangeKey]);+ useEffect(() => () => ctx?.unregister(id), [ctx, id]);+}++/**+ * The page's side: settled once its own reads (`ownReady`) and every section+ * that reported have the range. Checked a turn later, so a section mounting+ * in the same render reports first. A read that hangs doesn't keep the page+ * hidden past `maxWaitMs`, about the reads' statement timeout: the section+ * then shows its own loading state.+ */+export function useRangeGate(rangeKey: string, ownReady: boolean, { maxWaitMs = 10_000 } = {}) {+ const reports = useRef(new Map<string, string | null>());+ const [version, setVersion] = useState(0);+ // Each range change waits anew, even back to a range that settled before+ // (All time → 7d → All time): its key alone would read as settled at once,+ // over whatever landed meanwhile.+ const [wait, setWait] = useState({ rangeKey, id: 0 });+ if (wait.rangeKey !== rangeKey) setWait({ rangeKey, id: wait.id + 1 });+ const [settledId, setSettledId] = useState<number | null>(null);++ const report = useCallback<Report>((id, range) => {+ if (reports.current.has(id) && reports.current.get(id) === range) return;+ reports.current.set(id, range);+ setVersion((v) => v + 1);+ }, []);+ const unregister = useCallback((id: string) => {+ if (reports.current.delete(id)) setVersion((v) => v + 1);+ }, []);++ const waitId = wait.id;+ useEffect(() => {+ if (settledId === waitId || !ownReady) return;+ const id = window.setTimeout(() => {+ if ([...reports.current.values()].every((range) => range === rangeKey)) {+ setSettledId(waitId);+ }+ }, 0);+ return () => window.clearTimeout(id);+ }, [rangeKey, waitId, ownReady, version, settledId]);++ useEffect(() => {+ if (settledId === waitId) return;+ const id = window.setTimeout(() => setSettledId(waitId), maxWaitMs);+ return () => window.clearTimeout(id);+ }, [waitId, settledId, maxWaitMs]);++ const value = useMemo(() => ({ rangeKey, report, unregister }), [rangeKey, report, unregister]);+ return { settled: settledId === wait.id && wait.rangeKey === rangeKey, value };+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.test.tsxindex 735c43ea7..b6359bda6 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.test.tsx@@ -20,7 +20,10 @@ vi.mock('@/i18n/navigation', () => ({}));// The AI bots card reads its connections on its own (AT-010, tested in// _bots-connect.test.tsx): here it stays loading.-vi.mock('@/lib/actions/ai-bots', () => ({ getBotConnections: () => new Promise(() => {}) }));+vi.mock('@/lib/actions/ai-bots', () => ({}));+vi.mock('@/lib/traffic-reads', () => ({+ getBotConnections: () => new Promise(() => {}),+}));const { SourcesStrip } = await import('./_sources-strip');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsxindex df35cb381..abdfb002c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsx@@ -13,9 +13,13 @@ import type { TrafficDateWindow, TrafficSummary } from '@/lib/actions/traffic';const getTrafficPages = vi.fn();const getUntrackedGoogleQueries = vi.fn();-vi.mock('@/lib/actions/traffic', () => ({- getTrafficPages: (...args: unknown[]) => getTrafficPages(...args),- getUntrackedGoogleQueries: (...args: unknown[]) => getUntrackedGoogleQueries(...args),+vi.mock('@/lib/actions/traffic', () => ({}));+// The counts the Pages card's and the Google section's reads carry (shared+// in lib/traffic-reads).+vi.mock('@/lib/traffic-reads', () => ({+ getTrafficPageCounts: async (...args: unknown[]) =>+ ((await getTrafficPages(...args)) as ReturnType<typeof cited>).counts,+ getUntrackedQueryCount: (...args: unknown[]) => getUntrackedGoogleQueries(...args),}));const { SummaryLine } = await import('./_summary-line');@@ -98,7 +102,7 @@ const text = () => container.textContent ?? '';describe('SummaryLine', () => {it('says the range in one or two sentences, with Analytics connected', async () => {await render();- expect(getTrafficPages).toHaveBeenCalledWith('b1', WEEK, { tab: 'citedNotClicked', limit: 0 });+ expect(getTrafficPages).toHaveBeenCalledWith('b1', WEEK);expect(text()).toBe('Last 7 days: 64 AI-referred visits, 0.8% of all traffic, up 12% on the previous period. ' +'ChatGPT sent the most (38); Perplexity visitors convert best (16.1% of their visits had a key event). ' +@@ -144,7 +148,7 @@ describe('SummaryLine', () => {it('states the untracked Google queries only with Search Console (AT-009)', async () => {getUntrackedGoogleQueries.mockResolvedValue({ count: 14, capped: false, rows: [] });await render({ gscReady: true });- expect(getUntrackedGoogleQueries).toHaveBeenCalledWith('b1', WEEK, { limit: 0 });+ expect(getUntrackedGoogleQueries).toHaveBeenCalledWith('b1', WEEK);expect(text()).toContain("14 Google queries with clicks aren't tracked as prompts.");// Tracking some from the page counts them again.diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsxindex e63777f07..1c5eae2a8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsx@@ -6,12 +6,9 @@ import { Skeleton } from '@/components/ui/skeleton';import { formatNumber } from '@/lib/format';import { getPlatformName } from '@/lib/traffic-platforms';import { summaryLine } from '@/lib/traffic-summary-line';-import {- getTrafficPages,- getUntrackedGoogleQueries,- type TrafficDateWindow,- type TrafficSummary,-} from '@/lib/actions/traffic';+import { type TrafficDateWindow, type TrafficSummary } from '@/lib/actions/traffic';+import { getTrafficPageCounts, getUntrackedQueryCount } from '@/lib/traffic-reads';+import { useRangeReady } from './_range-ready';/*** The summary line above the KPI cards (AT-007, spec §3.1): the range's@@ -65,7 +62,8 @@ export function SummaryLine({useEffect(() => {if (!gscReady) return;let cancelled = false;- getUntrackedGoogleQueries(brandId, dateWindow, { limit: 0 })+ // The count the Google section's list read carries, when it's on the page.+ getUntrackedQueryCount(brandId, dateWindow).then((queries) => {if (!cancelled) {setUntracked({ key: untrackedKey, count: queries.count, capped: queries.capped });@@ -82,9 +80,10 @@ export function SummaryLine({useEffect(() => {let cancelled = false;- getTrafficPages(brandId, dateWindow, { tab: 'citedNotClicked', limit: 0 })- .then((pages) => {- if (!cancelled) setCited({ key, count: pages.counts.citedNotClicked });+ // The Pages card's read carries every tab's count: shared with it.+ getTrafficPageCounts(brandId, dateWindow)+ .then((counts) => {+ if (!cancelled) setCited({ key, count: counts.citedNotClicked });}).catch(() => {// Best effort: the line still states what else it knows.@@ -95,6 +94,11 @@ export function SummaryLine({};}, [brandId, dateWindow, key]);+ useRangeReady(+ 'summaryLine',+ cited?.key === key && (!gscReady || untracked?.key === untrackedKey),+ );+const citedNow = cited?.key === key ? cited : null;const untrackedNow = gscReady ? (untracked?.key === untrackedKey ? untracked : null) : undefined;if (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.test.tsxindex 76357f61d..fac3a5a6c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.test.tsx@@ -12,7 +12,8 @@ import type { TrafficDateWindow, TrafficUntrackedQueries } from '@/lib/actions/t*/const getUntrackedGoogleQueries = vi.fn();-vi.mock('@/lib/actions/traffic', () => ({+vi.mock('@/lib/actions/traffic', () => ({}));+vi.mock('@/lib/traffic-reads', () => ({getUntrackedGoogleQueries: (...args: unknown[]) => getUntrackedGoogleQueries(...args),}));const getLocationQuota = vi.fn();diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.tsxindex 78e0fba77..28591f905 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.tsx@@ -19,12 +19,10 @@ import { cn } from '@/lib/utils';import { formatNumber } from '@/lib/format';import { getLocationQuota } from '@/lib/actions/prompt';import { trackPagePrompts } from '@/lib/actions/prompt-suggestions';-import {- getUntrackedGoogleQueries,- type TrafficDateWindow,- type TrafficUntrackedQueries,-} from '@/lib/actions/traffic';+import { type TrafficDateWindow, type TrafficUntrackedQueries } from '@/lib/actions/traffic';import { formatTrafficBucketDate } from './_charts';+import { getUntrackedGoogleQueries } from '@/lib/traffic-reads';+import { useRangeReady } from './_range-ready';/*** Prompt slots left on the plan: null when the plan has no cap, or it@@ -65,30 +63,45 @@ export function UntrackedQueriesCard({const [loaded, setLoaded] = useState<{key: string;result: TrafficUntrackedQueries | null;- slotsLeft: number | null;} | null>(null);+ // The prompt slots left don't depend on the range: read again only after+ // a Track.+ const quotaKey = `${brandId}|${reloads}`;+ const [quota, setQuota] = useState<{ key: string; slotsLeft: number | null } | null>(null);const [tracking, setTracking] = useState<Set<string>>(new Set());useEffect(() => {let cancelled = false;- Promise.all([- getUntrackedGoogleQueries(brandId, dateWindow).catch((err) => {+ getUntrackedGoogleQueries(brandId, dateWindow)+ .catch((err) => {// Best effort: the rest of the page doesn't depend on this card.console.error('Failed to load the untracked Google queries:', err);return null;- }),- getLocationQuota(brandId).catch(() => null),- ]).then(([result, quota]) => {- if (!cancelled) setLoaded({ key, result, slotsLeft: slotsLeftOf(quota) });- });+ })+ .then((result) => {+ if (!cancelled) setLoaded({ key, result });+ });return () => {cancelled = true;};}, [brandId, dateWindow, key, reloads]);- const current = loaded?.key === key ? loaded : null;+ useEffect(() => {+ let cancelled = false;+ getLocationQuota(brandId)+ .catch(() => null)+ .then((q) => {+ if (!cancelled) setQuota({ key: quotaKey, slotsLeft: slotsLeftOf(q) });+ });+ return () => {+ cancelled = true;+ };+ }, [brandId, quotaKey]);++ useRangeReady('untrackedQueries', loaded?.key === key && quota?.key === quotaKey);+ const current = loaded?.key === key && quota?.key === quotaKey ? loaded : null;const result = current?.result ?? null;- const slotsLeft = current?.slotsLeft ?? null;+ const slotsLeft = current ? (quota?.slotsLeft ?? null) : null;const busy = tracking.size > 0;const track = async (queries: string[]) => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex d97b06fbc..8cc48aab7 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -21,10 +21,6 @@ import { useTranslations } from 'next-intl';import { useBrandStore } from '@/stores/use-brand-store';import type { Brand } from '@/types';import {- getTrafficSources,- getTrafficSummary,- getTrafficTrend,- getTrafficLogs,type TrafficSources,type TrafficSummary,type TrafficTrendPoint,@@ -38,7 +34,7 @@ import {} from '@/components/filters/date-range-filter';import { PagesCard } from './_pages-card';import { ConversionsSection } from './_conversions';-import { TRAFFIC_KPI_GRID, TrafficKpis } from './_kpis';+import { TrafficKpis } from './_kpis';import { VisitListSourceNote } from './_visit-list-note';import { EngagedCell, KeyEventsCell, PlatformValueNote } from './_platform-value';import { ExportMenu, TableExport, useTrafficExport } from './_export';@@ -50,6 +46,7 @@ import { BotsReportSection } from './_bots-report';import { NeedsTag } from './_source-gate';import { googleSourceStatus, snippetDetected } from '@/lib/traffic-sources';import { useUserRole } from '@/hooks/use-user-role';+import { useLatestRequest } from '@/hooks/use-latest-request';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';@@ -85,6 +82,13 @@ import {SelectTrigger,SelectValue,} from '@/components/ui/select';+import {+ getTrafficLogs,+ getTrafficSources,+ getTrafficSummary,+ getTrafficTrend,+} from '@/lib/traffic-reads';+import { RangeReadyProvider, rangeKeyOf, useRangeGate } from './_range-ready';const PAGE_SIZE = 10;@@ -441,6 +445,10 @@ function TrafficPageContent({ brand }: { brand: Brand }) {const [logsPageviews, setLogsPageviews] = useState(0);const [isLoadingSummary, setIsLoadingSummary] = useState(true);const [isLoadingLogs, setIsLoadingLogs] = useState(false);+ // The range the summary and the visit list on screen answer, read or failed.+ const rangeKey = rangeKeyOf(dateWindow);+ const [summaryRange, setSummaryRange] = useState<string | null>(null);+ const [logsRange, setLogsRange] = useState<string | null>(null);// What feeds the page (AT-001); null while it loads.const [sources, setSources] = useState<TrafficSources | null>(null);// A failed read hides the strip and leaves the snippet code open, as before it.@@ -491,23 +499,37 @@ function TrafficPageContent({ brand }: { brand: Brand }) {return () => window.clearTimeout(id);}, [searchInput]);+ // The reads run side by side (/api/traffic/read), so they can answer out of+ // order: 90d then 24h, or "pri" then "pricing". Only the latest request of+ // each loader sets state.+ const startSummary = useLatestRequest();+ const startLogs = useLatestRequest();+const loadSummary = useCallback(async () => {+ const latest = startSummary();+ const range = rangeKeyOf(dateWindow);setIsLoadingSummary(true);try {const [s, t] = await Promise.all([getTrafficSummary(brand.id, dateWindow),getTrafficTrend(brand.id, dateWindow),]);+ if (!latest()) return;setSummary(s);setTrend(t);} catch (err) {- console.error('Failed to load traffic summary:', err);+ if (latest()) console.error('Failed to load traffic summary:', err);} finally {- setIsLoadingSummary(false);+ if (latest()) {+ setIsLoadingSummary(false);+ setSummaryRange(range);+ }}- }, [brand.id, dateWindow]);+ }, [brand.id, dateWindow, startSummary]);const loadLogs = useCallback(async () => {+ const latest = startLogs();+ const range = rangeKeyOf(dateWindow);setIsLoadingLogs(true);try {const result = await getTrafficLogs(brand.id, {@@ -518,15 +540,19 @@ function TrafficPageContent({ brand }: { brand: Brand }) {dateFrom: dateWindow.dateFrom,dateTo: dateWindow.dateTo,});+ if (!latest()) return;setLogs(result.logs);setLogsTotal(result.total);setLogsPageviews(result.pageviews);} catch (err) {- console.error('Failed to load traffic logs:', err);+ if (latest()) console.error('Failed to load traffic logs:', err);} finally {- setIsLoadingLogs(false);+ if (latest()) {+ setIsLoadingLogs(false);+ setLogsRange(range);+ }}- }, [brand.id, page, filters.platform, filters.search, dateWindow]);+ }, [brand.id, page, filters.platform, filters.search, dateWindow, startLogs]);const handleFiltersChange = useCallback((patch: Partial<TrafficFilters>) => {setPage(0);@@ -548,37 +574,32 @@ function TrafficPageContent({ brand }: { brand: Brand }) {setCustomTo(value);}, []);+ // Apart, so a visit-list page or filter reads only the list.useEffect(() => {- const id = window.setTimeout(() => {- void loadSummary();- void loadLogs();- }, 0);+ const id = window.setTimeout(() => void loadSummary(), 0);+ return () => window.clearTimeout(id);+ }, [loadSummary]);+ useEffect(() => {+ const id = window.setTimeout(() => void loadLogs(), 0);return () => window.clearTimeout(id);- }, [loadSummary, loadLogs]);+ }, [loadLogs]);const primaryDomain = brand.domains.find((d) => d.isPrimary)?.domain ?? brand.domains[0]?.domain;- if (isLoadingSummary && summary === null) {- return (- <div className="space-y-6">- <div>- <Skeleton className="h-8 w-64" />- <Skeleton className="h-4 w-96 mt-2" />- </div>- <div className={TRAFFIC_KPI_GRID}>- {Array.from({ length: 7 }, (_, i) => (- // The cards' own height, so nothing shifts when they arrive.- <Skeleton key={i} className="h-[133px] rounded-xl" />- ))}- </div>- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">- <Skeleton className="h-64 lg:col-span-2" />- <Skeleton className="h-64" />- </div>- </div>- );- }+ // A new range shows only a spinner until the page and every section have+ // its data, rather than one range's numbers beside another's.+ const rangeGate = useRangeGate(+ rangeKey,+ summaryRange === rangeKey && logsRange === rangeKey && (sources !== null || sourcesFailed),+ );+ const rangeSpinner = (+ <div className="flex justify-center py-24" role="status" aria-label={t('loadingRange')}>+ <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />+ </div>+ );+ // No early spinner for the first read: the gate shows it, and the sections+ // stay mounted behind it, so they read alongside the summary.const totalVisits = summary?.totalVisits ?? 0;// From the summary, not the selected range: while a new range loads, the// numbers on screen are still the previous range's.@@ -696,361 +717,380 @@ function TrafficPageContent({ brand }: { brand: Brand }) {</div></div>- {!sourcesFailed && (- <SourcesStrip- brandId={brand.id}- sources={sources}- domain={primaryDomain}- hasTrackingCode={Boolean(brand.trackingCode)}- canConnect={canManage}- onShowCode={() => setCodeOpen(true)}- onConnected={() => void loadSources()}- botsRevision={botsRevision}- onBotsChanged={() => setBotsRevision((n) => n + 1)}- />- )}- {/* The code stays open only while the snippet sends nothing (F3). */}- {(sourcesFailed || (sources && !snippetDetected(sources.snippetLastVisitAt))) && (- <SnippetBanner trackingCode={brand.trackingCode} />- )}- <SnippetDialog trackingCode={brand.trackingCode} open={codeOpen} onOpenChange={setCodeOpen} />-- {trulyEmpty ? (- <Card>- <CardContent className="py-16 text-center">- <Globe className="h-10 w-10 mx-auto text-muted-foreground/50" />- <h3 className="text-lg font-semibold mt-4">{t('noDataTitle')}</h3>- <p className="text-sm text-muted-foreground mt-1 max-w-md mx-auto">- {brand.trackingCode ? t('noVisitsDescription') : t('noDataDescriptionNoSnippet')}- </p>- </CardContent>- </Card>- ) : isEmpty ? (- <NoTrafficForPeriod- rangeLabel={rangeSubLabel}- onReset={() => handleDatePresetChange('all')}- onShowWeek={datePreset === '24h' ? () => handleDatePresetChange('7d') : undefined}- />- ) : null}- {isEmpty && conversionsSection}- {isEmpty && pagesCard}- {isEmpty && googleSection}- {isEmpty && botsSection}- {!isEmpty && (- <>- {/* KPI cards: two rows of four (AT-017, spec §3.2). */}- <TrafficKpis- brandId={brand.id}- rangeLabel={rangeSubLabel}- dateWindow={dateWindow}- preset={datePreset}- summary={summary}- summaryLoading={isLoadingSummary}- sources={sources}- sourcesFailed={sourcesFailed}- canConnect={canManage}- onConnected={() => void loadSources()}- onRangeChange={handleDatePresetChange}- queriesRevision={queriesRevision}+ {!rangeGate.settled && rangeSpinner}+ <RangeReadyProvider value={rangeGate.value}>+ {/* Kept mounted while hidden, so every section reads the new range+ side by side; laid out at full width, so charts measure right. */}+ <div+ className={cn('space-y-6', !rangeGate.settled && 'invisible h-0 overflow-hidden')}+ aria-hidden={!rangeGate.settled || undefined}+ >+ {!sourcesFailed && (+ <SourcesStrip+ brandId={brand.id}+ sources={sources}+ domain={primaryDomain}+ hasTrackingCode={Boolean(brand.trackingCode)}+ canConnect={canManage}+ onShowCode={() => setCodeOpen(true)}+ onConnected={() => void loadSources()}+ botsRevision={botsRevision}+ onBotsChanged={() => setBotsRevision((n) => n + 1)}+ />+ )}+ {/* The code stays open only while the snippet sends nothing (F3). */}+ {(sourcesFailed || (sources && !snippetDetected(sources.snippetLastVisitAt))) && (+ <SnippetBanner trackingCode={brand.trackingCode} />+ )}+ <SnippetDialog+ trackingCode={brand.trackingCode}+ open={codeOpen}+ onOpenChange={setCodeOpen}/>- {/* Charts row */}- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">- <Card className="lg:col-span-2">- <CardHeader className="pb-2">- <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">- <div className="flex items-center gap-2">- <CardTitle className="font-medium text-sm">{trendTitle}</CardTitle>- {trendView === 'google' && <NeedsTag provider="google-search-console" />}- </div>- {/* By platform, or AI visits against Google clicks (AT-008, spec §3.3). */}- <Tabs- value={trendView}- onValueChange={(v) => setTrendView(v as 'platforms' | 'google')}- >- <TabsList variant="line" aria-label={trendTitle}>- <TabsTrigger value="platforms">{tTrend('tabs.platforms')}</TabsTrigger>- <TabsTrigger value="google">{tTrend('tabs.google')}</TabsTrigger>- </TabsList>- </Tabs>- </div>- </CardHeader>- <CardContent>- {trendView === 'google' ? (- <GoogleTrendView- brandId={brand.id}- trend={trend}- rangeStart={dateWindow.dateFrom}- gscConnected={gscConnected}- onShowWeek={() => handleDatePresetChange('7d')}- />- ) : (- <ReferralTrendChart data={trend} analyticsDays={summary?.analyticsDays} />- )}- </CardContent>- </Card>-+ {trulyEmpty ? (<Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">Platform Breakdown</CardTitle>- </CardHeader>- <CardContent>- <PlatformBreakdownChart data={summary?.platformBreakdown ?? []} />+ <CardContent className="py-16 text-center">+ <Globe className="h-10 w-10 mx-auto text-muted-foreground/50" />+ <h3 className="text-lg font-semibold mt-4">{t('noDataTitle')}</h3>+ <p className="text-sm text-muted-foreground mt-1 max-w-md mx-auto">+ {brand.trackingCode ? t('noVisitsDescription') : t('noDataDescriptionNoSnippet')}+ </p></CardContent></Card>- </div>+ ) : isEmpty ? (+ <NoTrafficForPeriod+ rangeLabel={rangeSubLabel}+ onReset={() => handleDatePresetChange('all')}+ onShowWeek={datePreset === '24h' ? () => handleDatePresetChange('7d') : undefined}+ />+ ) : null}+ {!isEmpty && (+ <>+ {/* KPI cards: two rows of four (AT-017, spec §3.2). */}+ <TrafficKpis+ brandId={brand.id}+ rangeLabel={rangeSubLabel}+ dateWindow={dateWindow}+ preset={datePreset}+ summary={summary}+ summaryLoading={isLoadingSummary}+ sources={sources}+ sourcesFailed={sourcesFailed}+ canConnect={canManage}+ onConnected={() => void loadSources()}+ onRangeChange={handleDatePresetChange}+ queriesRevision={queriesRevision}+ />- {/* Tables row: side by side from 1,280px. The platform table's five+ {/* Charts row */}+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">+ <Card className="lg:col-span-2">+ <CardHeader className="pb-2">+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">+ <div className="flex items-center gap-2">+ <CardTitle className="font-medium text-sm">{trendTitle}</CardTitle>+ {trendView === 'google' && <NeedsTag provider="google-search-console" />}+ </div>+ {/* By platform, or AI visits against Google clicks (AT-008, spec §3.3). */}+ <Tabs+ value={trendView}+ onValueChange={(v) => setTrendView(v as 'platforms' | 'google')}+ >+ <TabsList variant="line" aria-label={trendTitle}>+ <TabsTrigger value="platforms">{tTrend('tabs.platforms')}</TabsTrigger>+ <TabsTrigger value="google">{tTrend('tabs.google')}</TabsTrigger>+ </TabsList>+ </Tabs>+ </div>+ </CardHeader>+ <CardContent>+ {trendView === 'google' ? (+ <GoogleTrendView+ brandId={brand.id}+ trend={trend}+ rangeStart={dateWindow.dateFrom}+ gscConnected={gscConnected}+ onShowWeek={() => handleDatePresetChange('7d')}+ />+ ) : (+ <ReferralTrendChart data={trend} analyticsDays={summary?.analyticsDays} />+ )}+ </CardContent>+ </Card>++ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">Platform Breakdown</CardTitle>+ </CardHeader>+ <CardContent>+ <PlatformBreakdownChart data={summary?.platformBreakdown ?? []} />+ </CardContent>+ </Card>+ </div>++ {/* Tables row: side by side from 1,280px. The platform table's fivecolumns (AT-005) need more than half the page below that, andnumeric cells never wrap (spec §3.2). */}- <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">- {/* Platform table */}- <Card>- <CardHeader className="pb-2">- <div className="flex items-center justify-between gap-2">- <CardTitle className="text-sm font-medium">Referrals by Platform</CardTitle>- <TableExport exporter={exporter} section="platforms" />- </div>- </CardHeader>- <CardContent className="p-0">- <Table>- <TableHeader>- <TableRow>- <TableHead className="pl-6">Platform</TableHead>- <TableHead className="text-right">Visits</TableHead>- <TableHead className="text-right">Change</TableHead>- {/* From Google Analytics (AT-005). */}- <TableHead className="text-right">{t('platforms.engaged')}</TableHead>- <TableHead className="text-right pr-6">{t('platforms.keyEvents')}</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {(summary?.platformBreakdown ?? []).map((row) => (- <TableRow key={row.platform} className="hover:bg-muted/50">- <TableCell className="pl-6">- <span className="font-medium text-sm">- {getPlatformName(row.platform)}- </span>- </TableCell>- <TableCell className="text-right font-semibold tabular-nums">- {formatNumber(row.visits)}- </TableCell>- <TableCell className="text-right">- <div className="flex justify-end">- <DeltaBadge- current={row.visits}- previous={row.visitsPrev}- comparable={comparable}- />- </div>- </TableCell>- <TableCell className="text-right">- <EngagedCell analytics={gaMissing ? null : row.analytics} />- </TableCell>- <TableCell className="text-right pr-6">- <KeyEventsCell analytics={gaMissing ? null : row.analytics} />- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- {gaMissing && <PlatformValueNote />}- </CardContent>- </Card>-- {/* Top Pages */}- <Card>- <CardHeader className="pb-2">- <div className="flex items-center justify-between gap-2">- <CardTitle className="text-sm font-medium">Top Landing Pages</CardTitle>- <TableExport exporter={exporter} section="pages" />- </div>- </CardHeader>- <CardContent className="p-0">- <Table>- <TableHeader>- <TableRow>- <TableHead className="pl-6">Page</TableHead>- <TableHead className="text-right">Visits</TableHead>- <TableHead className="text-right">Change</TableHead>- {/* How often tracked AI answers cite the page (AT-006). */}- <TableHead className="text-right pr-6">- {t('pageList.columns.citedInAnswers')}- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {(summary?.topPages ?? []).map((row) => (- <TableRow key={row.url} className="hover:bg-muted/50">- <TableCell className="pl-6 max-w-[200px]">- <span className="font-mono text-xs text-muted-foreground line-clamp-1">- {row.url}- </span>- </TableCell>- <TableCell className="text-right font-semibold tabular-nums text-sm">- {formatNumber(row.visits)}- </TableCell>- <TableCell className="text-right">- <div className="flex justify-end">- <DeltaBadge- current={row.visits}- previous={row.visitsPrev}- comparable={comparable}- />- </div>- </TableCell>- <TableCell className="text-right pr-6 tabular-nums text-sm">- {formatNumber(row.citations)}- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </CardContent>- </Card>- </div>+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">+ {/* Platform table */}+ <Card>+ <CardHeader className="pb-2">+ <div className="flex items-center justify-between gap-2">+ <CardTitle className="text-sm font-medium">Referrals by Platform</CardTitle>+ <TableExport exporter={exporter} section="platforms" />+ </div>+ </CardHeader>+ <CardContent className="p-0">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-6">Platform</TableHead>+ <TableHead className="text-right">Visits</TableHead>+ <TableHead className="text-right">Change</TableHead>+ {/* From Google Analytics (AT-005). */}+ <TableHead className="text-right">{t('platforms.engaged')}</TableHead>+ <TableHead className="text-right pr-6">+ {t('platforms.keyEvents')}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {(summary?.platformBreakdown ?? []).map((row) => (+ <TableRow key={row.platform} className="hover:bg-muted/50">+ <TableCell className="pl-6">+ <span className="font-medium text-sm">+ {getPlatformName(row.platform)}+ </span>+ </TableCell>+ <TableCell className="text-right font-semibold tabular-nums">+ {formatNumber(row.visits)}+ </TableCell>+ <TableCell className="text-right">+ <div className="flex justify-end">+ <DeltaBadge+ current={row.visits}+ previous={row.visitsPrev}+ comparable={comparable}+ />+ </div>+ </TableCell>+ <TableCell className="text-right">+ <EngagedCell analytics={gaMissing ? null : row.analytics} />+ </TableCell>+ <TableCell className="text-right pr-6">+ <KeyEventsCell analytics={gaMissing ? null : row.analytics} />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ {gaMissing && <PlatformValueNote />}+ </CardContent>+ </Card>+ {/* Top Pages */}+ <Card>+ <CardHeader className="pb-2">+ <div className="flex items-center justify-between gap-2">+ <CardTitle className="text-sm font-medium">Top Landing Pages</CardTitle>+ <TableExport exporter={exporter} section="pages" />+ </div>+ </CardHeader>+ <CardContent className="p-0">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-6">Page</TableHead>+ <TableHead className="text-right">Visits</TableHead>+ <TableHead className="text-right">Change</TableHead>+ {/* How often tracked AI answers cite the page (AT-006). */}+ <TableHead className="text-right pr-6">+ {t('pageList.columns.citedInAnswers')}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {(summary?.topPages ?? []).map((row) => (+ <TableRow key={row.url} className="hover:bg-muted/50">+ <TableCell className="pl-6 max-w-[200px]">+ <span className="font-mono text-xs text-muted-foreground line-clamp-1">+ {row.url}+ </span>+ </TableCell>+ <TableCell className="text-right font-semibold tabular-nums text-sm">+ {formatNumber(row.visits)}+ </TableCell>+ <TableCell className="text-right">+ <div className="flex justify-end">+ <DeltaBadge+ current={row.visits}+ previous={row.visitsPrev}+ comparable={comparable}+ />+ </div>+ </TableCell>+ <TableCell className="text-right pr-6 tabular-nums text-sm">+ {formatNumber(row.citations)}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ </div>+ </>+ )}+ {/* In one place whether the range has visits or not, so a range+ that has none (or some again) keeps these sections and their+ data rather than mounting them anew and reading it again. */}{conversionsSection}-{pagesCard}-{googleSection}-{botsSection}-- {/* Recent Visit Log with filtering and pagination*/}- <Card>- <CardHeader className="pb-3">- <div className="flex flex-col gap-3">- <div className="flex items-center justify-between">- <div className="flex items-center gap-2">- <LayoutList className="h-4 w-4 text-muted-foreground" />- <CardTitle className="text-sm font-medium">Recent AI Referral Visits</CardTitle>+ {!isEmpty && (+ <>+ {/* Recent Visit Log with filtering and pagination*/}+ <Card>+ <CardHeader className="pb-3">+ <div className="flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <LayoutList className="h-4 w-4 text-muted-foreground" />+ <CardTitle className="text-sm font-medium">+ Recent AI Referral Visits+ </CardTitle>+ </div>+ <div className="flex flex-wrap items-center justify-end gap-2">+ {logsTotal > 0 && (+ <Badge variant="secondary" className="text-xs">+ {tVisits('listTotal', { visits: logsTotal, pageviews: logsPageviews })}+ </Badge>+ )}+ <TableExport exporter={exporter} section="visits" />+ </div>+ </div>+ <TrafficFilterBar+ filters={filters}+ searchInput={searchInput}+ onSearchInputChange={setSearchInput}+ onChange={handleFiltersChange}+ platforms={summary?.platformBreakdown.map((p) => p.platform) ?? []}+ isLoading={isLoadingLogs}+ /></div>- <div className="flex flex-wrap items-center justify-end gap-2">- {logsTotal > 0 && (- <Badge variant="secondary" className="text-xs">- {tVisits('listTotal', { visits: logsTotal, pageviews: logsPageviews })}- </Badge>- )}- <TableExport exporter={exporter} section="visits" />- </div>- </div>- <TrafficFilterBar- filters={filters}- searchInput={searchInput}- onSearchInputChange={setSearchInput}- onChange={handleFiltersChange}- platforms={summary?.platformBreakdown.map((p) => p.platform) ?? []}- isLoading={isLoadingLogs}- />- </div>- </CardHeader>- <CardContent className="p-0">- {isLoadingLogs ? (- <div className="flex items-center justify-center py-8">- <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />- </div>- ) : (filters.platform || filters.search) && logs.length === 0 ? (- <EmptyLogsState hasFilters={true} />- ) : logs.length === 0 ? (- <EmptyLogsState hasFilters={false} />- ) : (- <>- <Table>- <TableHeader>- <TableRow>- <TableHead className="pl-6 w-[100px]">Time</TableHead>- <TableHead>Platform</TableHead>- <TableHead>Page</TableHead>- <TableHead className="text-right pr-6">Country</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {logs.map((row) => (- <TableRow key={row.id} className="hover:bg-muted/50">- <TableCell className="pl-6 text-xs text-muted-foreground whitespace-nowrap">- {formatRelative(row.createdAt, tCommon)}- </TableCell>- <TableCell>- <span className="text-sm">- {getPlatformName(row.sourcePlatform ?? 'unknown')}- </span>- </TableCell>- <TableCell>- <div className="flex min-w-0 items-center gap-1.5">- <span className="font-mono text-xs text-muted-foreground line-clamp-1">- {(() => {- try {- return new URL(row.url).pathname;- } catch {- return row.url;- }- })()}- </span>- {/* A reload or a further link in the same visit (AT-003). */}- {row.pageviews > 1 && (- <span className="shrink-0 whitespace-nowrap rounded-full bg-muted px-1.5 text-[11px] font-medium leading-4 text-muted-foreground">- {tVisits('rowPageviews', { count: row.pageviews })}+ </CardHeader>+ <CardContent className="p-0">+ {isLoadingLogs ? (+ <div className="flex items-center justify-center py-8">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ </div>+ ) : (filters.platform || filters.search) && logs.length === 0 ? (+ <EmptyLogsState hasFilters={true} />+ ) : logs.length === 0 ? (+ <EmptyLogsState hasFilters={false} />+ ) : (+ <>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-6 w-[100px]">Time</TableHead>+ <TableHead>Platform</TableHead>+ <TableHead>Page</TableHead>+ <TableHead className="text-right pr-6">Country</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {logs.map((row) => (+ <TableRow key={row.id} className="hover:bg-muted/50">+ <TableCell className="pl-6 text-xs text-muted-foreground whitespace-nowrap">+ {formatRelative(row.createdAt, tCommon)}+ </TableCell>+ <TableCell>+ <span className="text-sm">+ {getPlatformName(row.sourcePlatform ?? 'unknown')}</span>- )}- </div>- </TableCell>- <TableCell className="text-right pr-6">- <span className="text-xs text-muted-foreground">- {row.country ?? '—'}- </span>- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- {(() => {- const totalPages = Math.max(1, Math.ceil(logsTotal / PAGE_SIZE));- const clampedPage = Math.min(page, totalPages - 1);- const start = clampedPage * PAGE_SIZE;- const end = Math.min(start + PAGE_SIZE, logsTotal);- return (- <TablePager- page={clampedPage}- totalPages={totalPages}- total={logsTotal}- start={start}- end={end}- onPage={setPage}- isLoading={isLoadingLogs}- />- );- })()}- {/* What the list covers, and a wider range when it is a short one+ </TableCell>+ <TableCell>+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="font-mono text-xs text-muted-foreground line-clamp-1">+ {(() => {+ try {+ return new URL(row.url).pathname;+ } catch {+ return row.url;+ }+ })()}+ </span>+ {/* A reload or a further link in the same visit (AT-003). */}+ {row.pageviews > 1 && (+ <span className="shrink-0 whitespace-nowrap rounded-full bg-muted px-1.5 text-[11px] font-medium leading-4 text-muted-foreground">+ {tVisits('rowPageviews', { count: row.pageviews })}+ </span>+ )}+ </div>+ </TableCell>+ <TableCell className="text-right pr-6">+ <span className="text-xs text-muted-foreground">+ {row.country ?? '—'}+ </span>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ {(() => {+ const totalPages = Math.max(1, Math.ceil(logsTotal / PAGE_SIZE));+ const clampedPage = Math.min(page, totalPages - 1);+ const start = clampedPage * PAGE_SIZE;+ const end = Math.min(start + PAGE_SIZE, logsTotal);+ return (+ <TablePager+ page={clampedPage}+ totalPages={totalPages}+ total={logsTotal}+ start={start}+ end={end}+ onPage={setPage}+ isLoading={isLoadingLogs}+ />+ );+ })()}+ {/* What the list covers, and a wider range when it is a short one(AT-017, spec §3.01). */}- <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 px-6 pb-1 text-xs text-muted-foreground">- <span>- {tVisits('listRange', {- visits: logsTotal,- pageviews: logsPageviews,- range: rangeSubLabel,- preset: datePreset === 'custom' || datePreset === 'all' ? 'other' : 'last',- })}- </span>- {datePreset === '24h' && (- <button- type="button"- onClick={() => handleDatePresetChange('7d')}- className="font-medium text-foreground underline-offset-4 hover:underline"- >- {tVisits('showLast7Days')}- </button>- )}- </div>- <VisitListSourceNote analyticsDays={summary?.analyticsDays.length ?? 0} />- <p className="px-6 pb-4 text-xs text-muted-foreground">{tVisits('listNote')}</p>- </>- )}- </CardContent>- </Card>- </>- )}+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 px-6 pb-1 text-xs text-muted-foreground">+ <span>+ {tVisits('listRange', {+ visits: logsTotal,+ pageviews: logsPageviews,+ range: rangeSubLabel,+ preset:+ datePreset === 'custom' || datePreset === 'all' ? 'other' : 'last',+ })}+ </span>+ {datePreset === '24h' && (+ <button+ type="button"+ onClick={() => handleDatePresetChange('7d')}+ className="font-medium text-foreground underline-offset-4 hover:underline"+ >+ {tVisits('showLast7Days')}+ </button>+ )}+ </div>+ <VisitListSourceNote analyticsDays={summary?.analyticsDays.length ?? 0} />+ <p className="px-6 pb-4 text-xs text-muted-foreground">+ {tVisits('listNote')}+ </p>+ </>+ )}+ </CardContent>+ </Card>+ </>+ )}+ </div>+ </RangeReadyProvider></div>);}diff --git a/web/src/app/api/traffic/read/route.test.ts b/web/src/app/api/traffic/read/route.test.tsnew file mode 100644index 000000000..ba156c13a--- /dev/null+++ b/web/src/app/api/traffic/read/route.test.ts@@ -0,0 +1,91 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * POST /api/traffic/read: one of the AI Traffic page's reads by name, run+ * with the member's session; a route so the page's reads run side by side.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';+let user: { id: string } | null;++vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({ auth: { getUser: async () => ({ data: { user } }) } }),+}));++const reads = vi.hoisted(() => ({+ getTrafficSummary: vi.fn(),+ getTrafficPages: vi.fn(),+ getBotConnections: vi.fn(),+}));+vi.mock('@/lib/actions/traffic', () => ({+ getTrafficBots: vi.fn(),+ getTrafficConversions: vi.fn(),+ getTrafficGooglePages: vi.fn(),+ getTrafficGoogleTotals: vi.fn(),+ getTrafficGoogleTrend: vi.fn(),+ getTrafficLogs: vi.fn(),+ getTrafficPages: reads.getTrafficPages,+ getTrafficSources: vi.fn(),+ getTrafficSummary: reads.getTrafficSummary,+ getTrafficTrend: vi.fn(),+ getUntrackedGoogleQueries: vi.fn(),+}));+vi.mock('@/lib/actions/ai-bots', () => ({ getBotConnections: reads.getBotConnections }));++const { POST } = await import('./route');++const post = (body: unknown) =>+ POST(+ new Request('http://localhost/api/traffic/read', {+ method: 'POST',+ body: JSON.stringify(body),+ }),+ );++const WEEK = { dateFrom: '2026-10-12T00:00:00.000Z', dateTo: '2026-10-19T00:00:00.000Z' };++beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ user = { id: 'u1' };+});++describe('POST /api/traffic/read', () => {+ it("runs the named read with the action's arguments", async () => {+ reads.getTrafficPages.mockResolvedValue({ counts: { all: 3 }, rows: [] });+ const res = await post({ read: 'pages', args: [BRAND, WEEK, { tab: 'all', limit: 10 }] });+ expect(res.status).toBe(200);+ expect(res.headers.get('Cache-Control')).toBe('private, no-store');+ expect(await res.json()).toEqual({ data: { counts: { all: 3 }, rows: [] } });+ expect(reads.getTrafficPages).toHaveBeenCalledWith(BRAND, WEEK, { tab: 'all', limit: 10 });+ });++ it('passes an argument the browser left out as undefined, not null', async () => {+ reads.getTrafficSummary.mockResolvedValue({ totalVisits: 1 });+ await post({ read: 'summary', args: [BRAND, null] });+ expect(reads.getTrafficSummary).toHaveBeenCalledWith(BRAND, undefined);+ });++ it('reads the bot connections too', async () => {+ reads.getBotConnections.mockResolvedValue({ connections: [] });+ expect(await (await post({ read: 'botConnections', args: [BRAND] })).json()).toEqual({+ data: { connections: [] },+ });+ });++ it('refuses an unknown read, a missing brand, and anyone signed out', async () => {+ expect((await post({ read: 'deleteBrand', args: [BRAND] })).status).toBe(400);+ expect((await post({ read: 'pages', args: ['not-a-brand'] })).status).toBe(400);+ expect((await post({ read: 'pages', args: [] })).status).toBe(400);+ user = null;+ expect((await post({ read: 'pages', args: [BRAND, WEEK] })).status).toBe(401);+ expect(reads.getTrafficPages).not.toHaveBeenCalled();+ });++ it("answers 500 without the read's own error", async () => {+ reads.getTrafficSummary.mockRejectedValue(new Error('canceling statement due to timeout'));+ const res = await post({ read: 'summary', args: [BRAND, WEEK] });+ expect(res.status).toBe(500);+ expect(await res.json()).toEqual({ error: 'Failed to load' });+ });+});diff --git a/web/src/app/api/traffic/read/route.ts b/web/src/app/api/traffic/read/route.tsnew file mode 100644index 000000000..d5adcd37f--- /dev/null+++ b/web/src/app/api/traffic/read/route.ts@@ -0,0 +1,77 @@+import { z } from 'zod';+import { createClient } from '@/lib/supabase/server';+import {+ getTrafficBots,+ getTrafficConversions,+ getTrafficGooglePages,+ getTrafficGoogleTotals,+ getTrafficGoogleTrend,+ getTrafficLogs,+ getTrafficPages,+ getTrafficSources,+ getTrafficSummary,+ getTrafficTrend,+ getUntrackedGoogleQueries,+} from '@/lib/actions/traffic';+import { getBotConnections } from '@/lib/actions/ai-bots';+import { TRAFFIC_READS, type TrafficRead } from '@/lib/traffic-reads';++/**+ * POST /api/traffic/read — one of the AI Traffic page's reads, by name, with+ * the server action's own arguments (lib/traffic-reads.ts). A route because+ * the browser runs fetches side by side, where Next runs a page's server+ * actions one at a time.+ *+ * Reads through the signed-in member's session, as the actions do, so RLS+ * and the reports' organization checks decide whose brand this is.+ */++export const runtime = 'nodejs';++// Every read takes the brand first.+// eslint-disable-next-line @typescript-eslint/no-explicit-any+const READS: Record<TrafficRead, (brandId: string, ...rest: any[]) => Promise<unknown>> = {+ sources: getTrafficSources,+ summary: getTrafficSummary,+ trend: getTrafficTrend,+ logs: getTrafficLogs,+ pages: getTrafficPages,+ conversions: getTrafficConversions,+ googleTotals: getTrafficGoogleTotals,+ googleTrend: getTrafficGoogleTrend,+ googlePages: getTrafficGooglePages,+ untrackedQueries: getUntrackedGoogleQueries,+ bots: getTrafficBots,+ botConnections: getBotConnections,+};++const body = z.object({+ read: z.enum(TRAFFIC_READS),+ args: z+ .tuple([z.guid()])+ .rest(z.unknown())+ .refine((args) => args.length <= 4),+});++export async function POST(req: Request) {+ const parsed = body.safeParse(await req.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: 'invalid' }, { status: 400 });++ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) return Response.json({ error: 'unauthorized' }, { status: 401 });++ const [brandId, ...rest] = parsed.data.args;+ // JSON has no undefined: an argument left out arrives as null.+ const args = rest.map((arg) => (arg === null ? undefined : arg));+ try {+ const data = await READS[parsed.data.read](brandId, ...args);+ return Response.json({ data }, { headers: { 'Cache-Control': 'private, no-store' } });+ } catch (err) {+ // The sections show their own failed state; the details stay in the log.+ console.error(`[traffic/read] ${parsed.data.read} failed:`, err);+ return Response.json({ error: 'Failed to load' }, { status: 500 });+ }+}diff --git a/web/src/hooks/use-latest-request.test.tsx b/web/src/hooks/use-latest-request.test.tsxnew file mode 100644index 000000000..83b48c501--- /dev/null+++ b/web/src/hooks/use-latest-request.test.tsx@@ -0,0 +1,40 @@+import { act, useEffect } from 'react';+import { createRoot } from 'react-dom/client';+import { describe, expect, it } from 'vitest';+import { useLatestRequest } from './use-latest-request';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++type Start = () => () => boolean;++function Probe({ onStart }: { onStart: (start: Start) => void }) {+ const start = useLatestRequest();+ useEffect(() => {+ onStart(start);+ }, [start, onStart]);+ return null;+}++/** Only the latest of several requests may set state (gkhngyk on #1216). */+describe('useLatestRequest', () => {+ it('tells each request whether a newer one started', () => {+ const seen: Start[] = [];+ const onStart = (start: Start) => seen.push(start);+ const root = createRoot(document.createElement('div'));+ act(() => root.render(<Probe onStart={onStart} />));+ const start = seen[0];++ // 90 days, then 24 hours before the first answered.+ const ninetyDays = start();+ const day = start();+ expect(day()).toBe(true);+ expect(ninetyDays()).toBe(false);++ // The same function across renders: a re-render doesn't reset the order.+ act(() => root.render(<Probe onStart={onStart} />));+ expect(seen.every((s) => s === start)).toBe(true);+ expect(day()).toBe(true);+ act(() => root.unmount());+ });+});diff --git a/web/src/hooks/use-latest-request.ts b/web/src/hooks/use-latest-request.tsnew file mode 100644index 000000000..b7f89e99e--- /dev/null+++ b/web/src/hooks/use-latest-request.ts@@ -0,0 +1,16 @@+'use client';++import { useCallback, useRef } from 'react';++/**+ * Requests that run side by side can answer out of order: a range picked,+ * then another before the first answered. Each call starts a request and+ * returns whether it is still the latest, so only the latest one sets state.+ */+export function useLatestRequest(): () => () => boolean {+ const latest = useRef(0);+ return useCallback(() => {+ const request = ++latest.current;+ return () => request === latest.current;+ }, []);+}diff --git a/web/src/lib/traffic-reads.test.ts b/web/src/lib/traffic-reads.test.tsnew file mode 100644index 000000000..bc12b961a--- /dev/null+++ b/web/src/lib/traffic-reads.test.ts@@ -0,0 +1,104 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ getBotConnections,+ getTrafficPageCounts,+ getTrafficPages,+ getUntrackedGoogleQueries,+ getUntrackedQueryCount,+} from './traffic-reads';++/** The AI Traffic page's reads from the browser: one POST each, run side by side. */++const BRAND = '33333333-3333-3333-3333-333333333333';+const WEEK = { dateFrom: '2026-10-12T00:00:00.000Z', dateTo: '2026-10-19T00:00:00.000Z' };+const fetchMock = vi.fn();+const answer = (status: number, body: unknown) => ({ ok: status < 300, json: async () => body });++beforeEach(() => {+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('traffic reads', () => {+ it('posts the read and its arguments, and returns its data', async () => {+ fetchMock.mockResolvedValue(answer(200, { data: { counts: { all: 3 }, rows: [] } }));+ expect(await getTrafficPages(BRAND, WEEK, { tab: 'all', limit: 10 })).toEqual({+ counts: { all: 3 },+ rows: [],+ });+ expect(fetchMock).toHaveBeenCalledWith('/api/traffic/read', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ read: 'pages', args: [BRAND, WEEK, { tab: 'all', limit: 10 }] }),+ });+ });++ it("doesn't wait for one read before sending the next", async () => {+ let release = () => {};+ fetchMock.mockImplementationOnce(+ () => new Promise((resolve) => (release = () => resolve(answer(200, { data: 1 })))),+ );+ fetchMock.mockResolvedValueOnce(answer(200, { data: { connections: [] } }));+ const first = getTrafficPages(BRAND, WEEK, { tab: 'all' });+ const second = getBotConnections(BRAND);+ expect(await second).toEqual({ connections: [] });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ release();+ expect(await first).toBe(1);+ });++ it('throws when the read failed', async () => {+ fetchMock.mockResolvedValue(answer(500, { error: 'Failed to load' }));+ await expect(getTrafficPages(BRAND, WEEK, { tab: 'all' })).rejects.toThrow('Failed to load');+ });+});++// gkhngyk on #1216: the summary line's counts repeated the Pages card's and+// the Google section's reads on every range change.+describe('counts another read carries', () => {+ const pages = { counts: { noAiTraffic: 1, citedNotClicked: 4, trafficNoPrompt: 0, all: 5 } };+ const MONTH = { dateFrom: '2026-09-19T00:00:00.000Z', dateTo: '2026-10-19T00:00:00.000Z' };++ it("takes the Pages card's read for the same range, sent in the same turn", async () => {+ fetchMock.mockResolvedValue(answer(200, { data: { ...pages, rows: [] } }));+ const count = getTrafficPageCounts(BRAND, MONTH);+ void getTrafficPages(BRAND, MONTH, { tab: 'all', limit: 10 });+ expect(await count).toEqual(pages.counts);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('reads the count on its own when no section read the range', async () => {+ fetchMock.mockResolvedValue(answer(200, { data: { ...pages, rows: [] } }));+ const range = { dateFrom: '2026-08-01T00:00:00.000Z', dateTo: '2026-08-08T00:00:00.000Z' };+ expect(await getTrafficPageCounts(BRAND, range)).toEqual(pages.counts);+ expect(fetchMock).toHaveBeenCalledWith(+ '/api/traffic/read',+ expect.objectContaining({+ body: JSON.stringify({+ read: 'pages',+ args: [BRAND, range, { tab: 'citedNotClicked', limit: 0 }],+ }),+ }),+ );+ });++ it("takes the untracked total from the Google section's list, not a failed one", async () => {+ const range = { dateFrom: '2026-07-01T00:00:00.000Z', dateTo: '2026-07-08T00:00:00.000Z' };+ fetchMock.mockResolvedValueOnce(answer(500, { error: 'boom' }));+ await getUntrackedGoogleQueries(BRAND, range).catch(() => null);+ fetchMock.mockResolvedValue(answer(200, { data: { count: 7, capped: true, rows: [] } }));+ // The failed list isn't shared: the count reads on its own.+ expect(await getUntrackedQueryCount(BRAND, range)).toEqual({ count: 7, capped: true });+ expect(fetchMock).toHaveBeenCalledTimes(2);++ fetchMock.mockClear();+ const count = getUntrackedQueryCount(BRAND, MONTH);+ void getUntrackedGoogleQueries(BRAND, MONTH);+ expect(await count).toEqual({ count: 7, capped: true });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/src/lib/traffic-reads.ts b/web/src/lib/traffic-reads.tsnew file mode 100644index 000000000..80f609a24--- /dev/null+++ b/web/src/lib/traffic-reads.ts@@ -0,0 +1,127 @@+import type * as traffic from '@/lib/actions/traffic';+import type * as aiBots from '@/lib/actions/ai-bots';++/**+ * The AI Traffic page's reads, from the browser, through one route+ * (/api/traffic/read) rather than as server actions.+ *+ * Next runs a page's server actions one at a time: a range change asked a+ * dozen sections for data, and each read waited for the one before it, so+ * the page took the sum of every read. Fetches to a route run side by side,+ * so it takes the slowest one. Each function keeps its server action's name+ * and arguments; the route calls that action with the member's session.+ */++export const TRAFFIC_READS = [+ 'sources',+ 'summary',+ 'trend',+ 'logs',+ 'pages',+ 'conversions',+ 'googleTotals',+ 'googleTrend',+ 'googlePages',+ 'untrackedQueries',+ 'bots',+ 'botConnections',+] as const;+export type TrafficRead = (typeof TRAFFIC_READS)[number];++async function read<T>(name: TrafficRead, args: unknown[]): Promise<T> {+ const res = await fetch('/api/traffic/read', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ read: name, args }),+ });+ const body = (await res.json().catch(() => ({}))) as { data?: T; error?: string };+ if (!res.ok) throw new Error(body.error || `Failed to load ${name}`);+ return body.data as T;+}++// eslint-disable-next-line @typescript-eslint/no-explicit-any+type Read = (...args: any[]) => Promise<unknown>;+const via =+ <F extends Read>(name: TrafficRead) =>+ (...args: Parameters<F>) =>+ read<Awaited<ReturnType<F>>>(name, args);++export const getTrafficSources = via<typeof traffic.getTrafficSources>('sources');+export const getTrafficSummary = via<typeof traffic.getTrafficSummary>('summary');+export const getTrafficTrend = via<typeof traffic.getTrafficTrend>('trend');+export const getTrafficLogs = via<typeof traffic.getTrafficLogs>('logs');+const readTrafficPages = via<typeof traffic.getTrafficPages>('pages');+export const getTrafficConversions = via<typeof traffic.getTrafficConversions>('conversions');+export const getTrafficGoogleTotals = via<typeof traffic.getTrafficGoogleTotals>('googleTotals');+export const getTrafficGoogleTrend = via<typeof traffic.getTrafficGoogleTrend>('googleTrend');+export const getTrafficGooglePages = via<typeof traffic.getTrafficGooglePages>('googlePages');+const readUntrackedGoogleQueries =+ via<typeof traffic.getUntrackedGoogleQueries>('untrackedQueries');+export const getTrafficBots = via<typeof traffic.getTrafficBots>('bots');+export const getBotConnections = via<typeof aiBots.getBotConnections>('botConnections');++/**+ * A count another section's read already carries is taken from it. The+ * Pages card's read returns every tab's count, and the Google section's list+ * its total, so the summary line's Cited, not clicked and untracked-queries+ * counts don't run those statements a second time on each range change.+ * The latest such read per brand and range is kept for a few seconds; a+ * count asks a turn later, so a section mounting in the same render has+ * sent its read first. Without one (the section isn't on the page), the+ * count reads on its own.+ */+const SHARE_MS = 5_000;+const shared = new Map<string, { at: number; promise: Promise<unknown> }>();++function shareKey(read: string, brandId: string, window: traffic.TrafficDateWindow | undefined) {+ return `${read}|${brandId}|${window?.dateFrom ?? ''}|${window?.dateTo ?? ''}`;+}++function keep<T>(key: string, promise: Promise<T>): Promise<T> {+ shared.set(key, { at: Date.now(), promise });+ // A failed read is no one's to share.+ promise.catch(() => shared.delete(key));+ return promise;+}++async function sharedRead<T>(key: string): Promise<T | undefined> {+ await new Promise((resolve) => setTimeout(resolve, 0));+ const hit = shared.get(key);+ if (!hit || Date.now() - hit.at > SHARE_MS) return undefined;+ return hit.promise as Promise<T>;+}++export const getTrafficPages: typeof readTrafficPages = (brandId, window, options) =>+ keep(shareKey('pages', brandId, window), readTrafficPages(brandId, window, options));++export const getUntrackedGoogleQueries: typeof readUntrackedGoogleQueries = (+ brandId,+ window,+ options,+) => {+ const read = readUntrackedGoogleQueries(brandId, window, options);+ // A count-only read (limit 0) has no rows to share.+ return options?.limit === 0 ? read : keep(shareKey('untracked', brandId, window), read);+};++/** Every Pages tab's count for the range (AT-006). */+export async function getTrafficPageCounts(+ brandId: string,+ window: traffic.TrafficDateWindow | undefined,+): Promise<traffic.TrafficPages['counts']> {+ const pages =+ (await sharedRead<traffic.TrafficPages>(shareKey('pages', brandId, window))) ??+ (await readTrafficPages(brandId, window, { tab: 'citedNotClicked', limit: 0 }));+ return pages.counts;+}++/** How many Google queries no prompt tracks in the range (AT-009). */+export async function getUntrackedQueryCount(+ brandId: string,+ window: traffic.TrafficDateWindow | undefined,+): Promise<{ count: number; capped: boolean }> {+ const queries =+ (await sharedRead<traffic.TrafficUntrackedQueries>(shareKey('untracked', brandId, window))) ??+ (await readUntrackedGoogleQueries(brandId, window, { limit: 0 }));+ return { count: queries.count, capped: queries.capped };+}