Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(traffic): send Pages to the Action Center and audit cited pages at once (#1171)
Cihan0f55275fcd6c
diff --git a/server/src/lib/action-center/from-traffic-pages.js b/server/src/lib/action-center/from-traffic-pages.jsnew file mode 100644index 000000000..e417af825--- /dev/null+++ b/server/src/lib/action-center/from-traffic-pages.js@@ -0,0 +1,284 @@+/**+ * "Send to Action Center" from the AI Traffic page's Pages section (AT-006,+ * spec §3.5): one page, or a list's pages, sent as one action.+ *+ * The person sends pages from a list; the lists themselves are read again+ * here from ai_traffic_pages (00178) over the same range, so only the pages+ * still on that list go, with their figures as the database has them, not as+ * a client says they are. Two lists can be sent:+ *+ * - Cited, not clicked: answers cite the pages and nobody clicks through —+ * Fix work, to make the cited page worth the click.+ * - No AI traffic: pages with visitors or in the sitemap that AI sends+ * nobody to — G01's plan (Capture AI Traffic), the one the nightly+ * detection gives the same pages.+ *+ * Measured afterwards on its pages like any person-sent action+ * (basket-metrics.js): their citations and AI-referred sessions.+ */++import { createHash } from 'node:crypto';+import supabaseAdmin from '../../config/supabase.js';+import captureAiTraffic from './definitions/g01-capture-ai-traffic.js';+import { priorityOnCreate } from './priority-data.js';+import { resolveBrandSources } from './sources.js';+import { planTasks } from './tasks/plan.js';++export const TRAFFIC_PAGES_ACTION_KIND = 'traffic_pages';++/** The lists a page can be sent from, as 00178 names its tabs. */+export const TRAFFIC_PAGE_REASONS = ['cited_not_clicked', 'no_ai_traffic'];++/** At most a few pages of the list at once. */+export const MAX_TRAFFIC_PAGES = 50;++const ACTIVE = ['new', 'in_progress', 'on_hold'];+const KPI_KEYS = ['ai_referral_traffic', 'citations'];+/** Every page of a list, however long, to find the ones sent. */+const LIST_LIMIT = 10_000;++/**+ * Cited, not clicked: the answers already show the page, so the work is the+ * page itself — what the answers say about it, what it lacks against them,+ * and the path from the answer to a click.+ */+export const CITED_NOT_CLICKED_TASKS = [+ 'analyze_citations',+ 'analyze_ai_responses',+ 'identify_content_gaps',+ 'optimize_content',+ 'improve_cta_path',+ 'publish_content',+ 'validate_ai_traffic',+ 'validate_citations',+ 'measure_action_outcome',+];++/** What the list asks for: Fix for cited pages nobody clicks, Growth for pages AI skips. */+export function trafficPagesTasks(reason) {+ return reason === 'cited_not_clicked' ? CITED_NOT_CLICKED_TASKS : captureAiTraffic.tasks;+}++function httpError(message, status) {+ const err = new Error(message);+ err.status = status;+ return err;+}++/** A page path as 00178 keys it: lowercased, without a trailing slash. */+export function pageKeyOf(path) {+ const trimmed = String(path ?? '')+ .trim()+ .replace(/\/+$/, '');+ return (trimmed || '/').toLowerCase();+}++/** One action per list and set of pages: the same pages sent again find it. */+export function trafficPagesDedupKey(reason, pages) {+ const digest = createHash('sha1')+ .update([...new Set(pages.map(pageKeyOf))].sort().join('\n'))+ .digest('hex');+ return `${TRAFFIC_PAGES_ACTION_KIND}:${reason}:${digest.slice(0, 20)}`;+}++/**+ * Category and impact. Cited pages nobody clicks are Fix work, more urgent+ * the more often answers show them; pages AI skips are Growth, worth more+ * when they make money or convert.+ */+export function trafficPagesWeight(pages, reason) {+ if (reason === 'cited_not_clicked') {+ const citations = pages.reduce((sum, p) => sum + p.citations, 0);+ return { category: 'fix', impact: citations >= 100 ? 'high' : 'medium' };+ }+ const sells = pages.some((p) => p.revenue > 0 || p.transactions > 0);+ const converts = pages.some((p) => p.keyEvents > 0);+ return { category: 'growth', impact: sells ? 'high' : converts ? 'medium' : 'low' };+}++/** What the pages are worth, in the strongest figure Analytics reports for them. */+export function trafficPagesValueSignal(pages) {+ if (pages.some((p) => p.revenue > 0)) return 'revenue';+ if (pages.some((p) => p.transactions > 0)) return 'transactions';+ if (pages.some((p) => p.keyEvents > 0)) return 'key_events';+ if (pages.some((p) => p.sessions > 0)) return 'engagement';+ return null;+}++/** A 00178 row in the action's terms. */+function pageFigures(row) {+ return {+ page: String(row.page),+ aiVisits: Number(row.ai_visits) || 0,+ citations: Number(row.citations) || 0,+ targetingPrompts: Number(row.targeting_prompts) || 0,+ sessions: Number(row.sessions) || 0,+ keyEvents: Number(row.key_events) || 0,+ transactions: Number(row.transactions) || 0,+ revenue: Number(row.revenue) || 0,+ inSitemap: Boolean(row.in_sitemap),+ valueRank:+ row.value_rank === null || row.value_rank === undefined ? null : Number(row.value_rank),+ };+}++/** The brand's primary host, for the pages' full URLs: measuring needs them. */+async function primaryHost(brandId) {+ const { data, error } = await supabaseAdmin+ .from('brand_domains')+ .select('domain, is_primary, created_at')+ .eq('brand_id', brandId)+ .order('is_primary', { ascending: false })+ .order('created_at', { ascending: true })+ .limit(1);+ if (error) throw new Error(error.message);+ const domain = data?.[0]?.domain;+ if (!domain) return null;+ return (+ String(domain)+ .trim()+ .replace(/^https?:\/\//i, '')+ .replace(/\/.*$/, '')+ .toLowerCase() || null+ );+}++/**+ * Creates the action, or returns the open one if these pages were already+ * sent from the same list.+ *+ * @param {string} brandId - checked against the caller's org by the route+ * @param {{ pages: string[], reason: 'cited_not_clicked' | 'no_ai_traffic',+ * from?: string, to?: string, userId: string }} opts+ * @returns {Promise<{ actionId: string, actionNo: number, created: boolean }>}+ */+export async function sendTrafficPagesToActionCenter(brandId, { pages, reason, from, to, userId }) {+ if (!TRAFFIC_PAGE_REASONS.includes(reason)) throw httpError('Unknown list', 400);+ const wanted = new Set(pages.slice(0, MAX_TRAFFIC_PAGES).map(pageKeyOf));++ // The list as the page showed it, read again over the same range.+ const { data: list, error: listErr } = await supabaseAdmin.rpc('ai_traffic_pages', {+ p_brand_id: brandId,+ p_from: from ?? null,+ p_to: to ?? null,+ p_tab: reason,+ p_limit: LIST_LIMIT,+ p_offset: 0,+ });+ if (listErr) throw new Error(listErr.message);+ const found = ((list ?? {}).rows ?? [])+ .filter((row) => wanted.has(pageKeyOf(row.page)))+ .map(pageFigures);+ if (!found.length) throw httpError('None of these pages are on the list for this range', 404);++ // Keyed on the pages found, so a page that left the list can't open a+ // second action for the same pages.+ const dedupKey = trafficPagesDedupKey(+ reason,+ found.map((p) => p.page),+ );+ const openAction = async () => {+ const { data } = await supabaseAdmin+ .from('actions')+ .select('id, action_no')+ .eq('brand_id', brandId)+ .eq('dedup_key', dedupKey)+ .in('status', ACTIVE)+ .maybeSingle();+ return data;+ };+ const open = await openAction();+ if (open) return { actionId: open.id, actionNo: Number(open.action_no), created: false };++ const host = await primaryHost(brandId);+ const { category, impact } = trafficPagesWeight(found, reason);+ const total = (field) => found.reduce((sum, p) => sum + p[field], 0);++ const payload = {+ source: TRAFFIC_PAGES_ACTION_KIND,+ reason,+ window: { from: from ?? null, to: to ?? null },+ pageCount: found.length,+ citations: total('citations'),+ sessions: total('sessions'),+ keyEvents: total('keyEvents'),+ revenue: total('revenue'),+ valueSignal: trafficPagesValueSignal(found),+ evidence: found,+ // Measured on these pages once done (basket-metrics.js), by full URL.+ pages: host ? found.map((p) => `https://${host}${p.page === '/' ? '' : p.page}`) : [],+ targetEntity: 'pages',+ targetCount: found.length,+ targets: found.map((p) => ({+ id: p.page,+ label: p.page,+ sessions: p.sessions,+ citations: p.citations,+ })),+ };++ const { data: action, error } = await supabaseAdmin+ .from('actions')+ .insert({+ brand_id: brandId,+ category,+ kind: TRAFFIC_PAGES_ACTION_KIND,+ definition_version: 1,+ impact,+ payload,+ kpi_keys: KPI_KEYS,+ baseline: {+ aiVisits: total('aiVisits'),+ citations: payload.citations,+ sessions: payload.sessions,+ },+ dedup_key: dedupKey,+ ...(await priorityOnCreate({ kind: TRAFFIC_PAGES_ACTION_KIND, category, impact, payload })),+ })+ .select('id, action_no')+ .single();+ if (error) {+ // Two sends at once: the other one opened it (the open-action dedup index, 00084).+ if (error.code === '23505') {+ const winner = await openAction();+ if (winner) {+ return { actionId: winner.id, actionNo: Number(winner.action_no), created: false };+ }+ }+ throw new Error(error.message);+ }++ const sources = await resolveBrandSources(brandId);+ const plan = planTasks(+ { id: TRAFFIC_PAGES_ACTION_KIND, tasks: trafficPagesTasks(reason) },+ { sources, payload },+ );+ const { error: tasksErr } = await supabaseAdmin.from('action_tasks').insert(+ plan.map((item) => ({+ action_id: action.id,+ position: item.position,+ task_key: item.taskKey,+ task_version: item.version,+ mode: item.mode,+ permission: item.permission,+ depends_on: item.dependsOn,+ title_params: item.titleParams,+ status: 'todo',+ })),+ );+ if (tasksErr) throw new Error(tasksErr.message);++ await supabaseAdmin.from('action_events').insert({+ action_id: action.id,+ event: 'created',+ actor_id: userId,+ data: {+ source: TRAFFIC_PAGES_ACTION_KIND,+ reason,+ pages: found.length,+ taskCount: plan.length,+ },+ });++ return { actionId: action.id, actionNo: Number(action.action_no), created: true };+}diff --git a/server/src/lib/action-center/from-traffic-pages.test.js b/server/src/lib/action-center/from-traffic-pages.test.jsnew file mode 100644index 000000000..756ed2034--- /dev/null+++ b/server/src/lib/action-center/from-traffic-pages.test.js@@ -0,0 +1,323 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * sendTrafficPagesToActionCenter (AT-006): pages from the AI Traffic page's+ * Pages section as one action. These pin that the list is read again on the+ * server over the same range (only pages still on it go), that the same+ * pages sent again return the open action, and that the action carries its+ * list's plan, its pages as full URLs for measuring, the figures as the+ * database has them and a person's "created" event.+ */++let db;++function table(name) {+ const state = { name, filters: {}, op: 'select', row: null };+ const result = () => {+ if (state.op === 'insert') {+ db.inserts.push({ table: name, row: state.row });+ if (name === 'actions') {+ return db.insertError+ ? { data: null, error: db.insertError }+ : { data: { id: 'act-1', action_no: 71 }, error: null };+ }+ return { data: null, error: null };+ }+ return { data: db.rows[name]?.(state.filters) ?? null, error: null };+ };+ const chain = {+ select: () => chain,+ insert: (row) => {+ state.op = 'insert';+ state.row = row;+ return chain;+ },+ eq: (col, val) => {+ state.filters[col] = val;+ return chain;+ },+ in: (col, val) => {+ state.filters[col] = val;+ return chain;+ },+ order: () => chain,+ limit: () => chain,+ maybeSingle: async () => result(),+ single: async () => result(),+ then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),+ };+ return chain;+}++const rpc = vi.fn();+vi.mock('../../config/supabase.js', () => ({+ default: { from: (name) => table(name), rpc: (...args) => rpc(...args) },+}));+vi.mock('./sources.js', () => ({+ resolveBrandSources: async () => new Set(['tracking', 'analytics', 'ai_traffic']),+}));+vi.mock('./priority-data.js', () => ({+ priorityOnCreate: async () => ({ priority_score: 61, priority_level: 'medium' }),+}));++const {+ CITED_NOT_CLICKED_TASKS,+ pageKeyOf,+ sendTrafficPagesToActionCenter,+ trafficPagesDedupKey,+ trafficPagesValueSignal,+ trafficPagesWeight,+} = await import('./from-traffic-pages.js');+const { default: captureAiTraffic } = await import('./definitions/g01-capture-ai-traffic.js');++const row = (page, over = {}) => ({+ page,+ ai_visits: 0,+ citations: 0,+ targeting_prompts: 0,+ sessions: 0,+ key_events: 0,+ transactions: 0,+ revenue: 0,+ in_sitemap: false,+ value_rank: null,+ ...over,+});++const FROM = '2026-09-18T12:00:00.000Z';+const TO = '2026-10-18T12:00:00.000Z';++beforeEach(() => {+ rpc.mockReset();+ rpc.mockResolvedValue({+ data: {+ counts: { cited_not_clicked: 2 },+ rows: [+ row('/Guides/Espresso', { citations: 80, targeting_prompts: 1 }),+ row('/shop/beans', { citations: 22, sessions: 240, key_events: 18, value_rank: 4 }),+ ],+ },+ error: null,+ });+ db = {+ inserts: [],+ insertError: null,+ rows: {+ actions: () => null,+ brand_domains: () => [{ domain: 'https://www.Acme-Coffee.example.com/', is_primary: true }],+ },+ };+});++describe('sendTrafficPagesToActionCenter', () => {+ it('creates a Fix action from the cited pages as the list has them', async () => {+ const result = await sendTrafficPagesToActionCenter('b1', {+ // Another spelling of a listed page, and a page no longer on the list.+ pages: ['/guides/espresso/', '/shop/beans', '/menu'],+ reason: 'cited_not_clicked',+ from: FROM,+ to: TO,+ userId: 'u1',+ });+ expect(result).toEqual({ actionId: 'act-1', actionNo: 71, created: true });++ // The same list over the same range.+ expect(rpc).toHaveBeenCalledWith('ai_traffic_pages', {+ p_brand_id: 'b1',+ p_from: FROM,+ p_to: TO,+ p_tab: 'cited_not_clicked',+ p_limit: 10_000,+ p_offset: 0,+ });++ const action = db.inserts.find((i) => i.table === 'actions').row;+ expect(action).toMatchObject({+ brand_id: 'b1',+ category: 'fix',+ kind: 'traffic_pages',+ impact: 'high',+ kpi_keys: ['ai_referral_traffic', 'citations'],+ baseline: { aiVisits: 0, citations: 102, sessions: 240 },+ // /menu isn't on the list, so it doesn't change which action these pages find.+ dedup_key: trafficPagesDedupKey('cited_not_clicked', ['/guides/espresso', '/shop/beans']),+ priority_score: 61,+ });+ expect(action.payload).toMatchObject({+ source: 'traffic_pages',+ reason: 'cited_not_clicked',+ window: { from: FROM, to: TO },+ pageCount: 2,+ citations: 102,+ sessions: 240,+ valueSignal: 'key_events',+ pages: [+ 'https://www.acme-coffee.example.com/Guides/Espresso',+ 'https://www.acme-coffee.example.com/shop/beans',+ ],+ targetEntity: 'pages',+ targetCount: 2,+ targets: [+ { id: '/Guides/Espresso', label: '/Guides/Espresso', sessions: 0, citations: 80 },+ { id: '/shop/beans', label: '/shop/beans', sessions: 240, citations: 22 },+ ],+ });+ expect(action.payload.evidence[1]).toEqual({+ page: '/shop/beans',+ aiVisits: 0,+ citations: 22,+ targetingPrompts: 0,+ sessions: 240,+ keyEvents: 18,+ transactions: 0,+ revenue: 0,+ inSitemap: false,+ valueRank: 4,+ });++ const tasks = db.inserts.find((i) => i.table === 'action_tasks').row;+ expect(tasks.map((t) => t.task_key)).toEqual(CITED_NOT_CLICKED_TASKS);+ const event = db.inserts.find((i) => i.table === 'action_events').row;+ expect(event).toMatchObject({+ event: 'created',+ actor_id: 'u1',+ data: { source: 'traffic_pages', reason: 'cited_not_clicked', pages: 2 },+ });+ });++ it("gives pages AI skips G01's plan, as Growth, over all time", async () => {+ rpc.mockResolvedValue({+ data: {+ rows: [row('/', { sessions: 90, revenue: 361.5, transactions: 3, in_sitemap: true })],+ },+ error: null,+ });+ await sendTrafficPagesToActionCenter('b1', {+ pages: ['/'],+ reason: 'no_ai_traffic',+ userId: 'u1',+ });+ expect(rpc.mock.calls[0][1]).toMatchObject({+ p_from: null,+ p_to: null,+ p_tab: 'no_ai_traffic',+ });+ const action = db.inserts.find((i) => i.table === 'actions').row;+ expect(action).toMatchObject({ category: 'growth', impact: 'high' });+ expect(action.payload).toMatchObject({+ pages: ['https://www.acme-coffee.example.com'],+ valueSignal: 'revenue',+ revenue: 361.5,+ });+ const tasks = db.inserts.find((i) => i.table === 'action_tasks').row;+ // The plan drops what the brand can't do; G01's tasks keep their order.+ const keys = tasks.map((t) => t.task_key);+ expect(keys.length).toBeGreaterThan(0);+ expect(keys.every((k) => captureAiTraffic.tasks.includes(k))).toBe(true);+ expect(keys).toEqual(captureAiTraffic.tasks.filter((k) => keys.includes(k)));+ });++ it('still sends, unmeasured, when the brand has no domain', async () => {+ db.rows.brand_domains = () => [];+ await sendTrafficPagesToActionCenter('b1', {+ pages: ['/shop/beans'],+ reason: 'cited_not_clicked',+ userId: 'u1',+ });+ const action = db.inserts.find((i) => i.table === 'actions').row;+ expect(action.payload.pages).toEqual([]);+ expect(action.payload.targetCount).toBe(1);+ });++ it('returns the open action when the same pages were sent from the list', async () => {+ db.rows.actions = () => ({ id: 'act-9', action_no: 9 });+ await expect(+ sendTrafficPagesToActionCenter('b1', {+ pages: ['/shop/beans', '/guides/espresso'],+ reason: 'cited_not_clicked',+ userId: 'u1',+ }),+ ).resolves.toEqual({ actionId: 'act-9', actionNo: 9, created: false });+ expect(db.inserts).toEqual([]);+ });++ it('refuses pages that are no longer on the list', async () => {+ await expect(+ sendTrafficPagesToActionCenter('b1', {+ pages: ['/menu'],+ reason: 'cited_not_clicked',+ userId: 'u1',+ }),+ ).rejects.toMatchObject({ status: 404 });+ expect(db.inserts).toEqual([]);+ });++ it('refuses a list it does not know', async () => {+ await expect(+ sendTrafficPagesToActionCenter('b1', { pages: ['/'], reason: 'all', userId: 'u1' }),+ ).rejects.toMatchObject({ status: 400 });+ expect(rpc).not.toHaveBeenCalled();+ });++ it('returns the winner when another send opened it first', async () => {+ db.insertError = { code: '23505', message: 'duplicate' };+ let reads = 0;+ db.rows.actions = () => (reads++ === 0 ? null : { id: 'act-7', action_no: 7 });+ await expect(+ sendTrafficPagesToActionCenter('b1', {+ pages: ['/shop/beans'],+ reason: 'cited_not_clicked',+ userId: 'u1',+ }),+ ).resolves.toEqual({ actionId: 'act-7', actionNo: 7, created: false });+ });+});++describe('the action’s weight and key', () => {+ const page = (over) => ({+ citations: 0,+ revenue: 0,+ transactions: 0,+ keyEvents: 0,+ sessions: 0,+ ...over,+ });++ it('makes cited pages Fix work, high from 100 citations', () => {+ expect(+ trafficPagesWeight([page({ citations: 60 }), page({ citations: 39 })], 'cited_not_clicked'),+ ).toEqual({+ category: 'fix',+ impact: 'medium',+ });+ expect(trafficPagesWeight([page({ citations: 100 })], 'cited_not_clicked').impact).toBe('high');+ });++ it('makes skipped pages Growth, weighted by what they earn', () => {+ expect(trafficPagesWeight([page({ revenue: 10 })], 'no_ai_traffic')).toEqual({+ category: 'growth',+ impact: 'high',+ });+ expect(trafficPagesWeight([page({ keyEvents: 2 })], 'no_ai_traffic').impact).toBe('medium');+ expect(trafficPagesWeight([page({ sessions: 40 })], 'no_ai_traffic').impact).toBe('low');+ });++ it('names the strongest value Analytics reports', () => {+ expect(trafficPagesValueSignal([page({ keyEvents: 1 }), page({ transactions: 1 })])).toBe(+ 'transactions',+ );+ expect(trafficPagesValueSignal([page({ sessions: 3 })])).toBe('engagement');+ expect(trafficPagesValueSignal([page({ citations: 30 })])).toBeNull();+ });++ it('keys the same pages the same way, in any order or spelling', () => {+ expect(pageKeyOf('/Shop/Beans/')).toBe('/shop/beans');+ expect(pageKeyOf('/')).toBe('/');+ expect(trafficPagesDedupKey('no_ai_traffic', ['/b', '/A/', '/a'])).toBe(+ trafficPagesDedupKey('no_ai_traffic', ['/a', '/b']),+ );+ expect(trafficPagesDedupKey('no_ai_traffic', ['/a'])).not.toBe(+ trafficPagesDedupKey('cited_not_clicked', ['/a']),+ );+ });+});diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.jsindex e107c93f6..96b75ae69 100644--- a/server/src/lib/action-center/priority.js+++ b/server/src/lib/action-center/priority.js@@ -249,6 +249,12 @@ function demandAndValue(payloads, signals, prompts) {if (typeof p?.valueSignal === 'string' && PAGE_VALUE[p.valueSignal]) {pageValue = Math.max(pageValue ?? 0, PAGE_VALUE[p.valueSignal]);}+ // Pages sent from AI Traffic (AT-006) carry their sessions over the range.+ if (p?.source === 'traffic_pages') {+ for (const t of targetsOf(p)) {+ if (Number.isFinite(t.sessions) && t.sessions > 0) pageSessions.push(t.sessions);+ }+ }}for (const s of signals) {// Sessions only from the AI-traffic kinds: other page targets carry@@ -345,6 +351,19 @@ function sentByHand(action) {subject: { entity: p.targetEntity ?? 'prompts', count: p.targetCount ?? null },};}+ // Pages sent from AI Traffic (AT-006). Answers citing a page nobody clicks+ // rest on two sources, citations and traffic, and the page already earns+ // the answer; a page AI skips rests on traffic alone.+ if (action.kind === 'traffic_pages') {+ const cited = p.reason === 'cited_not_clicked';+ return {+ change: 'gap',+ severity: cited ? 0.55 : 0.45,+ confidence: cited ? 0.6 : 0.45,+ recoverability: cited ? 0.7 : 0.5,+ subject: { entity: 'pages', count: p.targetCount ?? null },+ };+ }return null;}diff --git a/server/src/lib/action-center/priority.test.js b/server/src/lib/action-center/priority.test.jsindex fd4e06442..91ee77d35 100644--- a/server/src/lib/action-center/priority.test.js+++ b/server/src/lib/action-center/priority.test.js@@ -306,6 +306,47 @@ describe('scorePriority', () => {expect(content.score).toBeGreaterThan(0);});+ it('scores pages sent from AI Traffic on their list, sessions and value (AT-006)', () => {+ const sent = (reason, payload = {}) =>+ scorePriority(+ {+ action: action({+ kind: 'traffic_pages',+ category: reason === 'cited_not_clicked' ? 'fix' : 'growth',+ impact: 'medium',+ created_at: daysAgo(0),+ payload: {+ source: 'traffic_pages',+ reason,+ targetEntity: 'pages',+ targetCount: 2,+ targets: [+ { id: '/shop/beans', sessions: 240 },+ { id: '/guides/espresso', sessions: 0 },+ ],+ ...payload,+ },+ }),+ },+ NOW,+ );+ const cited = sent('cited_not_clicked');+ expect(cited.reason).toMatchObject({+ change: 'gap',+ subject: { entity: 'pages', count: 2 },+ // The pages' sessions are its demand.+ demand: expect.any(String),+ });+ expect(cited.reason.factors.severity).toBe(0.55);+ // Answers already cite it: more certain, and closer to done, than a page AI skips.+ const skipped = sent('no_ai_traffic');+ expect(skipped.reason.factors.severity).toBe(0.45);+ expect(cited.score).toBeGreaterThan(skipped.score);+ // Pages that make money are worth more.+ expect(sent('no_ai_traffic', { valueSignal: 'revenue' }).score).toBeGreaterThan(skipped.score);+ expect(sent('no_ai_traffic', { valueSignal: 'revenue' }).reason.commercial).toBe(true);+ });+it('stays within 0–100 and returns whole numbers', () => {for (const impact of ['high', 'medium', 'low', 'unknown']) {const { score } = scorePriority({ action: action({ impact }), signals: [] }, NOW);diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex afd1d1f18..942857b43 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -239,13 +239,15 @@ export async function validateAction(action, { now = new Date() } = {}) {// and pages; the brand-wide numbers would bury a single piece of content.// An Improve action (PROMPT-004) likewise, on its one prompt, and a topic// gap (VIS-010) or opportunity (VIS-011) sent from Insights on the topic's- // prompts, and answers sent from Mentions (MS-08) on their prompts.+ // prompts, answers sent from Mentions (MS-08) on their prompts, and pages+ // sent from AI Traffic (AT-006) on those pages.if (action.kind === 'content_opportunity' ||action.kind === 'prompt_improve' ||action.kind === 'topic_competitor_gap' ||action.kind === 'topic_opportunity' ||- action.kind === 'mention_review'+ action.kind === 'mention_review' ||+ action.kind === 'traffic_pages') {const scope = await basketScope(action);const [before, after] = await Promise.all([diff --git a/server/src/lib/action-center/validate.test.js b/server/src/lib/action-center/validate.test.jsindex a40fdcdd8..ef131be92 100644--- a/server/src/lib/action-center/validate.test.js+++ b/server/src/lib/action-center/validate.test.js@@ -270,6 +270,26 @@ describe('validateAction', () => {expect(patch.validation.scope).toEqual({ kind: 'basket', prompts: 2, pages: 0 });});+ it('measures pages sent from AI Traffic on those pages (AT-006)', async () => {+ const writes = mockWrites();+ rpc.mockResolvedValue({ data: {}, error: null });++ await validateAction(+ action({+ kind: 'traffic_pages',+ kpi_keys: ['ai_referral_traffic', 'citations'],+ payload: {+ pages: ['https://acme.example/shop/beans', 'https://acme.example/guides/espresso'],+ },+ }),+ { now: NOW },+ );++ expect(rpc).toHaveBeenCalledWith('opportunity_basket_metrics', expect.anything());+ const patch = writes.updated.find((w) => w.table === 'actions').patch;+ expect(patch.validation.scope).toEqual({ kind: 'basket', prompts: 0, pages: 2 });+ });+it('records the verdict on the action trail', async () => {const writes = mockWrites();rpc.mockResolvedValue({ data: { total_citations: 10 }, error: null });diff --git a/server/src/routes/action-center-pages.test.js b/server/src/routes/action-center-pages.test.jsnew file mode 100644index 000000000..18a2efbdc--- /dev/null+++ b/server/src/routes/action-center-pages.test.js@@ -0,0 +1,181 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for "Send to Action Center" on the AI Traffic page's+ * Pages section (AT-006): POST /api/action-center/pages. The action itself+ * is tested in from-traffic-pages.test.js; what shows up only here is what+ * the route lets through: ids in the format seeded data uses, paths, a list+ * it knows, the page's range, and a caller from the brand's organization.+ */++const assertBrandAccess = vi.fn();+const sendTrafficPagesToActionCenter = vi.fn();++let server;+let baseUrl;++async function startApp() {+ vi.resetModules();+ vi.doMock('../config/supabase.js', () => ({ default: {} }));+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess }));+ vi.doMock('../lib/action-center/priority-data.js', () => ({ rescoreActionsForSignal: vi.fn() }));+ vi.doMock('../lib/plan-guard.js', () => ({ PlanLimitError: class extends Error {} }));+ vi.doMock('../lib/action-center/task-writer/index.js', () => ({+ TaskWriterError: class extends Error {},+ isTaskWriterEnabled: () => false,+ writeTasksForAction: vi.fn(),+ }));+ vi.doMock('../lib/action-center/task-send.js', () => ({+ TaskSendError: class extends Error {},+ loadTask: vi.fn(),+ sendTaskToContent: vi.fn(),+ sendTaskToWebhook: vi.fn(),+ }));+ vi.doMock('../lib/action-center/from-traffic-pages.js', () => ({+ MAX_TRAFFIC_PAGES: 50,+ TRAFFIC_PAGE_REASONS: ['cited_not_clicked', 'no_ai_traffic'],+ sendTrafficPagesToActionCenter,+ }));++ const { default: router } = await import('./action-center.js');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/action-center', router);++ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/action-center`;+}++// Seeded ids aren't RFC 4122 versions; the route must still take them.+const BRAND = '33333333-3333-3333-3333-333333333333';+const FROM = '2026-09-18T12:00:00.000Z';+const TO = '2026-10-18T12:00:00.000Z';++const post = (body) =>+ fetch(`${baseUrl}/pages`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ assertBrandAccess.mockReset().mockResolvedValue({});+ sendTrafficPagesToActionCenter.mockReset();+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /api/action-center/pages', () => {+ it('sends the pages for a member and says whether it was created', async () => {+ sendTrafficPagesToActionCenter.mockResolvedValue({+ actionId: 'a1',+ actionNo: 71,+ created: true,+ });+ const body = {+ brandId: BRAND,+ pages: ['/shop/beans', '/'],+ reason: 'cited_not_clicked',+ from: FROM,+ to: TO,+ };+ const res = await post(body);+ expect(res.status).toBe(201);+ expect(await res.json()).toEqual({ actionId: 'a1', actionNo: 71, created: true });+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');+ expect(sendTrafficPagesToActionCenter).toHaveBeenCalledWith(BRAND, {+ pages: ['/shop/beans', '/'],+ reason: 'cited_not_clicked',+ from: FROM,+ to: TO,+ userId: 'u1',+ });++ // All time has no range; the same pages again find the open action.+ sendTrafficPagesToActionCenter.mockResolvedValue({+ actionId: 'a1',+ actionNo: 71,+ created: false,+ });+ expect((await post({ brandId: BRAND, pages: ['/'], reason: 'no_ai_traffic' })).status).toBe(+ 200,+ );+ });++ it('rejects a body without pages, with URLs, too many pages or another list', async () => {+ expect((await post({ brandId: BRAND, pages: [], reason: 'no_ai_traffic' })).status).toBe(400);+ expect(+ (+ await post({+ brandId: BRAND,+ pages: ['https://acme.example/menu'],+ reason: 'no_ai_traffic',+ })+ ).status,+ ).toBe(400);+ expect(+ (await post({ brandId: BRAND, pages: Array(51).fill('/a'), reason: 'no_ai_traffic' })).status,+ ).toBe(400);+ expect((await post({ brandId: BRAND, pages: ['/'], reason: 'all' })).status).toBe(400);+ expect((await post({ brandId: 'nope', pages: ['/'], reason: 'no_ai_traffic' })).status).toBe(+ 400,+ );+ expect(+ (await post({ brandId: BRAND, pages: ['/'], reason: 'no_ai_traffic', from: 'last week' }))+ .status,+ ).toBe(400);+ expect(sendTrafficPagesToActionCenter).not.toHaveBeenCalled();+ });++ it("takes a custom range's first day as the page sends it", async () => {+ sendTrafficPagesToActionCenter.mockResolvedValue({+ actionId: 'a1',+ actionNo: 71,+ created: true,+ });+ const res = await post({+ brandId: BRAND,+ pages: ['/'],+ reason: 'no_ai_traffic',+ from: '2026-10-01',+ to: '2026-10-11T23:59:59.999Z',+ });+ expect(res.status).toBe(201);+ expect(sendTrafficPagesToActionCenter).toHaveBeenCalledWith(+ BRAND,+ expect.objectContaining({ from: '2026-10-01', to: '2026-10-11T23:59:59.999Z' }),+ );+ });++ it('refuses a caller outside the brand’s organization', async () => {+ assertBrandAccess.mockRejectedValue(Object.assign(new Error('Unauthorized'), { status: 403 }));+ const res = await post({ brandId: BRAND, pages: ['/'], reason: 'no_ai_traffic' });+ expect(res.status).toBe(403);+ expect(sendTrafficPagesToActionCenter).not.toHaveBeenCalled();+ });++ it('says why when no page is on the list any more', async () => {+ sendTrafficPagesToActionCenter.mockRejectedValue(+ Object.assign(new Error('None of these pages are on the list for this range'), {+ status: 404,+ }),+ );+ const res = await post({ brandId: BRAND, pages: ['/menu'], reason: 'cited_not_clicked' });+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({+ error: 'Failed to send to the Action Center',+ details: 'None of these pages are on the list for this range',+ });+ });+});diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.jsindex 0a92fb455..a62f0f8ab 100644--- a/server/src/routes/action-center.js+++ b/server/src/routes/action-center.js@@ -15,6 +15,11 @@ import {isTaskWriterEnabled,writeTasksForAction,} from '../lib/action-center/task-writer/index.js';+import {+ MAX_TRAFFIC_PAGES,+ TRAFFIC_PAGE_REASONS,+ sendTrafficPagesToActionCenter,+} from '../lib/action-center/from-traffic-pages.js';const router = Router();@@ -216,4 +221,52 @@ router.post('/tasks/:id/send', async (req, res) => {}});+const trafficPagesSchema = z.object({+ // guid, not uuid: seeded ids aren't RFC 4122 versions.+ brandId: z.guid(),+ // Paths, as the Pages section lists them.+ pages: z.array(z.string().min(1).max(2048).startsWith('/')).min(1).max(MAX_TRAFFIC_PAGES),+ reason: z.enum(TRAFFIC_PAGE_REASONS),+ // The page's range, as its loaders take it: a timestamp, or a day from a+ // custom range; absent for all time.+ from: z.union([z.iso.datetime({ offset: true }), z.iso.date()]).optional(),+ to: z.union([z.iso.datetime({ offset: true }), z.iso.date()]).optional(),+});++/**+ * POST /api/action-center/pages+ * Body: { brandId, pages, reason, from?, to? }+ *+ * "Send to Action Center" on the AI Traffic page's Pages section (AT-006):+ * pages from the Cited, not clicked or No AI traffic list as one action.+ * Sending the same pages from the same list again returns the action+ * already open.+ */+router.post('/pages', async (req, res) => {+ try {+ const parsed = trafficPagesSchema.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });+ }+ const { brandId, pages, reason, from, to } = parsed.data;+ await assertBrandAccess(brandId, req.user.id);++ const result = await sendTrafficPagesToActionCenter(brandId, {+ pages,+ reason,+ from,+ to,+ userId: req.user.id,+ });+ return res.status(result.created ? 201 : 200).json(result);+ } catch (error) {+ const status = error.status || 500;+ req.log.error({ err: error }, 'traffic pages action error');+ return res.status(status).json({+ error: 'Failed to send to the Action Center',+ details: error.message,+ });+ }+});+export default router;diff --git a/web/messages/en.json b/web/messages/en.jsonindex 71a56b255..8b352f0a8 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1314,6 +1314,7 @@},"noSignalsTopicOpportunity": "This action was sent from Insights' Opportunities, so it has no detection signals. Its evidence is the topic and suggested prompts on the Overview tab.","noSignalsMentionReview": "This action was sent from Mentions, so it has no detection signals. Its evidence is the answers quoted on the Overview tab.",+ "noSignalsTrafficPages": "This action was sent from AI Traffic Analytics, so it has no detection signals. Its evidence is the pages and figures on the Overview tab.","topicOpportunity": {"source": "Source","sourceValue": "Insights › Opportunities",@@ -1339,6 +1340,19 @@"neutral": "Neutral","negative": "Negative"}+ },+ "trafficPages": {+ "source": "Source",+ "sourceValue": "AI Traffic Analytics › Pages · {list}",+ "lists": {+ "cited_not_clicked": "Cited, not clicked",+ "no_ai_traffic": "No AI traffic"+ },+ "openTraffic": "Open AI Traffic",+ "range": "Range when sent",+ "rangeAll": "All time",+ "pages": "Pages when sent",+ "figures": "{citations, plural, one {# citation} other {# citations}} · {sessions, plural, one {# session} other {# sessions}} · {aiVisits, plural, one {# AI visit} other {# AI visits}}"}}},@@ -1761,6 +1775,18 @@"descriptionCounts": "Sent from Mentions: {count, plural, one {# answer} other {# answers}} naming your brand.","descriptionNegative": "Sent from Mentions: {count, plural, one {# answer} other {# answers}} naming your brand, {negative} of them negative.","goal": "Get AI to describe the brand accurately and favourably in these answers."+ },+ "traffic_pages": {+ "title": "Earn AI visits for {targets}",+ "titleGeneric": "Earn AI visits for your pages",+ "citedTitle": "Turn AI answers citing {page} into visits",+ "citedTitleMany": "Turn AI answers citing {count, plural, one {# page} other {# pages}} into visits",+ "noAiTitle": "Capture AI traffic for {page}",+ "noAiTitleMany": "Capture AI traffic for {count, plural, one {# page} other {# pages}}",+ "description": "Sent from AI Traffic Analytics: pages from the Pages section.",+ "citedDescription": "Sent from AI Traffic Analytics: AI answers cited {count, plural, one {this page} other {these pages}} {citations, plural, one {# time} other {# times}} in the range, and none sent a visit.",+ "noAiDescription": "Sent from AI Traffic Analytics: {count, plural, one {a page} other {# pages}} with visitors or in your sitemap that got no AI visit in the range.",+ "goal": "Earn AI-referred visits to these pages."}},"actionTasks": {@@ -3370,7 +3396,27 @@"failed": "The pages couldn't be loaded.","shown": "{shown, number} of {total, plural, one {# page} other {# pages}}","sameWindow": "same range as the rest of the page",- "showMore": "Show more"+ "showMore": "Show more",+ "actions": {+ "menu": "More actions for {page}",+ "sendToActionCenter": "Send to Action Center",+ "sending": "Sending to the Action Center…",+ "sent": "Sent to the Action Center",+ "sentDescription": "AC-{number} · {count, plural, one {# page} other {# pages}}",+ "alreadySent": "Already in the Action Center",+ "alreadySentDescription": "AC-{number} is open with these pages.",+ "open": "Open",+ "sendFailed": "Couldn't send to the Action Center",+ "auditCited": "Audit {count, plural, one {# cited page} other {# cited pages}}",+ "auditPages": "Audit {count, plural, one {# page} other {# pages}}",+ "auditing": "Starting the audits…",+ "auditsStarted": "{count, plural, one {# audit started} other {# audits started}}",+ "auditsStartedDescription": "They run a few at a time; results appear in Site Audit.",+ "openAudit": "Open Site Audit",+ "auditsFailed": "Couldn't start the audits",+ "noneLeft": "No audits left this month",+ "overQuota": "{count, plural, one {# audit} other {# audits}}, {remaining} left this month"+ }}},"prompts": {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 a85a648ec..967453f41 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@@ -8,23 +8,38 @@ import type { TrafficDateWindow, TrafficPageRow, TrafficPages } from '@/lib/acti/*** The Pages section (AT-006): three work lists and the full list, each with* its count, read for the page's range; a row's next step is an audit or- * prompts that point to the page.+ * prompts that point to the page, and its menu sends it to the Action+ * Center. Under the two lists Action Center works from, the pages shown go+ * as one action and their cited pages are audited at once, within the+ * month's audits (part B).*/const getTrafficPages = vi.fn();+const sendTrafficPagesToActionCenter = vi.fn();const runAudit = vi.fn();+const runAuditsBulk = vi.fn();+const getAuditQuota = vi.fn();const push = vi.fn();+const toast = vi.hoisted(() => ({+ error: vi.fn(),+ loading: vi.fn(() => 'toast-1'),+ success: vi.fn(),+ info: vi.fn(),+}));vi.mock('@/lib/actions/traffic', () => ({getTrafficPages: (...args: unknown[]) => getTrafficPages(...args),+ sendTrafficPagesToActionCenter: (...args: unknown[]) => sendTrafficPagesToActionCenter(...args),}));vi.mock('@/lib/actions/audits', () => ({runAudit: (...args: unknown[]) => runAudit(...args),+ runAuditsBulk: (...args: unknown[]) => runAuditsBulk(...args),+ getAuditQuota: (...args: unknown[]) => getAuditQuota(...args),}));vi.mock('@/i18n/navigation', () => ({Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,useRouter: () => ({ push }),}));-vi.mock('sonner', () => ({ toast: { error: vi.fn() } }));+vi.mock('sonner', () => ({ toast }));const { PagesCard } = await import('./_pages-card');@@ -62,8 +77,13 @@ let root: Root;beforeEach(() => {getTrafficPages.mockReset();+ sendTrafficPagesToActionCenter.mockReset();runAudit.mockReset();+ runAuditsBulk.mockReset();+ // Unlimited unless a test says otherwise.+ getAuditQuota.mockReset().mockResolvedValue({ used: 3, limit: -1, remaining: -1 });push.mockReset();+ for (const fn of Object.values(toast)) fn.mockClear();container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -233,4 +253,170 @@ describe('PagesCard', () => {await act(async () => tab('Cited, not clicked').click());expect(text()).toContain("The pages couldn't be loaded.");});++ it('audits a page on a domain stored with its scheme', async () => {+ getTrafficPages.mockResolvedValue(pages([page({ citations: 6 })]));+ runAudit.mockResolvedValue({ id: 'audit-2' });+ await render({ domain: 'https://acme-coffee.example.com/' });+ await act(async () => button('Audit page').click());+ expect(runAudit).toHaveBeenCalledWith(BRAND, 'https://acme-coffee.example.com/gifts');+ });+});++describe('PagesCard actions (AT-006 part B)', () => {+ it('sends the No AI traffic pages shown as one action', async () => {+ getTrafficPages.mockResolvedValue(+ pages([page({ citations: 6 }), page({ page: '/about', valueRank: 2 })]),+ );+ sendTrafficPagesToActionCenter.mockResolvedValue({+ actionId: 'act-1',+ actionNo: 71,+ created: true,+ });+ await render();++ await act(async () => button('Send to Action Center').click());+ expect(sendTrafficPagesToActionCenter).toHaveBeenCalledWith(+ BRAND,+ WEEK,+ ['/gifts', '/about'],+ 'no_ai_traffic',+ );+ expect(toast.success).toHaveBeenCalledWith(+ 'Sent to the Action Center',+ expect.objectContaining({ description: 'AC-71 · 2 pages' }),+ );+ // Its Open goes to the action.+ const { action } = toast.success.mock.calls[0][1] as { action: { onClick: () => void } };+ action.onClick();+ expect(push).toHaveBeenCalledWith('/dashboard/action-center/actions?action=act-1');+ });++ it('says when the pages are already in the Action Center, or why they could not go', async () => {+ getTrafficPages.mockResolvedValue(pages([page()]));+ sendTrafficPagesToActionCenter.mockResolvedValue({+ actionId: 'act-1',+ actionNo: 71,+ created: false,+ });+ await render();+ await act(async () => button('Send to Action Center').click());+ expect(toast.info).toHaveBeenCalledWith(+ 'Already in the Action Center',+ expect.objectContaining({ description: 'AC-71 is open with these pages.' }),+ );++ sendTrafficPagesToActionCenter.mockResolvedValue({+ error: 'None of these pages are on the list for this range',+ });+ await act(async () => button('Send to Action Center').click());+ expect(toast.error).toHaveBeenCalledWith("Couldn't send to the Action Center", {+ id: 'toast-1',+ description: 'None of these pages are on the list for this range',+ });+ });++ it('sends one page from its row menu', async () => {+ getTrafficPages.mockResolvedValue(pages([page({ citations: 6 })]));+ sendTrafficPagesToActionCenter.mockResolvedValue({+ actionId: 'act-2',+ actionNo: 72,+ created: true,+ });+ await render();++ const trigger = container.querySelector<HTMLElement>('[aria-label="More actions for /gifts"]')!;+ await act(async () => trigger.click());+ const item = [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(+ (el) => el.textContent === 'Send to Action Center',+ )!;+ await act(async () => item.click());+ expect(sendTrafficPagesToActionCenter).toHaveBeenCalledWith(+ BRAND,+ WEEK,+ ['/gifts'],+ 'no_ai_traffic',+ );+ });++ it('audits the cited pages of No AI traffic at once', async () => {+ getTrafficPages.mockResolvedValue(+ pages([+ page({ citations: 6 }),+ page({ page: '/menu', citations: 2, valueRank: 2 }),+ page({ page: '/about', valueRank: 3 }),+ ]),+ );+ runAuditsBulk.mockResolvedValue({ started: 2 });+ await render();++ await act(async () => button('Audit 2 cited pages').click());+ expect(runAuditsBulk).toHaveBeenCalledWith(BRAND, [+ 'https://acme-coffee.example.com/gifts',+ 'https://acme-coffee.example.com/menu',+ ]);+ expect(toast.success).toHaveBeenCalledWith(+ '2 audits started',+ expect.objectContaining({ description: expect.stringContaining('Site Audit') }),+ );+ // The month's audits are read again after.+ expect(getAuditQuota).toHaveBeenCalledTimes(2);+ });++ it('sends and audits Cited, not clicked as its own list', async () => {+ getTrafficPages.mockResolvedValue(pages([]));+ await render();+ getTrafficPages.mockResolvedValue(+ pages([+ page({ page: '/guides/espresso', citations: 80, sessions: 0 }),+ page({ page: '/shop/beans', citations: 22 }),+ ]),+ );+ await act(async () => tab('Cited, not clicked').click());+ sendTrafficPagesToActionCenter.mockResolvedValue({+ actionId: 'act-3',+ actionNo: 73,+ created: true,+ });+ runAuditsBulk.mockResolvedValue({ started: 2 });++ await act(async () => button('Send to Action Center').click());+ expect(sendTrafficPagesToActionCenter).toHaveBeenCalledWith(+ BRAND,+ WEEK,+ ['/guides/espresso', '/shop/beans'],+ 'cited_not_clicked',+ );+ await act(async () => button('Audit 2 pages').click());+ expect(runAuditsBulk).toHaveBeenCalledWith(BRAND, [+ 'https://acme-coffee.example.com/guides/espresso',+ 'https://acme-coffee.example.com/shop/beans',+ ]);+ });++ it("won't start more audits than the month has left", async () => {+ getAuditQuota.mockResolvedValue({ used: 99, limit: 100, remaining: 1 });+ getTrafficPages.mockResolvedValue(+ pages([page({ citations: 6 }), page({ page: '/menu', citations: 2, valueRank: 2 })]),+ );+ await render();+ expect(text()).toContain('2 audits, 1 left this month');+ expect(button('Audit 2 cited pages').hasAttribute('disabled')).toBe(true);++ getAuditQuota.mockResolvedValue({ used: 100, limit: 100, remaining: 0 });+ act(() => root.unmount());+ root = createRoot(container);+ await render();+ expect(text()).toContain('No audits left this month');+ });++ it('offers no footer actions on Traffic, no prompt or All pages', async () => {+ getTrafficPages.mockResolvedValue(pages([page({ aiVisits: 3, citations: 0 })]));+ await render();+ await act(async () => tab('Traffic, no prompt').click());+ expect(button('Send to Action Center')).toBeUndefined();+ await act(async () => tab('All pages').click());+ expect(button('Send to Action Center')).toBeUndefined();+ expect(container.querySelector('[aria-label^="More actions"]')).toBeNull();+ });});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsxindex 4ff2b5342..bcf85d3a6 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx@@ -3,10 +3,16 @@import { useEffect, useState, type ReactNode } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';-import { FileSearch, Loader2 } from 'lucide-react';+import { FileSearch, Loader2, MoreHorizontal, Send } from 'lucide-react';import { Link, useRouter } from '@/i18n/navigation';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import { Button } from '@/components/ui/button';import { buttonVariants } from '@/components/ui/button-variants';import { Skeleton } from '@/components/ui/skeleton';@@ -22,15 +28,17 @@ import {import { cn } from '@/lib/utils';import { formatNumber } from '@/lib/format';import { getPlatformName } from '@/lib/traffic-platforms';-import { citationState, pageStatuses } from '@/lib/traffic-pages';+import { citationState, pageStatuses, pageUrl } from '@/lib/traffic-pages';import {getTrafficPages,type TrafficDateWindow,type TrafficPageRow,type TrafficPages,+ type TrafficPagesReason,type TrafficPagesTab,} from '@/lib/actions/traffic';import { runAudit } from '@/lib/actions/audits';+import { PAGE_ACTION_MAX, auditBlock, usePageActions } from './_use-page-actions';/*** Pages: which answers send visitors (AT-006, spec §3.5, "the@@ -46,8 +54,9 @@ import { runAudit } from '@/lib/actions/audits';* prompt's answer covers.** A row's action is the next step for it: audit the page, or track prompts- * that point to it. Sending pages to Action Center and suggested prompts- * come with AT-006 part B.+ * that point to it; its menu sends it to the Action Center. Under the two+ * lists Action Center works from, the pages shown go as one action, and+ * their cited pages can be audited at once (AT-006 part B).*/const TABS: TrafficPagesTab[] = ['noAiTraffic', 'citedNotClicked', 'trafficNoPrompt', 'all'];@@ -108,6 +117,7 @@ export function PagesCard({const [tab, setTab] = useState<TrafficPagesTab>('noAiTraffic');const [limit, setLimit] = useState(PAGE_SIZE);const [auditing, setAuditing] = useState<string | null>(null);+ const pageActions = usePageActions(brandId, dateWindow);const key = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}|${tab}|${limit}`;// The loaded result carries the request it answers, as the KPI cards do:@@ -153,7 +163,7 @@ export function PagesCard({setAuditing(page);try {// A running audit opens on its own page, which follows it to the end.- const started = await runAudit(brandId, `https://${domain}${page}`);+ const started = await runAudit(brandId, pageUrl(domain, page));router.push(`/dashboard/audit/${started.id}`);} catch (err) {toast.error(err instanceof Error ? err.message : t('auditFailed'));@@ -190,6 +200,48 @@ export function PagesCard({const platforms = (row: TrafficPageRow) =>row.aiPlatforms.length ? row.aiPlatforms.map(getPlatformName).join(', ') : '—';+ /** A row's next step, with its menu: send the page to the Action Center. */+ const rowActions = (row: TrafficPageRow, next: ReactNode, reason: TrafficPagesReason) => (+ <div className="flex items-center justify-end gap-1">+ {next}+ <DropdownMenu>+ <DropdownMenuTrigger+ className="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"+ aria-label={t('actions.menu', { page: row.page })}+ >+ <MoreHorizontal className="h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-56">+ <DropdownMenuItem+ className="gap-2"+ disabled={pageActions.sending}+ onClick={() => void pageActions.send([row.page], reason)}+ >+ <Send className="h-3.5 w-3.5" />+ {t('actions.sendToActionCenter')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );++ // The footer's actions, under the lists Action Center works from: the+ // pages shown as one action, and their cited pages audited at once.+ const listReason: TrafficPagesReason | null =+ tab === 'noAiTraffic'+ ? 'no_ai_traffic'+ : tab === 'citedNotClicked'+ ? 'cited_not_clicked'+ : null;+ const auditUrls =+ domain && listReason+ ? rows+ .filter((row) => tab === 'citedNotClicked' || citationState(row) === 'cited')+ .slice(0, PAGE_ACTION_MAX)+ .map((row) => pageUrl(domain, row.page))+ : [];+ const block = auditBlock(pageActions.quota, auditUrls.length);+return (<Card aria-busy={stale} className={cn('transition-opacity', stale && 'opacity-60')}><CardHeader className="pb-2">@@ -334,7 +386,9 @@ export function PagesCard({<TableCell className="text-right text-sm text-muted-foreground tabular-nums">{row.valueRank === null ? '—' : `#${row.valueRank}`}</TableCell>- <TableCell className="pr-6 text-right">{reasonAction(row)}</TableCell>+ <TableCell className="pr-6 text-right">+ {rowActions(row, reasonAction(row), 'no_ai_traffic')}+ </TableCell></>)}{tab === 'citedNotClicked' && (@@ -346,7 +400,9 @@ export function PagesCard({{num(row.targetingPrompts)}</TableCell><TableCell className="text-right text-sm">{num(row.sessions)}</TableCell>- <TableCell className="pr-6 text-right">{auditButton(row.page)}</TableCell>+ <TableCell className="pr-6 text-right">+ {rowActions(row, auditButton(row.page), 'cited_not_clicked')}+ </TableCell></>)}{tab === 'trafficNoPrompt' && (@@ -394,18 +450,63 @@ export function PagesCard({{!loading && result && (<div className="flex flex-wrap items-center justify-between gap-2 px-6 py-3 text-xs text-muted-foreground">- <span>- {t('shown', { shown: rows.length, total })} · {t('sameWindow')}+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <span>+ {t('shown', { shown: rows.length, total })} · {t('sameWindow')}+ </span>+ {rows.length < total && (+ <button+ type="button"+ disabled={stale}+ onClick={() => setLimit((n) => n + PAGE_SIZE)}+ className="font-medium text-foreground underline-offset-4 hover:underline disabled:opacity-50"+ >+ {t('showMore')}+ </button>+ )}</span>- {rows.length < total && (- <button- type="button"- disabled={stale}- onClick={() => setLimit((n) => n + PAGE_SIZE)}- className="font-medium text-foreground underline-offset-4 hover:underline disabled:opacity-50"- >- {t('showMore')}- </button>+ {listReason && rows.length > 0 && (+ <div className="flex flex-wrap items-center justify-end gap-2">+ {auditUrls.length > 0 && block && (+ <span>+ {block.reason === 'noneLeft'+ ? t('actions.noneLeft')+ : t('actions.overQuota', {+ count: auditUrls.length,+ remaining: block.remaining,+ })}+ </span>+ )}+ {auditUrls.length > 0 && (+ <Button+ size="sm"+ variant="outline"+ className="h-7 gap-1.5 text-xs"+ disabled={stale || pageActions.auditing || block !== null}+ onClick={() => void pageActions.auditMany(auditUrls)}+ >+ {pageActions.auditing && <Loader2 className="h-3 w-3 animate-spin" />}+ {tab === 'noAiTraffic'+ ? t('actions.auditCited', { count: auditUrls.length })+ : t('actions.auditPages', { count: auditUrls.length })}+ </Button>+ )}+ <Button+ size="sm"+ variant="outline"+ className="h-7 gap-1.5 text-xs"+ disabled={stale || pageActions.sending}+ onClick={() =>+ void pageActions.send(+ rows.map((row) => row.page),+ listReason,+ )+ }+ >+ {pageActions.sending && <Loader2 className="h-3 w-3 animate-spin" />}+ {t('actions.sendToActionCenter')}+ </Button>+ </div>)}</div>)}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.test.tsnew file mode 100644index 000000000..958c7ce88--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('@/lib/actions/audits', () => ({}));+vi.mock('@/lib/actions/traffic', () => ({}));+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));++const { auditBlock } = await import('./_use-page-actions');++/** When a bulk audit from the Pages section can't start (AT-006 part B). */+describe('auditBlock', () => {+ it('never blocks an unlimited or unknown quota', () => {+ expect(auditBlock(null, 50)).toBeNull();+ expect(auditBlock({ used: 900, limit: -1, remaining: -1 }, 50)).toBeNull();+ });++ it('blocks when the month is spent, or fewer are left than pages', () => {+ expect(auditBlock({ used: 100, limit: 100, remaining: 0 }, 1)).toEqual({ reason: 'noneLeft' });+ // Running audits and the auto-audit share can take it below zero.+ expect(auditBlock({ used: 98, limit: 100, remaining: -2 }, 1)).toEqual({ reason: 'noneLeft' });+ expect(auditBlock({ used: 97, limit: 100, remaining: 3 }, 4)).toEqual({+ reason: 'overQuota',+ remaining: 3,+ });+ expect(auditBlock({ used: 97, limit: 100, remaining: 3 }, 3)).toBeNull();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.tsnew file mode 100644index 000000000..8cc416543--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts@@ -0,0 +1,126 @@+'use client';++import { useCallback, useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { useRouter } from '@/i18n/navigation';+import { getAuditQuota, runAuditsBulk, type AuditQuota } from '@/lib/actions/audits';+import {+ sendTrafficPagesToActionCenter,+ type TrafficDateWindow,+ type TrafficPagesReason,+} from '@/lib/actions/traffic';++/** The most pages one action, or one bulk audit, takes. */+export const PAGE_ACTION_MAX = 50;++/**+ * The Pages section's actions (AT-006 part B), shared by its rows and its+ * footer: send pages to the Action Center as one action, and audit several+ * pages at once within the month's audits. Each reports how it went in a+ * toast that opens what it made.+ */+export function usePageActions(brandId: string, dateWindow: TrafficDateWindow) {+ const t = useTranslations('traffic.pageList.actions');+ const router = useRouter();+ const [sending, setSending] = useState(false);+ const [auditing, setAuditing] = useState(false);+ // The organization's audits this month, for the bulk audit's limit.+ const [quota, setQuota] = useState<AuditQuota | null>(null);++ const loadQuota = useCallback(() => {+ getAuditQuota()+ .then(setQuota)+ // Unknown: the server still refuses audits over the limit.+ .catch(() => setQuota(null));+ }, []);+ useEffect(loadQuota, [loadQuota]);++ const send = useCallback(+ async (pages: string[], reason: TrafficPagesReason): Promise<boolean> => {+ const sent = pages.slice(0, PAGE_ACTION_MAX);+ if (sent.length === 0) return false;+ setSending(true);+ const toastId = toast.loading(t('sending'));+ try {+ const result = await sendTrafficPagesToActionCenter(brandId, dateWindow, sent, reason);+ if ('error' in result) {+ toast.error(t('sendFailed'), { id: toastId, description: result.error });+ return false;+ }+ const open = {+ label: t('open'),+ onClick: () => router.push(`/dashboard/action-center/actions?action=${result.actionId}`),+ };+ if (result.created) {+ toast.success(t('sent'), {+ id: toastId,+ description: t('sentDescription', { number: result.actionNo, count: sent.length }),+ duration: 10_000,+ action: open,+ });+ } else {+ toast.info(t('alreadySent'), {+ id: toastId,+ description: t('alreadySentDescription', { number: result.actionNo }),+ duration: 10_000,+ action: open,+ });+ }+ return true;+ } catch {+ toast.error(t('sendFailed'), { id: toastId });+ return false;+ } finally {+ setSending(false);+ }+ },+ [brandId, dateWindow, router, t],+ );++ const auditMany = useCallback(+ async (urls: string[]): Promise<boolean> => {+ if (urls.length === 0) return false;+ setAuditing(true);+ const toastId = toast.loading(t('auditing'));+ try {+ const { started } = await runAuditsBulk(brandId, urls.slice(0, PAGE_ACTION_MAX));+ toast.success(t('auditsStarted', { count: started }), {+ id: toastId,+ description: t('auditsStartedDescription'),+ duration: 10_000,+ action: { label: t('openAudit'), onClick: () => router.push('/dashboard/audit') },+ });+ return true;+ } catch (err) {+ toast.error(t('auditsFailed'), {+ id: toastId,+ description: err instanceof Error ? err.message : undefined,+ });+ return false;+ } finally {+ setAuditing(false);+ loadQuota();+ }+ },+ [brandId, loadQuota, router, t],+ );++ return { send, sending, auditMany, auditing, quota };+}++/**+ * Why a bulk audit of `count` pages can't start, or null when it can: the+ * month's audits are spent, or fewer are left than pages (the server starts+ * all of them or none). An unknown or unlimited quota never blocks.+ */+export function auditBlock(+ quota: AuditQuota | null,+ count: number,+): { reason: 'noneLeft' } | { reason: 'overQuota'; remaining: number } | null {+ if (!quota || quota.limit === -1) return null;+ const remaining = Math.max(0, quota.remaining);+ if (remaining === 0) return { reason: 'noneLeft' };+ if (count > remaining) return { reason: 'overQuota', remaining };+ return null;+}diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex ee5cf8220..46eb18fc3 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -70,6 +70,7 @@ import { ImproveContext } from './improve-context';import { TopicGapContext } from './topic-gap-context';import { TopicOpportunityContext } from './topic-opportunity-context';import { MentionReviewContext } from './mention-review-context';+import { TrafficPagesContext } from './traffic-pages-context';import { TaskDetailForm, TaskDetailView, TaskTypeBadge, type TaskSendOptions } from './task-detail';import { hasActiveWebhook, sendActionTask } from '@/lib/actions/action-task-send';import { RegenerateTasks, taskWriterEnabled } from './regenerate-tasks';@@ -583,6 +584,11 @@ export function ActionDrawer({<Separator /><MentionReviewContext payload={action.payload ?? {}} /></>+ ) : action.kind === 'traffic_pages' ? (+ <>+ <Separator />+ <TrafficPagesContext payload={action.payload ?? {}} />+ </>) : opportunityId ? (<><Separator />@@ -665,9 +671,11 @@ export function ActionDrawer({? t('drawer.noSignalsTopicOpportunity'): action.kind === 'mention_review'? t('drawer.noSignalsMentionReview')- : opportunityId- ? t('drawer.noSignalsOpportunity')- : t('drawer.noSignals')}+ : action.kind === 'traffic_pages'+ ? t('drawer.noSignalsTrafficPages')+ : opportunityId+ ? t('drawer.noSignalsOpportunity')+ : t('drawer.noSignals')}</p>)}{detail.signals.map((signal) => {diff --git a/web/src/components/action-center/traffic-pages-context.test.tsx b/web/src/components/action-center/traffic-pages-context.test.tsxnew file mode 100644index 000000000..1b8b7de2a--- /dev/null+++ b/web/src/components/action-center/traffic-pages-context.test.tsx@@ -0,0 +1,76 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';++/**+ * The drawer's Overview for pages sent from AI Traffic (AT-006): the list and+ * range they were sent from, and each page's figures when sent.+ */++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,+}));++const { TrafficPagesContext } = await import('./traffic-pages-context');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++function render(payload: Record<string, unknown>) {+ act(() =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <TrafficPagesContext payload={payload} />+ </NextIntlClientProvider>,+ ),+ );+ return container.textContent ?? '';+}++describe('TrafficPagesContext', () => {+ it('names the list, the range and each page as sent', () => {+ const text = render({+ reason: 'cited_not_clicked',+ window: { from: '2026-09-18T12:00:00.000Z', to: '2026-10-18T12:00:00.000Z' },+ evidence: [+ { page: '/guides/espresso', citations: 80, sessions: 0, aiVisits: 0 },+ { page: '/shop/beans', citations: 1, sessions: 240, aiVisits: 0 },+ ],+ });+ expect(text).toContain('AI Traffic Analytics › Pages · Cited, not clicked');+ expect(text).toContain('Sep 18, 2026 – Oct 18, 2026');+ expect(text).toContain('/guides/espresso80 citations · 0 sessions · 0 AI visits');+ expect(text).toContain('/shop/beans1 citation · 240 sessions · 0 AI visits');+ expect(container.querySelector('a')?.getAttribute('href')).toBe('/dashboard/traffic');+ });++ it('reads a 24-hour range in hours, and all time as such', () => {+ expect(+ render({+ reason: 'no_ai_traffic',+ window: { from: '2026-10-17T12:00:00.000Z', to: '2026-10-18T12:00:00.000Z' },+ evidence: [],+ }),+ ).toContain('No AI traffic');+ expect(container.textContent).toMatch(/Oct 17, 2026, \d+:\d{2} [AP]M – Oct 18, 2026/);+ expect(render({ reason: 'no_ai_traffic', window: { from: null, to: null } })).toContain(+ 'All time',+ );+ });+});diff --git a/web/src/components/action-center/traffic-pages-context.tsx b/web/src/components/action-center/traffic-pages-context.tsxnew file mode 100644index 000000000..8af4a67cc--- /dev/null+++ b/web/src/components/action-center/traffic-pages-context.tsx@@ -0,0 +1,98 @@+'use client';++import { useTranslations } from 'next-intl';+import { ExternalLink } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { formatDate, formatDateTime } from '@/lib/format';++interface SentPage {+ page: string;+ citations: number;+ sessions: number;+ aiVisits: number;+}++/** The page's 24-hour range, with its slack (as isHourlyWindow allows). */+const HOURLY_MS = 25 * 60 * 60 * 1000;++/** The range the pages were read over, in days, or hours when it was one day. */+function rangeLabel(from: string | null, to: string | null, allTime: string): string {+ if (!from) return allTime;+ const end = to ?? new Date().toISOString();+ const format = Date.parse(end) - Date.parse(from) <= HOURLY_MS ? formatDateTime : formatDate;+ return `${format(from)} – ${format(end)}`;+}++/**+ * What pages sent from AI Traffic's Pages section are about (AT-006): the+ * list they came from, the range they were read over, and each page with its+ * citations, sessions and AI visits when sent. Copied onto the action at send+ * time, so it still reads after the figures move.+ */+export function TrafficPagesContext({ payload }: { payload: Record<string, unknown> }) {+ const t = useTranslations('actionCenter.actionsPage.drawer.trafficPages');+ const list =+ payload.reason === 'cited_not_clicked' || payload.reason === 'no_ai_traffic'+ ? payload.reason+ : null;+ const window = (payload.window ?? {}) as { from?: unknown; to?: unknown };+ const from = typeof window.from === 'string' ? window.from : null;+ const to = typeof window.to === 'string' ? window.to : null;+ const pages: SentPage[] = Array.isArray(payload.evidence)+ ? (payload.evidence as Record<string, unknown>[]).flatMap((e) =>+ typeof e?.page === 'string'+ ? [+ {+ page: e.page,+ citations: Number(e.citations) || 0,+ sessions: Number(e.sessions) || 0,+ aiVisits: Number(e.aiVisits) || 0,+ },+ ]+ : [],+ )+ : [];++ return (+ <section className="space-y-3">+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('source')}</p>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <span>{t('sourceValue', { list: list ? t(`lists.${list}`) : '—' })}</span>+ <Link+ href="/dashboard/traffic"+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"+ >+ {t('openTraffic')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ </div>+ </div>+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('range')}</p>+ <p className="mt-1 tabular-nums">{rangeLabel(from, to, t('rangeAll'))}</p>+ </div>+ {pages.length > 0 && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('pages')}</p>+ <ul className="mt-1.5 space-y-1.5">+ {pages.map((p) => (+ <li key={p.page} className="rounded-md border px-3 py-2 text-xs">+ <p className="truncate font-mono" title={p.page}>+ {p.page}+ </p>+ <p className="mt-0.5 tabular-nums text-muted-foreground">+ {t('figures', {+ citations: p.citations,+ sessions: p.sessions,+ aiVisits: p.aiVisits,+ })}+ </p>+ </li>+ ))}+ </ul>+ </div>+ )}+ </section>+ );+}diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex b442af534..c834f1187 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -53,8 +53,50 @@ describe('actionTexts', () => {expect(() => actionGoal(kind, t)).not.toThrow();});- it('holds copy for all sixty-two definitions and the five person-sent kinds', () => {- expect(ACTION_KINDS).toHaveLength(67);+ it('holds copy for all sixty-two definitions and the six person-sent kinds', () => {+ expect(ACTION_KINDS).toHaveLength(68);+ });++ it('names pages sent from AI Traffic after their list and page, or how many (AT-006)', () => {+ const cited = {+ reason: 'cited_not_clicked',+ pageCount: 1,+ citations: 80,+ targetEntity: 'pages',+ targetCount: 1,+ targets: [{ id: '/guides/espresso', label: '/guides/espresso' }],+ };+ const texts = actionTexts(action({ kind: 'traffic_pages', payload: cited }), t);+ expect(texts.title).toBe('Turn AI answers citing /guides/espresso into visits');+ // Plurals read as their `other` branch here (see `t` above).+ expect(texts.description).toBe(+ 'Sent from AI Traffic Analytics: AI answers cited these pages 80 times in the range, and none sent a visit.',+ );+ const skipped = {+ reason: 'no_ai_traffic',+ pageCount: 10,+ citations: 6,+ targetEntity: 'pages',+ targetCount: 10,+ targets: [{ id: '/gifts', label: '/gifts' }],+ };+ const many = actionTexts(action({ kind: 'traffic_pages', payload: skipped }), t);+ expect(many.title).toBe('Capture AI traffic for 10 pages');+ expect(many.description).toBe(+ 'Sent from AI Traffic Analytics: 10 pages with visitors or in your sitemap that got no AI visit in the range.',+ );+ // An action without the list it came from still reads, from its targets.+ expect(+ actionTexts(+ action({ kind: 'traffic_pages', payload: { targetEntity: 'pages', targetCount: 2 } }),+ t,+ ).title,+ ).toBe('Earn AI visits for 2 pages');+ const tags = actionContextTags(+ action({ kind: 'traffic_pages', payload: skipped, signalCount: 0 }),+ (key: string) => key,+ );+ expect(tags).not.toContain('tags.signals');});it('names answers sent from Mentions after their prompt, or how many (MS-08)', () => {diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 0f6fa768e..b747e4059 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -129,6 +129,26 @@ export function actionTexts(: t(`${action.kind}.descriptionCounts`, { count: p.mentionCount }),};}+ // Pages sent from AI Traffic (AT-006) name their list and the page, or how many.+ if (+ action.kind === 'traffic_pages' &&+ (p.reason === 'cited_not_clicked' || p.reason === 'no_ai_traffic') &&+ typeof p.pageCount === 'number' &&+ Array.isArray(p.targets)+ ) {+ const list = p.reason === 'cited_not_clicked' ? 'cited' : 'noAi';+ const first = (p.targets[0] as { label?: unknown } | undefined)?.label;+ return {+ title:+ p.pageCount === 1 && typeof first === 'string' && first+ ? t(`${action.kind}.${list}Title`, { page: first })+ : t(`${action.kind}.${list}TitleMany`, { count: p.pageCount }),+ description: t(`${action.kind}.${list}Description`, {+ count: p.pageCount,+ citations: typeof p.citations === 'number' ? p.citations : 0,+ }),+ };+ }const targets = targetLabel(p, t);return {title: targets ? t(`${action.kind}.title`, { targets }) : t(`${action.kind}.titleGeneric`),@@ -204,6 +224,7 @@ const PERSON_SENT_KINDS: string[] = ['topic_competitor_gap','topic_opportunity','mention_review',+ 'traffic_pages',];/** Compact evidence chips under the title: signal count plus the kind's owndiff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex 2073b5489..8a901ddd3 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -110,7 +110,9 @@ export type ActionKind =// Sent by a person from an Insights Opportunities topic (VIS-011).| 'topic_opportunity'// Sent by a person from answers on the Mentions tab (MS-08).- | 'mention_review';+ | 'mention_review'+ // Sent by a person from AI Traffic's Pages section (AT-006).+ | 'traffic_pages';export type TaskStatus =| 'todo'@@ -245,6 +247,7 @@ export const ACTION_KINDS: readonly ActionKind[] = ['topic_competitor_gap','topic_opportunity','mention_review',+ 'traffic_pages',];/**diff --git a/web/src/lib/actions/traffic-pages.test.ts b/web/src/lib/actions/traffic-pages.test.tsindex 1c2e86add..40dc7afce 100644--- a/web/src/lib/actions/traffic-pages.test.ts+++ b/web/src/lib/actions/traffic-pages.test.ts@@ -7,11 +7,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';*/const rpc = vi.fn();+let session: { access_token: string } | null = { access_token: 'tok' };vi.mock('@/lib/supabase/server', () => ({- createClient: async () => ({ rpc }),+ createClient: async () => ({+ rpc,+ auth: { getSession: async () => ({ data: { session } }) },+ }),}));+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));-import { getTrafficPages } from './traffic';+import { getTrafficPages, sendTrafficPagesToActionCenter } from './traffic';beforeEach(() => {vi.useFakeTimers();@@ -21,6 +26,8 @@ beforeEach(() => {afterEach(() => {vi.useRealTimers();+ vi.unstubAllGlobals();+ session = { access_token: 'tok' };});describe('getTrafficPages', () => {@@ -132,3 +139,57 @@ describe('getTrafficPages', () => {await expect(getTrafficPages('b1', undefined, { tab: 'all' })).rejects.toThrow('unknown tab');});});++describe('sendTrafficPagesToActionCenter (part B)', () => {+ it('posts the pages, their list and the page range for the signed-in member', async () => {+ const fetchMock = vi.fn(+ async () =>+ new Response(JSON.stringify({ actionId: 'a1', actionNo: 71, created: true }), {+ status: 201,+ }),+ );+ vi.stubGlobal('fetch', fetchMock);++ const result = await sendTrafficPagesToActionCenter(+ 'b1',+ { dateFrom: '2026-10-11T12:30:00.000Z' },+ ['/gifts', '/menu'],+ 'no_ai_traffic',+ );+ expect(result).toEqual({ actionId: 'a1', actionNo: 71, created: true });+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('http://api.test/api/action-center/pages');+ expect(init.headers).toMatchObject({ Authorization: 'Bearer tok' });+ expect(JSON.parse(init.body as string)).toEqual({+ brandId: 'b1',+ pages: ['/gifts', '/menu'],+ reason: 'no_ai_traffic',+ from: '2026-10-11T12:30:00.000Z',+ to: '2026-10-18T12:30:00.000Z',+ });+ });++ it("returns the server's reason rather than throwing it", async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(+ async () =>+ new Response(+ JSON.stringify({+ error: 'Failed to send to the Action Center',+ details: 'None of these pages are on the list for this range',+ }),+ { status: 404 },+ ),+ ),+ );+ expect(+ await sendTrafficPagesToActionCenter('b1', undefined, ['/menu'], 'cited_not_clicked'),+ ).toEqual({ error: 'None of these pages are on the list for this range' });++ session = null;+ expect(+ await sendTrafficPagesToActionCenter('b1', undefined, ['/menu'], 'cited_not_clicked'),+ ).toEqual({ error: 'Not authenticated' });+ });+});diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.tsindex 4fda79b40..bae8f43d5 100644--- a/web/src/lib/actions/traffic.ts+++ b/web/src/lib/actions/traffic.ts@@ -1,6 +1,7 @@'use server';import { createClient } from '@/lib/supabase/server';+import { API_BASE_URL } from '@/config/api';import { TRAFFIC_PAGE_SIZE, countTrafficLogs, scanTrafficLogs } from '@/lib/traffic-scan';import { expandDateToEndOfDay, utcDay } from '@/lib/dates';import { isHourlyWindow, listUtcHours, utcHourKey } from '@/lib/traffic-buckets';@@ -598,6 +599,45 @@ export async function getTrafficPages(};}+/** A list a page can be sent to the Action Center from (AT-006). */+export type TrafficPagesReason = 'cited_not_clicked' | 'no_ai_traffic';++/**+ * "Send to Action Center" on the Pages section (AT-006): pages from the+ * Cited, not clicked or No AI traffic list as one action. The server reads+ * the list again over the same range and keeps the pages still on it; the+ * same pages sent again return the open action.+ */+export async function sendTrafficPagesToActionCenter(+ brandId: string,+ window: TrafficDateWindow | undefined,+ pages: string[],+ reason: TrafficPagesReason,+): Promise<{ actionId: string; actionNo: number; created: boolean } | { error: string }> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'Not authenticated' };++ const { from, to } = resolveTrafficWindow(window);+ const res = await fetch(`${API_BASE_URL}/api/action-center/pages`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ brandId, pages, reason, from, to }),+ });++ // Returned, not thrown: a thrown error's message is masked in production.+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ return { error: body.details || body.error || `Server error: ${res.status}` };+ }+ return res.json();+}+/** Analytics' engagement figures for one group of sessions (AT-005). */export interface TrafficEngagement {sessions: number;diff --git a/web/src/lib/traffic-pages.test.ts b/web/src/lib/traffic-pages.test.tsindex f70bb2d99..5d46cad9a 100644--- a/web/src/lib/traffic-pages.test.ts+++ b/web/src/lib/traffic-pages.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { CITED_NOT_CLICKED_MIN, citationState, pageStatuses } from './traffic-pages';+import { CITED_NOT_CLICKED_MIN, citationState, pageStatuses, pageUrl } from './traffic-pages';/** The Pages section's lists, as 00178 sorts pages into them (AT-006). */@@ -41,3 +41,11 @@ describe('citationState', () => {expect(citationState({ citations: 0, targetingPrompts: 0 })).toBe('not_targeted');});});++describe('pageUrl', () => {+ it("builds a page's URL on the brand's domain, however the domain is stored", () => {+ expect(pageUrl('acme.example', '/gifts')).toBe('https://acme.example/gifts');+ expect(pageUrl('https://www.acme.example/', '/gifts')).toBe('https://www.acme.example/gifts');+ expect(pageUrl(' http://acme.example ', '/')).toBe('https://acme.example/');+ });+});diff --git a/web/src/lib/traffic-pages.ts b/web/src/lib/traffic-pages.tsindex 81c6210d8..ce48607c5 100644--- a/web/src/lib/traffic-pages.ts+++ b/web/src/lib/traffic-pages.ts@@ -36,3 +36,15 @@ export function citationState(if (row.targetingPrompts > 0) return 'targeted_not_cited';return 'not_targeted';}++/**+ * A listed page's full URL on the brand's domain, for auditing it. The+ * domain may be stored with its scheme or a trailing slash.+ */+export function pageUrl(domain: string, page: string): string {+ const host = domain+ .trim()+ .replace(/^https?:\/\//i, '')+ .replace(/\/+$/, '');+ return `https://${host}${page}`;+}