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(topics): persisted AI topic suggestions on the Topics page (#497)

Gökhan Geyikaf75ce56c435
diff --git a/server/src/config/plans.js b/server/src/config/plans.js
index 96c8d910f..5fa8b9f24 100644
--- a/server/src/config/plans.js
+++ b/server/src/config/plans.js
@@ -21,6 +21,7 @@ export const PLANS = {
features: [
'basic_insights',
'prompt_suggestions',
+ 'topic_suggestions',
'prompt_volumes',
'advanced_analytics',
'daily_monitoring',
@@ -53,6 +54,7 @@ export const PLANS = {
'basic_insights',
'advanced_analytics',
'prompt_suggestions',
+ 'topic_suggestions',
'prompt_volumes',
'daily_monitoring',
'competitor_tracking',
@@ -83,6 +85,7 @@ export const PLANS = {
features: [
'basic_insights',
'prompt_suggestions',
+ 'topic_suggestions',
'prompt_volumes',
'advanced_analytics',
'daily_monitoring',
@@ -117,6 +120,7 @@ export const PLANS = {
features: [
'basic_insights',
'prompt_suggestions',
+ 'topic_suggestions',
'prompt_volumes',
'advanced_analytics',
'daily_monitoring',
diff --git a/server/src/routes/topics.js b/server/src/routes/topics.js
index 7910b0b64..091615048 100644
--- a/server/src/routes/topics.js
+++ b/server/src/routes/topics.js
@@ -1,6 +1,9 @@
import { Router } from 'express';
import { generateText, generateObject } from 'ai';
import { z } from 'zod';
+import supabaseAdmin from '../config/supabase.js';
+import { assertBrandAccess } from '../lib/access.js';
+import { requireFeature } from '../lib/plan-guard.js';
import { resolveModel } from '../lib/ai-provider.js';
import { withRetry } from '../lib/retry.js';
import { getLanguageName } from '../lib/languages.js';
@@ -21,25 +24,142 @@ const topicSchema = z.object({
});
/**
- * POST /api/topics/suggest
- * Body: { brandName, industry, description?, website?, language? }
- * Returns: { topics: [{ name }] }
+ * Tracked-data signals for topic generation (#463 follow-up): high-volume /
+ * low-competition prompts and underperforming topics, mined from the brand's
+ * own prompt_volumes and prompt_results. Returns null when the brand has no
+ * usable data yet (nothing tracked, no volume analysis) — generation then
+ * runs on the brand profile alone, exactly like onboarding.
*/
-router.post('/suggest', async (req, res) => {
- try {
- const { brandName, industry, description, website, language } = req.body;
- const langName = getLanguageName(language);
+async function loadTopicSignals(brandId) {
+ const [{ data: prompts }, { data: topicRows }, { data: results }] = await Promise.all([
+ supabaseAdmin
+ .from('prompts')
+ .select('id, text, topic_id, prompt_sets!inner(brand_id), prompt_volumes(est_ai_volume)')
+ .eq('prompt_sets.brand_id', brandId)
+ .eq('is_active', true)
+ .limit(200),
+ supabaseAdmin.from('topics').select('id, name').eq('brand_id', brandId).eq('is_active', true),
+ // #155 — shopping results are excluded from every aggregate.
+ supabaseAdmin
+ .from('prompt_results')
+ .select('prompt_id, mention_count, citation_count, competitor_mentions')
+ .eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping')
+ .order('created_at', { ascending: false })
+ .limit(500),
+ ]);
+ if (!prompts?.length || !results?.length) return null;
- if (!brandName) {
- return res.status(400).json({ error: 'brandName is required' });
+ const topicNameById = new Map((topicRows || []).map((t) => [t.id, t.name]));
+
+ // Per-prompt aggregates over the recent results window.
+ const byPrompt = new Map();
+ for (const r of results) {
+ const agg = byPrompt.get(r.prompt_id) || { runs: 0, visible: 0, competitors: new Set() };
+ agg.runs += 1;
+ if ((r.mention_count || 0) > 0 || (r.citation_count || 0) > 0) agg.visible += 1;
+ const mentions = r.competitor_mentions;
+ if (Array.isArray(mentions)) {
+ for (const m of mentions) {
+ const name = typeof m === 'string' ? m : m?.name;
+ if (name) agg.competitors.add(name);
+ }
+ } else if (mentions && typeof mentions === 'object') {
+ for (const name of Object.keys(mentions)) agg.competitors.add(name);
}
+ byPrompt.set(r.prompt_id, agg);
+ }
- const topicModel = process.env.TOPIC_SUGGESTION_MODEL || 'google/gemini-3-flash-preview';
+ const enriched = prompts
+ .map((p) => {
+ const pv = p.prompt_volumes;
+ const volume = (Array.isArray(pv) ? pv[0]?.est_ai_volume : pv?.est_ai_volume) || 0;
+ const agg = byPrompt.get(p.id);
+ return {
+ text: p.text,
+ topicName: topicNameById.get(p.topic_id) || null,
+ volume,
+ runs: agg?.runs || 0,
+ visibleRate: agg && agg.runs > 0 ? agg.visible / agg.runs : null,
+ competitorCount: agg ? agg.competitors.size : null,
+ };
+ })
+ .filter((p) => p.runs > 0);
+ if (!enriched.length) return null;
- const researchPrompt = `Search the web and research "${brandName}" (${website || 'no website provided'}).
+ // Gap prompts: real demand (volume), weak brand presence, few competitors
+ // already owning the answer — the space a new topic can still win.
+ const gaps = enriched
+ .filter((p) => p.volume > 0 && p.visibleRate !== null && p.visibleRate < 0.5)
+ .sort((a, b) => b.volume - a.volume || (a.competitorCount ?? 99) - (b.competitorCount ?? 99))
+ .slice(0, 8);
+
+ // Weakest existing topics by visible-answer rate (needs a few runs to mean
+ // anything) — candidates for adjacent, more winnable topic variants.
+ const topicAgg = new Map();
+ for (const p of enriched) {
+ if (!p.topicName || p.visibleRate === null) continue;
+ const t = topicAgg.get(p.topicName) || { runs: 0, visible: 0 };
+ t.runs += p.runs;
+ t.visible += p.visibleRate * p.runs;
+ topicAgg.set(p.topicName, t);
+ }
+ const weakTopics = [...topicAgg.entries()]
+ .filter(([, t]) => t.runs >= 5)
+ .map(([name, t]) => ({ name, visibleRate: t.visible / t.runs }))
+ .sort((a, b) => a.visibleRate - b.visibleRate)
+ .slice(0, 3);
+
+ if (!gaps.length && !weakTopics.length) return null;
+ return { gaps, weakTopics };
+}
+
+function formatTopicSignals(signals) {
+ if (!signals) return '';
+ const pct = (rate) => `${Math.round(rate * 100)}%`;
+ const lines = [];
+ if (signals.gaps.length) {
+ lines.push(
+ `Opportunity signal (from this brand's tracked prompts — high user demand, weak brand presence, little competition):`,
+ ...signals.gaps.map(
+ (g) =>
+ ` • [~${g.volume.toLocaleString('en-US')}/mo, visible in ${pct(g.visibleRate)} of answers, ${g.competitorCount ?? '?'} competitors cited${g.topicName ? `, topic: ${g.topicName}` : ''}] ${g.text}`,
+ ),
+ `Prioritize NEW topics that cover the themes behind these prompts — demand exists and no one owns the answer yet.`,
+ );
+ }
+ if (signals.weakTopics.length) {
+ lines.push(
+ `Weakest existing topics by AI visibility (consider adjacent, more winnable angles — do NOT re-suggest these names):`,
+ ...signals.weakTopics.map(
+ (t) => ` • ${t.name} (visible in ${pct(t.visibleRate)} of answers)`,
+ ),
+ );
+ }
+ return `\n${lines.join('\n')}\n`;
+}
+
+/**
+ * Two-phase generation (web research → structured extraction), shared by the
+ * ephemeral onboarding endpoint below and the persisted Topics-page
+ * suggestions (#463). `signals` (optional) injects tracked-prompt data into
+ * the research phase; onboarding has none and passes nothing.
+ */
+async function generateTopicIdeas({
+ brandName,
+ industry,
+ description,
+ website,
+ language,
+ signals,
+}) {
+ const langName = getLanguageName(language);
+ const topicModel = process.env.TOPIC_SUGGESTION_MODEL || 'google/gemini-3-flash-preview';
+
+ const researchPrompt = `Search the web and research "${brandName}" (${website || 'no website provided'}).
Industry: ${industry || 'Not specified'}
Description: ${description || 'Not specified'}
-
+${formatTopicSignals(signals)}
Find 8-12 relevant TOPICS that this brand should track for Answer Engine Optimization (AEO). Topics should represent key areas where users might ask AI assistants about this brand or its industry.
IMPORTANT: Do NOT include the brand name "${brandName}" in any topic. Topics must be generic industry terms.
@@ -57,26 +177,49 @@ Topics should be diverse: include competitive comparisons, product features, ind
IMPORTANT: Generate all topic names in ${langName}.`;
- // #379 — retry the WHOLE two-phase flow: a schema miss in the structuring
- // phase re-runs the research too, not just the last call.
- const { object } = await withRetry(
- async () => {
- const { text: research } = await generateText({
- model: resolveModel(topicModel, { useSearchGrounding: true }),
- prompt: researchPrompt,
- });
-
- return generateObject({
- model: resolveModel(topicModel),
- schema: topicSchema,
- system: `Extract AEO tracking topics from the research below. Each topic should be concise (3-8 words) and represent an area where AI assistants might mention or discuss "${brandName}". Do NOT include the brand name "${brandName}" in any topic — keep them generic. Include a mix of: competitive comparisons, product/service features, industry trends, use cases, and problem-solving topics. Each topic MUST focus on a single concept — never combine two ideas with "and" or "&". IMPORTANT: All topic names MUST be written in ${langName}.`,
- prompt: research,
- });
- },
- { attempts: 3, baseDelayMs: 500, label: 'topic-suggest' },
- );
+ // #379 — retry the WHOLE two-phase flow: a schema miss in the structuring
+ // phase re-runs the research too, not just the last call.
+ const { object } = await withRetry(
+ async () => {
+ const { text: research } = await generateText({
+ model: resolveModel(topicModel, { useSearchGrounding: true }),
+ prompt: researchPrompt,
+ });
+
+ return generateObject({
+ model: resolveModel(topicModel),
+ schema: topicSchema,
+ system: `Extract AEO tracking topics from the research below. Each topic should be concise (3-8 words) and represent an area where AI assistants might mention or discuss "${brandName}". Do NOT include the brand name "${brandName}" in any topic — keep them generic. Include a mix of: competitive comparisons, product/service features, industry trends, use cases, and problem-solving topics. Each topic MUST focus on a single concept — never combine two ideas with "and" or "&". IMPORTANT: All topic names MUST be written in ${langName}.`,
+ prompt: research,
+ });
+ },
+ { attempts: 3, baseDelayMs: 500, label: 'topic-suggest' },
+ );
+
+ return object.topics;
+}
+
+/**
+ * POST /api/topics/suggest
+ * Body: { brandName, industry, description?, website?, language? }
+ * Returns: { topics: [{ name }] }
+ */
+router.post('/suggest', async (req, res) => {
+ try {
+ const { brandName, industry, description, website, language } = req.body;
+
+ if (!brandName) {
+ return res.status(400).json({ error: 'brandName is required' });
+ }
- return res.json({ topics: object.topics });
+ const topics = await generateTopicIdeas({
+ brandName,
+ industry,
+ description,
+ website,
+ language,
+ });
+ return res.json({ topics });
} catch (error) {
req.log.error({ err: error }, 'topic suggestion error');
return res.status(500).json({
@@ -86,4 +229,186 @@ IMPORTANT: Generate all topic names in ${langName}.`;
}
});
+/**
+ * GET /api/topics/suggestions/:brandId
+ * Returns the persisted suggestions still awaiting a decision (#463).
+ * Never triggers generation — the Topics page load path must stay LLM-free.
+ */
+router.get('/suggestions/:brandId', async (req, res) => {
+ try {
+ await assertBrandAccess(req.params.brandId, req.user.id);
+ const { data, error } = await supabaseAdmin
+ .from('topic_suggestions')
+ .select('*')
+ .eq('brand_id', req.params.brandId)
+ .eq('status', 'new')
+ .order('generated_at', { ascending: false });
+ if (error) throw error;
+ return res.json({ suggestions: data || [] });
+ } catch (error) {
+ const status = error.status || 500;
+ req.log.error({ err: error }, 'topic-suggestions list error');
+ return res.status(status).json({ error: error.message || 'Failed to load suggestions' });
+ }
+});
+
+/**
+ * POST /api/topics/suggestions/:brandId/refresh
+ * Generates a fresh batch with the same flow onboarding uses, then persists
+ * it — excluding topics the brand already tracks and names it previously
+ * dismissed or added, so decided suggestions never reappear (#463).
+ */
+router.post(
+ '/suggestions/:brandId/refresh',
+ requireFeature('topic_suggestions'),
+ async (req, res) => {
+ try {
+ const brandId = req.params.brandId;
+ await assertBrandAccess(brandId, req.user.id);
+
+ const { data: brand } = await supabaseAdmin
+ .from('brands')
+ .select('name, industry, description, language')
+ .eq('id', brandId)
+ .single();
+ if (!brand) return res.status(404).json({ error: 'Brand not found' });
+
+ const [{ data: primaryDomain }, signals] = await Promise.all([
+ supabaseAdmin
+ .from('brand_domains')
+ .select('domain')
+ .eq('brand_id', brandId)
+ .order('is_primary', { ascending: false })
+ .limit(1)
+ .maybeSingle(),
+ loadTopicSignals(brandId),
+ ]);
+
+ const ideas = await generateTopicIdeas({
+ brandName: brand.name,
+ industry: brand.industry,
+ description: brand.description,
+ website: primaryDomain?.domain,
+ language: brand.language,
+ signals,
+ });
+
+ const [{ data: existingTopics }, { data: decided }] = await Promise.all([
+ supabaseAdmin.from('topics').select('name').eq('brand_id', brandId),
+ supabaseAdmin
+ .from('topic_suggestions')
+ .select('name')
+ .eq('brand_id', brandId)
+ .in('status', ['dismissed', 'added']),
+ ]);
+ const taken = new Set(
+ [...(existingTopics || []), ...(decided || [])].map((r) => r.name.trim().toLowerCase()),
+ );
+
+ const seen = new Set();
+ const fresh = ideas.filter((t) => {
+ const key = t.name.trim().toLowerCase();
+ if (!key || taken.has(key) || seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+
+ // Replace the undecided batch wholesale — same behavior as prompt
+ // suggestions refresh. Dismissed/added rows are never touched.
+ await supabaseAdmin
+ .from('topic_suggestions')
+ .delete()
+ .eq('brand_id', brandId)
+ .eq('status', 'new');
+
+ if (fresh.length === 0) {
+ return res.json({ suggestions: [] });
+ }
+
+ const { data: inserted, error } = await supabaseAdmin
+ .from('topic_suggestions')
+ .insert(
+ fresh.map((t) => ({
+ brand_id: brandId,
+ name: t.name.trim(),
+ source: 'llm',
+ status: 'new',
+ })),
+ )
+ .select();
+ if (error) throw error;
+
+ return res.json({ suggestions: inserted });
+ } catch (error) {
+ const status = error.status || 500;
+ req.log.error({ err: error }, 'topic-suggestions refresh error');
+ return res.status(status).json({ error: error.message || 'Failed to generate suggestions' });
+ }
+ },
+);
+
+/**
+ * POST /api/topics/suggestions/:id/dismiss
+ * Marks a suggestion dismissed; its name is excluded from future refreshes.
+ */
+router.post('/suggestions/:id/dismiss', async (req, res) => {
+ try {
+ const { data: suggestion } = await supabaseAdmin
+ .from('topic_suggestions')
+ .select('brand_id')
+ .eq('id', req.params.id)
+ .single();
+ if (!suggestion) return res.status(404).json({ error: 'Not found' });
+ await assertBrandAccess(suggestion.brand_id, req.user.id);
+
+ const { error } = await supabaseAdmin
+ .from('topic_suggestions')
+ .update({ status: 'dismissed', updated_at: new Date().toISOString() })
+ .eq('id', req.params.id);
+ if (error) throw error;
+ return res.json({ success: true });
+ } catch (error) {
+ const status = error.status || 500;
+ req.log.error({ err: error }, 'topic-suggestions dismiss error');
+ return res.status(status).json({ error: error.message || 'Failed to dismiss' });
+ }
+});
+
+/**
+ * POST /api/topics/suggestions/:id/accept
+ * Body: { topicId } — the topic the web app just created via the singular
+ * createTopic action. This only records the outcome; topic creation itself
+ * happens RLS-checked in the web app.
+ */
+router.post('/suggestions/:id/accept', async (req, res) => {
+ try {
+ const { topicId } = req.body || {};
+ if (!topicId) {
+ return res.status(400).json({ error: 'topicId is required' });
+ }
+ const { data: suggestion } = await supabaseAdmin
+ .from('topic_suggestions')
+ .select('brand_id')
+ .eq('id', req.params.id)
+ .single();
+ if (!suggestion) return res.status(404).json({ error: 'Not found' });
+ await assertBrandAccess(suggestion.brand_id, req.user.id);
+
+ const { error } = await supabaseAdmin
+ .from('topic_suggestions')
+ .update({
+ status: 'added',
+ added_topic_id: topicId,
+ updated_at: new Date().toISOString(),
+ })
+ .eq('id', req.params.id);
+ if (error) throw error;
+ return res.json({ success: true });
+ } catch (error) {
+ const status = error.status || 500;
+ req.log.error({ err: error }, 'topic-suggestions accept error');
+ return res.status(status).json({ error: error.message || 'Failed to accept' });
+ }
+});
+
export default router;
diff --git a/supabase/migrations/00030_topic_suggestions.sql b/supabase/migrations/00030_topic_suggestions.sql
new file mode 100644
index 000000000..ee8706d63
--- /dev/null
+++ b/supabase/migrations/00030_topic_suggestions.sql
@@ -0,0 +1,63 @@
+-- 00030_topic_suggestions.sql
+-- Persisted AI topic suggestions for the Topics page (#463).
+--
+-- Mirrors prompt_suggestions: rows are generated only on explicit user
+-- action (never on page load), survive reloads, and dismissed suggestions
+-- never reappear. All writes go through the Express server's service-role
+-- client; RLS below covers the web app's direct reads.
+
+CREATE TABLE IF NOT EXISTS "public"."topic_suggestions" (
+ "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
+ "brand_id" "uuid" NOT NULL,
+ "name" "text" NOT NULL,
+ "reason" "text",
+ "source" "text" DEFAULT 'llm'::"text" NOT NULL,
+ "status" "text" DEFAULT 'new'::"text" NOT NULL,
+ "added_topic_id" "uuid",
+ "generated_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ CONSTRAINT "topic_suggestions_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "topic_suggestions_status_check" CHECK (
+ "status" = ANY (ARRAY['new'::"text", 'added'::"text", 'dismissed'::"text"])
+ ),
+ CONSTRAINT "topic_suggestions_brand_id_fkey" FOREIGN KEY ("brand_id")
+ REFERENCES "public"."brands"("id") ON DELETE CASCADE,
+ CONSTRAINT "topic_suggestions_added_topic_id_fkey" FOREIGN KEY ("added_topic_id")
+ REFERENCES "public"."topics"("id") ON DELETE SET NULL
+);
+
+ALTER TABLE "public"."topic_suggestions" OWNER TO "postgres";
+
+CREATE INDEX IF NOT EXISTS "idx_topic_suggestions_brand_status"
+ ON "public"."topic_suggestions" ("brand_id", "status");
+
+ALTER TABLE "public"."topic_suggestions" ENABLE ROW LEVEL SECURITY;
+
+-- Same policy shape as prompt_suggestions: every org member can read,
+-- admin/manager/analyst can update (dismiss/accept acks happen server-side,
+-- but the web app reads rows directly when accepting).
+CREATE POLICY "topic_suggestions: member select" ON "public"."topic_suggestions"
+ FOR SELECT USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ )
+ );
+
+CREATE POLICY "topic_suggestions: admin/manager/analyst update" ON "public"."topic_suggestions"
+ FOR UPDATE USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ AND "p"."role" = ANY (ARRAY['admin'::"public"."user_role", 'manager'::"public"."user_role", 'analyst'::"public"."user_role"])
+ )
+ );
+
+GRANT ALL ON TABLE "public"."topic_suggestions" TO "anon";
+GRANT ALL ON TABLE "public"."topic_suggestions" TO "authenticated";
+GRANT ALL ON TABLE "public"."topic_suggestions" TO "service_role";
diff --git a/supabase/schema.sql b/supabase/schema.sql
index b480c7d48..a04b9abcd 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -3582,3 +3582,70 @@ AS $$
FROM brand_totals b;
$$;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00030_topic_suggestions.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- 00030_topic_suggestions.sql
+-- Persisted AI topic suggestions for the Topics page (#463).
+--
+-- Mirrors prompt_suggestions: rows are generated only on explicit user
+-- action (never on page load), survive reloads, and dismissed suggestions
+-- never reappear. All writes go through the Express server's service-role
+-- client; RLS below covers the web app's direct reads.
+
+CREATE TABLE IF NOT EXISTS "public"."topic_suggestions" (
+ "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
+ "brand_id" "uuid" NOT NULL,
+ "name" "text" NOT NULL,
+ "reason" "text",
+ "source" "text" DEFAULT 'llm'::"text" NOT NULL,
+ "status" "text" DEFAULT 'new'::"text" NOT NULL,
+ "added_topic_id" "uuid",
+ "generated_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ CONSTRAINT "topic_suggestions_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "topic_suggestions_status_check" CHECK (
+ "status" = ANY (ARRAY['new'::"text", 'added'::"text", 'dismissed'::"text"])
+ ),
+ CONSTRAINT "topic_suggestions_brand_id_fkey" FOREIGN KEY ("brand_id")
+ REFERENCES "public"."brands"("id") ON DELETE CASCADE,
+ CONSTRAINT "topic_suggestions_added_topic_id_fkey" FOREIGN KEY ("added_topic_id")
+ REFERENCES "public"."topics"("id") ON DELETE SET NULL
+);
+
+ALTER TABLE "public"."topic_suggestions" OWNER TO "postgres";
+
+CREATE INDEX IF NOT EXISTS "idx_topic_suggestions_brand_status"
+ ON "public"."topic_suggestions" ("brand_id", "status");
+
+ALTER TABLE "public"."topic_suggestions" ENABLE ROW LEVEL SECURITY;
+
+-- Same policy shape as prompt_suggestions: every org member can read,
+-- admin/manager/analyst can update (dismiss/accept acks happen server-side,
+-- but the web app reads rows directly when accepting).
+CREATE POLICY "topic_suggestions: member select" ON "public"."topic_suggestions"
+ FOR SELECT USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ )
+ );
+
+CREATE POLICY "topic_suggestions: admin/manager/analyst update" ON "public"."topic_suggestions"
+ FOR UPDATE USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ AND "p"."role" = ANY (ARRAY['admin'::"public"."user_role", 'manager'::"public"."user_role", 'analyst'::"public"."user_role"])
+ )
+ );
+
+GRANT ALL ON TABLE "public"."topic_suggestions" TO "anon";
+GRANT ALL ON TABLE "public"."topic_suggestions" TO "authenticated";
+GRANT ALL ON TABLE "public"."topic_suggestions" TO "service_role";
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 6b4716eb4..979799905 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -673,11 +673,10 @@ function NoDataForPeriod({ datePreset, onReset }: { datePreset: DatePreset; onRe
// ─── Recommendations ──────────────────────────────────────────────────────────
-/** Targets on the Prompts page. The prompt-suggestions card lives on the
- * default All Prompts tab and already expands + scrolls itself for this
- * hash; the similar-topics card lives on the Insights tab, which is
- * selected via `?tab=` (a bare hash would land on the wrong tab). */
-const TOPIC_OPPORTUNITIES_HREF = '/dashboard/prompts?tab=insights#topic-opportunities';
+/** Teaser targets. Topic suggestions live on the Topics page (#463) — its
+ * card expands + scrolls itself for this hash; the prompt-suggestions card
+ * lives on the Prompts page's default All Prompts tab and does the same. */
+const TOPIC_OPPORTUNITIES_HREF = '/dashboard/topics#topic-opportunities';
const PROMPT_OPPORTUNITIES_HREF = '/dashboard/prompts#prompt-opportunities';
function RecommendationCard({
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/_suggestions-card.tsx
new file mode 100644
index 000000000..4a9855243
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/_suggestions-card.tsx
@@ -0,0 +1,287 @@
+'use client';
+
+import { useEffect, useState, useCallback, useTransition } from 'react';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ Sparkles,
+ Plus,
+ X,
+ RefreshCw,
+ Loader2,
+ Info,
+ ChevronDown,
+ ChevronRight,
+} from 'lucide-react';
+import { toast } from 'sonner';
+import {
+ getTopicSuggestions,
+ refreshTopicSuggestions,
+ acceptTopicSuggestion,
+ dismissTopicSuggestion,
+ type TopicSuggestion,
+} from '@/lib/actions/topic-suggestions';
+
+interface Props {
+ brandId: string;
+ /** admin/manager only — read-only card when false (#463). */
+ canManage: boolean;
+ onAccepted?: () => void;
+}
+
+/** localStorage key remembering whether the card is expanded across visits. */
+const EXPANDED_KEY = 'aeo:topic-suggestions-expanded';
+
+export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props) {
+ const [suggestions, setSuggestions] = useState<TopicSuggestion[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [loaded, setLoaded] = useState(false);
+ const [refreshing, setRefreshing] = useState(false);
+ const [pendingId, setPendingId] = useState<string | null>(null);
+ // Collapsed by default so the card is a one-line strip and the leaderboard
+ // stays above the fold; the user's last choice is remembered. Starts false
+ // on both server and client (no hydration mismatch), then the effect below
+ // restores the stored preference.
+ const [expanded, setExpanded] = useState(false);
+ const [, startTransition] = useTransition();
+
+ useEffect(() => {
+ try {
+ if (localStorage.getItem(EXPANDED_KEY) === '1') setExpanded(true);
+ } catch {
+ // Storage unavailable (private mode) — stay collapsed.
+ }
+ if (window.location.hash === '#topic-opportunities') {
+ // Deep links mean "show me the suggestions" — expand (without touching
+ // the stored preference) and scroll the card into view.
+ setExpanded(true);
+ document.getElementById('topic-opportunities')?.scrollIntoView();
+ }
+ }, []);
+
+ const toggleExpanded = () => {
+ setExpanded((prev) => {
+ const next = !prev;
+ try {
+ localStorage.setItem(EXPANDED_KEY, next ? '1' : '0');
+ } catch {
+ // Preference just won't persist.
+ }
+ return next;
+ });
+ };
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const s = await getTopicSuggestions(brandId);
+ setSuggestions(s);
+ setLoaded(true);
+ } catch (err) {
+ console.error('Failed to load topic suggestions:', err);
+ } finally {
+ setLoading(false);
+ }
+ }, [brandId]);
+
+ // Fetch ONLY once the card is actually expanded — never on page load. The
+ // collapsed strip must not fire a server action (#313: a mount-time call
+ // would sit first in Next's serialized action queue and stall the
+ // leaderboard's own data fetch behind it). Generation is a separate,
+ // explicit button — this fetch only reads persisted rows.
+ useEffect(() => {
+ setLoaded(false);
+ setSuggestions([]);
+ }, [brandId]);
+
+ useEffect(() => {
+ if (expanded && !loaded && !loading) {
+ load();
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [expanded, loaded, brandId]);
+
+ const handleRefresh = async () => {
+ setRefreshing(true);
+ try {
+ const fresh = await refreshTopicSuggestions(brandId);
+ setSuggestions(fresh);
+ setLoaded(true);
+ toast.success('Topic suggestions refreshed');
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Refresh failed');
+ } finally {
+ setRefreshing(false);
+ }
+ };
+
+ const handleAccept = (s: TopicSuggestion) => {
+ setPendingId(s.id);
+ startTransition(async () => {
+ try {
+ await acceptTopicSuggestion(s.id);
+ setSuggestions((prev) => prev.filter((x) => x.id !== s.id));
+ onAccepted?.();
+ toast.success(`"${s.name}" added to your topics`);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to add');
+ } finally {
+ setPendingId(null);
+ }
+ });
+ };
+
+ const handleDismiss = (s: TopicSuggestion) => {
+ setPendingId(s.id);
+ setSuggestions((prev) => prev.filter((x) => x.id !== s.id));
+ dismissTopicSuggestion(s.id)
+ .catch(() => {
+ // Roll back on failure
+ setSuggestions((prev) => [...prev, s]);
+ toast.error('Failed to dismiss');
+ })
+ .finally(() => setPendingId(null));
+ };
+
+ return (
+ <Card id="topic-opportunities">
+ <CardHeader className={expanded ? 'pb-3' : 'py-4'}>
+ <div className="flex items-center justify-between gap-4 flex-wrap">
+ <button
+ type="button"
+ onClick={toggleExpanded}
+ aria-expanded={expanded}
+ className="flex items-center gap-2 text-left"
+ >
+ {expanded ? (
+ <ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" />
+ ) : (
+ <ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
+ )}
+ <Sparkles className="h-4 w-4 text-primary" />
+ <CardTitle className="text-sm font-medium">Topic Suggestions</CardTitle>
+ <Info
+ className="h-3.5 w-3.5 text-muted-foreground cursor-help"
+ aria-label="AI-generated topic ideas for your brand. Topics you already track and dismissed ideas never reappear."
+ >
+ <title>
+ AI-generated topic ideas for your brand. Topics you already track and dismissed
+ ideas never reappear.
+ </title>
+ </Info>
+ {loading ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />
+ ) : loaded && suggestions.length > 0 ? (
+ <Badge variant="secondary" className="text-xs tabular-nums">
+ {suggestions.length}
+ </Badge>
+ ) : loaded ? (
+ !expanded && (
+ <span className="text-xs text-muted-foreground">no new ideas — expand</span>
+ )
+ ) : (
+ !expanded && (
+ <span className="text-xs text-muted-foreground">expand for AI topic ideas</span>
+ )
+ )}
+ </button>
+ {expanded && canManage && (
+ <Button
+ onClick={handleRefresh}
+ disabled={refreshing}
+ size="sm"
+ variant="outline"
+ className="gap-2"
+ >
+ {refreshing ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <RefreshCw className="h-3.5 w-3.5" />
+ )}
+ {refreshing ? 'Generating…' : 'Refresh'}
+ </Button>
+ )}
+ </div>
+ </CardHeader>
+ {expanded && (
+ <CardContent>
+ {loading ? (
+ <div className="flex items-center justify-center py-10">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
+ </div>
+ ) : suggestions.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-10 text-center">
+ <Sparkles className="h-8 w-8 text-muted-foreground/40 mb-2" />
+ <p className="text-sm font-medium mb-1">No suggestions right now</p>
+ <p className="text-xs text-muted-foreground mb-3 max-w-sm">
+ {canManage
+ ? 'Generate AI topic ideas tailored to your brand and industry. Topics you already track are excluded automatically.'
+ : 'No topic suggestions have been generated for this brand yet.'}
+ </p>
+ {canManage && (
+ <Button onClick={handleRefresh} disabled={refreshing} size="sm" className="gap-2">
+ {refreshing ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Sparkles className="h-3.5 w-3.5" />
+ )}
+ Generate Suggestions
+ </Button>
+ )}
+ </div>
+ ) : (
+ <ul className="space-y-2">
+ {suggestions.map((s) => {
+ const busy = pendingId === s.id;
+ return (
+ <li
+ key={s.id}
+ className="group flex items-center gap-3 rounded-lg border bg-muted/20 p-3 transition-colors hover:bg-muted/40"
+ >
+ <div className="flex-1 min-w-0 space-y-1">
+ <p className="text-sm font-medium leading-snug">{s.name}</p>
+ {s.reason && (
+ <p className="text-xs text-muted-foreground leading-relaxed">{s.reason}</p>
+ )}
+ </div>
+ {canManage && (
+ <div className="flex items-center gap-1 shrink-0">
+ <Button
+ size="icon"
+ variant="outline"
+ className="h-8 w-8"
+ onClick={() => handleAccept(s)}
+ disabled={busy}
+ title="Add to tracked topics"
+ aria-label="Add to tracked topics"
+ >
+ {busy ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Plus className="h-3.5 w-3.5" />
+ )}
+ </Button>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8 text-muted-foreground"
+ onClick={() => handleDismiss(s)}
+ disabled={busy}
+ title="Dismiss suggestion"
+ aria-label="Dismiss suggestion"
+ >
+ <X className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </CardContent>
+ )}
+ </Card>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
index a75df0deb..d9d565003 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
@@ -3,7 +3,9 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link } from '@/i18n/navigation';
import { useBrandStore } from '@/stores/use-brand-store';
+import { useUserRole } from '@/hooks/use-user-role';
import { getTopicsOverview, type TopicOverviewRow } from '@/lib/actions/topic';
+import { TopicSuggestionsCard } from './_suggestions-card';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
Table,
@@ -152,6 +154,7 @@ export default function TopicsPage() {
const activeBrand = useBrandStore(
(s) => s.brands.find((brand) => brand.id === s.activeBrandId) ?? null,
);
+ const { canManage } = useUserRole();
const [topics, setTopics] = useState<TopicOverviewRow[]>([]);
const [unassignedPromptCount, setUnassignedPromptCount] = useState(0);
const [loading, setLoading] = useState(true);
@@ -342,6 +345,10 @@ export default function TopicsPage() {
</div>
) : null}
+ {/* Topic Suggestions (#463) — collapsed strip by default; loads its
+ persisted rows only when expanded and never generates on page load. */}
+ <TopicSuggestionsCard brandId={activeBrandId} canManage={canManage} onAccepted={loadData} />
+
{/* Leaderboard */}
<Card>
<CardHeader className="pb-3">
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index c8c9ea36d..436e6164b 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -2,6 +2,7 @@ export const FEATURES = [
'basic_insights',
'advanced_analytics',
'prompt_suggestions',
+ 'topic_suggestions',
'prompt_volumes',
'daily_monitoring',
'competitor_tracking',
@@ -86,6 +87,7 @@ export const PLANS: Record<PlanId, Plan> = {
features: [
'basic_insights',
'prompt_suggestions',
+ 'topic_suggestions',
'prompt_volumes',
'advanced_analytics',
'daily_monitoring',
@@ -122,6 +124,7 @@ export const PLANS: Record<PlanId, Plan> = {
'basic_insights',
'advanced_analytics',
'prompt_suggestions',
+ 'topic_suggestions',
'prompt_volumes',
'daily_monitoring',
'competitor_tracking',
@@ -159,6 +162,7 @@ export const PLANS: Record<PlanId, Plan> = {
features: [
'basic_insights',
'prompt_suggestions',
+ 'topic_suggestions',
'prompt_volumes',
'advanced_analytics',
'daily_monitoring',
@@ -197,6 +201,7 @@ export const PLANS: Record<PlanId, Plan> = {
features: [
'basic_insights',
'prompt_suggestions',
+ 'topic_suggestions',
'prompt_volumes',
'advanced_analytics',
'daily_monitoring',
diff --git a/web/src/lib/actions/topic-suggestions.ts b/web/src/lib/actions/topic-suggestions.ts
new file mode 100644
index 000000000..2d534cbfb
--- /dev/null
+++ b/web/src/lib/actions/topic-suggestions.ts
@@ -0,0 +1,130 @@
+'use server';
+
+import { revalidatePath } from 'next/cache';
+import { createClient } from '@/lib/supabase/server';
+import { createTopic } from '@/lib/actions/topic';
+import { API_BASE_URL } from '@/config/api';
+
+const AEO_SERVER_URL = API_BASE_URL;
+
+export interface TopicSuggestion {
+ id: string;
+ brandId: string;
+ name: string;
+ reason: string | null;
+ source: 'llm';
+ status: 'new' | 'added' | 'dismissed';
+ generatedAt: string;
+}
+
+interface SuggestionRow {
+ id: string;
+ brand_id: string;
+ name: string;
+ reason: string | null;
+ source: 'llm';
+ status: 'new' | 'added' | 'dismissed';
+ generated_at: string;
+}
+
+function mapRow(row: SuggestionRow): TopicSuggestion {
+ return {
+ id: row.id,
+ brandId: row.brand_id,
+ name: row.name,
+ reason: row.reason,
+ source: row.source,
+ status: row.status,
+ generatedAt: row.generated_at,
+ };
+}
+
+async function getSession() {
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) throw new Error('Not authenticated');
+ return session;
+}
+
+export async function getTopicSuggestions(brandId: string): Promise<TopicSuggestion[]> {
+ const session = await getSession();
+ const res = await fetch(`${AEO_SERVER_URL}/api/topics/suggestions/${brandId}`, {
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ cache: 'no-store',
+ // Read-only lookup — a hung upstream must not pin the suggestions card
+ // (and the serialized server-action queue behind it) indefinitely.
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.error || `Server error: ${res.status}`);
+ }
+ const data = (await res.json()) as { suggestions: SuggestionRow[] };
+ return data.suggestions.map(mapRow);
+}
+
+export async function refreshTopicSuggestions(brandId: string): Promise<TopicSuggestion[]> {
+ const session = await getSession();
+ const res = await fetch(`${AEO_SERVER_URL}/api/topics/suggestions/${brandId}/refresh`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.error || `Server error: ${res.status}`);
+ }
+ const data = (await res.json()) as { suggestions: SuggestionRow[] };
+ return data.suggestions.map(mapRow);
+}
+
+export async function dismissTopicSuggestion(suggestionId: string): Promise<{ success: boolean }> {
+ const session = await getSession();
+ const res = await fetch(`${AEO_SERVER_URL}/api/topics/suggestions/${suggestionId}/dismiss`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.error || `Server error: ${res.status}`);
+ }
+ return res.json();
+}
+
+/**
+ * Accept a suggestion: create exactly ONE topic via the singular createTopic
+ * action (never the plural createTopics, which replaces the brand's whole
+ * topic list), then ack the server so the suggestion moves to `added`.
+ */
+export async function acceptTopicSuggestion(suggestionId: string): Promise<{ topicId: string }> {
+ const session = await getSession();
+ const supabase = await createClient();
+
+ const { data: row, error: rowErr } = await supabase
+ .from('topic_suggestions')
+ .select('id, brand_id, name')
+ .eq('id', suggestionId)
+ .eq('status', 'new')
+ .single();
+ if (rowErr || !row) {
+ throw new Error('Suggestion not found or already processed');
+ }
+
+ const topic = await createTopic(row.brand_id, row.name);
+
+ const ack = await fetch(`${AEO_SERVER_URL}/api/topics/suggestions/${suggestionId}/accept`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${session.access_token}`,
+ },
+ body: JSON.stringify({ topicId: topic.id }),
+ });
+ if (!ack.ok) {
+ console.error('[topic-suggestions] accept ack failed:', await ack.text().catch(() => ''));
+ }
+
+ revalidatePath('/dashboard/topics');
+ return { topicId: topic.id };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 09bd6da48..741f55cd4 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1040,6 +1040,60 @@ export type Database = {
},
];
};
+ topic_suggestions: {
+ Row: {
+ added_topic_id: string | null;
+ brand_id: string;
+ created_at: string;
+ generated_at: string;
+ id: string;
+ name: string;
+ reason: string | null;
+ source: string;
+ status: string;
+ updated_at: string;
+ };
+ Insert: {
+ added_topic_id?: string | null;
+ brand_id: string;
+ created_at?: string;
+ generated_at?: string;
+ id?: string;
+ name: string;
+ reason?: string | null;
+ source?: string;
+ status?: string;
+ updated_at?: string;
+ };
+ Update: {
+ added_topic_id?: string | null;
+ brand_id?: string;
+ created_at?: string;
+ generated_at?: string;
+ id?: string;
+ name?: string;
+ reason?: string | null;
+ source?: string;
+ status?: string;
+ updated_at?: string;
+ };
+ Relationships: [
+ {
+ foreignKeyName: 'topic_suggestions_added_topic_id_fkey';
+ columns: ['added_topic_id'];
+ isOneToOne: false;
+ referencedRelation: 'topics';
+ referencedColumns: ['id'];
+ },
+ {
+ foreignKeyName: 'topic_suggestions_brand_id_fkey';
+ columns: ['brand_id'];
+ isOneToOne: false;
+ referencedRelation: 'brands';
+ referencedColumns: ['id'];
+ },
+ ];
+ };
topics: {
Row: {
brand_id: string;