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): suggest prompts for a page and track them pointing at it (#1172)
Cihan4b37cf5c47f4
diff --git a/server/src/lib/ga-suggestions.js b/server/src/lib/ga-suggestions.jsindex 988614df6..575cc31fe 100644--- a/server/src/lib/ga-suggestions.js+++ b/server/src/lib/ga-suggestions.js@@ -201,7 +201,8 @@ export function summaryText(summary) {.join(' — ');}-async function readPage(url) {+/** A page's summary, read through Scrape.do; null when it can't be read. */+export async function readPage(url) {try {const res = await fetchViaScrapeDo(url, { render: false, retries: 0 });if (!res.ok || !res.html) return null;diff --git a/server/src/lib/page-prompt-suggestions.js b/server/src/lib/page-prompt-suggestions.jsnew file mode 100644index 000000000..038379f51--- /dev/null+++ b/server/src/lib/page-prompt-suggestions.js@@ -0,0 +1,302 @@+/**+ * Prompts suggested for one page (AT-006 part B2, spec §3.5): "Add prompts+ * (suggested from GA4 landing page and GSC queries; uses slots, PROMPT-012)".+ *+ * A page AI sends visitors to without any tracked prompt citing it, or a+ * valuable page nothing points to, needs prompts whose best answer is that+ * page, so tracking shows whether AI answers cite it. This writes a handful,+ * from what the page says it is about (its sitemap entry, or the page read+ * once), its figures over the page's range, and the brand's Search Console+ * queries that share its words — Search Console keeps no queries per page.+ *+ * Nothing is stored: the person picks which to track, and those become+ * prompts pointing at the page.+ */++import { NoObjectGeneratedError, generateObject } from 'ai';+import { z } from 'zod';+import supabaseAdmin from '../config/supabase.js';+import { resolveModel } from './ai-provider.js';+import { getLanguageName } from './languages.js';+import { withRetry } from './retry.js';+import { isCoveredByPrompts, normalizeTokens } from './gsc-suggestions.js';+import { readPage, summaryText, toAbsoluteUrl } from './ga-suggestions.js';++/** Suggestions asked for; the schema floor keeps a short answer usable. */+export const PAGE_SUGGESTIONS = 5;+const MIN_PAGE_SUGGESTIONS = 3;+/** Search Console queries shown to the model, the page's best first. */+export const MAX_PAGE_QUERIES = 10;+/** Share of a query's words the page must use for the query to be its. */+const QUERY_OVERLAP = 0.5;+const GSC_WINDOW_DAYS = 28;+const GSC_MIN_IMPRESSIONS = 10;+const ATTEMPTS = 3;+/** Every page of the list, however long, to find this one. */+const LIST_LIMIT = 10_000;++const pageSuggestionSchema = z.object({+ suggestions: z+ .array(+ z.object({+ text: z+ .string()+ .min(20)+ .max(120)+ .describe('A short, generic question for an AI assistant, without any brand names'),+ topic: z+ .string()+ .min(3)+ .max(60)+ .describe(+ 'A 2-4 word topic label that groups this prompt (e.g. "Pricing", "Gift Ideas")',+ ),+ reason: z+ .string()+ .min(20)+ .max(220)+ .describe('One sentence on why this page answers the prompt, and the demand behind it'),+ sourceQuery: z+ .string()+ .max(200)+ .optional()+ .describe(+ 'ONLY when derived from one of the provided Search Console queries: the EXACT query, verbatim.',+ ),+ }),+ )+ .min(MIN_PAGE_SUGGESTIONS)+ .max(PAGE_SUGGESTIONS + 1),+});++/** A page path as 00178 keys it: lowercased, without a trailing slash. */+function pageKeyOf(path) {+ const trimmed = String(path ?? '')+ .trim()+ .replace(/\/+$/, '');+ return (trimmed || '/').toLowerCase();+}++/** The path of a stored URL, or null for something that isn't one. */+function pathOf(url) {+ try {+ return new URL(url).pathname;+ } catch {+ return null;+ }+}++/** The words a page is known by: its path and what it says it is about. */+export function pageWords(page, summary) {+ const slug = String(page ?? '').replace(/[/_-]+/g, ' ');+ return new Set(normalizeTokens(`${slug} ${summaryText(summary)}`));+}++/**+ * The brand's Search Console queries that are this page's: most of their+ * words are the page's, and no tracked prompt covers them already. Its+ * busiest first.+ */+export function matchPageQueries(rows, words, existingPromptTexts, max = MAX_PAGE_QUERIES) {+ return (rows ?? [])+ .map((r) => ({+ query: String(r.query ?? ''),+ impressions: Number(r.impressions) || 0,+ clicks: Number(r.clicks) || 0,+ }))+ .filter((r) => {+ const tokens = normalizeTokens(r.query);+ if (tokens.length === 0) return false;+ const hits = tokens.filter((t) => words.has(t)).length;+ return hits / tokens.length >= QUERY_OVERLAP;+ })+ .filter((r) => !isCoveredByPrompts(r.query, existingPromptTexts))+ .sort((a, b) => b.impressions - a.impressions || b.clicks - a.clicks)+ .slice(0, max);+}++/**+ * The suggestions as they go out: not a prompt the brand tracks already, one+ * of each, and a Search Console query only when it was one of those given.+ */+export function finishSuggestions(raw, { existingPromptTexts, queries }) {+ const tracked = new Set(existingPromptTexts.map((t) => t.trim().toLowerCase()));+ const byQuery = new Map(queries.map((q) => [q.query.trim().toLowerCase(), q]));+ const seen = new Set();+ const out = [];+ for (const s of raw) {+ const key = s.text.trim().toLowerCase();+ if (tracked.has(key) || seen.has(key)) continue;+ seen.add(key);+ const query = s.sourceQuery ? byQuery.get(s.sourceQuery.trim().toLowerCase()) : undefined;+ out.push({+ text: s.text.trim(),+ topic: s.topic.trim(),+ reason: s.reason.trim(),+ sourceQuery: query?.query ?? null,+ impressions: query?.impressions ?? null,+ });+ }+ return out.slice(0, PAGE_SUGGESTIONS);+}++/** The page's figures over the range, from the Pages section's own list (00178). */+async function pageFigures(brandId, page, from, to) {+ const { data, error } = await supabaseAdmin.rpc('ai_traffic_pages', {+ p_brand_id: brandId,+ p_from: from ?? null,+ p_to: to ?? null,+ p_tab: 'all',+ p_limit: LIST_LIMIT,+ p_offset: 0,+ });+ if (error) throw new Error(error.message);+ const key = pageKeyOf(page);+ const row = ((data ?? {}).rows ?? []).find((r) => pageKeyOf(r.page) === key);+ if (!row) return null;+ return {+ 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,+ };+}++/** What the page says it is about: its sitemap entry, else the page read once. */+async function pageSummary(brandId, page) {+ const key = pageKeyOf(page);+ const { data: rows, error } = await supabaseAdmin+ .from('site_pages')+ .select('url, title, description, h1')+ .eq('brand_id', brandId);+ if (error) throw new Error(error.message);+ const known = (rows ?? []).find((r) => {+ const path = pathOf(r.url);+ return path !== null && pageKeyOf(path) === key;+ });+ if (known && (known.title || known.h1 || known.description)) {+ return { title: known.title, description: known.description, h1: known.h1, headings: [] };+ }++ const { data: domains } = await supabaseAdmin+ .from('brand_domains')+ .select('domain')+ .eq('brand_id', brandId)+ .order('is_primary', { ascending: false })+ .limit(1);+ const url = toAbsoluteUrl(domains?.[0]?.domain, page);+ return url ? await readPage(url) : null;+}++/** The brand's Search Console queries over the last four weeks. */+async function searchConsoleRows(brandId) {+ const since = new Date(Date.now() - GSC_WINDOW_DAYS * 24 * 60 * 60 * 1000)+ .toISOString()+ .slice(0, 10);+ const { data, error } = await supabaseAdmin.rpc('gsc_candidate_queries', {+ p_brand_id: brandId,+ p_since: since,+ p_min_impressions: GSC_MIN_IMPRESSIONS,+ });+ if (error) throw new Error(error.message);+ return data ?? [];+}++/** The model's instructions and request, for one page. */+export function buildPagePrompt({ context, page, summary, figures, queries }) {+ const langName = getLanguageName(context.brand.language);+ const system = `You are an AEO (Answer Engine Optimization) strategist. You suggest NEW prompts people would ask an AI assistant (ChatGPT, Perplexity, Gemini, Claude) whose best answer is ONE page of a brand's site, so the brand can track whether AI answers cite that page. Current year: ${new Date().getFullYear()}.++RULES:+- Suggest ${PAGE_SUGGESTIONS} prompts that are NOT already tracked by this brand. No two may be rephrasings of the same question.+- Each prompt: 30-100 chars, generic, no brand names, written in ${langName}.+- Write at the level of the need the page serves, NOT the page's product name or URL.+- Group each prompt under a short topic label (2-4 words). Reuse existing topic labels when they fit.+- Reasons are one concrete sentence: what on the page answers the prompt, and the demand behind it.${+ queries.length+ ? `+- REAL SEARCH DEMAND: Google Search Console queries that share this page's words are provided. Derive suggestions from those that fit the page: rephrase the query as a natural question to an AI assistant, keeping its intent exactly. For each such suggestion set sourceQuery to the EXACT original query, verbatim. Never set sourceQuery otherwise.`+ : ''+ }`;++ const facts = figures+ ? `In the range shown: ${figures.sessions} sessions from every channel, ${figures.keyEvents} key events, ${figures.aiVisits} visits from AI assistants, cited ${figures.citations} times in tracked AI answers, ${figures.targetingPrompts} tracked prompts pointing to it.`+ : 'No traffic or citation figures for this page in the range shown.';++ const prompt = `Brand: ${context.brand.name}+Description: ${context.brand.description || '(none)'}++The page: ${page}+${summary ? `What the page says it is about: ${summaryText(summary).slice(0, 600)}` : 'The page could not be read; go by its path.'}+${facts}++Existing tracked prompts (DO NOT duplicate these):+${context.existingPromptTexts.length ? context.existingPromptTexts.map((p, i) => `${i + 1}. ${p}`).join('\n') : '(none yet)'}++Existing topics for this brand (prefer reusing):+${context.existingTopicNames.length ? context.existingTopicNames.join(', ') : '(none)'}${+ queries.length+ ? `++Google Search Console queries sharing this page's words (last 28 days, not tracked yet):+${queries.map((q) => ` • "${q.query}" — ${q.impressions} impressions, ${q.clicks} clicks`).join('\n')}`+ : ''+ }++Suggest ${PAGE_SUGGESTIONS} prompts this brand should track for this page, each with a topic and a reason.`;++ return { system, prompt };+}++/**+ * Suggests prompts for one page of the brand's site.+ *+ * @param {string} brandId - checked against the caller's org by the route+ * @param {{ page: string, from?: string, to?: string,+ * context: { brand: object, existingPromptTexts: string[], existingTopicNames: string[] } }} opts+ * @returns {Promise<{ page: { path: string, title: string|null }, queries: number,+ * suggestions: Array<{ text: string, topic: string, reason: string,+ * sourceQuery: string|null, impressions: number|null }> }>}+ */+export async function suggestPromptsForPage(brandId, { page, from, to, context }) {+ const [figures, summary, gscRows] = await Promise.all([+ pageFigures(brandId, page, from, to),+ pageSummary(brandId, page),+ searchConsoleRows(brandId),+ ]);+ const queries = matchPageQueries(gscRows, pageWords(page, summary), context.existingPromptTexts);+ const { system, prompt } = buildPagePrompt({ context, page, summary, figures, queries });++ const modelId = process.env.PROMPT_SUGGESTION_MODEL || 'google/gemini-3-flash-preview';+ let object;+ try {+ ({ object } = await withRetry(+ () =>+ generateObject({+ model: resolveModel(modelId),+ schema: pageSuggestionSchema,+ system,+ prompt,+ }),+ { attempts: ATTEMPTS, baseDelayMs: 500, label: 'page-prompt-suggestions' },+ ));+ } catch (err) {+ // Every attempt missed the schema: nothing usable, said plainly.+ if (NoObjectGeneratedError.isInstance(err)) {+ const failure = new Error("Couldn't write suggestions for this page. Try again.");+ failure.status = 502;+ throw failure;+ }+ throw err;+ }++ return {+ page: { path: page, title: summary?.title ?? summary?.h1 ?? null },+ queries: queries.length,+ suggestions: finishSuggestions(object.suggestions, {+ existingPromptTexts: context.existingPromptTexts,+ queries,+ }),+ };+}diff --git a/server/src/lib/page-prompt-suggestions.test.js b/server/src/lib/page-prompt-suggestions.test.jsnew file mode 100644index 000000000..96117dbe2--- /dev/null+++ b/server/src/lib/page-prompt-suggestions.test.js@@ -0,0 +1,277 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Prompts suggested for one page (AT-006 part B2). These pin which Search+ * Console queries count as the page's, that the model is told what the page+ * says and how it does, that a sitemap entry saves reading the page, and+ * that what goes out is new, one of each, with a query only when it was one+ * of those given.+ */++let db;+const rpc = vi.fn();+const generateObject = vi.fn();+const readPage = vi.fn();++function table(name) {+ const chain = {+ select: () => chain,+ eq: () => chain,+ order: () => chain,+ limit: () => chain,+ then: (resolve, reject) =>+ Promise.resolve({ data: db[name] ?? [], error: null }).then(resolve, reject),+ };+ return chain;+}++vi.mock('../config/supabase.js', () => ({+ default: { from: (name) => table(name), rpc: (...args) => rpc(...args) },+}));+vi.mock('ai', () => ({+ generateObject: (...args) => generateObject(...args),+ NoObjectGeneratedError: { isInstance: (err) => err?.name === 'NoObjectGenerated' },+}));+vi.mock('./ai-provider.js', () => ({ resolveModel: () => 'model' }));+vi.mock('./retry.js', () => ({ withRetry: (fn) => fn() }));+vi.mock('./ga-suggestions.js', async (importOriginal) => ({+ ...(await importOriginal()),+ readPage: (...args) => readPage(...args),+}));++const {+ PAGE_SUGGESTIONS,+ buildPagePrompt,+ finishSuggestions,+ matchPageQueries,+ pageWords,+ suggestPromptsForPage,+} = await import('./page-prompt-suggestions.js');++const context = {+ brand: { name: 'Acme Coffee', description: 'Specialty coffee roaster', language: 'en' },+ existingPromptTexts: ['Best monthly coffee bean subscription for offices'],+ existingTopicNames: ['Subscriptions', 'Espresso'],+};++const listRow = {+ page: '/Gifts',+ ai_visits: 0,+ citations: 6,+ targeting_prompts: 0,+ sessions: 90,+ key_events: 6,+};++const suggestion = (text, over = {}) => ({+ text,+ topic: 'Gift Ideas',+ reason: 'The gifts page lists coffee gift boxes by budget, which answers this directly.',+ ...over,+});++beforeEach(() => {+ rpc.mockReset();+ generateObject.mockReset();+ readPage.mockReset();+ db = {+ site_pages: [+ {+ url: 'https://acme-coffee.example.com/gifts/',+ title: 'Coffee gifts',+ description: 'Coffee gift boxes and sets for every budget',+ h1: 'Coffee gift ideas',+ },+ ],+ brand_domains: [{ domain: 'acme-coffee.example.com' }],+ };+ rpc.mockImplementation(async (fn) =>+ fn === 'ai_traffic_pages'+ ? { data: { rows: [listRow] }, error: null }+ : {+ data: [+ { query: 'coffee gift box ideas', impressions: 400, clicks: 12 },+ { query: 'best coffee gifts under 50', impressions: 900, clicks: 30 },+ { query: 'espresso machine descaling', impressions: 2000, clicks: 80 },+ ],+ error: null,+ },+ );+});++describe('matchPageQueries', () => {+ const words = pageWords('/gifts', {+ title: 'Coffee gifts',+ description: 'Coffee gift boxes and sets',+ h1: null,+ });++ it("keeps queries most of whose words are the page's, busiest first", () => {+ const rows = [+ { query: 'coffee gift box', impressions: 100, clicks: 1 },+ { query: 'coffee gifts', impressions: 300, clicks: 9 },+ { query: 'espresso machine descaling', impressions: 2000, clicks: 80 },+ { query: 'the best', impressions: 50, clicks: 0 },+ ];+ expect(matchPageQueries(rows, words, []).map((q) => q.query)).toEqual([+ 'coffee gifts',+ 'coffee gift box',+ ]);+ });++ it('leaves out queries a tracked prompt already covers, and caps the list', () => {+ const rows = [{ query: 'coffee gifts', impressions: 300, clicks: 9 }];+ expect(matchPageQueries(rows, words, ['Which coffee gifts do people love?'])).toEqual([]);+ const many = Array.from({ length: 14 }, (_, i) => ({+ query: `coffee gift ${i}`,+ impressions: i,+ clicks: 0,+ }));+ expect(matchPageQueries(many, words, [])).toHaveLength(10);+ });+});++describe('finishSuggestions', () => {+ it('drops tracked prompts and repeats, and keeps only queries it was given', () => {+ const out = finishSuggestions(+ [+ suggestion('Best monthly coffee bean subscription for offices'),+ suggestion('What coffee gift box should I buy for a coffee lover?', {+ sourceQuery: 'Coffee Gift Box Ideas ',+ }),+ suggestion('What coffee gift box should I buy for a coffee lover?'),+ suggestion('Good coffee gifts for a new home owner?', { sourceQuery: 'made up query' }),+ ],+ {+ existingPromptTexts: context.existingPromptTexts,+ queries: [{ query: 'coffee gift box ideas', impressions: 400, clicks: 12 }],+ },+ );+ expect(out).toEqual([+ expect.objectContaining({+ text: 'What coffee gift box should I buy for a coffee lover?',+ sourceQuery: 'coffee gift box ideas',+ impressions: 400,+ }),+ expect.objectContaining({+ text: 'Good coffee gifts for a new home owner?',+ sourceQuery: null,+ impressions: null,+ }),+ ]);+ });++ it(`sends at most ${PAGE_SUGGESTIONS}`, () => {+ const raw = Array.from({ length: PAGE_SUGGESTIONS + 1 }, (_, i) =>+ suggestion(`Which coffee gift works best for occasion number ${i}?`),+ );+ expect(finishSuggestions(raw, { existingPromptTexts: [], queries: [] })).toHaveLength(+ PAGE_SUGGESTIONS,+ );+ });+});++describe('buildPagePrompt', () => {+ it("tells the model what the page says, its figures and the brand's queries", () => {+ const { system, prompt } = buildPagePrompt({+ context,+ page: '/gifts',+ summary: { title: 'Coffee gifts', description: 'Gift boxes', h1: null },+ figures: { sessions: 90, keyEvents: 6, aiVisits: 0, citations: 6, targetingPrompts: 0 },+ queries: [{ query: 'coffee gift box ideas', impressions: 400, clicks: 12 }],+ });+ expect(system).toContain('whose best answer is ONE page');+ expect(system).toContain('sourceQuery');+ expect(prompt).toContain('The page: /gifts');+ expect(prompt).toContain('Coffee gifts — Gift boxes');+ expect(prompt).toContain('90 sessions');+ expect(prompt).toContain('cited 6 times');+ expect(prompt).toContain('"coffee gift box ideas" — 400 impressions');+ expect(prompt).toContain('1. Best monthly coffee bean subscription for offices');+ });++ it('says when the page could not be read and has no figures, and asks for no queries', () => {+ const { system, prompt } = buildPagePrompt({+ context,+ page: '/about',+ summary: null,+ figures: null,+ queries: [],+ });+ expect(system).not.toContain('sourceQuery');+ expect(prompt).toContain('could not be read');+ expect(prompt).toContain('No traffic or citation figures');+ });+});++describe('suggestPromptsForPage', () => {+ it("writes suggestions from the page's sitemap entry, figures and queries", async () => {+ generateObject.mockResolvedValue({+ object: {+ suggestions: [+ suggestion('What coffee gift box should I buy for a coffee lover?', {+ sourceQuery: 'coffee gift box ideas',+ }),+ suggestion('Good coffee gifts under 50 dollars?'),+ suggestion('Which coffee gift set suits a beginner?'),+ ],+ },+ });+ const result = await suggestPromptsForPage('b1', {+ page: '/gifts',+ from: '2026-09-18T12:00:00.000Z',+ to: '2026-10-18T12:00:00.000Z',+ context,+ });++ // The same range as the page's list.+ expect(rpc).toHaveBeenCalledWith('ai_traffic_pages', {+ p_brand_id: 'b1',+ p_from: '2026-09-18T12:00:00.000Z',+ p_to: '2026-10-18T12:00:00.000Z',+ p_tab: 'all',+ p_limit: 10_000,+ p_offset: 0,+ });+ // The sitemap entry says what the page is: nothing to read.+ expect(readPage).not.toHaveBeenCalled();+ const { prompt } = generateObject.mock.calls[0][0];+ expect(prompt).toContain('Coffee gifts');+ expect(prompt).toContain('90 sessions');+ expect(prompt).toContain('"best coffee gifts under 50"');+ expect(prompt).not.toContain('espresso machine descaling');++ expect(result.page).toEqual({ path: '/gifts', title: 'Coffee gifts' });+ expect(result.queries).toBe(2);+ expect(result.suggestions).toHaveLength(3);+ expect(result.suggestions[0]).toMatchObject({+ sourceQuery: 'coffee gift box ideas',+ impressions: 400,+ });+ });++ it('reads a page the sitemap knows nothing about, on the primary domain', async () => {+ db.site_pages = [];+ readPage.mockResolvedValue({ title: 'About Acme', description: null, h1: null, headings: [] });+ generateObject.mockResolvedValue({+ object: {+ suggestions: [+ suggestion('Which coffee roasters source beans directly from farms?'),+ suggestion('How do specialty coffee roasters choose their beans?'),+ suggestion('What makes a coffee roaster sustainable and ethical?'),+ ],+ },+ });+ const result = await suggestPromptsForPage('b1', { page: '/about', context });+ expect(readPage).toHaveBeenCalledWith('https://acme-coffee.example.com/about');+ expect(result.page.title).toBe('About Acme');+ });++ it('says plainly when no attempt gave usable suggestions', async () => {+ generateObject.mockRejectedValue(Object.assign(new Error('x'), { name: 'NoObjectGenerated' }));+ await expect(suggestPromptsForPage('b1', { page: '/gifts', context })).rejects.toMatchObject({+ status: 502,+ message: "Couldn't write suggestions for this page. Try again.",+ });+ });+});diff --git a/server/src/routes/prompts-page-suggestions.test.js b/server/src/routes/prompts-page-suggestions.test.jsnew file mode 100644index 000000000..8cf5f2890--- /dev/null+++ b/server/src/routes/prompts-page-suggestions.test.js@@ -0,0 +1,143 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * POST /api/prompts/suggestions/:brandId/page (AT-006 part B2): prompts+ * suggested for one page of the AI Traffic page's Pages section. The+ * suggestions themselves are tested in page-prompt-suggestions.test.js; what+ * shows up only here is what the route lets through: a path, the page's+ * range, a caller from the brand's organization, and the brand's tracked+ * prompts and topics handed on.+ */++const suggestPromptsForPage = vi.fn();+let profileOrg;++function table(name) {+ const result = () => {+ if (name === 'brands') {+ return {+ data: {+ id: 'b1',+ name: 'Acme',+ description: 'Coffee',+ language: 'en',+ organization_id: 'o1',+ },+ error: null,+ };+ }+ if (name === 'profiles') return { data: { organization_id: profileOrg }, error: null };+ if (name === 'prompts')+ return { data: [{ id: 'p1', text: 'Best espresso beans?' }], error: null };+ if (name === 'topics') return { data: [{ name: 'Espresso' }], error: null };+ return { data: [], error: null };+ };+ const chain = new Proxy(+ {},+ {+ get: (_t, prop) => {+ if (prop === 'then') {+ return (resolve, reject) => Promise.resolve(result()).then(resolve, reject);+ }+ if (prop === 'single' || prop === 'maybeSingle') return async () => result();+ return () => chain;+ },+ },+ );+ return chain;+}++vi.mock('../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));+vi.mock('../lib/plan-guard.js', () => ({+ PlanLimitError: class extends Error {},+ enforceFeature: vi.fn(),+ enforceImproveQuota: vi.fn(),+ getImproveQuotaStatus: vi.fn(),+ requireFeature: () => (req, res, next) => next(),+ reserveRelevanceAllowance: vi.fn(),+ settleRelevanceUsage: vi.fn(),+}));+vi.mock('../lib/page-prompt-suggestions.js', () => ({ suggestPromptsForPage }));++const { default: router } = await import('./prompts.js');++const BRAND = '33333333-3333-3333-3333-333333333333';+let server;+let baseUrl;++const post = (body) =>+ fetch(`${baseUrl}/suggestions/${BRAND}/page`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ suggestPromptsForPage.mockReset();+ profileOrg = 'o1';+ 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/prompts', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/prompts`;+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /api/prompts/suggestions/:brandId/page', () => {+ it("suggests prompts for the page over the page's range", async () => {+ const answer = {+ page: { path: '/gifts', title: 'Coffee gifts' },+ queries: 1,+ suggestions: [{ text: 'Best coffee gifts?', topic: 'Gifts', reason: 'r' }],+ };+ suggestPromptsForPage.mockResolvedValue(answer);+ const res = await post({ page: '/gifts', from: '2026-10-01', to: '2026-10-18T23:59:59.999Z' });+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual(answer);+ expect(suggestPromptsForPage).toHaveBeenCalledWith(BRAND, {+ page: '/gifts',+ from: '2026-10-01',+ to: '2026-10-18T23:59:59.999Z',+ context: expect.objectContaining({+ existingPromptTexts: ['Best espresso beans?'],+ existingTopicNames: ['Espresso'],+ }),+ });+ });++ it('rejects a URL instead of a path, or a range it cannot read', async () => {+ expect((await post({ page: 'https://acme.example/gifts' })).status).toBe(400);+ expect((await post({ page: '/gifts', from: 'last week' })).status).toBe(400);+ expect(suggestPromptsForPage).not.toHaveBeenCalled();+ });++ it('refuses a caller outside the brand’s organization', async () => {+ profileOrg = 'o2';+ expect((await post({ page: '/gifts' })).status).toBe(403);+ expect(suggestPromptsForPage).not.toHaveBeenCalled();+ });++ it('passes on why no suggestions came', async () => {+ suggestPromptsForPage.mockRejectedValue(+ Object.assign(new Error("Couldn't write suggestions for this page. Try again."), {+ status: 502,+ }),+ );+ const res = await post({ page: '/gifts' });+ expect(res.status).toBe(502);+ expect(await res.json()).toEqual({+ error: "Couldn't write suggestions for this page. Try again.",+ });+ });+});diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.jsindex 823afec10..bcd23af09 100644--- a/server/src/routes/prompts.js+++ b/server/src/routes/prompts.js@@ -17,6 +17,7 @@ import {import { withRetry } from '../lib/retry.js';import { getGscSuggestionCandidates } from '../lib/gsc-suggestions.js';import { getGaSuggestionCandidates } from '../lib/ga-suggestions.js';+import { suggestPromptsForPage } from '../lib/page-prompt-suggestions.js';import { RELEVANCE_SCALE, ratingCostUsd, toRelevance } from '../lib/suggestion-relevance.js';import {ACTIONABLE_STATES,@@ -522,6 +523,46 @@ router.post(},);+const pageSuggestionsSchema = z.object({+ // A path, as the AI Traffic page's Pages section lists it.+ page: z.string().min(1).max(2048).startsWith('/'),+ // 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/prompts/suggestions/:brandId/page+ * Body: { page, from?, to? }+ *+ * Prompts suggested for one page of the brand's site, from the AI Traffic+ * page's Pages section (AT-006 part B2). Not stored: the person picks the+ * ones to track, which then point at the page.+ */+router.post(+ '/suggestions/:brandId/page',+ requireFeature('prompt_suggestions'),+ async (req, res) => {+ try {+ const parsed = pageSuggestionsSchema.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });+ }+ await assertBrandAccess(req.params.brandId, req.user.id);+ const context = await loadSuggestionContext(req.params.brandId);+ const result = await suggestPromptsForPage(req.params.brandId, { ...parsed.data, context });+ return res.json(result);+ } catch (error) {+ const status = error.status || 500;+ req.log.error({ err: error }, 'page prompt suggestions error');+ return res+ .status(status)+ .json({ error: error.message || 'Failed to suggest prompts for this page' });+ }+ },+);+router.get('/suggestions/:brandId', async (req, res) => {try {await assertBrandAccess(req.params.brandId, req.user.id);diff --git a/web/messages/en.json b/web/messages/en.jsonindex 8b352f0a8..72014a426 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3416,6 +3416,26 @@"auditsFailed": "Couldn't start the audits","noneLeft": "No audits left this month","overQuota": "{count, plural, one {# audit} other {# audits}}, {remaining} left this month"+ },+ "prompts": {+ "title": "Suggested prompts",+ "explain": "Questions people ask AI assistants that {page} answers. The prompts you track point to this page, so their answers show whether AI cites it.",+ "pageTitle": "The page: {title}",+ "loading": "Writing prompt suggestions for this page…",+ "failed": "Couldn't suggest prompts for this page.",+ "empty": "No new prompts to suggest for this page: the ones it answers are tracked already.",+ "fromQuery": "From Search Console: “{query}” · {impressions} impressions",+ "slotsLeft": "{count, plural, one {# prompt} other {# prompts}} left to add on your plan",+ "unlimited": "No prompt limit on your plan",+ "overSlots": "Select up to {count, plural, one {# prompt} other {# prompts}}: that's what your plan has left",+ "addOwn": "Add your own",+ "track": "Track {count, plural, one {# prompt} other {# prompts}}",+ "tracked": "Now tracking {count, plural, one {# prompt} other {# prompts}}",+ "trackedDescription": "They point to {page}; their first answers come with the next tracking run.",+ "trackedPartly": "Tracked {tracked} of {total}: your plan's prompt locations are full.",+ "planFull": "Your plan's prompt locations are full",+ "trackFailed": "Couldn't track the prompts.",+ "openPrompts": "Open Prompts"}}},diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_page-prompts-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_page-prompts-dialog.test.tsxnew file mode 100644index 000000000..e8c0366c6--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_page-prompts-dialog.test.tsx@@ -0,0 +1,197 @@+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';+import type { PagePromptSuggestion, TrafficDateWindow } from '@/lib/actions/traffic';++/**+ * "Add prompts" for one page (AT-006 part B2): the page's suggested prompts,+ * as many ticked as the plan's prompt slots allow (PROMPT-012), tracked so+ * they point at the page; never more than the slots left.+ */++const suggestPagePrompts = vi.fn();+const getLocationQuota = vi.fn();+const trackPagePrompts = vi.fn();+const push = vi.fn();+const toast = vi.hoisted(() => ({+ success: vi.fn(),+ warning: vi.fn(),+ error: vi.fn(),+}));+vi.mock('@/lib/actions/traffic', () => ({+ suggestPagePrompts: (...args: unknown[]) => suggestPagePrompts(...args),+}));+vi.mock('@/lib/actions/prompt', () => ({+ getLocationQuota: (...args: unknown[]) => getLocationQuota(...args),+}));+vi.mock('@/lib/actions/prompt-suggestions', () => ({+ trackPagePrompts: (...args: unknown[]) => trackPagePrompts(...args),+}));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,+ useRouter: () => ({ push }),+}));+vi.mock('sonner', () => ({ toast }));++const { PagePromptsDialog } = await import('./_page-prompts-dialog');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const BRAND = '33333333-3333-3333-3333-333333333333';+const WEEK: TrafficDateWindow = { dateFrom: '2026-10-11T09:00:00.000Z' };++const suggestion = (text: string, over: Partial<PagePromptSuggestion> = {}) => ({+ text,+ topic: 'Gift Ideas',+ reason: 'The gifts page lists coffee gift boxes by budget.',+ sourceQuery: null,+ impressions: null,+ ...over,+});++const SUGGESTIONS = [+ suggestion('What coffee gift box should I buy for a coffee lover?', {+ sourceQuery: 'coffee gift box ideas',+ impressions: 1400,+ }),+ suggestion('Good coffee gifts under 50 dollars?'),+ suggestion('Which coffee gift set suits a beginner?'),+];++let container: HTMLDivElement;+let root: Root;+const onClose = vi.fn();+const onTracked = vi.fn();++beforeEach(() => {+ suggestPagePrompts.mockReset().mockResolvedValue({+ page: { path: '/gifts', title: 'Coffee gifts' },+ queries: 1,+ suggestions: SUGGESTIONS,+ });+ getLocationQuota.mockReset().mockResolvedValue({ maxPrompts: 50, used: 48 });+ trackPagePrompts.mockReset();+ for (const fn of [push, onClose, onTracked, ...Object.values(toast)]) fn.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++async function render({ domain = 'acme-coffee.example.com' }: { domain?: string } = {}) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <PagePromptsDialog+ brandId={BRAND}+ dateWindow={WEEK}+ domain={domain}+ page="/gifts"+ onClose={onClose}+ onTracked={onTracked}+ />+ </NextIntlClientProvider>,+ );+ });+}++const text = () => document.body.textContent ?? '';+const boxes = () => [...document.body.querySelectorAll<HTMLElement>('[role="checkbox"]')];+const ticked = () => boxes().map((b) => b.getAttribute('aria-checked') === 'true');+const trackButton = () =>+ [...document.body.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.startsWith('Track'),+ )!;++describe('PagePromptsDialog', () => {+ it("shows the page's suggestions, ticking as many as the plan has slots for", async () => {+ await render();+ expect(suggestPagePrompts).toHaveBeenCalledWith(BRAND, WEEK, '/gifts');+ expect(text()).toContain('The page: Coffee gifts');+ expect(text()).toContain('What coffee gift box should I buy for a coffee lover?');+ expect(text()).toContain('From Search Console: “coffee gift box ideas” · 1,400 impressions');+ expect(ticked()).toEqual([true, true, false]);+ expect(text()).toContain('2 prompts left to add on your plan');+ expect(trackButton().textContent).toBe('Track 2 prompts');+ });++ it('never tracks more than the slots left', async () => {+ await render();+ await act(async () => boxes()[2].click());+ expect(ticked()).toEqual([true, true, true]);+ expect(text()).toContain("Select up to 2 prompts: that's what your plan has left");+ expect(trackButton().disabled).toBe(true);+ });++ it('ticks every suggestion on a plan without a prompt limit', async () => {+ getLocationQuota.mockResolvedValue({ maxPrompts: -1, used: 900 });+ await render();+ expect(ticked()).toEqual([true, true, true]);+ expect(text()).toContain('No prompt limit on your plan');+ });++ it('tracks the ticked prompts pointing at the page, then refreshes the list', async () => {+ trackPagePrompts.mockResolvedValue({ promptIds: ['p1', 'p2'] });+ await render({ domain: 'https://acme-coffee.example.com/' });+ await act(async () => trackButton().click());++ expect(trackPagePrompts).toHaveBeenCalledWith(BRAND, 'https://acme-coffee.example.com/gifts', [+ { text: SUGGESTIONS[0].text, topic: 'Gift Ideas' },+ { text: SUGGESTIONS[1].text, topic: 'Gift Ideas' },+ ]);+ expect(toast.success).toHaveBeenCalledWith(+ 'Now tracking 2 prompts',+ expect.objectContaining({+ description: 'They point to /gifts; their first answers come with the next tracking run.',+ }),+ );+ expect(onTracked).toHaveBeenCalled();+ expect(onClose).toHaveBeenCalled();+ });++ it('says how far it got when the plan ran out, and when nothing could be added', async () => {+ trackPagePrompts.mockResolvedValue({+ promptIds: ['p1'],+ error: 'full',+ code: 'plan_limit',+ });+ await render();+ await act(async () => trackButton().click());+ expect(toast.warning).toHaveBeenCalledWith(+ "Tracked 1 of 2: your plan's prompt locations are full.",+ expect.anything(),+ );+ expect(onTracked).toHaveBeenCalled();++ trackPagePrompts.mockResolvedValue({ promptIds: [], error: 'full', code: 'plan_limit' });+ await act(async () => trackButton().click());+ expect(toast.error).toHaveBeenCalledWith("Your plan's prompt locations are full");+ });++ it("says when the page's prompts couldn't be written", async () => {+ suggestPagePrompts.mockResolvedValue({+ error: "Couldn't write suggestions for this page. Try again.",+ });+ await render();+ expect(text()).toContain("Couldn't suggest prompts for this page.");+ expect(text()).toContain('Try again.');+ expect(trackButton().disabled).toBe(true);+ });++ it('says when every prompt the page answers is tracked already', async () => {+ suggestPagePrompts.mockResolvedValue({+ page: { path: '/gifts', title: null },+ queries: 0,+ suggestions: [],+ });+ await render();+ expect(text()).toContain('No new prompts to suggest for this page');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_page-prompts-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_page-prompts-dialog.tsxnew file mode 100644index 000000000..b81ad6556--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_page-prompts-dialog.tsx@@ -0,0 +1,246 @@+'use client';++import { useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Loader2 } from 'lucide-react';+import { Link, useRouter } from '@/i18n/navigation';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import { Checkbox } from '@/components/ui/checkbox';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Skeleton } from '@/components/ui/skeleton';+import { cn } from '@/lib/utils';+import { formatNumber } from '@/lib/format';+import { pageUrl } from '@/lib/traffic-pages';+import { getLocationQuota } from '@/lib/actions/prompt';+import { trackPagePrompts } from '@/lib/actions/prompt-suggestions';+import {+ suggestPagePrompts,+ type PagePromptSuggestions,+ type TrafficDateWindow,+} from '@/lib/actions/traffic';++/**+ * Prompts slots left on the plan, from its tracked-location cap: null when+ * the plan has no cap, or it couldn't be read (the server still checks).+ */+function slotsLeftOf(quota: { maxPrompts: number; used: number } | null): number | null {+ if (!quota || quota.maxPrompts === -1) return null;+ return Math.max(0, quota.maxPrompts - quota.used);+}++/**+ * "Add prompts" for one page of the Pages section (AT-006 part B2): prompts+ * whose best answer is the page, to pick from and track within the plan's+ * prompt slots (PROMPT-012). As many as the slots allow start ticked; the+ * ones tracked point at the page, so their answers show whether AI cites it.+ */+export function PagePromptsDialog({+ brandId,+ dateWindow,+ domain,+ page,+ onClose,+ onTracked,+}: {+ brandId: string;+ dateWindow: TrafficDateWindow;+ /** The brand's primary domain, for the prompts' target URL. */+ domain: string | undefined;+ /** The page to suggest prompts for; null keeps the dialog closed. */+ page: string | null;+ onClose: () => void;+ /** Prompts were added: the list's prompt counts changed. */+ onTracked: () => void;+}) {+ const t = useTranslations('traffic.pageList.prompts');+ const router = useRouter();+ // The loaded suggestions carry the page they are for, so another page's+ // never show while this one's load.+ const [loaded, setLoaded] = useState<{+ page: string;+ result: PagePromptSuggestions | { error: string };+ slotsLeft: number | null;+ unlimited: boolean;+ } | null>(null);+ const [selected, setSelected] = useState<Set<number>>(new Set());+ const [tracking, setTracking] = useState(false);++ useEffect(() => {+ if (!page) return;+ let cancelled = false;+ Promise.all([+ suggestPagePrompts(brandId, dateWindow, page).catch(() => ({ error: '' })),+ getLocationQuota(brandId).catch(() => null),+ ]).then(([result, quota]) => {+ if (cancelled) return;+ const slotsLeft = slotsLeftOf(quota);+ setLoaded({ page, result, slotsLeft, unlimited: quota?.maxPrompts === -1 });+ const count = 'suggestions' in result ? result.suggestions.length : 0;+ setSelected(+ new Set(Array.from({ length: Math.min(count, slotsLeft ?? count) }, (_, i) => i)),+ );+ });+ return () => {+ cancelled = true;+ };+ }, [brandId, dateWindow, page]);++ const current = page && loaded?.page === page ? loaded : null;+ const suggestions = current && 'suggestions' in current.result ? current.result.suggestions : [];+ const slotsLeft = current?.slotsLeft ?? null;+ const over = slotsLeft !== null && selected.size > slotsLeft;++ const toggle = (index: number, on: boolean) =>+ setSelected((prev) => {+ const next = new Set(prev);+ if (on) next.add(index);+ else next.delete(index);+ return next;+ });++ const track = async () => {+ if (!page || selected.size === 0) return;+ const picked = suggestions.filter((_, i) => selected.has(i));+ setTracking(true);+ try {+ const result = await trackPagePrompts(+ brandId,+ domain ? pageUrl(domain, page) : null,+ picked.map((s) => ({ text: s.text, topic: s.topic })),+ );+ const open = { label: t('openPrompts'), onClick: () => router.push('/dashboard/prompts') };+ const done = result.promptIds.length;+ if (done > 0) onTracked();+ if (done === picked.length) {+ toast.success(t('tracked', { count: done }), {+ description: t('trackedDescription', { page }),+ duration: 10_000,+ action: open,+ });+ onClose();+ } else if (done > 0) {+ toast.warning(t('trackedPartly', { tracked: done, total: picked.length }), {+ action: open,+ });+ onClose();+ } else if (result.code === 'plan_limit') {+ toast.error(t('planFull'));+ } else {+ toast.error(t('trackFailed'), { description: result.error });+ }+ } catch {+ toast.error(t('trackFailed'));+ } finally {+ setTracking(false);+ }+ };++ return (+ <Dialog open={page !== null} onOpenChange={(open) => !open && !tracking && onClose()}>+ <DialogContent className="sm:max-w-xl">+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ <DialogDescription>+ {t('explain', { page: page ?? '' })}+ {current && 'page' in current.result && current.result.page.title && (+ <span className="mt-1 block text-xs">+ {t('pageTitle', { title: current.result.page.title })}+ </span>+ )}+ </DialogDescription>+ </DialogHeader>++ {!current ? (+ <div className="space-y-3" aria-busy>+ <p className="text-sm text-muted-foreground">{t('loading')}</p>+ <Skeleton className="h-4 w-3/4" />+ <Skeleton className="h-4 w-2/3" />+ <Skeleton className="h-4 w-4/5" />+ </div>+ ) : 'error' in current.result ? (+ <div className="space-y-1 text-sm">+ <p>{t('failed')}</p>+ {current.result.error && (+ <p className="text-xs text-muted-foreground">{current.result.error}</p>+ )}+ </div>+ ) : suggestions.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('empty')}</p>+ ) : (+ <ul className="max-h-[60vh] space-y-2 overflow-y-auto">+ {suggestions.map((s, i) => (+ <li key={s.text}>+ <label className="flex cursor-pointer items-start gap-3 rounded-md border px-3 py-2 hover:bg-muted/40">+ <Checkbox+ className="mt-0.5"+ checked={selected.has(i)}+ onCheckedChange={(on) => toggle(i, on === true)}+ aria-label={s.text}+ />+ <span className="min-w-0 space-y-1">+ <span className="block font-medium">{s.text}</span>+ <span className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">+ <Badge variant="outline" className="text-[10px]">+ {s.topic}+ </Badge>+ {s.reason}+ </span>+ {s.sourceQuery && (+ <span className="block text-xs text-muted-foreground">+ {t('fromQuery', {+ query: s.sourceQuery,+ impressions: formatNumber(s.impressions ?? 0),+ })}+ </span>+ )}+ </span>+ </label>+ </li>+ ))}+ </ul>+ )}++ <DialogFooter className="sm:items-center sm:justify-between">+ <p+ className={cn(+ 'text-xs',+ over ? 'text-amber-700 dark:text-amber-400' : 'text-muted-foreground',+ )}+ >+ {current && suggestions.length > 0+ ? over+ ? t('overSlots', { count: slotsLeft ?? 0 })+ : current.unlimited+ ? t('unlimited')+ : slotsLeft !== null+ ? t('slotsLeft', { count: slotsLeft })+ : null+ : null}+ </p>+ <div className="flex flex-col-reverse gap-2 sm:flex-row">+ <Link href="/dashboard/prompts" className={buttonVariants({ variant: 'outline' })}>+ {t('addOwn')}+ </Link>+ <Button+ disabled={!current || selected.size === 0 || over || tracking}+ onClick={() => void track()}+ >+ {tracking && <Loader2 className="h-4 w-4 animate-spin" />}+ {t('track', { count: selected.size })}+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}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 967453f41..a64836146 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@@ -40,6 +40,19 @@ vi.mock('@/i18n/navigation', () => ({useRouter: () => ({ push }),}));vi.mock('sonner', () => ({ toast }));+// The suggested-prompts dialog (part B2) is tested on its own: here, which+// page it opens for, and that tracking reads the list again.+vi.mock('./_page-prompts-dialog', () => ({+ PagePromptsDialog: ({ page, onTracked }: { page: string | null; onTracked: () => void }) =>+ page ? (+ <div data-testid="prompts-dialog">+ {`prompts for ${page}`}+ <button type="button" onClick={onTracked}>+ tracked+ </button>+ </div>+ ) : null,+}));const { PagesCard } = await import('./_pages-card');@@ -118,6 +131,8 @@ const tab = (label: string) =>[...container.querySelectorAll<HTMLElement>('[role="tab"]')].find((el) =>el.textContent?.startsWith(label),)!;+const dialog = () =>+ container.querySelector('[data-testid="prompts-dialog"]')?.firstChild?.textContent ?? null;const button = (label: string) =>[...container.querySelectorAll<HTMLElement>('button, a')].find((el) => el.textContent === label)!;@@ -155,8 +170,9 @@ describe('PagesCard', () => {runAudit.mockResolvedValue({ id: 'audit-1' });await render();- const links = [...container.querySelectorAll('a')].map((a) => a.getAttribute('href'));- expect(links).toEqual(['/dashboard/prompts']);+ // Nothing points at /about: its next step is prompts suggested for it.+ await act(async () => button('Add prompts').click());+ expect(dialog()).toBe('prompts for /about');await act(async () => button('Audit page').click());expect(runAudit).toHaveBeenCalledWith(BRAND, 'https://acme-coffee.example.com/gifts');@@ -190,7 +206,8 @@ describe('PagesCard', () => {});expect(text()).toContain('/subscriptions');expect(text()).toContain('ChatGPT, Perplexity');- expect(button('Add prompts').getAttribute('href')).toBe('/dashboard/prompts');+ await act(async () => button('Add prompts').click());+ expect(dialog()).toBe('prompts for /subscriptions');});it("never shows one list's rows under another's columns while it loads", async () => {@@ -419,4 +436,25 @@ describe('PagesCard actions (AT-006 part B)', () => {expect(button('Send to Action Center')).toBeUndefined();expect(container.querySelector('[aria-label^="More actions"]')).toBeNull();});++ it('suggests prompts from the row menu of a page whose next step is an audit', async () => {+ getTrafficPages.mockResolvedValue(pages([page({ citations: 6 })]));+ 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 === 'Add prompts',+ )!;+ await act(async () => item.click());+ expect(dialog()).toBe('prompts for /gifts');+ });++ it('reads the list again once prompts were tracked', async () => {+ getTrafficPages.mockResolvedValue(pages([page({ page: '/about', valueRank: 2 })]));+ await render();+ await act(async () => button('Add prompts').click());+ expect(getTrafficPages).toHaveBeenCalledTimes(1);+ await act(async () => button('tracked').click());+ expect(getTrafficPages).toHaveBeenCalledTimes(2);+ });});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsxindex bcf85d3a6..bb46efd61 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx@@ -3,8 +3,8 @@import { useEffect, useState, type ReactNode } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';-import { FileSearch, Loader2, MoreHorizontal, Send } from 'lucide-react';-import { Link, useRouter } from '@/i18n/navigation';+import { FileSearch, ListPlus, Loader2, MoreHorizontal, Send } from 'lucide-react';+import { useRouter } from '@/i18n/navigation';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';import {@@ -14,7 +14,6 @@ import {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';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import {@@ -39,6 +38,7 @@ import {} from '@/lib/actions/traffic';import { runAudit } from '@/lib/actions/audits';import { PAGE_ACTION_MAX, auditBlock, usePageActions } from './_use-page-actions';+import { PagePromptsDialog } from './_page-prompts-dialog';/*** Pages: which answers send visitors (AT-006, spec §3.5, "the@@ -54,7 +54,7 @@ import { PAGE_ACTION_MAX, auditBlock, usePageActions } from './_use-page-actions* prompt's answer covers.** A row's action is the next step for it: audit the page, or track prompts- * that point to it; its menu sends it to the Action Center. Under the two+ * suggested for it 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).*/@@ -118,8 +118,13 @@ export function PagesCard({const [limit, setLimit] = useState(PAGE_SIZE);const [auditing, setAuditing] = useState<string | null>(null);const pageActions = usePageActions(brandId, dateWindow);+ // The page whose suggested prompts are open (part B2); each opening starts+ // afresh, and tracking some reads the list again for its prompt counts.+ const [promptsFor, setPromptsFor] = useState<string | null>(null);+ const [promptsOpened, setPromptsOpened] = useState(0);+ const [reloads, setReloads] = useState(0);- const key = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}|${tab}|${limit}`;+ const key = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}|${tab}|${limit}|${reloads}`;// The loaded result carries the request it answers, as the KPI cards do:// no loading flag reset inside the effect, and the last list stays on// screen, faded, while another loads.@@ -184,24 +189,34 @@ export function PagesCard({</Button>);- const addPromptsLink = (- <Link- href="/dashboard/prompts"- className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 text-xs')}- >+ const openPrompts = (page: string) => {+ setPromptsFor(page);+ setPromptsOpened((n) => n + 1);+ };++ const addPromptsButton = (page: string) => (+ <Button size="sm" variant="outline" className="h-7 text-xs" onClick={() => openPrompts(page)}>{t('addPrompts')}- </Link>+ </Button>);/** A No AI traffic row's next step, by why AI engines skip it. */const reasonAction = (row: TrafficPageRow) =>- citationState(row) === 'not_targeted' ? addPromptsLink : auditButton(row.page);+ citationState(row) === 'not_targeted' ? addPromptsButton(row.page) : auditButton(row.page);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) => (+ /**+ * A row's next step, with its menu: send the page to the Action Center, and+ * suggest prompts for it when that isn't already its next step.+ */+ const rowActions = (+ row: TrafficPageRow,+ next: ReactNode,+ reason: TrafficPagesReason,+ { addPrompts = true }: { addPrompts?: boolean } = {},+ ) => (<div className="flex items-center justify-end gap-1">{next}<DropdownMenu>@@ -220,6 +235,12 @@ export function PagesCard({<Send className="h-3.5 w-3.5" />{t('actions.sendToActionCenter')}</DropdownMenuItem>+ {addPrompts && (+ <DropdownMenuItem className="gap-2" onClick={() => openPrompts(row.page)}>+ <ListPlus className="h-3.5 w-3.5" />+ {t('addPrompts')}+ </DropdownMenuItem>+ )}</DropdownMenuContent></DropdownMenu></div>@@ -387,7 +408,9 @@ export function PagesCard({{row.valueRank === null ? '—' : `#${row.valueRank}`}</TableCell><TableCell className="pr-6 text-right">- {rowActions(row, reasonAction(row), 'no_ai_traffic')}+ {rowActions(row, reasonAction(row), 'no_ai_traffic', {+ addPrompts: citationState(row) !== 'not_targeted',+ })}</TableCell></>)}@@ -414,7 +437,9 @@ export function PagesCard({{platforms(row)}</TableCell><TableCell className="text-right text-sm">{num(row.aiKeyEvents)}</TableCell>- <TableCell className="pr-6 text-right">{addPromptsLink}</TableCell>+ <TableCell className="pr-6 text-right">+ {addPromptsButton(row.page)}+ </TableCell></>)}{tab === 'all' && (@@ -511,6 +536,15 @@ export function PagesCard({</div>)}</CardContent>+ <PagePromptsDialog+ key={promptsOpened}+ brandId={brandId}+ dateWindow={dateWindow}+ domain={domain}+ page={promptsFor}+ onClose={() => setPromptsFor(null)}+ onTracked={() => setReloads((n) => n + 1)}+ /></Card>);}diff --git a/web/src/lib/actions/prompt-suggestions.test.ts b/web/src/lib/actions/prompt-suggestions.test.tsindex b04ce7c8b..b4f6109b9 100644--- a/web/src/lib/actions/prompt-suggestions.test.ts+++ b/web/src/lib/actions/prompt-suggestions.test.ts@@ -12,6 +12,11 @@ let added: string[] = [];/** Suggestions still 'new'; others were accepted or dismissed elsewhere. */let open: Set<string>;let reads: string[] = [];+/** The brand's topics, and the ones made or removed while tracking. */+let brandTopics: string[] = [];+let madeTopics: string[] = [];+let removedTopics: string[] = [];+let categories: (string | undefined)[] = [];vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://server' }));@@ -30,18 +35,37 @@ vi.mock('@/lib/supabase/server', () => ({});const row = () =>table === 'prompt_sets' ? { id: 'ps1' } : { platforms: ['chatgpt-web'], models: [] };+ let made: { id: string; name: string } | null = null;+ let removing = false;const chain = {select: () => chain,in: (_col: string, val: string[]) => {ids = val;return chain;},- eq: () => chain,+ eq: (_col: string, val: string) => {+ if (removing) removedTopics.push(val);+ return chain;+ },order: () => chain,limit: () => chain,+ insert: (r: { name: string }) => {+ madeTopics.push(r.name);+ made = { id: `topic-${madeTopics.length}`, name: r.name };+ return chain;+ },+ delete: () => {+ removing = true;+ return chain;+ },+ single: async () => ({ data: made, error: null }),maybeSingle: async () => ({ data: row(), error: null }),then: (resolve: (r: unknown) => void) =>- resolve({ data: ids.filter((id) => open.has(id)).map(suggestion), error: null }),+ resolve(+ table === 'topics'+ ? { data: brandTopics.map((name) => ({ name })), error: null }+ : { data: ids.filter((id) => open.has(id)).map(suggestion), error: null },+ ),};return chain;},@@ -49,7 +73,8 @@ vi.mock('@/lib/supabase/server', () => ({}));vi.mock('@/lib/actions/prompt', () => ({- addPromptToSet: vi.fn(async ({ text }: { text: string }) => {+ addPromptToSet: vi.fn(async ({ text, category }: { text: string; category?: string }) => {+ categories.push(category);if (slotsLeft <= 0) {return { error: 'Your plan’s prompt locations are full.', code: 'plan_limit' };}@@ -59,14 +84,30 @@ vi.mock('@/lib/actions/prompt', () => ({}),}));+const targets: { promptId: string; url: string }[] = [];+let targetError: string | null = null;+vi.mock('@/lib/actions/prompt-workflow', () => ({+ addPromptTargetUrl: vi.fn(async (promptId: string, url: string) => {+ if (targetError) return { error: targetError };+ targets.push({ promptId, url });+ return { targetUrl: { id: `t-${promptId}`, url } };+ }),+}));+const fetchMock = vi.fn(async () => new Response('{}', { status: 200 }));vi.stubGlobal('fetch', fetchMock);-const { trackSuggestions } = await import('./prompt-suggestions');+const { trackPagePrompts, trackSuggestions } = await import('./prompt-suggestions');beforeEach(() => {slotsLeft = Infinity;added = [];+ targets.length = 0;+ targetError = null;+ brandTopics = [];+ madeTopics = [];+ removedTopics = [];+ categories = [];reads = [];open = new Set(['s1', 's2', 's3', 's4']);fetchMock.mockClear();@@ -116,3 +157,70 @@ describe('trackSuggestions', () => {expect(added).toEqual([]);});});++describe('trackPagePrompts (AT-006 part B2)', () => {+ const picked = [+ { text: 'Best coffee gifts under 50 dollars?', topic: 'Gift Ideas' },+ { text: 'Which coffee gift set suits a beginner?', topic: 'Gift Ideas' },+ ];++ it('tracks each prompt pointing at the page', async () => {+ const result = await trackPagePrompts('b1', 'https://acme.example/gifts', picked);+ expect(result).toEqual({ promptIds: ['p-1', 'p-2'] });+ expect(added).toEqual(picked.map((p) => p.text));+ expect(targets).toEqual([+ { promptId: 'p-1', url: 'https://acme.example/gifts' },+ { promptId: 'p-2', url: 'https://acme.example/gifts' },+ ]);+ });++ it('stops where the plan’s prompt locations run out', async () => {+ slotsLeft = 1;+ expect(await trackPagePrompts('b1', 'https://acme.example/gifts', picked)).toEqual({+ promptIds: ['p-1'],+ error: 'Your plan’s prompt locations are full.',+ code: 'plan_limit',+ });+ });++ it('keeps a prompt tracked when its target URL could not be saved, or without a domain', async () => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});+ targetError = 'duplicate';+ expect((await trackPagePrompts('b1', 'https://acme.example/gifts', picked)).promptIds).toEqual([+ 'p-1',+ 'p-2',+ ]);+ targetError = null;+ await trackPagePrompts('b1', null, picked.slice(0, 1));+ expect(targets).toEqual([]);+ log.mockRestore();+ });++ it('refuses an empty list before adding anything', async () => {+ expect(await trackPagePrompts('b1', null, [{ text: ' ', topic: 'x' }])).toEqual({+ promptIds: [],+ error: 'Pick at least one prompt.',+ });+ expect(added).toEqual([]);+ });++ it("files each prompt under the brand's topic, making the ones it lacks", async () => {+ brandTopics = ['gift ideas'];+ await trackPagePrompts('b1', null, [+ { text: 'Best coffee gifts under 50 dollars?', topic: 'Gift Ideas' },+ { text: 'Is a coffee subscription a good gift?', topic: 'Coffee Subscriptions' },+ { text: 'Which coffee gift set suits a beginner?', topic: 'coffee subscriptions' },+ ]);+ // The brand's own spelling, then a topic made once and reused.+ expect(categories).toEqual(['gift ideas', 'Coffee Subscriptions', 'Coffee Subscriptions']);+ expect(madeTopics).toEqual(['Coffee Subscriptions']);+ expect(removedTopics).toEqual([]);+ });++ it('removes a topic made for a prompt the plan had no room for', async () => {+ slotsLeft = 0;+ await trackPagePrompts('b1', null, [{ text: 'Best coffee gifts?', topic: 'Coffee Gifts' }]);+ expect(madeTopics).toEqual(['Coffee Gifts']);+ expect(removedTopics).toEqual(['topic-1']);+ });+});diff --git a/web/src/lib/actions/prompt-suggestions.ts b/web/src/lib/actions/prompt-suggestions.tsindex 27acac5d6..319bd4b17 100644--- a/web/src/lib/actions/prompt-suggestions.ts+++ b/web/src/lib/actions/prompt-suggestions.ts@@ -3,6 +3,7 @@import { revalidatePath } from 'next/cache';import { createClient } from '@/lib/supabase/server';import { addPromptToSet } from '@/lib/actions/prompt';+import { addPromptTargetUrl } from '@/lib/actions/prompt-workflow';import { API_BASE_URL } from '@/config/api';// Types only — this file is `'use server'`, so the guards that go with them// live in a plain module (every runtime export here must be a server action).@@ -284,3 +285,83 @@ export async function trackSuggestions(suggestionIds: string[]): Promise<TrackSuif (added.length > 0) revalidatePath('/dashboard/prompts');return { trackedIds: added.map((a) => a.id), skippedIds, ...failure };}++export interface TrackPagePromptsResult {+ /** The prompts added, in the order given. */+ promptIds: string[];+ /** Why the rest weren't; `code` 'plan_limit' when the plan's prompt locations ran out. */+ error?: string;+ code?: 'plan_limit';+}++/** More than a page's suggestions: it gets five. */+const MAX_PAGE_PROMPTS = 10;++/**+ * Track prompts suggested for one page (AT-006 part B2), each pointing at+ * it. Added one by one through addPromptToSet, as Insights' "Track N" does,+ * so each passes the same plan check and the run stops at the first that+ * fails. A prompt goes under the brand's topic of that name, in the brand's+ * own spelling, or a new topic made for it, as an import does. Each added+ * prompt gets the page as its target URL, so its answers show whether AI+ * cites the page; a target that can't be saved leaves the prompt tracked.+ * Their first answers come with the next tracking run.+ */+export async function trackPagePrompts(+ brandId: string,+ pageUrl: string | null,+ prompts: { text: string; topic: string }[],+): Promise<TrackPagePromptsResult> {+ const wanted = (Array.isArray(prompts) ? prompts : [])+ .filter((p) => typeof p?.text === 'string' && p.text.trim())+ .slice(0, MAX_PAGE_PROMPTS);+ if (wanted.length === 0) return { promptIds: [], error: 'Pick at least one prompt.' };++ const supabase = await createClient();+ const target = await promptTarget(supabase, brandId);+ if ('error' in target) return { promptIds: [], error: target.error };++ const keyOf = (t: string) => t.trim().toLowerCase().replace(/\s+/g, ' ');+ const { data: topicRows } = await supabase.from('topics').select('name').eq('brand_id', brandId);+ const topics = new Map((topicRows ?? []).map((t) => [keyOf(t.name as string), t.name as string]));++ const promptIds: string[] = [];+ let failure: { error: string; code?: 'plan_limit' } | undefined;+ for (const p of wanted) {+ const named = typeof p.topic === 'string' ? p.topic.trim().slice(0, 60) : '';+ let topic = named ? topics.get(keyOf(named)) : undefined;+ let madeTopicId: string | null = null;+ if (named && !topic) {+ const { data: made } = await supabase+ .from('topics')+ .insert({ brand_id: brandId, name: named, is_active: true })+ .select('id, name')+ .single();+ if (made) {+ topic = made.name as string;+ madeTopicId = made.id as string;+ topics.set(keyOf(topic), topic);+ }+ }++ const result = await addPromptToSet({+ ...target,+ text: p.text.trim(),+ category: topic ?? (named || undefined),+ });+ if ('error' in result) {+ // A topic made for a prompt that wasn't added would sit empty.+ if (madeTopicId) await supabase.from('topics').delete().eq('id', madeTopicId);+ failure = { error: result.error, code: result.code };+ break;+ }+ promptIds.push(result.prompt.id);+ if (pageUrl) {+ const targeted = await addPromptTargetUrl(result.prompt.id, pageUrl);+ if ('error' in targeted) console.error('Page target URL not saved:', targeted.error);+ }+ }++ if (promptIds.length > 0) revalidatePath('/dashboard/prompts');+ return { promptIds, ...failure };+}diff --git a/web/src/lib/actions/traffic-pages.test.ts b/web/src/lib/actions/traffic-pages.test.tsindex 40dc7afce..c9e87f815 100644--- a/web/src/lib/actions/traffic-pages.test.ts+++ b/web/src/lib/actions/traffic-pages.test.ts@@ -16,7 +16,7 @@ vi.mock('@/lib/supabase/server', () => ({}));vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));-import { getTrafficPages, sendTrafficPagesToActionCenter } from './traffic';+import { getTrafficPages, sendTrafficPagesToActionCenter, suggestPagePrompts } from './traffic';beforeEach(() => {vi.useFakeTimers();@@ -193,3 +193,42 @@ describe('sendTrafficPagesToActionCenter (part B)', () => {).toEqual({ error: 'Not authenticated' });});});++describe('suggestPagePrompts (part B2)', () => {+ it("asks the server for the page's prompts over the page range", async () => {+ const answer = {+ page: { path: '/gifts', title: 'Coffee gifts' },+ queries: 1,+ suggestions: [],+ };+ const fetchMock = vi.fn(async () => new Response(JSON.stringify(answer), { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);++ expect(+ await suggestPagePrompts('b1', { dateFrom: '2026-10-11T12:30:00.000Z' }, '/gifts'),+ ).toEqual(answer);+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('http://api.test/api/prompts/suggestions/b1/page');+ expect(JSON.parse(init.body as string)).toEqual({+ page: '/gifts',+ from: '2026-10-11T12:30:00.000Z',+ to: '2026-10-18T12:30:00.000Z',+ });+ });++ it("returns the server's reason, a plan limit's message first", async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(+ async () =>+ new Response(+ JSON.stringify({ error: 'plan_limit', message: 'Your plan has no suggestions.' }),+ { status: 403 },+ ),+ ),+ );+ expect(await suggestPagePrompts('b1', undefined, '/gifts')).toEqual({+ error: 'Your plan has no suggestions.',+ });+ });+});diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.tsindex bae8f43d5..2e3aff46e 100644--- a/web/src/lib/actions/traffic.ts+++ b/web/src/lib/actions/traffic.ts@@ -638,6 +638,61 @@ export async function sendTrafficPagesToActionCenter(return res.json();}+/** A prompt suggested for one page (AT-006 part B2). */+export interface PagePromptSuggestion {+ text: string;+ topic: string;+ reason: string;+ /** The Search Console query it came from, when it did. */+ sourceQuery: string | null;+ impressions: number | null;+}++export interface PagePromptSuggestions {+ page: { path: string; title: string | null };+ /** Search Console queries that shared the page's words. */+ queries: number;+ suggestions: PagePromptSuggestion[];+}++/**+ * "Add prompts" on the Pages section (AT-006 part B2): prompts whose best+ * answer is this page, written from what the page says, its figures over the+ * page's range and the brand's Search Console queries that share its words.+ * Nothing is stored until the person tracks some.+ */+export async function suggestPagePrompts(+ brandId: string,+ window: TrafficDateWindow | undefined,+ page: string,+): Promise<PagePromptSuggestions | { 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/prompts/suggestions/${encodeURIComponent(brandId)}/page`,+ {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ page, 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.message || body.error || `Server error: ${res.status}` };+ }+ return res.json();+}+/** Analytics' engagement figures for one group of sessions (AT-005). */export interface TrafficEngagement {sessions: number;