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(insights): Topic & Prompt Opportunities teaser cards (#459) (#479)
Gökhan Geyike2f3ed19631e
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex 19b05ad9f..8c112f2f3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -1,7 +1,7 @@'use client';import { useState, useRef, useEffect, useCallback } from 'react';-import { useRouter } from '@/i18n/navigation';+import { Link, useRouter } from '@/i18n/navigation';import { useSearchParams } from 'next/navigation';import { createPortal } from 'react-dom';import { useTranslations } from 'next-intl';@@ -48,6 +48,7 @@ import {type TrackedPromptsKpi,type CompetitorComparisonData,type ShareOfVoiceData,+ type InsightsRecommendations,type TrackingJobStatus,type BreakdownMetric,} from '@/lib/actions/tracking';@@ -77,6 +78,9 @@ import {ArrowUpRight,Download,Layers,+ Lightbulb,+ Sparkles,+ Tag,} from 'lucide-react';import {Select,@@ -89,6 +93,7 @@ import { Input } from '@/components/ui/input';import { cn } from '@/lib/utils';import { getAIProviderDisplayName, resolveAIProvider } from '@/components/ai-provider-avatar';import { usePlanContext } from '@/components/providers/plan-provider';+import { formatCompactNumber } from '@/lib/format';import { toast } from 'sonner';// ─── Filter Types ─────────────────────────────────────────────────────────────@@ -664,6 +669,139 @@ 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';+const PROMPT_OPPORTUNITIES_HREF = '/dashboard/prompts#prompt-opportunities';++function RecommendationCard({+ title,+ icon: Icon,+ href,+ emptyText,+ children,+ isEmpty,+}: {+ title: string;+ icon: React.ElementType;+ href: string;+ emptyText: string;+ children: React.ReactNode;+ isEmpty: boolean;+}) {+ return (+ <Card>+ <CardHeader className="pb-2">+ <div className="flex items-center justify-between gap-3">+ <CardTitle className="flex items-center gap-2 text-sm font-medium">+ <Icon className="h-4 w-4 text-primary" />+ {title}+ </CardTitle>+ {!isEmpty && (+ <Link+ href={href}+ className="shrink-0 text-xs font-medium text-primary underline-offset-2 hover:underline"+ >+ See all+ </Link>+ )}+ </div>+ </CardHeader>+ <CardContent>+ {isEmpty ? (+ <div className="flex flex-col items-center justify-center py-6 text-center gap-2">+ <p className="text-xs text-muted-foreground max-w-xs">{emptyText}</p>+ <Link+ href={href}+ className="text-xs font-medium text-primary underline-offset-2 hover:underline"+ >+ Generate ideas →+ </Link>+ </div>+ ) : (+ children+ )}+ </CardContent>+ </Card>+ );+}++/**+ * The "so what, what next?" row (#459) filling the space freed by the removed+ * results tree (#458). Reads only stored data assembled server-side inside+ * getInsightsData — no extra client round trip, no LLM call. Deliberately+ * outside the date-filter contract: no delta badges, own section heading+ * (see #457 for why period-scoped and account-scoped numbers must not mix).+ */+function RecommendationsSection({ data }: { data: InsightsRecommendations }) {+ return (+ <div className="space-y-3">+ <div>+ <h2 className="flex items-center gap-2 text-sm font-semibold">+ <Lightbulb className="h-4 w-4 text-primary" />+ Recommendations+ </h2>+ <p className="text-xs text-muted-foreground mt-0.5">+ Ideas from your stored analyses — independent of the date filters above.+ </p>+ </div>+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <RecommendationCard+ title="Topic Opportunities"+ icon={Tag}+ href={TOPIC_OPPORTUNITIES_HREF}+ isEmpty={data.topics.length === 0}+ emptyText="No topic clusters yet. Analyze your prompt volumes to surface the themes with the most AI search demand."+ >+ <ul className="divide-y">+ {data.topics.map((t) => (+ <li key={t.keyword} className="flex items-center gap-3 py-2 first:pt-0 last:pb-0">+ <p className="flex-1 min-w-0 truncate text-sm">{t.keyword}</p>+ <span className="shrink-0 text-xs text-muted-foreground tabular-nums">+ {t.promptCount} prompt{t.promptCount !== 1 ? 's' : ''}+ </span>+ <Badge variant="outline" className="shrink-0 gap-1 text-xs tabular-nums">+ <TrendingUp className="h-3 w-3" />~{formatCompactNumber(t.estimatedAiVolume)}/mo+ </Badge>+ </li>+ ))}+ </ul>+ </RecommendationCard>+ <RecommendationCard+ title="Prompt Opportunities"+ icon={Sparkles}+ href={PROMPT_OPPORTUNITIES_HREF}+ isEmpty={data.prompts.length === 0}+ emptyText="No prompt suggestions stored yet. Generate AI prompt ideas based on your brand and competitor citations."+ >+ <ul className="divide-y">+ {data.prompts.map((p) => (+ <li key={p.id} className="flex items-center gap-3 py-2 first:pt-0 last:pb-0">+ <p className="flex-1 min-w-0 truncate text-sm">{p.text}</p>+ {p.topicName && (+ <Badge variant="outline" className="hidden sm:inline-flex shrink-0 gap-1 text-xs">+ <Tag className="h-3 w-3" />+ {p.topicName}+ </Badge>+ )}+ {p.estVolume != null && p.estVolume > 0 && (+ <Badge variant="outline" className="shrink-0 gap-1 text-xs tabular-nums">+ <TrendingUp className="h-3 w-3" />~{formatCompactNumber(p.estVolume)}/mo+ </Badge>+ )}+ </li>+ ))}+ </ul>+ </RecommendationCard>+ </div>+ </div>+ );+}+// ─── Tracking Progress ────────────────────────────────────────────────────────import { saveTrackingJob, loadTrackingJob, clearTrackingJob } from '@/lib/tracking-job-store';@@ -765,6 +903,7 @@ export default function InsightsPage() {const [availableTopics, setAvailableTopics] = useState<Topic[]>([]);const [competitorData, setCompetitorData] = useState<CompetitorComparisonData | null>(null);const [sovData, setSovData] = useState<ShareOfVoiceData | null>(null);+ const [recommendations, setRecommendations] = useState<InsightsRecommendations | null>(null);const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);const [isExporting, setIsExporting] = useState(false);const filtersRef = useRef(filters);@@ -802,6 +941,7 @@ export default function InsightsPage() {setTrackedPrompts(insights.trackedPrompts);setCompetitorData(insights.competitors.brands.length > 1 ? insights.competitors : null);setSovData(insights.sov.byPlatform.length > 0 ? insights.sov : null);+ setRecommendations(insights.recommendations);setHasAnyData(insights.hasAnyData);// Group raw model slugs by their resolved display name so different@@ -1321,6 +1461,9 @@ export default function InsightsPage() {</Card></div>)}++ {/* Recommendations (#459) — stored data, not period-scoped */}+ {recommendations && <RecommendationsSection data={recommendations} />}</>)}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex a96afaadf..995410f6e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -300,9 +300,21 @@ export default function PromptsPage() {if (current === tab) return;const params = new URLSearchParams(Array.from(searchParams.entries()));params.set('tab', tab);- window.history.replaceState(null, '', `?${params.toString()}`);+ // Keep the hash: deep links like #prompt-opportunities arrive without a+ // tab param, and this sync must not strip their anchor from the URL.+ window.history.replaceState(null, '', `?${params.toString()}${window.location.hash}`);}, [tab, searchParams]);+ // Deep link from the Insights Recommendations row (#459): the target card+ // only exists once the Insights tab's volume data has rendered, so a bare+ // anchor never scrolls on its own — re-apply the hash after loading ends.+ useEffect(() => {+ if (tab !== 'insights' || loading) return;+ if (window.location.hash === '#topic-opportunities') {+ document.getElementById('topic-opportunities')?.scrollIntoView();+ }+ }, [tab, loading]);+const loadData = useCallback(async (isCancelled?: () => boolean) => {if (!activeBrandId) {@@ -789,7 +801,7 @@ export default function PromptsPage() {</CardContent></Card>- <Card>+ <Card id="topic-opportunities"><CardHeader className="pb-2"><div className="flex items-start justify-between gap-3"><div>diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 8e58d9840..2198b30a7 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -14,6 +14,9 @@ import type {import { API_BASE_URL } from '@/config/api';import { getTopicById } from '@/lib/actions/topic';import { getOrgPlan } from '@/lib/guards/plan-guard';+import { getPromptVolumes } from '@/lib/actions/volumes';+import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';+import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';/** Round to one decimal place (keeps sub-1 averages visible instead of flooring to 0). */function roundTo1(n: number): number {@@ -411,6 +414,62 @@ async function getInsightsFilterOptions(brandId: string): Promise<InsightsFilter};}+export interface TopicOpportunity {+ keyword: string;+ estimatedAiVolume: number;+ promptCount: number;+}++export interface PromptOpportunity {+ id: string;+ text: string;+ topicName?: string;+ estVolume?: number;+}++export interface InsightsRecommendations {+ topics: TopicOpportunity[];+ prompts: PromptOpportunity[];+}++/** Items per Recommendations teaser card on the Insights page (#459). */+const RECOMMENDATION_ITEM_LIMIT = 5;++/**+ * Teaser data for the Insights Recommendations row (#459): the top stored+ * similar-topic clusters and prompt suggestions. Both are bounded reads of+ * already-persisted data — generation only ever happens from the Prompts+ * page's explicit refresh actions, never from the Insights load path.+ * Each read degrades independently to an empty list on failure so a hiccup+ * here can never take the Insights page down with it.+ */+async function getInsightsRecommendations(brandId: string): Promise<InsightsRecommendations> {+ const [topics, prompts] = await Promise.all([+ getPromptVolumes(brandId)+ .then(({ volumes }) =>+ aggregatePromptVolumeClusters(volumes)+ .slice(0, RECOMMENDATION_ITEM_LIMIT)+ .map((c) => ({+ keyword: c.keyword,+ estimatedAiVolume: c.estimatedAiVolume,+ promptCount: c.prompts.length,+ })),+ )+ .catch(() => [] as TopicOpportunity[]),+ getPromptSuggestions(brandId)+ .then(({ suggestions }) =>+ suggestions.slice(0, RECOMMENDATION_ITEM_LIMIT).map((s) => ({+ id: s.id,+ text: s.suggestedText,+ topicName: s.topicName ?? undefined,+ estVolume: s.estVolume ?? undefined,+ })),+ )+ .catch(() => [] as PromptOpportunity[]),+ ]);+ return { topics, prompts };+}+/** Cheap existence check for a brand's (non-shopping) prompt_results — counts, no rows. */async function getBrandResultsTotal(brandId: string): Promise<number> {const supabase = await createClient();@@ -431,6 +490,7 @@ export interface InsightsData {sov: ShareOfVoiceData;trackedPrompts: TrackedPromptsKpi;filterOptions: InsightsFilterOptions;+ recommendations: InsightsRecommendations;hasAnyData: boolean;}@@ -465,15 +525,23 @@ export async function getInsightsData(dateTo: opts.dateTo,};- const [summary, competitors, sov, trackedPrompts, filterOptions, unfilteredTotal] =- await Promise.all([- getInsightsSummary(brandId, filterOpts),- getCompetitorComparison(brandId, filterOpts),- getShareOfVoiceData(brandId, filterOpts),- getTrackedPromptsKpi(brandId, filterOpts),- getInsightsFilterOptions(brandId),- opts.checkUnfiltered ? getBrandResultsTotal(brandId) : Promise.resolve(null),- ]);+ const [+ summary,+ competitors,+ sov,+ trackedPrompts,+ filterOptions,+ recommendations,+ unfilteredTotal,+ ] = await Promise.all([+ getInsightsSummary(brandId, filterOpts),+ getCompetitorComparison(brandId, filterOpts),+ getShareOfVoiceData(brandId, filterOpts),+ getTrackedPromptsKpi(brandId, filterOpts),+ getInsightsFilterOptions(brandId),+ getInsightsRecommendations(brandId),+ opts.checkUnfiltered ? getBrandResultsTotal(brandId) : Promise.resolve(null),+ ]);// insights_aggregates counts the same filtered set the summary shows, so it// stands in for the removed results fetch when no unfiltered check ran.@@ -485,6 +553,7 @@ export async function getInsightsData(sov,trackedPrompts,filterOptions,+ recommendations,hasAnyData,};}