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
fix(traffic): count visits, not pageviews, in every reader of the snippet's data (#1161)
Cihanc5488a2fffbe
diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex 2fc4f9c2e..afd1d1f18 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -161,16 +161,17 @@ export async function measureKpis(brandId, kpiKeys, from, to) {/*** AI-referred visits over a window.*- * Two sources exist and they measure different things: the tracking snippet- * logs each referred visit, while the analytics integration reports sessions.- * Whichever the brand actually has is used — and when it has neither, the- * metric is unmeasured, not zero.+ * Two sources exist: the tracking snippet, counted one row per visit (a row+ * whose visit_of is null starts a visit, 00172; reloads are further rows of+ * it), and the analytics integration's sessions. Whichever the brand actually+ * has is used — and when it has neither, the metric is unmeasured, not zero.*/async function measureTraffic(brandId, from, to) {const { count, error } = await supabaseAdmin.from('ai_traffic_logs').select('id', { count: 'exact', head: true }).eq('brand_id', brandId)+ .is('visit_of', null).gte('created_at', `${from}T00:00:00Z`).lte('created_at', `${to}T23:59:59Z`);if (error) throw new Error(`ai_traffic_logs: ${error.message}`);diff --git a/server/src/lib/action-center/validate.test.js b/server/src/lib/action-center/validate.test.jsindex 2de3ec7ae..a40fdcdd8 100644--- a/server/src/lib/action-center/validate.test.js+++ b/server/src/lib/action-center/validate.test.js@@ -27,6 +27,7 @@ function mockWrites() {const builder = {select: () => builder,eq: () => builder,+ is: () => builder,gte: () => builder,lte: () => builder,not: () => builder,@@ -138,6 +139,62 @@ describe('measureKpis', () => {expect(values.ai_visibility).toBeNull();});++ describe('AI referral traffic', () => {+ // Each query's calls, and what it answers with.+ function mockTraffic({ snippetVisits, gaRows }) {+ const queries = [];+ from.mockImplementation((table) => {+ const calls = [];+ queries.push({ table, calls });+ const builder = {};+ for (const method of ['select', 'eq', 'is', 'gte', 'lte']) {+ builder[method] = (...args) => {+ calls.push([method, ...args]);+ return builder;+ };+ }+ builder.then = (resolve) =>+ resolve(+ table === 'ai_traffic_logs'+ ? { count: snippetVisits, error: null }+ : { data: gaRows, error: null },+ );+ return builder;+ });+ return queries;+ }++ it("counts the snippet's visits, not its pageviews", async () => {+ // A visit starts on a row whose visit_of is null (00172); its reloads+ // are further rows of the same visit.+ const queries = mockTraffic({ snippetVisits: 26, gaRows: [] });++ const values = await measureKpis(+ 'brand-1',+ ['ai_referral_traffic'],+ '2026-09-01',+ '2026-09-07',+ );++ expect(values.ai_referral_traffic).toBe(26);+ expect(queries[0].table).toBe('ai_traffic_logs');+ expect(queries[0].calls).toContainEqual(['is', 'visit_of', null]);+ });++ it("falls back to Analytics' sessions when the snippet has no visits", async () => {+ mockTraffic({ snippetVisits: 0, gaRows: [{ sessions: 4 }, { sessions: '3' }] });++ const values = await measureKpis(+ 'brand-1',+ ['ai_referral_traffic'],+ '2026-09-01',+ '2026-09-07',+ );++ expect(values.ai_referral_traffic).toBe(7);+ });+ });});describe('validateAction', () => {diff --git a/supabase/migrations/00173_traffic_reads_count_visits.sql b/supabase/migrations/00173_traffic_reads_count_visits.sqlnew file mode 100644index 000000000..7e8ed229d--- /dev/null+++ b/supabase/migrations/00173_traffic_reads_count_visits.sql@@ -0,0 +1,136 @@+-- ============================================================================+-- 00173: the Action Center's traffic reads count visits, not pageviews+-- ============================================================================+-- 00172 made a visit one session: a row of ai_traffic_logs whose visit_of is+-- null starts a visit, and the rows pointing at it are its reloads and+-- further links. The AI Traffic page counts visits since then, but the two+-- detector reads below still counted every row as a session, so a signal+-- could rest on a number the page no longer shows.+--+-- Each now reads the snippet's visit starts only. Analytics' side is+-- unchanged: it already reports sessions. The bodies are otherwise 00091's+-- (ae_ai_traffic_pages) and 00143's (ae_page_traffic_evidence); the+-- signatures and return types are the same, so CREATE OR REPLACE keeps their+-- grants, and their settings are restated as they were.+--+-- Counts fall where visitors reloaded or followed a second link (14,777+-- rows were 8,983 visits on production when 00172 ran), so a detector+-- threshold is reached later on the same traffic.++create or replace function public.ae_ai_traffic_pages(+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date+) returns jsonb+language sql stable+as $$+ with ga as (+ select landing_page as page,+ sum(sessions) filter (where date between p_cur_from and p_cur_to) as cur_sessions,+ sum(sessions) filter (where date between p_prev_from and p_prev_to) as prev_sessions,+ sum(engaged_sessions) filter (where date between p_cur_from and p_cur_to) as cur_engaged,+ sum(key_events) filter (where date between p_cur_from and p_cur_to) as cur_key_events,+ sum(key_events) filter (where date between p_prev_from and p_prev_to) as prev_key_events+ from public.ga_ai_traffic_stats+ where brand_id = p_brand_id and date between p_prev_from and p_cur_to+ group by landing_page+ ),+ snippet as (+ select url as page,+ count(*) filter (where created_at::date between p_cur_from and p_cur_to) as cur_sessions,+ count(*) filter (where created_at::date between p_prev_from and p_prev_to) as prev_sessions+ from public.ai_traffic_logs+ where brand_id = p_brand_id and created_at >= p_prev_from+ and visit_of is null+ group by url+ )+ select jsonb_build_object(+ 'analytics', (select coalesce(jsonb_agg(row_to_json(g)), '[]'::jsonb) from (select * from ga order by cur_sessions desc nulls last limit 300) g),+ 'snippet', (select coalesce(jsonb_agg(row_to_json(s)), '[]'::jsonb) from (select * from snippet order by cur_sessions desc nulls last limit 300) s)+ )+$$;++create or replace function public.ae_page_traffic_evidence(+ p_brand_id uuid,+ p_pages text[],+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_exact boolean default false+) returns jsonb+language sql+stable+set search_path = public+as $$+ with pages as (+ select distinct page,+ case when p_exact then page else lower(normalize_page_path(page)) end as match_key,+ lower(normalize_page_path(page)) as page_key+ from unnest(p_pages) as page+ ),+ -- Each visit row's key is computed once, so the join below is an equality+ -- the planner can hash, not a function call per row and page.+ ga_rows as (+ select platform, date, sessions,+ case+ when p_pages is null then null+ when p_exact then landing_page+ else lower(normalize_page_path(landing_page))+ end as match_key+ from ga_ai_traffic_stats+ where brand_id = p_brand_id+ and date between p_prev_from and p_cur_to+ and (p_pages is null or landing_page <> '')+ ),+ -- A visit's first pageview only (00172): its reloads are not more visits.+ log_rows as (+ select source_platform as platform, created_at,+ case+ when p_pages is null then null+ when p_exact then url+ else lower(normalize_page_path(url))+ end as match_key+ from ai_traffic_logs+ where brand_id = p_brand_id+ and created_at >= p_prev_from+ and visit_of is null+ and (p_pages is null or not p_exact or url = any(p_pages))+ ),+ analytics as (+ select pg.page, r.platform,+ coalesce(sum(r.sessions) filter (where r.date between p_cur_from and p_cur_to), 0) as cur_sessions,+ coalesce(sum(r.sessions) filter (where r.date between p_prev_from and p_prev_to), 0) as prev_sessions+ from ga_rows r+ left join pages pg on pg.match_key = r.match_key+ where p_pages is null or pg.page is not null+ group by pg.page, r.platform+ ),+ snippet as (+ select pg.page, r.platform,+ count(*) filter (where r.created_at::date between p_cur_from and p_cur_to) as cur_sessions,+ count(*) filter (where r.created_at::date between p_prev_from and p_prev_to) as prev_sessions+ from log_rows r+ left join pages pg on pg.match_key = r.match_key+ where p_pages is null or pg.page is not null+ group by pg.page, r.platform+ ),+ targeted as (+ -- Explicit targeting only, as in 00075: a URL a customer attached to a+ -- prompt is a fact; "a prompt covers this page's topic" is a guess. A+ -- paused prompt is not asked, so the page can't be cited on it.+ select distinct pg.page, p.id as prompt_id, p.text+ from prompt_target_urls ptu+ join prompts p on p.id = ptu.prompt_id+ join prompt_sets ps on ps.id = p.prompt_set_id+ join pages pg on pg.page_key = lower(normalize_page_path(ptu.url))+ where ps.brand_id = p_brand_id+ and p.is_active+ )+ select jsonb_build_object(+ 'analytics', coalesce((select jsonb_agg(a) from analytics a), '[]'::jsonb),+ 'snippet', coalesce((select jsonb_agg(s) from snippet s), '[]'::jsonb),+ 'prompts', coalesce(+ (select jsonb_agg(t order by t.page, t.text, t.prompt_id) from targeted t),+ '[]'::jsonb+ )+ )+$$;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 9ea99e640..8c8f80dcf 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -23330,3 +23330,143 @@ create index if not exists idx_ai_traffic_logs_visit_ofon public.ai_traffic_logs (visit_of)where visit_of is not null;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00173_traffic_reads_count_visits.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00173: the Action Center's traffic reads count visits, not pageviews+-- ============================================================================+-- 00172 made a visit one session: a row of ai_traffic_logs whose visit_of is+-- null starts a visit, and the rows pointing at it are its reloads and+-- further links. The AI Traffic page counts visits since then, but the two+-- detector reads below still counted every row as a session, so a signal+-- could rest on a number the page no longer shows.+--+-- Each now reads the snippet's visit starts only. Analytics' side is+-- unchanged: it already reports sessions. The bodies are otherwise 00091's+-- (ae_ai_traffic_pages) and 00143's (ae_page_traffic_evidence); the+-- signatures and return types are the same, so CREATE OR REPLACE keeps their+-- grants, and their settings are restated as they were.+--+-- Counts fall where visitors reloaded or followed a second link (14,777+-- rows were 8,983 visits on production when 00172 ran), so a detector+-- threshold is reached later on the same traffic.++create or replace function public.ae_ai_traffic_pages(+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date+) returns jsonb+language sql stable+as $$+ with ga as (+ select landing_page as page,+ sum(sessions) filter (where date between p_cur_from and p_cur_to) as cur_sessions,+ sum(sessions) filter (where date between p_prev_from and p_prev_to) as prev_sessions,+ sum(engaged_sessions) filter (where date between p_cur_from and p_cur_to) as cur_engaged,+ sum(key_events) filter (where date between p_cur_from and p_cur_to) as cur_key_events,+ sum(key_events) filter (where date between p_prev_from and p_prev_to) as prev_key_events+ from public.ga_ai_traffic_stats+ where brand_id = p_brand_id and date between p_prev_from and p_cur_to+ group by landing_page+ ),+ snippet as (+ select url as page,+ count(*) filter (where created_at::date between p_cur_from and p_cur_to) as cur_sessions,+ count(*) filter (where created_at::date between p_prev_from and p_prev_to) as prev_sessions+ from public.ai_traffic_logs+ where brand_id = p_brand_id and created_at >= p_prev_from+ and visit_of is null+ group by url+ )+ select jsonb_build_object(+ 'analytics', (select coalesce(jsonb_agg(row_to_json(g)), '[]'::jsonb) from (select * from ga order by cur_sessions desc nulls last limit 300) g),+ 'snippet', (select coalesce(jsonb_agg(row_to_json(s)), '[]'::jsonb) from (select * from snippet order by cur_sessions desc nulls last limit 300) s)+ )+$$;++create or replace function public.ae_page_traffic_evidence(+ p_brand_id uuid,+ p_pages text[],+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_exact boolean default false+) returns jsonb+language sql+stable+set search_path = public+as $$+ with pages as (+ select distinct page,+ case when p_exact then page else lower(normalize_page_path(page)) end as match_key,+ lower(normalize_page_path(page)) as page_key+ from unnest(p_pages) as page+ ),+ -- Each visit row's key is computed once, so the join below is an equality+ -- the planner can hash, not a function call per row and page.+ ga_rows as (+ select platform, date, sessions,+ case+ when p_pages is null then null+ when p_exact then landing_page+ else lower(normalize_page_path(landing_page))+ end as match_key+ from ga_ai_traffic_stats+ where brand_id = p_brand_id+ and date between p_prev_from and p_cur_to+ and (p_pages is null or landing_page <> '')+ ),+ -- A visit's first pageview only (00172): its reloads are not more visits.+ log_rows as (+ select source_platform as platform, created_at,+ case+ when p_pages is null then null+ when p_exact then url+ else lower(normalize_page_path(url))+ end as match_key+ from ai_traffic_logs+ where brand_id = p_brand_id+ and created_at >= p_prev_from+ and visit_of is null+ and (p_pages is null or not p_exact or url = any(p_pages))+ ),+ analytics as (+ select pg.page, r.platform,+ coalesce(sum(r.sessions) filter (where r.date between p_cur_from and p_cur_to), 0) as cur_sessions,+ coalesce(sum(r.sessions) filter (where r.date between p_prev_from and p_prev_to), 0) as prev_sessions+ from ga_rows r+ left join pages pg on pg.match_key = r.match_key+ where p_pages is null or pg.page is not null+ group by pg.page, r.platform+ ),+ snippet as (+ select pg.page, r.platform,+ count(*) filter (where r.created_at::date between p_cur_from and p_cur_to) as cur_sessions,+ count(*) filter (where r.created_at::date between p_prev_from and p_prev_to) as prev_sessions+ from log_rows r+ left join pages pg on pg.match_key = r.match_key+ where p_pages is null or pg.page is not null+ group by pg.page, r.platform+ ),+ targeted as (+ -- Explicit targeting only, as in 00075: a URL a customer attached to a+ -- prompt is a fact; "a prompt covers this page's topic" is a guess. A+ -- paused prompt is not asked, so the page can't be cited on it.+ select distinct pg.page, p.id as prompt_id, p.text+ from prompt_target_urls ptu+ join prompts p on p.id = ptu.prompt_id+ join prompt_sets ps on ps.id = p.prompt_set_id+ join pages pg on pg.page_key = lower(normalize_page_path(ptu.url))+ where ps.brand_id = p_brand_id+ and p.is_active+ )+ select jsonb_build_object(+ 'analytics', coalesce((select jsonb_agg(a) from analytics a), '[]'::jsonb),+ 'snippet', coalesce((select jsonb_agg(s) from snippet s), '[]'::jsonb),+ 'prompts', coalesce(+ (select jsonb_agg(t order by t.page, t.text, t.prompt_id) from targeted t),+ '[]'::jsonb+ )+ )+$$;+diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.tsindex ce6ad1f82..ac7846ab7 100644--- a/web/src/lib/actions/brand.ts+++ b/web/src/lib/actions/brand.ts@@ -410,10 +410,12 @@ export async function getBrandsCardSummary(.select('id, prompt_sets!inner(brand_id)').in('prompt_sets.brand_id', brandIds).eq('is_active', true),+ // Visits, not pageviews (00172), as the AI Traffic page counts them.supabase.from('ai_traffic_logs').select('brand_id, created_at').in('brand_id', brandIds)+ .is('visit_of', null).gte('created_at', new Date(now - 7 * 86400000).toISOString()),]);diff --git a/web/src/lib/actions/citations.ts b/web/src/lib/actions/citations.tsindex 1f3711518..7e9dcb1ec 100644--- a/web/src/lib/actions/citations.ts+++ b/web/src/lib/actions/citations.ts@@ -843,8 +843,9 @@ export async function getCitationUrlDetail().eq('prompts.prompt_sets.brand_id', brandId);- // (b) AI-referred visits to this page. The ilike narrows server-side; the- // exact match happens on the loose key below.+ // (b) AI-referred visits that landed on this page: the rows that start a+ // visit (00172), so a reload isn't another visit. The ilike narrows+ // server-side; the exact match happens on the loose key below.const pathForSearch = (() => {try {return new URL(targetUrl).pathname.replace(/\/+$/, '');@@ -856,6 +857,7 @@ export async function getCitationUrlDetail(.from('ai_traffic_logs').select('url, source_platform, created_at').eq('brand_id', brandId)+ .is('visit_of', null).order('created_at', { ascending: false }).range(0, URL_DETAIL_TRAFFIC_MAX_ROWS - 1);if (pathForSearch) trafficQuery = trafficQuery.ilike('url', `%${escapeIlike(pathForSearch)}%`);diff --git a/web/src/lib/actions/reports.ts b/web/src/lib/actions/reports.tsindex 69a646409..e4aa9a40c 100644--- a/web/src/lib/actions/reports.ts+++ b/web/src/lib/actions/reports.ts@@ -479,17 +479,21 @@ async function getTrafficSnapshot(const supabase = await createClient();const prev = previousWindow(dateFrom, dateTo);+ // Visits, not pageviews: a row whose visit_of is null starts one (00172),+ // as the AI Traffic page counts them.const [{ data: cur, error }, { data: prevRows }] = await Promise.all([supabase.from('ai_traffic_logs').select('source_platform, url').eq('brand_id', brandId)+ .is('visit_of', null).gte('created_at', dateFrom).lte('created_at', dateTo),supabase.from('ai_traffic_logs').select('id').eq('brand_id', brandId)+ .is('visit_of', null).gte('created_at', prev.from).lt('created_at', prev.to),]);diff --git a/web/src/lib/actions/traffic-visit-readers.test.ts b/web/src/lib/actions/traffic-visit-readers.test.tsnew file mode 100644index 000000000..e6fe135c5--- /dev/null+++ b/web/src/lib/actions/traffic-visit-readers.test.ts@@ -0,0 +1,185 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { McpAuthContext } from '@/lib/mcp-auth';++/**+ * Every reader of the tracking snippet's rows counts visits, as the AI+ * Traffic page does since 00172: a row whose visit_of is null starts a visit,+ * and the rows pointing at it are its reloads. The report, the brand cards,+ * a citation's page detail and the MCP / API traffic tool must say the same+ * number as the page for the same days.+ */++type Call = [string, ...unknown[]];+type Answer = { data?: unknown; count?: number; error: null };++const queries: { table: string; calls: Call[] }[] = [];+const inserted: Record<string, unknown>[] = [];++// One visit to /menu with two reloads, and one visit to /pricing: two+// visits, four pageviews.+const PAGEVIEWS = [+ {+ id: 'v1',+ brand_id: 'b1',+ url: 'https://acme.example/menu',+ source_platform: 'gemini',+ country: 'US',+ created_at: '2026-10-15T09:00:00Z',+ visit_of: null,+ },+ {+ id: 'r1',+ brand_id: 'b1',+ url: 'https://acme.example/menu',+ source_platform: 'gemini',+ country: 'US',+ created_at: '2026-10-15T09:01:00Z',+ visit_of: 'v1',+ },+ {+ id: 'r2',+ brand_id: 'b1',+ url: 'https://acme.example/menu',+ source_platform: 'gemini',+ country: 'US',+ created_at: '2026-10-15T09:02:00Z',+ visit_of: 'v1',+ },+ {+ id: 'v2',+ brand_id: 'b1',+ url: 'https://acme.example/pricing',+ source_platform: 'chatgpt',+ country: 'DE',+ created_at: '2026-10-16T09:00:00Z',+ visit_of: null,+ },+];++const visitsOnly = (calls: Call[]) =>+ calls.some(([m, col, val]) => m === 'is' && col === 'visit_of' && val === null);++function answer(table: string, calls: Call[]): Answer {+ if (table === 'ai_traffic_logs') {+ // The rows a query gets back depend on whether it asked for visits.+ const rows = visitsOnly(calls) ? PAGEVIEWS.filter((r) => r.visit_of === null) : PAGEVIEWS;+ return { data: rows, count: rows.length, error: null };+ }+ if (table === 'brands')+ return { data: { id: 'b1', name: 'Acme', shopping_mode_enabled: false }, error: null };+ if (table === 'brand_domains') return { data: [{ domain: 'acme.example' }], error: null };+ if (table === 'reports') return { data: { id: 'report-1' }, error: null };+ return { data: [], error: null };+}++function query(table: string) {+ const calls: Call[] = [];+ queries.push({ table, calls });+ const builder: Record<string, unknown> = {};+ for (const method of [+ 'select',+ 'eq',+ 'is',+ 'in',+ 'gte',+ 'lte',+ 'lt',+ 'ilike',+ 'order',+ 'range',+ 'limit',+ ]) {+ builder[method] = (...args: unknown[]) => {+ calls.push([method, ...args]);+ return builder;+ };+ }+ builder.insert = (row: Record<string, unknown>) => {+ inserted.push(row);+ return builder;+ };+ builder.single = async () => answer(table, calls);+ builder.maybeSingle = async () => answer(table, calls);+ builder.then = (resolve: (a: Answer) => unknown) => resolve(answer(table, calls));+ return builder;+}++const client = {+ from: (table: string) => query(table),+ rpc: async () => ({ data: [], error: null }),+ auth: {+ getSession: async () => ({ data: { session: { access_token: 'tok', user: { id: 'u1' } } } }),+ },+};+vi.mock('@/lib/supabase/server', () => ({ createClient: async () => client }));+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: client }));+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));++const { createReport } = await import('./reports');+const { getBrandsCardSummary } = await import('./brand');+const { getCitationUrlDetail } = await import('./citations');+const { getAiTrafficFor } = await import('@/lib/mcp/data');++const trafficQueries = () => queries.filter((q) => q.table === 'ai_traffic_logs');++beforeEach(() => {+ queries.length = 0;+ inserted.length = 0;+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response(JSON.stringify({ summary: '' }), { status: 200 })),+ );+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('readers of the snippet count visits, not pageviews', () => {+ it("the report's AI traffic section", async () => {+ await createReport('b1', {+ dateFrom: '2026-10-11T00:00:00.000Z',+ dateTo: '2026-10-17T23:59:59.999Z',+ sections: ['aiTraffic'],+ });++ const payload = inserted[0].payload as { aiTraffic: Record<string, unknown> };+ expect(payload.aiTraffic.totalVisits).toBe(2);+ expect(payload.aiTraffic.platformBreakdown).toEqual([+ { platform: 'gemini', visits: 1 },+ { platform: 'chatgpt', visits: 1 },+ ]);+ // This window and the one before it.+ expect(trafficQueries()).toHaveLength(2);+ for (const q of trafficQueries()) expect(visitsOnly(q.calls)).toBe(true);+ });++ it("the brand cards' last 7 days", async () => {+ const summary = await getBrandsCardSummary(['b1']);+ expect(summary.b1.trafficVisits7d).toBe(2);+ expect(visitsOnly(trafficQueries()[0].calls)).toBe(true);+ });++ it("a brand page's visits on its citation detail", async () => {+ const detail = await getCitationUrlDetail('b1', 'https://acme.example/menu', {+ datePreset: 'all',+ });+ expect(detail.owned?.traffic).toEqual({+ totalVisits: 1,+ byPlatform: [{ platform: 'gemini', visits: 1 }],+ });+ expect(visitsOnly(trafficQueries()[0].calls)).toBe(true);+ });++ it('the MCP and API traffic tool', async () => {+ const auth = { organizationId: 'org-1' } as McpAuthContext;+ const result = await getAiTrafficFor(auth, { brandId: 'b1' });+ expect(result?.total_visits).toBe(2);+ expect(result?.top_pages).toEqual([+ { url: '/menu', visits: 1 },+ { url: '/pricing', visits: 1 },+ ]);+ expect(visitsOnly(trafficQueries()[0].calls)).toBe(true);+ });+});diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex a688852be..3a55205a5 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -2200,10 +2200,13 @@ export async function getAiTrafficFor(.maybeSingle();if (!brand) return null;+ // Visits, not pageviews: a row whose visit_of is null starts one (00172),+ // as the AI Traffic page counts them.let query = supabaseAdmin.from('ai_traffic_logs').select('source_platform, url, country')- .eq('brand_id', params.brandId);+ .eq('brand_id', params.brandId)+ .is('visit_of', null);if (params.dateFrom) query = query.gte('created_at', params.dateFrom);const expandedDateTo = expandDateToEndOfDay(params.dateTo);