Skip to content

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.

fix(traffic): name only known platforms and pages in the weekly AI Traffic digest (#1229)

Cihan7a215830820d
diff --git a/server/src/lib/traffic-digest/engine.js b/server/src/lib/traffic-digest/engine.js
index cf635293c..476741746 100644
--- a/server/src/lib/traffic-digest/engine.js
+++ b/server/src/lib/traffic-digest/engine.js
@@ -5,9 +5,11 @@ import { isCloud, isSubscriptionActive } from '../../config/plans.js';
import { appUrl, resolveRecipients } from '../pulse/engine.js';
import { untrackedGoogleQueries } from '../untracked-queries.js';
import {
+ brokenCandidates,
dailyVisits,
digestWeek,
formatShare,
+ pageCandidates,
summarySentences,
topChanges,
topPlatforms,
@@ -43,6 +45,9 @@ const STALE_CLAIM_MS = 60 * 60 * 1000;
/** A read is tried this many times before the brand's week waits for the next sweep. */
const READ_ATTEMPTS = 3;
+/** Broken AI links read for the week's line, as the nightly signal reads them. */
+const BROKEN_LINKS_READ = 50;
+
async function withRetries(read, waitMs) {
for (let attempt = 1; ; attempt++) {
try {
@@ -115,11 +120,14 @@ export async function readDigestData(brandId, week) {
p_limit: 0,
p_offset: 0,
}),
+ // As many as the broken_citation_target signal reads: the line counts
+ // only those it would raise (cited, or brokenLinkMinVisits), and the
+ // most visited come first.
rpc('ai_traffic_broken_links', {
p_brand_id: brandId,
p_from: week.start,
p_to: until,
- p_limit: 1,
+ p_limit: BROKEN_LINKS_READ,
p_offset: 0,
}),
untrackedGoogleQueries(brandId, {
@@ -129,16 +137,23 @@ export async function readDigestData(brandId, week) {
limit: 0,
}),
]);
+ // The pages the changes could name, and the broken link with its redirect,
+ // checked against sources the public beacon can't write (00194).
+ const candidates = [...new Set([...pageCandidates(data), ...brokenCandidates(broken)])].sort();
// Share and conversions only from a connected Analytics (§3.8b rule 5).
const gaSessions = (Number(totals?.sessions) || 0) > 0 ? Number(totals.sessions) : null;
- const platformValue =
+ const [knownPages, platformValue] = await Promise.all([
+ candidates.length === 0
+ ? []
+ : rpc('ai_traffic_known_pages', { p_brand_id: brandId, p_pages: candidates }),
gaSessions === null
? null
- : await rpc('ga_platform_value', {
+ : rpc('ga_platform_value', {
p_brand_id: brandId,
p_since: week.firstDay,
p_until: week.lastDay,
- });
+ }),
+ ]);
return {
...data,
gaSessions,
@@ -146,6 +161,7 @@ export async function readDigestData(brandId, week) {
citedNotClicked: Number(pages?.counts?.cited_not_clicked) || 0,
broken: broken ?? null,
untrackedQueries: untracked?.count ?? 0,
+ knownPages: new Set(Array.isArray(knownPages) ? knownPages : []),
};
}
diff --git a/server/src/lib/traffic-digest/engine.test.js b/server/src/lib/traffic-digest/engine.test.js
index 8d1d8cf41..07f2f3acb 100644
--- a/server/src/lib/traffic-digest/engine.test.js
+++ b/server/src/lib/traffic-digest/engine.test.js
@@ -164,6 +164,54 @@ describe('sendTrafficDigestForBrand', () => {
]);
});
+ it('names only pages a source other than the public beacon knows (00194)', async () => {
+ state.rpc.ai_traffic_merged = (p) =>
+ p.p_from === '2026-10-12T00:00:00.000Z'
+ ? {
+ visits: 36,
+ platforms: [{ platform: 'chatgpt.com', visits: 36 }],
+ pages: [
+ { page: '/menu', visits: 30 },
+ { page: '/cheap-pills', visits: 6 },
+ ],
+ }
+ : { visits: 30, platforms: [{ platform: 'chatgpt.com', visits: 30 }], pages: [] };
+ state.rpc.ai_traffic_known_pages = () => ['/menu'];
+
+ await sendTrafficDigestForBrand('b1', { now: MONDAY });
+
+ const asked = state.rpcCalls.find((c) => c.name === 'ai_traffic_known_pages');
+ expect(asked.params).toEqual({ p_brand_id: 'b1', p_pages: ['/cheap-pills', '/menu'] });
+ const [mail] = deliverEmail.mock.calls[0];
+ expect(mail.html).toContain('/menu got 30 AI visits, none the week before.');
+ expect(mail.html).not.toContain('cheap-pills');
+ });
+
+ // gkhngyk on #1229: the broken-link line printed the first row's page and
+ // redirect whatever they were, and the beacon is public.
+ it('names a broken link only when it is cited or known, and counts the rest', async () => {
+ state.rpc.ai_traffic_broken_links = () => ({
+ count: 3,
+ rows: [
+ { page: '/win-a-prize', target: '/prizes', visits: 6, citations: 0 },
+ { page: '/old-menu', target: '/menu', visits: 3, citations: 0 },
+ { page: '/typo', target: '/', visits: 1, citations: 0 },
+ ],
+ });
+ state.rpc.ai_traffic_known_pages = () => ['/menu'];
+
+ await sendTrafficDigestForBrand('b1', { now: MONDAY });
+
+ const read = state.rpcCalls.find((c) => c.name === 'ai_traffic_broken_links');
+ expect(read.params.p_limit).toBe(50);
+ const asked = state.rpcCalls.find((c) => c.name === 'ai_traffic_known_pages');
+ expect(asked.params).toEqual({ p_brand_id: 'b1', p_pages: ['/prizes', '/win-a-prize'] });
+ const [mail] = deliverEmail.mock.calls[0];
+ expect(mail.html).toContain('2 pages AI visitors landed on don’t exist.');
+ expect(mail.html).not.toContain('win-a-prize');
+ expect(mail.html).not.toContain('/prizes');
+ });
+
it("reads each week to its Sunday's last second, so the Monday between them counts once", async () => {
await sendTrafficDigestForBrand('b1', { now: MONDAY });
const merged = state.rpcCalls.filter((c) => c.name === 'ai_traffic_merged');
diff --git a/server/src/lib/traffic-digest/summary.js b/server/src/lib/traffic-digest/summary.js
index 370b3d18c..6331bf793 100644
--- a/server/src/lib/traffic-digest/summary.js
+++ b/server/src/lib/traffic-digest/summary.js
@@ -16,6 +16,7 @@
*/
import { createRequire } from 'module';
+import { ENGINE_THRESHOLDS } from '../../config/action-engine.js';
// The AI Traffic page's names (web/src/lib/traffic-platforms.ts); a web test
// keeps the two the same.
@@ -35,6 +36,14 @@ export const TOP_CHANGES = 3;
export const platformName = (key) => PLATFORM_NAMES[key] ?? key;
+/**
+ * A platform the page can name. The snippet's beacon is public, so a source
+ * key can be anything a caller sent; the e-mail names only the platforms it
+ * knows (old keys included), never `unknown`.
+ */
+export const isNamedPlatform = (key) =>
+ key !== 'unknown' && Object.hasOwn(PLATFORM_NAMES, String(key ?? ''));
+
const n = (value) => Number(value) || 0;
const formatNumber = (value) => Math.round(value).toLocaleString('en-US');
const plural = (count, one, other) => (count === 1 ? one : other);
@@ -78,7 +87,7 @@ export function dailyVisits(week, days = []) {
export function topPlatforms(platforms = [], limit = 5) {
return platforms
.map((p) => ({ platform: String(p.platform ?? ''), visits: n(p.visits) }))
- .filter((p) => p.visits > 0 && p.platform)
+ .filter((p) => p.visits > 0 && isNamedPlatform(p.platform))
.sort((a, b) => b.visits - a.visits || a.platform.localeCompare(b.platform))
.slice(0, limit);
}
@@ -136,7 +145,7 @@ export function summarySentences(input) {
sentences.push(`${first.join(', ')}.`);
const top = [...(input.platforms ?? [])]
- .filter((p) => n(p.visits) > 0)
+ .filter((p) => n(p.visits) > 0 && isNamedPlatform(p.platform))
.sort((a, b) => n(b.visits) - n(a.visits))[0];
const best = input.gaSessions !== null ? bestConvertingPlatform(input.platformValue ?? []) : null;
const rate = best ? `${best.rate.toLocaleString('en-US')}%` : '';
@@ -173,7 +182,7 @@ export function summarySentences(input) {
return sentences;
}
-function movers(cur = [], prev = [], keyOf, type) {
+function movers(cur = [], prev = [], keyOf, type, accept) {
const before = new Map();
const now = new Map();
const names = new Map();
@@ -185,6 +194,7 @@ function movers(cur = [], prev = [], keyOf, type) {
const raw = keyOf(row);
if (!raw || raw === 'unknown') continue;
const key = type === 'page' ? raw.toLowerCase() : raw;
+ if (accept && !accept(key)) continue;
if (!names.has(key)) names.set(key, raw);
into.set(key, (into.get(key) ?? 0) + n(row.visits));
}
@@ -197,25 +207,75 @@ function movers(cur = [], prev = [], keyOf, type) {
}));
}
+/**
+ * The pages whose AI visits moved by MIN_CHANGE_VISITS or more, keyed as the
+ * Pages section keys them: the ones the digest asks ai_traffic_known_pages
+ * (00194) about before it may name them.
+ */
+export function pageCandidates({ cur, prev }) {
+ return movers(cur?.pages, prev?.pages, (r) => r.page, 'page')
+ .filter((m) => Math.abs(m.now - m.before) >= MIN_CHANGE_VISITS)
+ .map((m) => m.name.toLowerCase())
+ .sort();
+}
+
+/**
+ * The missing pages worth a line, as the broken_citation_target signal reads
+ * them (#1228): one AI answers cite from its first visit, any other from
+ * brokenLinkMinVisits. The beacon is public, so one stray or made-up 404
+ * visit doesn't reach the e-mail.
+ */
+export function brokenRows(broken) {
+ const rows = Array.isArray(broken?.rows) ? broken.rows : [];
+ return rows.filter(
+ (r) => n(r.citations) > 0 || n(r.visits) >= ENGINE_THRESHOLDS.library.brokenLinkMinVisits,
+ );
+}
+
+/**
+ * The broken link the e-mail would name and its redirect, keyed as
+ * pageCandidates are: they go to ai_traffic_known_pages too, since both can
+ * come from the beacon (00186 picks redirects among the pages it logged).
+ */
+export function brokenCandidates(broken) {
+ const [top] = brokenRows(broken);
+ if (!top) return [];
+ return [top.page, top.target].filter(Boolean).map((p) => String(p).toLowerCase());
+}
+
/**
* The week's top changes: broken AI links first — visitors are landing on
* missing pages every day until someone adds a redirect — then the platforms
- * and pages whose AI visits moved most, by at least MIN_CHANGE_VISITS.
+ * and pages whose AI visits moved most, by at least MIN_CHANGE_VISITS. Only
+ * platforms the page can name, and pages a source other than the public
+ * beacon knows (`knownPages`, from ai_traffic_known_pages); without it, no
+ * page. A broken link is named when AI answers cite it or it's known, and
+ * its redirect when that's known; otherwise the line gives only the count.
*/
-export function topChanges({ cur, prev, broken }, limit = TOP_CHANGES) {
+export function topChanges({ cur, prev, broken, knownPages }, limit = TOP_CHANGES) {
const changes = [];
- const brokenRows = Array.isArray(broken?.rows) ? broken.rows : [];
- if (brokenRows.length > 0) {
+ const known = knownPages ?? new Set();
+ const isKnown = (page) => !!page && known.has(String(page).toLowerCase());
+ const rows = brokenRows(broken);
+ if (rows.length > 0) {
+ const [top] = rows;
+ const named = n(top.citations) > 0 || isKnown(top.page);
changes.push({
type: 'broken',
- count: n(broken.count) || brokenRows.length,
- page: brokenRows[0].page,
- target: brokenRows[0].target ?? null,
+ count: rows.length,
+ page: named ? top.page : null,
+ target: named && isKnown(top.target) ? top.target : null,
});
}
const moved = [
- ...movers(cur?.platforms, prev?.platforms, (r) => r.platform, 'platform'),
- ...movers(cur?.pages, prev?.pages, (r) => r.page, 'page'),
+ ...movers(cur?.platforms, prev?.platforms, (r) => r.platform, 'platform', isNamedPlatform),
+ ...movers(
+ cur?.pages,
+ prev?.pages,
+ (r) => r.page,
+ 'page',
+ (key) => known.has(key),
+ ),
]
.filter((m) => Math.abs(m.now - m.before) >= MIN_CHANGE_VISITS)
.sort(
@@ -234,6 +294,7 @@ export function changeText(change) {
change.count === 1
? '1 page AI visitors landed on doesn’t exist'
: `${formatNumber(change.count)} pages AI visitors landed on don’t exist`;
+ if (!change.page) return `${pages}.`;
const redirect = change.target ? `, redirect to ${change.target}` : '';
return `${pages}: ${change.page}${redirect}.`;
}
diff --git a/server/src/lib/traffic-digest/summary.test.js b/server/src/lib/traffic-digest/summary.test.js
index a05d8de11..cd2639c37 100644
--- a/server/src/lib/traffic-digest/summary.test.js
+++ b/server/src/lib/traffic-digest/summary.test.js
@@ -1,9 +1,11 @@
import { describe, expect, it } from 'vitest';
import {
bestConvertingPlatform,
+ brokenCandidates,
changeText,
dailyVisits,
digestWeek,
+ pageCandidates,
summarySentences,
topChanges,
topPlatforms,
@@ -59,6 +61,9 @@ describe('the charts', () => {
{ platform: 'perplexity.ai', visits: 11 },
{ platform: 'claude.ai', visits: 0 },
{ platform: 'chatgpt.com', visits: '21' },
+ // A key only the public beacon sent, and a referrer nobody named.
+ { platform: 'made-up.example', visits: 90 },
+ { platform: 'unknown', visits: 40 },
]),
).toEqual([
{ platform: 'chatgpt.com', visits: 21 },
@@ -151,13 +156,24 @@ describe('topChanges', () => {
{ platform: 'chatgpt.com', visits: 12 },
{ platform: 'perplexity.ai', visits: 11 },
{ platform: 'grok.com', visits: 3 },
+ // The beacon is public: a key it was sent isn't a platform.
+ { platform: 'made-up.example', visits: 500 },
],
[
{ page: '/menu', visits: 8 },
{ page: '/gifts', visits: 6 },
+ // Nor is a path no source but the beacon knows.
+ { page: '/buy-now-spam', visits: 400 },
],
),
- broken: { count: 2, rows: [{ page: '/old-menu', target: '/menu' }] },
+ broken: {
+ count: 2,
+ rows: [
+ { page: '/old-menu', target: '/menu', visits: 4, citations: 2 },
+ { page: '/old-gifts', target: null, visits: 3, citations: 0 },
+ ],
+ },
+ knownPages: new Set(['/menu', '/gifts']),
});
expect(changes).toEqual([
{ type: 'broken', count: 2, page: '/old-menu', target: '/menu' },
@@ -166,6 +182,69 @@ describe('topChanges', () => {
]);
});
+ it('asks about the pages that moved, and names none it was not told are known', () => {
+ const data = {
+ prev: week(
+ [],
+ [
+ { page: '/Menu', visits: 10 },
+ { page: '/a', visits: 1 },
+ ],
+ ),
+ cur: week(
+ [],
+ [
+ { page: '/menu', visits: 2 },
+ { page: '/b', visits: 4 },
+ ],
+ ),
+ broken: null,
+ };
+ expect(pageCandidates(data)).toEqual(['/b', '/menu']);
+ expect(topChanges(data)).toEqual([]);
+ });
+
+ // gkhngyk on #1229: the beacon is public, so a broken page or its redirect
+ // can be any text a caller sent; and #1228's rule decides what counts.
+ it('counts broken links that are cited or have 3 visits, and names only known pages', () => {
+ const broken = {
+ count: 3,
+ rows: [
+ { page: '/Free-Crypto-Here', target: '/free-crypto', visits: 5, citations: 0 },
+ { page: '/old-menu', target: '/menu-2025', visits: 3, citations: 0 },
+ // One stray 404 visit isn't a broken link worth a line.
+ { page: '/typo', target: '/', visits: 1, citations: 0 },
+ ],
+ };
+ expect(brokenCandidates(broken)).toEqual(['/free-crypto-here', '/free-crypto']);
+ // Neither the page nor the redirect is known: only the count.
+ expect(topChanges({ broken, knownPages: new Set(['/menu']) })).toEqual([
+ { type: 'broken', count: 2, page: null, target: null },
+ ]);
+ // The page is known, its redirect isn't.
+ expect(topChanges({ broken, knownPages: new Set(['/free-crypto-here']) })).toEqual([
+ { type: 'broken', count: 2, page: '/Free-Crypto-Here', target: null },
+ ]);
+ // AI answers cite it: named, as the signal lists it.
+ const cited = {
+ count: 1,
+ rows: [{ page: '/old-menu', target: '/menu', visits: 1, citations: 4 }],
+ };
+ expect(topChanges({ broken: cited, knownPages: new Set(['/menu']) })).toEqual([
+ { type: 'broken', count: 1, page: '/old-menu', target: '/menu' },
+ ]);
+ // Only stray visits: no line at all.
+ const stray = {
+ count: 2,
+ rows: [
+ { page: '/a', visits: 2 },
+ { page: '/b', visits: 1 },
+ ],
+ };
+ expect(topChanges({ broken: stray })).toEqual([]);
+ expect(brokenCandidates(stray)).toEqual([]);
+ });
+
it('names nothing that moved by less than 3 visits', () => {
expect(
topChanges({
@@ -183,6 +262,9 @@ describe('topChanges', () => {
expect(changeText({ type: 'broken', count: 1, page: '/', target: null })).toBe(
'1 page AI visitors landed on doesn’t exist: /.',
);
+ expect(changeText({ type: 'broken', count: 3, page: null, target: null })).toBe(
+ '3 pages AI visitors landed on don’t exist.',
+ );
expect(changeText({ type: 'platform', name: 'chatgpt.com', before: 30, now: 12 })).toBe(
'ChatGPT sent 12 AI visits, down from 30.',
);
diff --git a/supabase/migrations/00194_ai_traffic_known_pages.sql b/supabase/migrations/00194_ai_traffic_known_pages.sql
new file mode 100644
index 000000000..618ffe506
--- /dev/null
+++ b/supabase/migrations/00194_ai_traffic_known_pages.sql
@@ -0,0 +1,73 @@
+-- ============================================================================
+-- 00194: which pages the weekly digest may name
+-- ============================================================================
+-- Follow-up from #1196's review (AT-013). The weekly AI Traffic e-mail names
+-- the pages whose AI visits moved most, and the top broken AI link with its
+-- suggested redirect. The snippet's beacon is public, so a page path in
+-- ai_traffic_logs can be anything a caller sent (00186 also picks redirects
+-- among the pages it logged), and the e-mail would print it.
+--
+-- ai_traffic_known_pages takes the page keys the digest would name (as the
+-- Pages section keys them: lower(normalize_page_path), 00178) and returns
+-- those a source the beacon can't write knows: the site's pages (site_pages,
+-- 00104: up to 500 from the sitemap, Analytics and citations, nightly),
+-- Google Analytics in the last 90 days, the pages tracked AI answers cited in
+-- the last 90 days, and active prompts' target URLs — and the home page,
+-- which every site has. The digest asks only about a handful of pages a
+-- week. Service role only.
+
+create or replace function public.ai_traffic_known_pages(
+ p_brand_id uuid,
+ p_pages text[]
+)
+returns text[]
+language sql
+stable
+security definer
+set search_path to 'public'
+as $$
+ with asked as (
+ select distinct p.page from unnest(p_pages) as p(page)
+ ),
+ known as (
+ select '/' as page
+ union
+ select lower(public.normalize_page_path(sp.url))
+ from public.site_pages sp
+ where sp.brand_id = p_brand_id
+ union
+ select lower(public.normalize_page_path(g.landing_page))
+ from public.ga_page_stats g
+ where g.brand_id = p_brand_id
+ and g.landing_page <> ''
+ and g.date >= current_date - 90
+ union
+ select lower(public.normalize_page_path(g.landing_page))
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.landing_page <> ''
+ and g.date >= current_date - 90
+ union
+ select c.page_key
+ from public.ai_traffic_page_citations(p_brand_id, current_date - 90, current_date) c
+ union
+ select lower(public.normalize_page_path(ptu.url))
+ from public.prompt_target_urls ptu
+ join public.prompts p on p.id = ptu.prompt_id and p.is_active
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = p_brand_id
+ )
+ select coalesce(array_agg(a.page order by a.page), '{}')
+ from asked a
+ where a.page in (select k.page from known k);
+$$;
+
+revoke all on function public.ai_traffic_known_pages(uuid, text[])
+ from public, anon, authenticated;
+grant execute on function public.ai_traffic_known_pages(uuid, text[])
+ to service_role;
+
+comment on function public.ai_traffic_known_pages(uuid, text[]) is
+ 'AI Traffic weekly digest (AT-013): of the given page keys, those the site''s pages, Google Analytics (90 days), AI answer citations (90 days) or active prompts'' target URLs know, so the e-mail never prints a path only the public beacon sent. Service role only.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 26e63c28f..623ff30cd 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -26849,6 +26849,83 @@ comment on function public.ai_traffic_platforms_seen(uuid, timestamptz, text[])
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00194_ai_traffic_known_pages.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00194: which pages the weekly digest may name
+-- ============================================================================
+-- Follow-up from #1196's review (AT-013). The weekly AI Traffic e-mail names
+-- the pages whose AI visits moved most, and the top broken AI link with its
+-- suggested redirect. The snippet's beacon is public, so a page path in
+-- ai_traffic_logs can be anything a caller sent (00186 also picks redirects
+-- among the pages it logged), and the e-mail would print it.
+--
+-- ai_traffic_known_pages takes the page keys the digest would name (as the
+-- Pages section keys them: lower(normalize_page_path), 00178) and returns
+-- those a source the beacon can't write knows: the site's pages (site_pages,
+-- 00104: up to 500 from the sitemap, Analytics and citations, nightly),
+-- Google Analytics in the last 90 days, the pages tracked AI answers cited in
+-- the last 90 days, and active prompts' target URLs — and the home page,
+-- which every site has. The digest asks only about a handful of pages a
+-- week. Service role only.
+
+create or replace function public.ai_traffic_known_pages(
+ p_brand_id uuid,
+ p_pages text[]
+)
+returns text[]
+language sql
+stable
+security definer
+set search_path to 'public'
+as $$
+ with asked as (
+ select distinct p.page from unnest(p_pages) as p(page)
+ ),
+ known as (
+ select '/' as page
+ union
+ select lower(public.normalize_page_path(sp.url))
+ from public.site_pages sp
+ where sp.brand_id = p_brand_id
+ union
+ select lower(public.normalize_page_path(g.landing_page))
+ from public.ga_page_stats g
+ where g.brand_id = p_brand_id
+ and g.landing_page <> ''
+ and g.date >= current_date - 90
+ union
+ select lower(public.normalize_page_path(g.landing_page))
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.landing_page <> ''
+ and g.date >= current_date - 90
+ union
+ select c.page_key
+ from public.ai_traffic_page_citations(p_brand_id, current_date - 90, current_date) c
+ union
+ select lower(public.normalize_page_path(ptu.url))
+ from public.prompt_target_urls ptu
+ join public.prompts p on p.id = ptu.prompt_id and p.is_active
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = p_brand_id
+ )
+ select coalesce(array_agg(a.page order by a.page), '{}')
+ from asked a
+ where a.page in (select k.page from known k);
+$$;
+
+revoke all on function public.ai_traffic_known_pages(uuid, text[])
+ from public, anon, authenticated;
+grant execute on function public.ai_traffic_known_pages(uuid, text[])
+ to service_role;
+
+comment on function public.ai_traffic_known_pages(uuid, text[]) is
+ 'AI Traffic weekly digest (AT-013): of the given page keys, those the site''s pages, Google Analytics (90 days), AI answer citations (90 days) or active prompts'' target URLs know, so the e-mail never prints a path only the public beacon sent. Service role only.';
+
+notify pgrst, 'reload schema';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00196_getting_started.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx
index 2f1301134..cb3e107d6 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx
@@ -193,6 +193,21 @@ describe('TrafficKpis', () => {
expect(card('Platforms')).toContain('3unique AI sources');
});
+ // gkhngyk on #1229: the beacon is public, so a source key can be any text.
+ it('names the top platform among those it can name, as the summary line does', async () => {
+ await render({
+ sum: summary({
+ platformBreakdown: [
+ { platform: 'made-up.example', visits: 5, visitsPrev: 0, analytics: null },
+ { platform: 'chatgpt.com', visits: 1, visitsPrev: 1, analytics: null },
+ ],
+ }),
+ });
+ expect(card('Top platform')).toContain('ChatGPT');
+ expect(card('Top platform')).toContain('1 visit');
+ expect(card('Top platform')).not.toContain('made-up');
+ });
+
it('says how many days came from Google Analytics instead of a partial pageview count (AT-004)', async () => {
await render({
preset: '30d',
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx
index 92e6ccea8..65aa5472b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx
@@ -30,7 +30,7 @@ import {
isShortRange,
organicRatio,
} from '@/lib/traffic-kpis';
-import { getPlatformName } from '@/lib/traffic-platforms';
+import { getPlatformName, isNamedPlatform } from '@/lib/traffic-platforms';
import { googleSourceStatus, TRAFFIC_SECTION_SOURCES } from '@/lib/traffic-sources';
import { MetricCard } from '../insights/_kpi-cards';
import { SummaryLine } from './_summary-line';
@@ -171,7 +171,11 @@ export function TrafficKpis({
// From the summary, not the selected range: while a new range loads, the
// numbers on screen are still the previous range's.
const comparable = summary?.hasPreviousPeriod ?? false;
- const topPlatform = summary?.platformBreakdown[0];
+ // The most visits among the platforms it can name, as the summary line and
+ // the weekly e-mail pick it: a key only the public beacon sent isn't one.
+ const topPlatform = summary?.platformBreakdown.find(
+ (p) => p.visits > 0 && isNamedPlatform(p.platform),
+ );
const totals = loaded?.key === key ? loaded.totals : null;
const ga = totals?.ga ?? null;
const gsc = totals?.gsc ?? null;
diff --git a/web/src/lib/traffic-platforms.ts b/web/src/lib/traffic-platforms.ts
index 3b50acccf..6a2b19463 100644
--- a/web/src/lib/traffic-platforms.ts
+++ b/web/src/lib/traffic-platforms.ts
@@ -27,3 +27,13 @@ const PLATFORM_NAMES: Record<string, string> = {
export function getPlatformName(platform: string): string {
return PLATFORM_NAMES[platform] ?? platform;
}
+
+/**
+ * A platform the page can name. The snippet's beacon is public, so a source
+ * key can be anything a caller sent. The weekly digest's isNamedPlatform
+ * (platform-names.json, the same names) reads it the same way, so the two
+ * name the same platform as the one that sent the most.
+ */
+export function isNamedPlatform(platform: string): boolean {
+ return platform !== 'unknown' && Object.hasOwn(PLATFORM_NAMES, platform);
+}
diff --git a/web/src/lib/traffic-summary-line.test.ts b/web/src/lib/traffic-summary-line.test.ts
index 7ece158bf..ef9aebe42 100644
--- a/web/src/lib/traffic-summary-line.test.ts
+++ b/web/src/lib/traffic-summary-line.test.ts
@@ -51,6 +51,23 @@ describe('summaryLine', () => {
expect(summaryLine(input({ totalVisits: 50, totalVisitsPrev: 100 })).change).toBe(-50);
});
+ // gkhngyk on #1229: the e-mail's "X sent the most" skips keys it can't name.
+ it('names the top platform among those it can name, as the weekly e-mail does', () => {
+ const line = summaryLine(
+ input({
+ platforms: [
+ { platform: 'made-up.example', visits: 90, analytics: null },
+ { platform: 'unknown', visits: 60, analytics: null },
+ { platform: 'perplexity.ai', visits: 20, analytics: null },
+ ],
+ }),
+ );
+ expect(line.top).toEqual({ platform: 'perplexity.ai', visits: 20 });
+ expect(
+ summaryLine(input({ platforms: [{ platform: 'unknown', visits: 9, analytics: null }] })).top,
+ ).toBeNull();
+ });
+
it('says nothing about cited pages while their count is unknown or zero', () => {
expect(summaryLine(input({ citedNotClicked: null })).citedNotClicked).toBe(0);
expect(summaryLine(input({ platforms: [] })).top).toBeNull();
diff --git a/web/src/lib/traffic-summary-line.ts b/web/src/lib/traffic-summary-line.ts
index c2656e5ce..21fa711f1 100644
--- a/web/src/lib/traffic-summary-line.ts
+++ b/web/src/lib/traffic-summary-line.ts
@@ -19,6 +19,7 @@
import type { TrafficEngagement } from '@/lib/actions/traffic';
import { LOW_SAMPLE_VISITS, visitChange } from '@/lib/traffic-change';
import { formatShare } from '@/lib/traffic-kpis';
+import { isNamedPlatform } from '@/lib/traffic-platforms';
/** Key events a platform needs before its conversions are compared (§5.4). */
export const MIN_COMPARED_KEY_EVENTS = 5;
@@ -72,13 +73,14 @@ export function summaryLine(input: SummaryLineInput): SummaryLine {
const change = visitChange(input.totalVisits, input.totalVisitsPrev, {
comparable: input.hasPreviousPeriod,
});
- const top = input.platforms[0];
+ // The most visits among the platforms it can name, as the weekly e-mail picks it.
+ const top = input.platforms.find((p) => p.visits > 0 && isNamedPlatform(p.platform));
const ga = input.gaSessions !== null;
return {
visits: input.totalVisits,
share: ga ? formatShare(input.totalVisits, input.gaSessions ?? 0) : null,
change: change.kind === 'pct' ? change.pct : null,
- top: top && top.visits > 0 ? { platform: top.platform, visits: top.visits } : null,
+ top: top ? { platform: top.platform, visits: top.visits } : null,
best: ga ? bestConvertingPlatform(input.platforms) : null,
citedNotClicked: input.citedNotClicked ?? 0,
untrackedQueries: input.untrackedQueries ?? 0,