Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(traffic): suggest content for a page from the prompts about it (#1173)

Cihan595f58103190
diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.js
index 1696b5ba1..456324c88 100644
--- a/server/src/lib/opportunity-generator.js
+++ b/server/src/lib/opportunity-generator.js
@@ -30,6 +30,12 @@ import { loadClusterOpportunities, loadOpportunityBaskets } from './open-opportu
import { basket, duplicateThreshold, findDuplicate, storedBasket } from './opportunity-dedup.js';
import { loadClusters } from './prompt-clusters.js';
import { cleanOpportunityText } from './opportunity-text.js';
+import {
+ focusClusters,
+ loadPageFocus,
+ pageFocusInstruction,
+ pickPageCluster,
+} from './opportunity-page-focus.js';
import { reopenStrengthened } from './opportunity-reopen.js';
import {
claimOpportunitySlots,
@@ -263,6 +269,7 @@ export const IDEA_MAX_LENGTH = 500;
* source?: 'system' | 'manual' | 'prompt',
* alternativeOf?: { id: string, title: string, description?: string|null, decision?: string|null, clusterId: string } | null,
* explicit?: boolean,
+ * pagePath?: string | null,
* }} [opts] - `count`, the focus (`topicId` / `promptId`) and `idea` come from
* an on-demand request (CONTENT-003); the nightly run passes none of them.
* `alternativeOf` asks for one more opportunity on that opportunity's
@@ -273,7 +280,11 @@ export const IDEA_MAX_LENGTH = 500;
* "Suggest content"): it is written even if the cluster was covered by a
* dismissed or finished opportunity, never when an open one covers it, and
* never merged away.
- * @returns {Promise<{ generated: number, merged: number, reopened?: number, duplicates?: number, limited?: boolean, opportunityIds?: string[], existingId?: string }>}
+ * `pagePath` asks for one page's content (AT-006 part B3): it is written
+ * from the clusters about that page (opportunity-page-focus.js), like an
+ * explicit request, with the page first among the candidate pages; with no
+ * such cluster nothing is written and `noMatch` says so.
+ * @returns {Promise<{ generated: number, merged: number, reopened?: number, duplicates?: number, limited?: boolean, noMatch?: boolean, opportunityIds?: string[], existingId?: string }>}
*/
export async function generateContentOpportunities(
brandId,
@@ -287,11 +298,13 @@ export async function generateContentOpportunities(
source = 'system',
alternativeOf = null,
explicit = false,
+ pagePath = null,
} = {},
) {
- // The user asked for this cluster by name: the duplicate check, merging
- // into another opportunity and reopening finished ones don't apply.
- const targeted = !!alternativeOf || explicit;
+ // The user asked for this cluster, or this page, by name: the duplicate
+ // check, merging into another opportunity and reopening finished ones
+ // don't apply.
+ const targeted = !!alternativeOf || explicit || !!pagePath;
onProgress?.({ phase: 'collecting_data', message: 'Fetching clusters and metrics...' });
const { data: brand } = await supabaseAdmin
@@ -357,6 +370,14 @@ export async function generateContentOpportunities(
]),
);
+ // One page's content (AT-006 part B3) comes from the clusters about it;
+ // without one there is nothing to write from, and no slot is claimed.
+ const focus = pagePath ? await loadPageFocus(brandId, pagePath, memberIds) : null;
+ const focusIds = focus
+ ? focusClusters([...clusterById.values()], focus.page, focus.targetedPromptIds)
+ : null;
+ if (focusIds && !focusIds.length) return { generated: 0, merged: 0, noMatch: true };
+
const measure = (clusterIds) => {
const metrics = clusterMetrics(
clusterIds.flatMap((id) => clusterById.get(id)?.prompt_ids || []),
@@ -382,15 +403,26 @@ export async function generateContentOpportunities(
const candidates = clusters.map((c) => ({ id: c.id, topicId: c.topic_id, ...measure([c.id]) }));
// A prompt's own request may revisit a cluster whose opportunity was
// dismissed or finished, never one with an open opportunity.
- const covered = explicit ? openlyCoveredClusterIds(existing) : coveredClusterIds(existing);
+ const covered =
+ explicit || focusIds ? openlyCoveredClusterIds(existing) : coveredClusterIds(existing);
// The fan-out baskets of every cluster still open for an opportunity: the
// duplicate check compares them, and the prompt shows the picked ones'.
// A focused request only considers its topic's clusters or its prompt's.
const inFocus = (c) =>
(!topicId || c.topicId === topicId) &&
- (!promptId || clusterById.get(c.id).prompt_ids.includes(promptId));
+ (!promptId || clusterById.get(c.id).prompt_ids.includes(promptId)) &&
+ (!focusIds || focusIds.includes(c.id));
const open = openCandidates(candidates, { covered, inFocus, alternativeOf });
+ // A page's request goes to its best-matching cluster that has an open
+ // opportunity, which it points at, or answers, which it writes from.
+ if (focusIds) {
+ const pick = pickPageCluster(focusIds, { openIds: new Set(open.map((c) => c.id)), covered });
+ if (pick && 'existing' in pick) {
+ return { generated: 0, merged: 0, existingId: openOpportunityOn(existing, pick.existing) };
+ }
+ open.splice(0, open.length, ...open.filter((c) => c.id === pick?.write));
+ }
const { data: basketRows, error: basketErr } = await selectInChunks(
open.map((c) => c.id),
(chunk) =>
@@ -465,7 +497,12 @@ export async function generateContentOpportunities(
const c = clusterById.get(cand.id);
const basket = basketSummary([c.id], basketRows || []);
const need = [c.label, c.primary_intent, ...c.promptTexts, ...basket.top.map((q) => q.query)];
- return [cand.id, candidatePages(need.join(' '), pagesRes.data || [])];
+ const pages = candidatePages(need.join(' '), pagesRes.data || []);
+ // The page asked about leads, so the model can work on it ([P0]).
+ return [
+ cand.id,
+ focus ? [focus.page, ...pages.filter((p) => p.url !== focus.page.url)] : pages,
+ ];
}),
);
const pageLine = (p, i) =>
@@ -500,6 +537,8 @@ Existing opportunities in other topics:
${shown.map((o, i) => `[E${i}] ${o.title} (topic: ${topicName(clusterById.get(o.cluster_id)) || 'none'})`).join('\n') || 'none'}
${alternativeOf ? `${alternativeInstruction(alternativeOf)}\n\n` : ''}${
+ focus ? `${pageFocusInstruction(focus.page)}\n\n` : ''
+ }${
idea
? `The user asked for ideas around: "${idea.slice(0, IDEA_MAX_LENGTH)}". Shape the opportunities toward it wherever the clusters' prompts allow; never invent a need the data doesn't show.\n\n`
: ''
@@ -617,6 +656,8 @@ ${alternativeOf ? `${alternativeInstruction(alternativeOf)}\n\n` : ''}${
...(alternativeOf
? { alternativeOf: { id: alternativeOf.id, title: alternativeOf.title } }
: {}),
+ // Asked for from AI Traffic's Pages section, for this page.
+ ...(focus ? { forPage: { path: pagePath, url: focus.page.url } } : {}),
},
});
}
diff --git a/server/src/lib/opportunity-page-focus.js b/server/src/lib/opportunity-page-focus.js
new file mode 100644
index 000000000..95ab9e41b
--- /dev/null
+++ b/server/src/lib/opportunity-page-focus.js
@@ -0,0 +1,165 @@
+/**
+ * "Suggest content" for one page of the AI Traffic page's Pages section
+ * (AT-006 part B3, spec §3.5: "Suggest content (Content, counts against the
+ * quota, CONTENT-001)").
+ *
+ * The generator writes an opportunity per prompt cluster, from the answers to
+ * its prompts, so a page's content suggestion has to come from the clusters
+ * that are about the page: the ones holding prompts that target it
+ * (prompt_target_urls), or, without any, the ones whose need shares the most
+ * words with what the page says. With neither there is nothing to write from
+ * yet, and the caller is told so rather than handed content about something
+ * else. The page itself goes first among the cluster's candidate pages, so the
+ * model can decide to optimize, expand or refresh it.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { selectInChunks } from './chunked-in.js';
+import { tokens } from './page-matching.js';
+
+/** Clusters a page's content may come from when no prompt targets the page. */
+export const MAX_MATCHED_CLUSTERS = 5;
+
+/** A page path as 00178 keys it: lowercased, without a trailing slash. */
+export function pagePathKey(path) {
+ const trimmed = String(path ?? '')
+ .trim()
+ .replace(/\/+$/, '');
+ return (trimmed || '/').toLowerCase();
+}
+
+/** The path a stored URL names, keyed like a page path; null for something that isn't a URL. */
+function urlPathKey(url) {
+ try {
+ return pagePathKey(new URL(url).pathname);
+ } catch {
+ return null;
+ }
+}
+
+const slugText = (url) => {
+ try {
+ return new URL(url).pathname.replace(/[-_/]+/g, ' ');
+ } catch {
+ return '';
+ }
+};
+
+/**
+ * The clusters a page's content suggestion comes from, best first: those
+ * holding prompts that target the page, most of them first; else those whose
+ * need shares at least two words with the page, twice as much for words in
+ * its title, first heading or URL, up to MAX_MATCHED_CLUSTERS.
+ *
+ * @param {Array<{ id: string, label?: string, primary_intent?: string,
+ * prompt_ids: string[], promptTexts?: string[] }>} clusters
+ * @param {{ url: string, title?: string|null, h1?: string|null, description?: string|null }} page
+ * @param {string[]} targetedPromptIds
+ * @returns {string[]}
+ */
+export function focusClusters(clusters, page, targetedPromptIds) {
+ const targeted = new Set(targetedPromptIds);
+ const byTargets = clusters
+ .map((c) => ({ id: c.id, hits: c.prompt_ids.filter((id) => targeted.has(id)).length }))
+ .filter((c) => c.hits > 0)
+ .sort((a, b) => b.hits - a.hits);
+ if (byTargets.length) return byTargets.map((c) => c.id);
+
+ const strong = new Set(tokens(`${page.title || ''} ${page.h1 || ''} ${slugText(page.url)}`));
+ const weak = new Set(tokens(page.description));
+ return clusters
+ .map((c) => {
+ let score = 0;
+ let shared = 0;
+ const need = new Set(
+ tokens([c.label, c.primary_intent, ...(c.promptTexts || [])].filter(Boolean).join(' ')),
+ );
+ for (const t of need) {
+ const weight = strong.has(t) ? 2 : weak.has(t) ? 1 : 0;
+ if (!weight) continue;
+ shared += 1;
+ score += weight;
+ }
+ return { id: c.id, score, shared };
+ })
+ .filter((c) => c.shared >= 2)
+ .sort((a, b) => b.score - a.score)
+ .slice(0, MAX_MATCHED_CLUSTERS)
+ .map((c) => c.id);
+}
+
+/**
+ * Which of a page's clusters decides its suggestion: the best-matching one
+ * that has either an open opportunity or answers to write from. An open
+ * opportunity is pointed at rather than written again, so asking twice
+ * spends nothing; clusters with neither are passed over.
+ *
+ * @param {string[]} focusIds - the page's clusters, best first
+ * @param {{ openIds: Set<string>, covered: Set<string> }} state - clusters
+ * that can be written (answers, no open opportunity) and clusters an open
+ * opportunity covers
+ * @returns {{ existing: string } | { write: string } | null}
+ */
+export function pickPageCluster(focusIds, { openIds, covered }) {
+ for (const id of focusIds) {
+ if (covered.has(id)) return { existing: id };
+ if (openIds.has(id)) return { write: id };
+ }
+ return null;
+}
+
+/** What the model is told when the user asked for content for one page. */
+export function pageFocusInstruction(page) {
+ const name = page.title || page.h1 ? ` ("${page.title || page.h1}")` : '';
+ return `The user asked for content for one page of the brand's site: ${page.url}${name}. It is listed first under the cluster as [P0], and AI assistants send it no visitors. Shape the opportunity around that page: optimize, expand or refresh it for this need wherever it fits, and create a new page only if it plainly cannot answer the need.`;
+}
+
+/**
+ * The page as the brand's sitemap crawl knows it, else its URL on the
+ * primary domain, and the brand's prompts (among `memberIds`) that target it.
+ *
+ * @param {string} brandId
+ * @param {string} pagePath
+ * @param {string[]} memberIds - the brand's clustered prompts
+ */
+export async function loadPageFocus(brandId, pagePath, memberIds) {
+ const key = pagePathKey(pagePath);
+ const [pagesRes, domainsRes, targets] = await Promise.all([
+ supabaseAdmin
+ .from('site_pages')
+ .select('url, title, h1, description, lastmod, ai_citations, ga_sessions')
+ .eq('brand_id', brandId),
+ supabaseAdmin
+ .from('brand_domains')
+ .select('domain')
+ .eq('brand_id', brandId)
+ .order('is_primary', { ascending: false })
+ .limit(1),
+ selectInChunks(memberIds, (chunk) =>
+ supabaseAdmin.from('prompt_target_urls').select('prompt_id, url').in('prompt_id', chunk),
+ ),
+ ]);
+ if (pagesRes.error) throw new Error(pagesRes.error.message);
+ if (targets.error) throw new Error(targets.error.message);
+
+ const known = (pagesRes.data || []).find((p) => urlPathKey(p.url) === key);
+ const host = String(domainsRes.data?.[0]?.domain ?? '')
+ .trim()
+ .replace(/^https?:\/\//i, '')
+ .replace(/\/+$/, '');
+ const page = known ?? {
+ url: host ? `https://${host}${pagePath}` : pagePath,
+ title: null,
+ h1: null,
+ description: null,
+ lastmod: null,
+ ai_citations: 0,
+ ga_sessions: 0,
+ };
+ const targetedPromptIds = [
+ ...new Set(
+ (targets.data || []).filter((t) => urlPathKey(t.url) === key).map((t) => t.prompt_id),
+ ),
+ ];
+ return { page, targetedPromptIds };
+}
diff --git a/server/src/lib/opportunity-page-focus.test.js b/server/src/lib/opportunity-page-focus.test.js
new file mode 100644
index 000000000..6a3ebf356
--- /dev/null
+++ b/server/src/lib/opportunity-page-focus.test.js
@@ -0,0 +1,158 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * One page's content suggestion (AT-006 part B3): the clusters it is written
+ * from — those holding prompts that target the page, else those sharing its
+ * words — and the page as the generator knows it.
+ */
+
+let db;
+
+function table(name) {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ in: () => 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) } }));
+
+const { focusClusters, loadPageFocus, pageFocusInstruction, pagePathKey, pickPageCluster } =
+ await import('./opportunity-page-focus.js');
+
+const cluster = (id, over = {}) => ({
+ id,
+ label: '',
+ primary_intent: '',
+ prompt_ids: [],
+ promptTexts: [],
+ ...over,
+});
+
+const gifts = {
+ url: 'https://acme-coffee.example.com/gifts',
+ title: 'Coffee gifts and gift boxes',
+ h1: 'Coffee gifts for every coffee lover',
+ description: 'Specialty coffee gift boxes and sampler sets for every budget.',
+};
+
+describe('focusClusters', () => {
+ const clusters = [
+ cluster('espresso', {
+ label: 'Home espresso machines',
+ prompt_ids: ['p1'],
+ promptTexts: ['Best espresso machines under $500?'],
+ }),
+ cluster('gift-sets', {
+ label: 'Coffee gift sets',
+ primary_intent: 'Find a coffee gift box',
+ prompt_ids: ['p2', 'p3'],
+ promptTexts: ['What coffee gift box should I buy?'],
+ }),
+ cluster('sampler', {
+ label: 'Coffee samplers',
+ prompt_ids: ['p4'],
+ promptTexts: ['Which coffee sampler set is best for beginners?'],
+ }),
+ ];
+
+ it('takes the clusters of prompts that target the page, most of them first', () => {
+ expect(focusClusters(clusters, gifts, ['p4', 'p2', 'p3', 'p9'])).toEqual([
+ 'gift-sets',
+ 'sampler',
+ ]);
+ });
+
+ it('falls back to the clusters sharing the most words with the page', () => {
+ expect(focusClusters(clusters, gifts, [])).toEqual(['gift-sets', 'sampler']);
+ });
+
+ it('finds none when nothing tracked is about the page', () => {
+ const about = { url: 'https://acme-coffee.example.com/careers', title: 'Careers at Acme' };
+ expect(focusClusters(clusters, about, [])).toEqual([]);
+ });
+
+ it('keeps at most five word-matched clusters', () => {
+ const many = Array.from({ length: 7 }, (_, i) =>
+ cluster(`c${i}`, { label: 'Coffee gift boxes', promptTexts: ['coffee gift sets'] }),
+ );
+ expect(focusClusters(many, gifts, [])).toHaveLength(5);
+ });
+});
+
+describe('pickPageCluster', () => {
+ const state = (openIds, covered) => ({ openIds: new Set(openIds), covered: new Set(covered) });
+
+ it("points at the best match's open opportunity rather than writing another", () => {
+ // c1 is covered; c2 could be written, but c1 matches the page better.
+ expect(pickPageCluster(['c1', 'c2'], state(['c2'], ['c1']))).toEqual({ existing: 'c1' });
+ });
+
+ it('writes for the best match with answers, passing over clusters with neither', () => {
+ expect(pickPageCluster(['c0', 'c2', 'c3'], state(['c2', 'c3'], []))).toEqual({ write: 'c2' });
+ });
+
+ it('finds nothing when no cluster has answers or an opportunity', () => {
+ expect(pickPageCluster(['c0'], state([], []))).toBeNull();
+ });
+});
+
+describe('pageFocusInstruction', () => {
+ it('names the page and asks to work on it before creating another', () => {
+ const text = pageFocusInstruction(gifts);
+ expect(text).toContain('https://acme-coffee.example.com/gifts ("Coffee gifts and gift boxes")');
+ expect(text).toContain('[P0]');
+ expect(text).toMatch(/optimize, expand or refresh it/);
+ expect(pageFocusInstruction({ url: 'https://acme.example/about' })).toContain(
+ 'https://acme.example/about. It is listed first',
+ );
+ });
+});
+
+describe('loadPageFocus', () => {
+ beforeEach(() => {
+ db = {
+ site_pages: [
+ { url: 'https://acme-coffee.example.com/gifts/', title: 'Coffee gifts', ai_citations: 6 },
+ { url: 'https://acme-coffee.example.com/menu', title: 'Menu' },
+ ],
+ brand_domains: [{ domain: 'https://www.acme-coffee.example.com/' }],
+ prompt_target_urls: [
+ { prompt_id: 'p2', url: 'https://acme-coffee.example.com/Gifts' },
+ { prompt_id: 'p2', url: 'https://www.acme-coffee.example.com/gifts/' },
+ { prompt_id: 'p5', url: 'https://acme-coffee.example.com/menu' },
+ ],
+ };
+ });
+
+ it("reads the page's sitemap entry and the prompts targeting it, in any spelling", async () => {
+ const focus = await loadPageFocus('b1', '/gifts', ['p2', 'p5']);
+ expect(focus.page).toMatchObject({ title: 'Coffee gifts', ai_citations: 6 });
+ expect(focus.targetedPromptIds).toEqual(['p2']);
+ });
+
+ it('builds the URL on the primary domain for a page the sitemap lacks', async () => {
+ const focus = await loadPageFocus('b1', '/about', []);
+ expect(focus.page).toEqual({
+ url: 'https://www.acme-coffee.example.com/about',
+ title: null,
+ h1: null,
+ description: null,
+ lastmod: null,
+ ai_citations: 0,
+ ga_sessions: 0,
+ });
+ expect(focus.targetedPromptIds).toEqual([]);
+ });
+
+ it('keys paths without case or a trailing slash', () => {
+ expect(pagePathKey('/Gifts/')).toBe('/gifts');
+ expect(pagePathKey('')).toBe('/');
+ });
+});
diff --git a/server/src/routes/content-suggest.test.js b/server/src/routes/content-suggest.test.js
index 36a4f44e6..1ab1377ad 100644
--- a/server/src/routes/content-suggest.test.js
+++ b/server/src/routes/content-suggest.test.js
@@ -20,6 +20,7 @@ class PlanLimitError extends Error {
}
const assertPromptAccess = vi.fn();
+const assertBrandAccess = vi.fn();
const getOpportunityRequestAllowance = vi.fn();
const createJob = vi.fn();
const runContentJob = vi.fn();
@@ -42,7 +43,7 @@ async function startApp() {
getOrgIdForUser: vi.fn(),
}));
vi.doMock('../lib/access.js', () => ({
- assertBrandAccess: vi.fn(),
+ assertBrandAccess,
assertOpportunitiesAccess: vi.fn(),
assertOpportunityAccess: vi.fn(),
assertPromptAccess,
@@ -104,6 +105,7 @@ beforeEach(async () => {
assertPromptAccess.mockResolvedValue([
{ id: 'p1', prompt_sets: { brand_id: 'b1', brands: { organization_id: 'org1' } } },
]);
+ assertBrandAccess.mockResolvedValue({ orgId: 'org1' });
runningSuggestionJob.mockResolvedValue(null);
openOpportunityForPrompt.mockResolvedValue(null);
getOpportunityRequestAllowance.mockResolvedValue(allowance(3));
@@ -202,3 +204,34 @@ describe('GET /prompts/:promptId/suggestion', () => {
expect(openOpportunityForPrompt).toHaveBeenCalledWith('b1', 'p1');
});
});
+
+describe('POST /opportunities/generate for one page (AT-006 part B3)', () => {
+ const BRAND = '33333333-3333-3333-3333-333333333333';
+ const generate = (body) =>
+ fetch(`${baseUrl}/opportunities/generate`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ brandId: BRAND, idempotencyKey: 'key-page-1', ...body }),
+ });
+
+ it("starts one opportunity for the page, whatever count it's sent with", async () => {
+ const res = await generate({ count: 3, pagePath: '/gifts' });
+ expect(res.status).toBe(202);
+ expect(await res.json()).toEqual({ jobId: 'job-new', count: 1 });
+ expect(createJob).toHaveBeenCalledWith(
+ expect.objectContaining({
+ brandId: BRAND,
+ data: expect.objectContaining({
+ request: expect.objectContaining({ count: 1, pagePath: '/gifts' }),
+ }),
+ }),
+ );
+ });
+
+ it('takes a path, not a URL, and spends nothing when the month is used up', async () => {
+ expect((await generate({ count: 1, pagePath: 'https://acme.example/gifts' })).status).toBe(400);
+ getOpportunityRequestAllowance.mockResolvedValue(allowance(0));
+ expect((await generate({ count: 1, pagePath: '/gifts' })).status).toBe(429);
+ expect(createJob).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index 856a94b2c..722834ef9 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -164,6 +164,8 @@ const onDemandSchema = z.object({
topicId: z.guid().nullish(),
promptId: z.guid().nullish(),
idea: z.string().trim().max(IDEA_MAX_LENGTH).nullish(),
+ // One page of the AI Traffic page's Pages section (AT-006 part B3), as a path.
+ pagePath: z.string().min(1).max(2048).startsWith('/').nullish(),
idempotencyKey: z.string().min(8).max(100),
});
@@ -173,8 +175,10 @@ const IDEMPOTENCY_WINDOW_MS = 10 * 60 * 1000;
/**
* POST /api/content/opportunities/generate
* "+ New" (CONTENT-003): generate opportunities now instead of waiting for
- * the nightly run, optionally around a topic, a prompt or a free-text idea.
- * Body: { brandId, count, topicId?, promptId?, idea?, idempotencyKey }.
+ * the nightly run, optionally around a topic, a prompt or a free-text idea,
+ * or for one page ("Suggest content" on AI Traffic's Pages, AT-006 part B3:
+ * one opportunity, from the clusters about the page).
+ * Body: { brandId, count, topicId?, promptId?, idea?, pagePath?, idempotencyKey }.
*
* The count is capped by the plan (Starter 3, Growth 5 per request) and by
* what is left of the month; the generation claims its quota slots
@@ -188,7 +192,7 @@ router.post('/opportunities/generate', requireFeature('content_optimization'), a
if (!parsed.success) {
return res.status(400).json({ error: 'Invalid request', details: parsed.error.issues });
}
- const { brandId, count, topicId, promptId, idea, idempotencyKey } = parsed.data;
+ const { brandId, count, topicId, promptId, idea, pagePath, idempotencyKey } = parsed.data;
try {
const { orgId } = await assertBrandAccess(brandId, req.user.id);
@@ -202,10 +206,12 @@ router.post('/opportunities/generate', requireFeature('content_optimization'), a
if (allowance.max <= 0) return quotaExhausted(res, allowance);
const request = {
- count: Math.min(count, allowance.max),
+ // A page gets one opportunity.
+ count: pagePath ? 1 : Math.min(count, allowance.max),
topicId: topicId ?? null,
promptId: promptId ?? null,
idea: idea || null,
+ pagePath: pagePath ?? null,
idempotencyKey,
};
const job = await createJob({
diff --git a/server/src/workers/content-worker.js b/server/src/workers/content-worker.js
index 5faf9fff7..be1d02603 100644
--- a/server/src/workers/content-worker.js
+++ b/server/src/workers/content-worker.js
@@ -41,6 +41,7 @@ export async function processContentJob({ brandId, model, job, request = null })
idea: request.idea ?? null,
alternativeOf: request.alternativeOf ?? null,
explicit: !!request.explicit,
+ pagePath: request.pagePath ?? null,
// "+ New" and "Another angle" are manual; "Suggest content" from
// the prompts table is tagged prompt.
source: request.source === 'prompt' ? 'prompt' : 'manual',
diff --git a/server/src/workers/content-worker.test.js b/server/src/workers/content-worker.test.js
index 4a44c6c2c..e318acd3c 100644
--- a/server/src/workers/content-worker.test.js
+++ b/server/src/workers/content-worker.test.js
@@ -42,9 +42,16 @@ describe('processContentJob', () => {
expect(refreshPromptClusters).toHaveBeenCalledWith('b1');
});
+ it("asks for one page's content from AI Traffic, as manual (AT-006 part B3)", async () => {
+ await processContentJob({ brandId: 'b1', job, request: { count: 1, pagePath: '/gifts' } });
+ expect(optsOf()).toMatchObject({ count: 1, pagePath: '/gifts', source: 'manual' });
+ // A page's prompts tracked a moment ago are only grouped by the refresh.
+ expect(refreshPromptClusters).toHaveBeenCalledWith('b1');
+ });
+
it('marks "+ New" as manual, with no special request', async () => {
await processContentJob({ brandId: 'b1', job, request: { count: 3, promptId: null } });
- expect(optsOf()).toMatchObject({ count: 3, explicit: false, source: 'manual' });
+ expect(optsOf()).toMatchObject({ count: 3, explicit: false, pagePath: null, source: 'manual' });
});
it('never lets a request pick its own tag', async () => {
diff --git a/web/messages/en.json b/web/messages/en.json
index 72014a426..4576e95b5 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3415,7 +3415,22 @@
"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"
+ "overQuota": "{count, plural, one {# audit} other {# audits}}, {remaining} left this month",
+ "suggestContent": "Suggest content",
+ "suggesting": "Writing a content suggestion for {page}…",
+ "suggested": "Content suggestion created",
+ "suggestedDescription": "For {page}, from the tracked prompts about it. It used one of this month's content suggestions.",
+ "suggestionExists": "This page already has a content suggestion",
+ "openExisting": "Open existing",
+ "suggestNoPrompts": "No tracked prompts are about {page} yet",
+ "suggestNoPromptsDescription": "Content suggestions are written from tracked prompts' answers. Add prompts for this page first; nothing was used from this month's content suggestions.",
+ "addPrompts": "Add prompts",
+ "suggestLimited": "Monthly content limit reached.",
+ "suggestNothing": "Couldn't write a suggestion for this page yet",
+ "suggestNothingDescription": "Its prompts need tracked answers first; they come with the next tracking run.",
+ "suggestFailed": "Couldn't write a content suggestion",
+ "suggestTimeout": "Still writing the content suggestion",
+ "suggestTimeoutDescription": "It will appear in Content when it is done."
},
"prompts": {
"title": "Suggested 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.tsx
index a64836146..ab563e7b1 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,14 @@ vi.mock('@/i18n/navigation', () => ({
useRouter: () => ({ push }),
}));
vi.mock('sonner', () => ({ toast }));
+const suggestForPage = vi.fn();
+vi.mock('@/lib/actions/content', () => ({
+ generateOpportunitiesOnDemand: vi.fn(),
+ getGenerationJobStatus: vi.fn(),
+}));
+vi.mock('@/lib/content-job', () => ({
+ suggestForPage: (...args: unknown[]) => suggestForPage(...args),
+}));
// 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', () => ({
@@ -97,6 +105,7 @@ beforeEach(() => {
getAuditQuota.mockReset().mockResolvedValue({ used: 3, limit: -1, remaining: -1 });
push.mockReset();
for (const fn of Object.values(toast)) fn.mockClear();
+ suggestForPage.mockReset();
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
@@ -457,4 +466,64 @@ describe('PagesCard actions (AT-006 part B)', () => {
await act(async () => button('tracked').click());
expect(getTrafficPages).toHaveBeenCalledTimes(2);
});
+
+ const suggestFromMenu = async (pagePath: string) => {
+ const trigger = container.querySelector<HTMLElement>(
+ `[aria-label="More actions for ${pagePath}"]`,
+ )!;
+ await act(async () => trigger.click());
+ const item = [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (el) => el.textContent === 'Suggest content',
+ )!;
+ await act(async () => item.click());
+ };
+
+ it("suggests content for a row's page and opens it (part B3)", async () => {
+ getTrafficPages.mockResolvedValue(pages([page({ citations: 6 })]));
+ suggestForPage.mockResolvedValue({ kind: 'created', opportunityId: 'o1' });
+ await render();
+ await suggestFromMenu('/gifts');
+
+ expect(suggestForPage).toHaveBeenCalledWith(BRAND, '/gifts', expect.anything());
+ expect(toast.loading).toHaveBeenCalledWith('Writing a content suggestion for /gifts…');
+ expect(toast.success).toHaveBeenCalledWith(
+ 'Content suggestion created',
+ expect.objectContaining({ id: 'toast-1' }),
+ );
+ const { action } = toast.success.mock.calls[0][1] as { action: { onClick: () => void } };
+ action.onClick();
+ expect(push).toHaveBeenCalledWith('/dashboard/content?opportunity=o1');
+ });
+
+ it('offers to add prompts when no tracked prompt is about the page', async () => {
+ getTrafficPages.mockResolvedValue(pages([page({ citations: 6 })]));
+ suggestForPage.mockResolvedValue({ kind: 'noMatch' });
+ await render();
+ await suggestFromMenu('/gifts');
+
+ expect(toast.info).toHaveBeenCalledWith(
+ 'No tracked prompts are about /gifts yet',
+ expect.objectContaining({
+ description: expect.stringContaining('Add prompts for this page'),
+ }),
+ );
+ const { action } = toast.info.mock.calls[0][1] as { action: { onClick: () => void } };
+ await act(async () => action.onClick());
+ expect(dialog()).toBe('prompts for /gifts');
+ });
+
+ it("says when the month's content suggestions are used up, or one exists", async () => {
+ getTrafficPages.mockResolvedValue(pages([page({ citations: 6 })]));
+ suggestForPage.mockResolvedValue({ kind: 'limited' });
+ await render();
+ await suggestFromMenu('/gifts');
+ expect(toast.error).toHaveBeenCalledWith('Monthly content limit reached.', { id: 'toast-1' });
+
+ suggestForPage.mockResolvedValue({ kind: 'existing', opportunityId: 'o9' });
+ await suggestFromMenu('/gifts');
+ expect(toast.info).toHaveBeenCalledWith(
+ 'This page already has a content suggestion',
+ expect.objectContaining({ action: expect.objectContaining({ label: 'Open existing' }) }),
+ );
+ });
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx
index bb46efd61..03fc78233 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx
@@ -3,7 +3,7 @@
import { useEffect, useState, type ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
-import { FileSearch, ListPlus, Loader2, MoreHorizontal, Send } from 'lucide-react';
+import { FileSearch, Lightbulb, 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';
@@ -208,8 +208,9 @@ export function PagesCard({
row.aiPlatforms.length ? row.aiPlatforms.map(getPlatformName).join(', ') : '—';
/**
- * 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.
+ * A row's next step, with its menu: send the page to the Action Center,
+ * suggest prompts for it when that isn't already its next step, and suggest
+ * content for it (part B3).
*/
const rowActions = (
row: TrafficPageRow,
@@ -241,6 +242,14 @@ export function PagesCard({
{t('addPrompts')}
</DropdownMenuItem>
)}
+ <DropdownMenuItem
+ className="gap-2"
+ disabled={pageActions.suggesting !== null}
+ onClick={() => void pageActions.suggestContent(row.page, openPrompts)}
+ >
+ <Lightbulb className="h-3.5 w-3.5" />
+ {t('actions.suggestContent')}
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
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.ts
index 8cc416543..7c71f0079 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts
@@ -5,6 +5,8 @@ import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
import { useRouter } from '@/i18n/navigation';
import { getAuditQuota, runAuditsBulk, type AuditQuota } from '@/lib/actions/audits';
+import { generateOpportunitiesOnDemand, getGenerationJobStatus } from '@/lib/actions/content';
+import { suggestForPage } from '@/lib/content-job';
import {
sendTrafficPagesToActionCenter,
type TrafficDateWindow,
@@ -14,17 +16,23 @@ import {
/** The most pages one action, or one bulk audit, takes. */
export const PAGE_ACTION_MAX = 50;
+/** The server calls behind a page's "Suggest content" (part B3). */
+const SUGGEST_CALLS = { start: generateOpportunitiesOnDemand, getStatus: getGenerationJobStatus };
+
/**
* 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.
+ * footer: send pages to the Action Center as one action, audit several
+ * pages at once within the month's audits, and suggest content for a page
+ * (part B3, one of the month's content suggestions). 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 page whose content suggestion is being written.
+ const [suggesting, setSuggesting] = useState<string | null>(null);
// The organization's audits this month, for the bulk audit's limit.
const [quota, setQuota] = useState<AuditQuota | null>(null);
@@ -106,7 +114,73 @@ export function usePageActions(brandId: string, dateWindow: TrafficDateWindow) {
[brandId, loadQuota, router, t],
);
- return { send, sending, auditMany, auditing, quota };
+ /**
+ * Writes a content suggestion for one page, from the tracked prompts about
+ * it. With none, it offers to add prompts for the page (`onAddPrompts`).
+ */
+ const suggestContent = useCallback(
+ async (page: string, onAddPrompts: (page: string) => void): Promise<void> => {
+ setSuggesting(page);
+ const toastId = toast.loading(t('suggesting', { page }));
+ const openOpportunity = (id: string, label: string) => ({
+ label,
+ onClick: () => router.push(`/dashboard/content?opportunity=${id}`),
+ });
+ try {
+ const outcome = await suggestForPage(brandId, page, SUGGEST_CALLS);
+ switch (outcome.kind) {
+ case 'created':
+ toast.success(t('suggested'), {
+ id: toastId,
+ description: t('suggestedDescription', { page }),
+ duration: 10_000,
+ action: openOpportunity(outcome.opportunityId, t('open')),
+ });
+ break;
+ case 'existing':
+ toast.info(t('suggestionExists'), {
+ id: toastId,
+ duration: 10_000,
+ action: openOpportunity(outcome.opportunityId, t('openExisting')),
+ });
+ break;
+ case 'noMatch':
+ toast.info(t('suggestNoPrompts', { page }), {
+ id: toastId,
+ description: t('suggestNoPromptsDescription'),
+ duration: 10_000,
+ action: { label: t('addPrompts'), onClick: () => onAddPrompts(page) },
+ });
+ break;
+ case 'limited':
+ toast.error(t('suggestLimited'), { id: toastId });
+ break;
+ case 'nothing':
+ toast.info(t('suggestNothing'), {
+ id: toastId,
+ description: t('suggestNothingDescription'),
+ });
+ break;
+ case 'timeout':
+ toast.info(t('suggestTimeout'), {
+ id: toastId,
+ description: t('suggestTimeoutDescription'),
+ });
+ break;
+ default:
+ toast.error(t('suggestFailed'), {
+ id: toastId,
+ description: outcome.message ?? undefined,
+ });
+ }
+ } finally {
+ setSuggesting(null);
+ }
+ },
+ [brandId, router, t],
+ );
+
+ return { send, sending, auditMany, auditing, quota, suggestContent, suggesting };
}
/**
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index 4f11c28ca..9d569326b 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -23,6 +23,8 @@ export interface OnDemandRequest {
topicId?: string | null;
promptId?: string | null;
idea?: string | null;
+ /** One page of AI Traffic's Pages section (AT-006 part B3), as a path: one opportunity. */
+ pagePath?: string | null;
/** One per submit, so a double click or a retried request starts one job. */
idempotencyKey: string;
}
@@ -71,6 +73,8 @@ export interface GenerationJobStatus {
opportunityIds?: string[];
/** A run for one prompt wrote nothing: the open opportunity that answers it. */
existingId?: string;
+ /** A run for one page found no tracked prompts about it (AT-006 part B3). */
+ noMatch?: boolean;
} | null;
failedReason: string | null;
}
diff --git a/web/src/lib/content-job.test.ts b/web/src/lib/content-job.test.ts
index 2b1d9b212..f7307b50e 100644
--- a/web/src/lib/content-job.test.ts
+++ b/web/src/lib/content-job.test.ts
@@ -5,8 +5,8 @@
*/
import { describe, expect, test } from 'vitest';
-import type { GenerationJobStatus } from '@/lib/actions/content';
-import { suggestForPrompt, waitForContentJob } from './content-job';
+import type { GenerationJobStatus, OnDemandRequest } from '@/lib/actions/content';
+import { suggestForPage, suggestForPrompt, waitForContentJob } from './content-job';
const status = (s: Partial<GenerationJobStatus>): GenerationJobStatus => ({
status: 'active',
@@ -138,3 +138,57 @@ describe('suggestForPrompt', () => {
).toEqual({ kind: 'failed', message: 'crypto.randomUUID is not a function' });
});
});
+
+describe('suggestForPage (AT-006 part B3)', () => {
+ const run = (
+ start: (
+ r: OnDemandRequest,
+ ) => Promise<
+ | { ok: true; jobId: string; count: number }
+ | { ok: false; error: string; quotaExhausted?: boolean }
+ >,
+ result: GenerationJobStatus['result'],
+ ) =>
+ suggestForPage('b1', '/gifts', {
+ start,
+ getStatus: async () => status({ status: 'completed', result }),
+ newKey: () => 'key-1',
+ ...fakeClock(),
+ });
+ const started = async () => ({ ok: true as const, jobId: 'j1', count: 1 });
+
+ test('asks for one opportunity for the page and opens what it made', async () => {
+ const requests: OnDemandRequest[] = [];
+ const outcome = await run(
+ async (r) => {
+ requests.push(r);
+ return started();
+ },
+ { generated: 1, opportunityIds: ['o1'] },
+ );
+ expect(requests).toEqual([
+ { brandId: 'b1', count: 1, pagePath: '/gifts', idempotencyKey: 'key-1' },
+ ]);
+ expect(outcome).toEqual({ kind: 'created', opportunityId: 'o1' });
+ });
+
+ test('points at the open suggestion, or says no tracked prompt is about the page', async () => {
+ expect(await run(started, { generated: 0, existingId: 'o9' })).toEqual({
+ kind: 'existing',
+ opportunityId: 'o9',
+ });
+ expect(await run(started, { generated: 0, noMatch: true })).toEqual({ kind: 'noMatch' });
+ expect(await run(started, { generated: 0 })).toEqual({ kind: 'nothing' });
+ });
+
+ test("says when the month's suggestions are used up, before or during the run", async () => {
+ expect(
+ await run(async () => ({ ok: false, error: 'used up', quotaExhausted: true }), null),
+ ).toEqual({ kind: 'limited' });
+ expect(await run(started, { generated: 0, limited: true })).toEqual({ kind: 'limited' });
+ expect(await run(async () => ({ ok: false, error: 'nope' }), null)).toEqual({
+ kind: 'failed',
+ message: 'nope',
+ });
+ });
+});
diff --git a/web/src/lib/content-job.ts b/web/src/lib/content-job.ts
index c121f916a..a7a11fc3d 100644
--- a/web/src/lib/content-job.ts
+++ b/web/src/lib/content-job.ts
@@ -5,7 +5,12 @@
* server.
*/
-import type { GenerationJobStatus, PromptSuggestionResult } from '@/lib/actions/content';
+import type {
+ GenerationJobStatus,
+ OnDemandRequest,
+ OnDemandResult,
+ PromptSuggestionResult,
+} from '@/lib/actions/content';
export type ContentJobOutcome =
| { kind: 'completed'; result: NonNullable<GenerationJobStatus['result']> }
@@ -99,3 +104,55 @@ export async function suggestForPrompt(
return { kind: 'failed', message: err instanceof Error ? err.message : null };
}
}
+
+/** How one page's "Suggest content" ended (AT-006 part B3). */
+export type PageSuggestionOutcome =
+ | Exclude<PromptSuggestionOutcome, { kind: 'nothing' }>
+ /** No tracked prompt is about the page: nothing to write from. */
+ | { kind: 'noMatch' }
+ /** The page's prompts have nothing to write from yet, e.g. no answers. */
+ | { kind: 'nothing' };
+
+/**
+ * Asks for one page's content suggestion and follows it to its end, as
+ * suggestForPrompt does for a prompt. Never throws: whatever goes wrong on
+ * the way comes back as `failed`.
+ */
+export async function suggestForPage(
+ brandId: string,
+ pagePath: string,
+ {
+ start,
+ getStatus,
+ newKey = () => crypto.randomUUID(),
+ ...waiting
+ }: {
+ start: (request: OnDemandRequest) => Promise<OnDemandResult>;
+ getStatus: (jobId: string) => Promise<GenerationJobStatus>;
+ newKey?: () => string;
+ intervalMs?: number;
+ timeoutMs?: number;
+ sleep?: (ms: number) => Promise<void>;
+ now?: () => number;
+ },
+): Promise<PageSuggestionOutcome> {
+ try {
+ const started = await start({ brandId, count: 1, pagePath, idempotencyKey: newKey() });
+ if (!started.ok) {
+ return started.quotaExhausted
+ ? { kind: 'limited' }
+ : { kind: 'failed', message: started.error };
+ }
+
+ const outcome = await waitForContentJob(started.jobId, { getStatus, ...waiting });
+ if (outcome.kind === 'failed') return { kind: 'failed', message: outcome.reason };
+ if (outcome.kind === 'timeout') return { kind: 'timeout' };
+ const { opportunityIds, existingId, limited, noMatch } = outcome.result;
+ if (opportunityIds?.[0]) return { kind: 'created', opportunityId: opportunityIds[0] };
+ if (existingId) return { kind: 'existing', opportunityId: existingId };
+ if (noMatch) return { kind: 'noMatch' };
+ return limited ? { kind: 'limited' } : { kind: 'nothing' };
+ } catch (err) {
+ return { kind: 'failed', message: err instanceof Error ? err.message : null };
+ }
+}