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(prompts): move Topics into the Prompts area as its Topics tab (#1107)

Cihan139e9b15f803
diff --git a/docs/concepts/topics-and-prompts.mdx b/docs/concepts/topics-and-prompts.mdx
index 88e6b00f9..8a22e4795 100644
--- a/docs/concepts/topics-and-prompts.mdx
+++ b/docs/concepts/topics-and-prompts.mdx
@@ -28,7 +28,7 @@ Topics serve three purposes:
<Steps>
<Step title="Aggregate analysis">
- The Topics page shows visibility per topic, so you spot which themes your brand owns and which it's losing.
+ The Topics view (Prompts → Topics) shows visibility per topic, so you spot which themes your brand owns and which it's losing.
</Step>
<Step title="Content planning">
Content briefs are generated per topic, ensuring your editorial output covers your weakest themes first.
@@ -51,7 +51,7 @@ Three sources:
Two paths:
- **Auto-created from suggestions** — when a new prompt suggestion comes with a topic label that doesn't exist for your brand yet, accepting the prompt creates the topic too.
-- **Manual** — you can rename, merge, or create topics on the Topics page. A prompt can belong to one topic at a time.
+- **Manual** — you can rename, merge, or create topics in the Topics view. A prompt can belong to one topic at a time.
## Practical workflow
diff --git a/docs/guides/topics.mdx b/docs/guides/topics.mdx
index a8b0e73c6..8a1e99935 100644
--- a/docs/guides/topics.mdx
+++ b/docs/guides/topics.mdx
@@ -3,13 +3,13 @@ title: "Topics"
description: "Cluster prompts by theme and see which areas your brand wins or loses."
---
-## What is the Topics page?
+## What is the Topics view?
-The **Topics** page (`/dashboard/topics`) groups your tracked prompts by theme so you can see AEO performance at a higher level than individual prompts. Each topic shows:
+The **Topics** view (Prompts → Topics, `/dashboard/prompts/topics`; the old `/dashboard/topics` address redirects there) groups your tracked prompts by theme so you can see AEO performance at a higher level than individual prompts. Each topic shows:
- Topic name and prompt count
- Average visibility score across the topic's prompts
-- 7-day delta
+- Change against the window of the same length just before (the date range offers 24h, 7d, 30d, 90d or custom, and opens on 24 hours)
- Top competitor cited within the topic
- One-click drill-down into the topic detail page
@@ -29,7 +29,7 @@ Clicking into a topic shows:
## Editing topics
-From the Topics page you can:
+From the Topics view you can:
- **Rename** a topic (the underlying prompts stay attached)
- **Merge** two topics — useful when AI suggestions create slightly different labels for the same theme
- **Delete** a topic (prompts become un-categorized)
diff --git a/web/messages/en.json b/web/messages/en.json
index e00fc61cf..67267ce23 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -51,7 +51,6 @@
"insights": "Visibility",
"traffic": "AI Traffic Analytics",
"prompts": "Prompts",
- "topics": "Topics",
"content": "Content",
"audit": "Site Audit",
"competitors": "Competitors",
@@ -68,6 +67,7 @@
"feedback": "Send feedback",
"trackedPrompts": "Tracked Prompts",
"promptSuggestions": "Prompt Suggestions",
+ "topics": "Topics",
"queryFanouts": "Query Fan-outs",
"promptsInsights": "Insights",
"toggleSubmenu": "Show or hide {label}"
@@ -2443,8 +2443,6 @@
"failedToAddTopic": "Failed to add topic",
"noBrandTitle": "No brand selected",
"noBrandBody": "Select a brand from the top switcher to view topic analytics.",
- "title": "Topics",
- "description": "Topic-level analytics across all tracked prompts",
"exportHint": "No topics yet - add topics or run a tracking job first.",
"manageTopics": "Manage topics",
"kpi": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx
index e385206af..07e568823 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx
@@ -82,7 +82,10 @@ export function TopicHeatmap({
{shown.map((row) => (
<tr key={row.topicId} className="border-b last:border-b-0">
<td className="truncate py-1.5 pr-3 font-medium" title={row.name}>
- <Link href={`/dashboard/topics/${row.topicId}`} className="hover:underline">
+ <Link
+ href={`/dashboard/prompts/topics/${row.topicId}`}
+ className="hover:underline"
+ >
{row.name}
</Link>
</td>
@@ -90,7 +93,7 @@ export function TopicHeatmap({
<td key={columns[i].key} className="px-1 py-1.5">
{/* The topic name is the keyboard stop; cells are a mouse shortcut to it. */}
<Link
- href={`/dashboard/topics/${row.topicId}`}
+ href={`/dashboard/prompts/topics/${row.topicId}`}
tabIndex={-1}
title={t('openTopic', { topic: row.name })}
className={cn(
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx
similarity index 100%
rename from web/src/app/[locale]/(dashboard)/dashboard/topics/_suggestions-card.tsx
rename to web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx
new file mode 100644
index 000000000..0ce9cf894
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx
@@ -0,0 +1,773 @@
+'use client';
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslations } from 'next-intl';
+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 { customUtcWindow } from '@/lib/topic-trend';
+import type { PromptRange, PromptRangePreset } from '@/config/prompt-options';
+import { TopicSuggestionsCard } from './_topic-suggestions-card';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { createTopic } from '@/lib/actions/topic';
+import { toast } from 'sonner';
+import { Input } from '@/components/ui/input';
+import { Loader2, Plus } from 'lucide-react';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Badge } from '@/components/ui/badge';
+import { Button, buttonVariants } from '@/components/ui/button';
+import {
+ AlertCircle,
+ ArrowRight,
+ ChevronDown,
+ ChevronUp,
+ Download,
+ Flame,
+ Layers,
+ Minus,
+ RotateCw,
+ Settings2,
+ Tag,
+ TrendingDown,
+ TrendingUp,
+ Trophy,
+} from 'lucide-react';
+import { cn } from '@/lib/utils';
+import { toCsv } from '@/lib/csv';
+import { formatRelative } from '@/lib/format-relative';
+import { compareNullsLast, type SortDir } from './prompt-sort';
+
+// ─── Helpers ─────────────────────────────────────────────────────────────
+
+function visibilityBarColor(score: number) {
+ if (score >= 75) return 'bg-emerald-500';
+ if (score >= 50) return 'bg-amber-500';
+ if (score >= 25) return 'bg-orange-500';
+ return 'bg-rose-500';
+}
+
+function visibilityTextColor(score: number) {
+ if (score >= 75) return 'text-emerald-600 dark:text-emerald-400';
+ if (score >= 50) return 'text-amber-600 dark:text-amber-400';
+ if (score >= 25) return 'text-orange-600 dark:text-orange-400';
+ return 'text-rose-600 dark:text-rose-400';
+}
+
+const TOPIC_EXPORT_HEADERS = [
+ 'topic',
+ 'prompt_count',
+ 'visibility_rate',
+ 'visible_prompts',
+ 'active_prompts',
+ 'visibility_change',
+ 'total_mentions',
+ 'total_citations',
+ 'share_of_voice',
+ 'top_competitor',
+ 'top_competitor_sov',
+ 'last_run_at',
+];
+
+// ─── Sparkline ───────────────────────────────────────────────────────────
+
+function Sparkline({ points }: { points: number[] }) {
+ if (!points.length) return null;
+ const width = 80;
+ const height = 24;
+ const max = Math.max(...points, 1);
+ const min = Math.min(...points);
+ const range = max - min || 1;
+ const step = width / Math.max(points.length - 1, 1);
+
+ const path = points
+ .map((p, i) => {
+ const x = i * step;
+ const y = height - ((p - min) / range) * height;
+ return `${i === 0 ? 'M' : 'L'}${x.toFixed(2)},${y.toFixed(2)}`;
+ })
+ .join(' ');
+
+ const last = points[points.length - 1];
+ const first = points[0];
+ const trendUp = last >= first;
+
+ return (
+ <svg width={width} height={height} className="inline-block">
+ <path
+ d={path}
+ fill="none"
+ strokeWidth={1.5}
+ className={trendUp ? 'stroke-emerald-500' : 'stroke-rose-500'}
+ />
+ </svg>
+ );
+}
+
+// ─── KPI Card ────────────────────────────────────────────────────────────
+
+function KpiCard({
+ icon: Icon,
+ label,
+ value,
+ sub,
+ tone = 'neutral',
+}: {
+ icon: React.ComponentType<{ className?: string }>;
+ label: string;
+ value: string | number;
+ sub?: string;
+ tone?: 'neutral' | 'positive' | 'negative' | 'warning';
+}) {
+ const toneClasses: Record<string, string> = {
+ neutral: 'text-foreground',
+ positive: 'text-emerald-600 dark:text-emerald-400',
+ negative: 'text-rose-600 dark:text-rose-400',
+ warning: 'text-amber-600 dark:text-amber-400',
+ };
+ return (
+ <Card>
+ <CardContent className="pt-6 pb-5">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2">
+ <Icon className="h-3.5 w-3.5" />
+ {label}
+ </div>
+ <div className={cn('text-2xl font-semibold tabular-nums', toneClasses[tone])}>{value}</div>
+ {sub && <p className="text-xs text-muted-foreground mt-1 truncate">{sub}</p>}
+ </CardContent>
+ </Card>
+ );
+}
+
+// ─── Sortable leaderboard columns ─────────────────────────────────────────
+
+type TopicSortKey = 'prompts' | 'visibility' | 'sov' | 'mentions' | 'citations' | 'lastRun';
+
+/**
+ * Clickable header that toggles asc⇄desc for its column and marks the active
+ * sort with a chevron. Mirrors the Prompts page's SortableHead (#597).
+ */
+function SortableHead({
+ children,
+ className,
+ sortKey,
+ activeSort,
+ dir,
+ onSort,
+}: {
+ children: React.ReactNode;
+ className?: string;
+ sortKey: TopicSortKey;
+ activeSort: TopicSortKey;
+ dir: SortDir;
+ onSort: (key: TopicSortKey) => void;
+}) {
+ const active = activeSort === sortKey;
+ return (
+ <TableHead
+ className={className}
+ aria-sort={active ? (dir === 'asc' ? 'ascending' : 'descending') : 'none'}
+ >
+ <button
+ type="button"
+ onClick={() => onSort(sortKey)}
+ aria-label={`Sort by ${typeof children === 'string' ? children : sortKey}`}
+ className={cn(
+ 'inline-flex items-center gap-1 transition-colors hover:text-foreground',
+ active ? 'text-foreground' : 'text-muted-foreground',
+ )}
+ >
+ {children}
+ {active &&
+ (dir === 'asc' ? (
+ <ChevronUp className="h-3.5 w-3.5" />
+ ) : (
+ <ChevronDown className="h-3.5 w-3.5" />
+ ))}
+ </button>
+ </TableHead>
+ );
+}
+
+// ─── Tab ─────────────────────────────────────────────────────────────────
+
+/**
+ * The Prompts page's Topics tab: the topic leaderboard, over the
+ * page's date range (Location doesn't apply). Loaded only when the tab is
+ * shown, as its own chunk, so it costs the other tabs nothing.
+ */
+export function TopicsTab({
+ range,
+ rangePreset,
+ customFrom,
+ customTo,
+ onLoaded,
+}: {
+ /** The page's range resolved; null for a custom range with no dates yet. */
+ range: PromptRange | null;
+ rangePreset: PromptRangePreset;
+ customFrom: string;
+ customTo: string;
+ /** Called once the first read has finished, so the page can load the rest. */
+ onLoaded?: () => void;
+}) {
+ const t = useTranslations('topics');
+ const common = useTranslations('common');
+ const activeBrandId = useBrandStore((s) => s.activeBrandId);
+ 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);
+ const [error, setError] = useState<string | null>(null);
+ const [isAdding, setIsAdding] = useState(false);
+ const [newName, setNewName] = useState('');
+ const [open, setOpen] = useState(false);
+ // Default matches the previous hard-coded order (#597): visibility descending.
+ const [sortKey, setSortKey] = useState<TopicSortKey>('visibility');
+ const [sortDir, setSortDir] = useState<SortDir>('desc');
+ // Only the latest request may fill the table: a slow 90-day read must not
+ // land after the 24-hour one picked since.
+ const requestRef = useRef(0);
+ const onLoadedRef = useRef(onLoaded);
+ useEffect(() => {
+ onLoadedRef.current = onLoaded;
+ }, [onLoaded]);
+
+ const handleSort = useCallback(
+ (key: TopicSortKey) => {
+ setSortDir((prevDir) => (sortKey === key && prevDir === 'desc' ? 'asc' : 'desc'));
+ setSortKey(key);
+ },
+ [sortKey],
+ );
+
+ const loadData = useCallback(async () => {
+ if (!activeBrandId) {
+ setTopics([]);
+ setLoading(false);
+ return;
+ }
+ if (!range) return;
+ const request = ++requestRef.current;
+ setLoading(true);
+ setError(null);
+ try {
+ const window =
+ rangePreset === 'custom'
+ ? customUtcWindow(customFrom, customTo, range)
+ : { from: range.from, to: range.to };
+ const data = await getTopicsOverview(activeBrandId, window);
+ if (request !== requestRef.current) return;
+ setTopics(data.topics);
+ setUnassignedPromptCount(data.unassignedPromptCount);
+ } catch (err) {
+ if (request !== requestRef.current) return;
+ console.error('Failed to load topics overview', err);
+ setError(err instanceof Error ? err.message : t('loadError'));
+ toast.error(t('loadError'));
+ } finally {
+ if (request === requestRef.current) setLoading(false);
+ onLoadedRef.current?.();
+ }
+ }, [activeBrandId, range, rangePreset, customFrom, customTo, t]);
+
+ useEffect(() => {
+ loadData();
+ }, [loadData]);
+
+ const sortedTopics = useMemo(() => {
+ const valueOf = (row: TopicOverviewRow): number | null => {
+ switch (sortKey) {
+ case 'prompts':
+ return row.promptCount;
+ case 'visibility':
+ return row.visibilityRate;
+ case 'sov':
+ return row.shareOfVoice;
+ case 'mentions':
+ return row.totalMentions;
+ case 'citations':
+ return row.totalCitations;
+ case 'lastRun':
+ return row.lastRunAt ? new Date(row.lastRunAt).getTime() : null;
+ }
+ };
+ return [...topics].sort((a, b) => compareNullsLast(valueOf(a), valueOf(b), sortDir));
+ }, [topics, sortKey, sortDir]);
+
+ const kpis = useMemo(() => {
+ if (topics.length === 0) return null;
+ const withData = topics.filter((t) => t.visibilityRate > 0);
+ if (withData.length === 0) {
+ return {
+ total: topics.length,
+ best: null as TopicOverviewRow | null,
+ weakest: null as TopicOverviewRow | null,
+ gainer: null as TopicOverviewRow | null,
+ };
+ }
+ const best = [...withData].sort((a, b) => b.visibilityRate - a.visibilityRate)[0];
+ const weakest = [...withData].sort((a, b) => a.visibilityRate - b.visibilityRate)[0];
+ const withChange = topics.filter((t) => t.visibilityChange !== null);
+ const gainer = withChange.length
+ ? [...withChange].sort((a, b) => (b.visibilityChange ?? 0) - (a.visibilityChange ?? 0))[0]
+ : null;
+
+ return {
+ total: topics.length,
+ best,
+ weakest,
+ gainer,
+ };
+ }, [topics]);
+
+ const canExport = !loading && topics.length > 0;
+
+ const handleExportCsv = useCallback(() => {
+ if (!canExport) return;
+
+ const rows = topics.map((t) => ({
+ topic: t.name,
+ prompt_count: t.promptCount,
+ visibility_rate: t.visibilityRate,
+ visible_prompts: t.visiblePrompts,
+ active_prompts: t.activePrompts,
+ visibility_change: t.visibilityChange ?? '',
+ total_mentions: t.totalMentions,
+ total_citations: t.totalCitations,
+ share_of_voice: t.shareOfVoice,
+ top_competitor: t.topCompetitor?.name ?? '',
+ top_competitor_sov: t.topCompetitor?.sov ?? '',
+ last_run_at: t.lastRunAt ?? '',
+ }));
+
+ const csv = toCsv(rows, TOPIC_EXPORT_HEADERS);
+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ const date = new Date().toISOString().slice(0, 10);
+ const slug = activeBrand?.slug ?? 'brand';
+
+ link.href = url;
+ link.download = `ansvisor_${slug}_topics_${rangePreset}_${date}.csv`;
+ link.click();
+
+ URL.revokeObjectURL(url);
+ }, [activeBrand?.slug, canExport, rangePreset, topics]);
+
+ if (!activeBrandId) {
+ return (
+ <div className="flex h-[60vh] items-center justify-center">
+ <Card className="max-w-md">
+ <CardContent className="pt-6 text-center">
+ <Tag className="mx-auto h-10 w-10 text-muted-foreground/50" />
+ <h2 className="mt-3 text-base font-semibold">{t('noBrandTitle')}</h2>
+ <p className="mt-1 text-sm text-muted-foreground">{t('noBrandBody')}</p>
+ </CardContent>
+ </Card>
+ </div>
+ );
+ }
+
+ const handleAddTopic = async () => {
+ if (isAdding) return;
+ const name = newName.trim();
+ if (!name) return;
+ if (topics.some((t) => t.name.toLowerCase() === name.toLowerCase())) {
+ toast.error(t('topicAlreadyExists'));
+ return;
+ }
+ setIsAdding(true);
+ try {
+ const added = await createTopic(activeBrandId, name);
+ await loadData();
+ setNewName('');
+ setOpen(false);
+ toast.success(t('topicAdded', { name: added.name }));
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : t('failedToAddTopic'));
+ } finally {
+ setIsAdding(false);
+ }
+ };
+
+ return (
+ <div className="space-y-6">
+ {/* Actions: the tab sits under the Prompts header, which names the area. */}
+ <div className="flex items-center justify-end gap-4 flex-wrap">
+ <div className="flex items-center gap-2">
+ <span title={!canExport ? t('exportHint') : undefined}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="gap-2"
+ onClick={handleExportCsv}
+ disabled={!canExport}
+ >
+ <Download className="h-4 w-4" />
+ {common('exportCsv')}
+ </Button>
+ </span>
+ <Link
+ href={`/dashboard/brands/${activeBrandId}/topics`}
+ className={buttonVariants({ variant: 'outline', size: 'sm' })}
+ >
+ <Settings2 className="h-4 w-4" />
+ {t('manageTopics')}
+ </Link>
+ {canManage && (
+ <>
+ <Button size="sm" onClick={() => setOpen(true)}>
+ <Plus className="mr-2 h-4 w-4" />
+ {t('addTopic')}
+ </Button>
+ <Dialog
+ open={open}
+ onOpenChange={(value) => {
+ setOpen(value);
+ if (!value) {
+ setNewName('');
+ }
+ }}
+ >
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>{t('addTopic')}</DialogTitle>
+ <DialogDescription>{t('addTopicDescription')}</DialogDescription>
+ </DialogHeader>
+ <div className="flex gap-2">
+ <Input
+ placeholder="e.g. Industry, Comparison..."
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && newName.trim() && handleAddTopic()}
+ className="flex-1"
+ />
+ </div>
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" />}>
+ {common('cancel')}
+ </DialogClose>
+ <Button
+ variant="default"
+ onClick={handleAddTopic}
+ disabled={isAdding || !newName.trim()}
+ className="gap-1.5 shrink-0"
+ >
+ {isAdding ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Plus className="h-4 w-4" />
+ )}
+ {t('addTopic')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* KPIs */}
+ {loading ? (
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-[104px]" />
+ ))}
+ </div>
+ ) : kpis ? (
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
+ <KpiCard
+ icon={Layers}
+ label={t('kpi.trackedTopics')}
+ value={kpis.total}
+ sub={
+ unassignedPromptCount > 0
+ ? t('kpi.unassignedPrompts', { count: unassignedPromptCount })
+ : t('kpi.allCategorised')
+ }
+ />
+ <KpiCard
+ icon={Trophy}
+ label={t('kpi.bestPerformer')}
+ value={kpis.best ? kpis.best.visibilityRate : '—'}
+ sub={kpis.best?.name ?? t('kpi.noDataYet')}
+ tone="positive"
+ />
+ <KpiCard
+ icon={TrendingDown}
+ label={t('kpi.biggestGap')}
+ value={kpis.weakest ? kpis.weakest.visibilityRate : '—'}
+ sub={kpis.weakest?.name ?? t('kpi.noDataYet')}
+ tone="warning"
+ />
+ <KpiCard
+ icon={Flame}
+ label={t('kpi.topMover')}
+ value={
+ kpis.gainer && kpis.gainer.visibilityChange !== null
+ ? t('ptsChange', {
+ value: `${kpis.gainer.visibilityChange > 0 ? '+' : ''}${kpis.gainer.visibilityChange.toFixed(1)}`,
+ })
+ : '—'
+ }
+ sub={kpis.gainer?.name ?? t('kpi.notEnoughData')}
+ tone={
+ kpis.gainer?.visibilityChange && kpis.gainer.visibilityChange >= 0
+ ? 'positive'
+ : 'negative'
+ }
+ />
+ </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">
+ <CardTitle className="text-sm font-medium">{t('leaderboardTitle')}</CardTitle>
+ <p className="text-xs text-muted-foreground">{t('leaderboardHint')}</p>
+ </CardHeader>
+ <CardContent className="p-0">
+ {loading ? (
+ <div className="p-6 space-y-2">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <Skeleton key={i} className="h-12" />
+ ))}
+ </div>
+ ) : error ? (
+ <div className="py-14 text-center text-sm">
+ <AlertCircle className="mx-auto h-9 w-9 text-destructive/60" />
+ <p className="mt-2 font-medium">{t('loadError')}</p>
+ <Button
+ className="mt-4 gap-2"
+ size="sm"
+ variant="outline"
+ onClick={() => void loadData()}
+ >
+ <RotateCw className="h-4 w-4" />
+ {common('retry')}
+ </Button>
+ </div>
+ ) : topics.length === 0 ? (
+ <div className="py-14 text-center text-sm text-muted-foreground">
+ <Tag className="mx-auto h-9 w-9 text-muted-foreground/40" />
+ <p className="mt-2">{t('emptyTitle')}</p>
+ <p className="text-xs">{t('emptyBody')}</p>
+ {canManage && (
+ <Button className="mt-4" onClick={() => setOpen(true)}>
+ <Plus className="mr-2 h-4 w-4" />
+ {t('addTopic')}
+ </Button>
+ )}
+ </div>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="pl-6">{t('columns.topic')}</TableHead>
+ <SortableHead
+ className="text-right"
+ sortKey="prompts"
+ activeSort={sortKey}
+ dir={sortDir}
+ onSort={handleSort}
+ >
+ {t('columns.prompts')}
+ </SortableHead>
+ <SortableHead
+ sortKey="visibility"
+ activeSort={sortKey}
+ dir={sortDir}
+ onSort={handleSort}
+ >
+ {t('columns.visibility')}
+ </SortableHead>
+ <SortableHead
+ className="text-right"
+ sortKey="sov"
+ activeSort={sortKey}
+ dir={sortDir}
+ onSort={handleSort}
+ >
+ {t('columns.sov')}
+ </SortableHead>
+ <SortableHead
+ className="text-right"
+ sortKey="mentions"
+ activeSort={sortKey}
+ dir={sortDir}
+ onSort={handleSort}
+ >
+ {t('columns.mentions')}
+ </SortableHead>
+ <SortableHead
+ className="text-right"
+ sortKey="citations"
+ activeSort={sortKey}
+ dir={sortDir}
+ onSort={handleSort}
+ >
+ {t('columns.citations')}
+ </SortableHead>
+ <TableHead>{t('columns.trend')}</TableHead>
+ <TableHead>{t('columns.topCompetitor')}</TableHead>
+ <SortableHead
+ className="text-right"
+ sortKey="lastRun"
+ activeSort={sortKey}
+ dir={sortDir}
+ onSort={handleSort}
+ >
+ {t('columns.lastRun')}
+ </SortableHead>
+ <TableHead className="pr-6 text-right w-[40px]" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {sortedTopics.map((topic) => (
+ <TableRow key={topic.id} className="group hover:bg-muted/50">
+ <TableCell className="pl-6 font-medium text-sm">
+ <Link
+ href={`/dashboard/prompts/topics/${topic.id}`}
+ className="hover:underline"
+ >
+ {topic.name}
+ </Link>
+ </TableCell>
+ <TableCell className="text-right tabular-nums text-sm">
+ {topic.promptCount}
+ </TableCell>
+ <TableCell className="min-w-[160px]">
+ {topic.activePrompts > 0 ? (
+ <div
+ className="flex items-center gap-2"
+ title={t('appearedIn', {
+ visible: topic.visiblePrompts,
+ active: topic.activePrompts,
+ })}
+ >
+ <span
+ className={cn(
+ 'text-sm font-semibold tabular-nums w-11',
+ visibilityTextColor(topic.visibilityRate),
+ )}
+ >
+ {topic.visibilityRate}
+ </span>
+ <div className="h-1.5 flex-1 max-w-[90px] rounded-full bg-muted overflow-hidden">
+ <div
+ className={cn(
+ 'h-full rounded-full',
+ visibilityBarColor(topic.visibilityRate),
+ )}
+ style={{
+ width: `${Math.min(100, topic.visibilityRate)}%`,
+ }}
+ />
+ </div>
+ </div>
+ ) : (
+ <span className="text-xs text-muted-foreground">—</span>
+ )}
+ </TableCell>
+ <TableCell className="text-right tabular-nums text-sm">
+ {topic.shareOfVoice > 0 ? `${topic.shareOfVoice}%` : '—'}
+ </TableCell>
+ <TableCell className="text-right tabular-nums text-sm">
+ {topic.totalMentions.toLocaleString()}
+ </TableCell>
+ <TableCell className="text-right tabular-nums text-sm">
+ {topic.totalCitations.toLocaleString()}
+ </TableCell>
+ <TableCell>
+ {/* Under two days there is no line, only the change. */}
+ {topic.trendSparkline.some((v) => v > 0) ||
+ topic.visibilityChange !== null ? (
+ <div className="flex items-center gap-2">
+ {topic.trendSparkline.some((v) => v > 0) && (
+ <Sparkline points={topic.trendSparkline} />
+ )}
+ {topic.visibilityChange !== null && topic.visibilityChange !== 0 && (
+ <span
+ className={cn(
+ 'text-xs font-medium tabular-nums',
+ topic.visibilityChange > 0
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : 'text-rose-600 dark:text-rose-400',
+ )}
+ >
+ {topic.visibilityChange > 0 ? (
+ <TrendingUp className="h-3 w-3 inline mr-0.5" />
+ ) : (
+ <TrendingDown className="h-3 w-3 inline mr-0.5" />
+ )}
+ {t('ptsChange', {
+ value: Math.abs(topic.visibilityChange).toFixed(1),
+ })}
+ </span>
+ )}
+ {topic.visibilityChange === 0 && (
+ <Minus className="h-3 w-3 text-muted-foreground" />
+ )}
+ </div>
+ ) : (
+ <span className="text-xs text-muted-foreground">—</span>
+ )}
+ </TableCell>
+ <TableCell>
+ {topic.topCompetitor ? (
+ <Badge variant="outline" className="text-[10px]">
+ {topic.topCompetitor.name} · {topic.topCompetitor.sov}%
+ </Badge>
+ ) : (
+ <span className="text-xs text-muted-foreground">—</span>
+ )}
+ </TableCell>
+ <TableCell className="text-right text-xs text-muted-foreground">
+ {formatRelative(topic.lastRunAt, common)}
+ </TableCell>
+ <TableCell className="pr-6 text-right">
+ <Link
+ href={`/dashboard/prompts/topics/${topic.id}`}
+ className="inline-flex opacity-0 group-hover:opacity-100 transition-opacity"
+ aria-label={t('openDetails')}
+ >
+ <ArrowRight className="h-4 w-4 text-muted-foreground" />
+ </Link>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 6a54746c8..70e114376 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -14,6 +14,12 @@ const PlatformVolumeChart = dynamic(() => import('./_charts').then((m) => m.Plat
loading: () => <Skeleton className="h-64 w-full" />,
});
import { QueryFanoutTab } from './_fanout-tab';
+// The Topics tab loads as its own chunk, only when it is shown, so it
+// adds nothing to the other tabs' first load.
+const TopicsTab = dynamic(() => import('./_topics-tab').then((m) => m.TopicsTab), {
+ ssr: false,
+ loading: () => <Skeleton className="h-64 w-full" />,
+});
import {
PromptUsageCards,
countByStatus,
@@ -352,7 +358,7 @@ const PROMPT_EXPORT_HINT = 'No prompts yet - add prompts first.';
// ─── Helpers ──────────────────────────────────────────────────────────────────
-const VALID_TABS = ['all', 'fanout', 'insights'] as const;
+const VALID_TABS = ['all', 'topics', 'fanout', 'insights'] as const;
/**
* The window a tab opens on. Query Fan-out opens on 7 days: one day of
@@ -1286,6 +1292,7 @@ export default function PromptsPage() {
const activeBrandId = useBrandStore((s) => s.activeBrandId);
const tCommon = useTranslations('common');
+ const tNav = useTranslations('nav');
const activeBrand = useBrandStore(
(s) => s.brands.find((brand) => brand.id === s.activeBrandId) ?? null,
);
@@ -1298,7 +1305,7 @@ export default function PromptsPage() {
const locationQuota = useMemo(() => (usage ? locationQuotaFromUsage(usage) : null), [usage]);
const [statusFilter, setStatusFilter] = useState<PromptStatusFilter>('active');
const searchParams = useSearchParams();
- // On /dashboard/prompts/{tracked,suggestions,fan-outs,insights} the route
+ // On /dashboard/prompts/{tracked,suggestions,topics,fan-outs,insights} the route
// names the view (PROMPT-001); ?tab= / ?view= are the older links' shape.
const section = sectionFromPath(usePathname());
@@ -1309,6 +1316,11 @@ export default function PromptsPage() {
return 'all';
})();
const [tab, setTab] = useState<TabId>(initialTab);
+ // Opened on Topics, the page holds back what only the other tabs show (the
+ // table, its locations, the volume run's status) until the topics are in or
+ // another tab is opened: server actions queue one behind another, and the
+ // table's read would otherwise make the topics wait. Once wanted, it stays.
+ const [promptDataWanted, setPromptDataWanted] = useState(initialTab !== 'topics');
// The Prompts tab holds two views of the same roster: what is tracked, and
// what could be. A sub-tab rather than a fourth top-level tab, because the
@@ -1368,35 +1380,80 @@ export default function PromptsPage() {
// the URL with no server request; Next's router syncs with the History API.
//
// The tab and view live in the path (PROMPT-001): /dashboard/prompts/tracked,
- // /suggestions, /fan-outs, /insights — the routes the sidebar's Prompts
- // submenu links to, so the sidebar and these tabs always agree. The path is
- // rewritten in place under any locale prefix.
+ // /suggestions, /topics, /fan-outs, /insights — the routes the sidebar's
+ // Prompts submenu links to, so the sidebar and these tabs always agree. The
+ // path is rewritten in place under any locale prefix.
+ const writeUrl = useCallback(
+ (next: {
+ tab: TabId;
+ view: PromptsView;
+ rangePreset: PromptRangePreset;
+ customFrom: string;
+ customTo: string;
+ regionFilter: string;
+ }) => {
+ // The default range stays out of the URL so shared links keep their
+ // existing shape unless the user actually picked a different window.
+ const want: Record<string, string | null> = {
+ range: next.rangePreset === defaultRangeFor(next.tab) ? null : next.rangePreset,
+ from: next.rangePreset === 'custom' && next.customFrom ? next.customFrom : null,
+ to: next.rangePreset === 'custom' && next.customTo ? next.customTo : null,
+ region: next.regionFilter || null,
+ tab: null,
+ view: null,
+ };
+ const { pathname, search, hash } = window.location;
+ const at = pathname.indexOf(PROMPTS_BASE);
+ const wantPath = `${at > 0 ? pathname.slice(0, at) : ''}${sectionFor(next.tab, next.view).href}`;
+ const params = new URLSearchParams(search);
+ if (pathname === wantPath && Object.entries(want).every(([k, v]) => params.get(k) === v)) {
+ return;
+ }
+ for (const [k, v] of Object.entries(want)) {
+ if (v) params.set(k, v);
+ else params.delete(k);
+ }
+ const query = params.toString();
+ // Keep the hash: deep links like #prompt-opportunities must keep their anchor.
+ window.history.replaceState(null, '', `${wantPath}${query ? `?${query}` : ''}${hash}`);
+ },
+ [],
+ );
useEffect(() => {
- // The default range stays out of the URL so shared links keep their
- // existing shape unless the user actually picked a different window.
- const want: Record<string, string | null> = {
- range: rangePreset === defaultRangeFor(tab) ? null : rangePreset,
- from: rangePreset === 'custom' && customFrom ? customFrom : null,
- to: rangePreset === 'custom' && customTo ? customTo : null,
- region: regionFilter || null,
- tab: null,
- view: null,
- };
- const { pathname, search, hash } = window.location;
- const at = pathname.indexOf(PROMPTS_BASE);
- const wantPath = `${at > 0 ? pathname.slice(0, at) : ''}${sectionFor(tab, view).href}`;
- const params = new URLSearchParams(search);
- if (pathname === wantPath && Object.entries(want).every(([k, v]) => params.get(k) === v)) {
- return;
- }
- for (const [k, v] of Object.entries(want)) {
- if (v) params.set(k, v);
- else params.delete(k);
- }
- const query = params.toString();
- // Keep the hash: deep links like #prompt-opportunities must keep their anchor.
- window.history.replaceState(null, '', `${wantPath}${query ? `?${query}` : ''}${hash}`);
- }, [tab, view, rangePreset, customFrom, customTo, regionFilter, searchParams]);
+ writeUrl({ tab, view, rangePreset, customFrom, customTo, regionFilter });
+ }, [tab, view, rangePreset, customFrom, customTo, regionFilter, searchParams, writeUrl]);
+
+ /**
+ * Move to another tab or list view, writing its route first.
+ *
+ * Next routes a replaceState through its action queue (a "restore"), and in
+ * Next 16 a restore that lands while a server action is in flight leaves
+ * the queue pointing at the discarded action: actions queued after it never
+ * run, and the table spins forever. The tab about to show fires its own
+ * server actions as it mounts, before the effect above would rewrite the
+ * route, so the route is written here, on an idle queue, ahead of them.
+ */
+ const showSection = useCallback(
+ (nextTab: TabId, nextView: PromptsView) => {
+ // A window still on this tab's default wasn't picked by the user, so it
+ // follows the next tab's own (Query Fan-out opens on 7 days).
+ const nextRange =
+ rangePreset === defaultRangeFor(tab) ? defaultRangeFor(nextTab) : rangePreset;
+ writeUrl({
+ tab: nextTab,
+ view: nextView,
+ rangePreset: nextRange,
+ customFrom,
+ customTo,
+ regionFilter,
+ });
+ setRangePreset(nextRange);
+ setView(nextView);
+ setTab(nextTab);
+ if (nextTab !== 'topics') setPromptDataWanted(true);
+ },
+ [tab, rangePreset, customFrom, customTo, regionFilter, writeUrl],
+ );
// 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
@@ -1453,12 +1510,13 @@ export default function PromptsPage() {
);
useEffect(() => {
+ if (!promptDataWanted) return undefined;
let cancelled = false;
loadData(() => cancelled);
return () => {
cancelled = true;
};
- }, [loadData]);
+ }, [loadData, promptDataWanted]);
// After prompts are added, paused, resumed, deleted or retargeted: reload
// the table and the usage cards together.
@@ -1476,6 +1534,7 @@ export default function PromptsPage() {
setAvailableRegions([]);
return;
}
+ if (!promptDataWanted) return;
let cancelled = false;
getBrandFilterOptions(activeBrandId)
.then((options) => {
@@ -1486,7 +1545,7 @@ export default function PromptsPage() {
return () => {
cancelled = true;
};
- }, [activeBrandId]);
+ }, [activeBrandId, promptDataWanted]);
// A location that stops producing results must not keep filtering the
// table to nothing — fall back to the blended view.
@@ -1548,7 +1607,7 @@ export default function PromptsPage() {
* page's narration of it stops.
*/
useEffect(() => {
- if (!activeBrandId) return undefined;
+ if (!activeBrandId || !promptDataWanted) return undefined;
const brandId = activeBrandId;
const gen = ++analysisGenRef.current;
@@ -1576,7 +1635,7 @@ export default function PromptsPage() {
setAnalyzing(false);
setAnalysisProgress(null);
};
- }, [activeBrandId, watchVolumeAnalysis]);
+ }, [activeBrandId, promptDataWanted, watchVolumeAnalysis]);
/**
* Start a run, then follow it to the end.
@@ -1789,19 +1848,11 @@ export default function PromptsPage() {
</div>
</div>
- <Tabs
- value={tab}
- onValueChange={(v) => {
- const next = v as TabId;
- // A window still on this tab's default wasn't picked by the user,
- // so it follows the next tab's own (Query Fan-out opens on 7 days).
- if (rangePreset === defaultRangeFor(tab)) setRangePreset(defaultRangeFor(next));
- setTab(next);
- }}
- >
+ <Tabs value={tab} onValueChange={(v) => showSection(v as TabId, view)}>
<div className="flex items-center justify-between gap-4 flex-wrap">
<TabsList>
<TabsTrigger value="all">Prompts</TabsTrigger>
+ <TabsTrigger value="topics">{tNav('topics')}</TabsTrigger>
<TabsTrigger value="fanout">Query Fan-out</TabsTrigger>
<TabsTrigger value="insights">Insights</TabsTrigger>
</TabsList>
@@ -1865,7 +1916,7 @@ export default function PromptsPage() {
type="button"
role="tab"
aria-selected={view === id}
- onClick={() => setView(id)}
+ onClick={() => showSection(tab, id)}
className={cn(
'flex items-center gap-2 rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
view === id
@@ -1882,7 +1933,8 @@ export default function PromptsPage() {
{/* Filter bar — same shape and position as Visibility and Citations
(#713). It sits outside the tab panels because the range governs
- both All Prompts and Query Fan-out.
+ All Prompts, Topics and Query Fan-out. Location doesn't apply to
+ Topics, so it is left off there.
Hidden on Insights: that tab shows keyword volume estimates, which
carry no date dimension, so a range there would be a control that
changes nothing. */}
@@ -1898,7 +1950,7 @@ export default function PromptsPage() {
onToChange={setCustomTo}
/>
- {availableRegions.length > 1 && (
+ {availableRegions.length > 1 && tab !== 'topics' && (
<div>
<label className="mb-1.5 block text-xs font-medium text-muted-foreground">
Location
@@ -2007,6 +2059,19 @@ export default function PromptsPage() {
)}
</TabsContent>
+ {/* ─── Topics tab ───────────────────────────────────────────────── */}
+ <TabsContent value="topics" className="mt-4">
+ {tab === 'topics' && (
+ <TopicsTab
+ range={range}
+ rangePreset={rangePreset}
+ customFrom={customFrom}
+ customTo={customTo}
+ onLoaded={() => setPromptDataWanted(true)}
+ />
+ )}
+ </TabsContent>
+
{/* ─── Query Fan-out tab ───────────────────────────────────────── */}
<TabsContent value="fanout" className="mt-4">
{activeBrandId && (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/[id]/page.tsx
new file mode 100644
index 000000000..29d001854
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/[id]/page.tsx
@@ -0,0 +1,479 @@
+'use client';
+
+import { useCallback, useEffect, useRef, useState, use } from 'react';
+import { toast } from 'sonner';
+import { Link, useRouter } from '@/i18n/navigation';
+import { useBrandStore } from '@/stores/use-brand-store';
+import {
+ getTopicDetail,
+ type InsightsSummary,
+ type VisibilityTrendPoint,
+ type ShareOfVoiceData,
+ type CompetitorComparisonData,
+ type PromptResultWithText,
+} from '@/lib/actions/tracking';
+import type { Topic } from '@/types';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import {
+ AlertCircle,
+ ArrowLeft,
+ BarChart3,
+ Eye,
+ Quote,
+ RotateCw,
+ TrendingDown,
+ TrendingUp,
+ Zap,
+ Users,
+} from 'lucide-react';
+import { ShareOfVoicePlatformChart } from '../../../insights/_charts';
+import { cn } from '@/lib/utils';
+import dynamic from 'next/dynamic';
+const DynamicVisibilityTrendChart = dynamic(
+ () => import('./topic_charts').then((m) => m.VisibilityTrendChartView),
+ {
+ ssr: false,
+ loading: () => <Skeleton className="h-[260px] w-full" />,
+ },
+);
+
+function ChartContainer({
+ height,
+ children,
+}: {
+ height: number;
+ children: (width: number) => React.ReactNode;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [width, setWidth] = useState(0);
+
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const update = () => setWidth(el.clientWidth);
+ update();
+ const ro = new ResizeObserver(update);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+
+ return (
+ <div ref={ref} style={{ width: '100%', height }}>
+ {width > 0 && children(width)}
+ </div>
+ );
+}
+
+// ─── KPI Card ────────────────────────────────────────────────────────────
+
+function KpiCard({
+ icon: Icon,
+ label,
+ value,
+ change,
+ suffix,
+ hint,
+}: {
+ icon: React.ComponentType<{ className?: string }>;
+ label: string;
+ value: string | number;
+ change?: number | null;
+ suffix?: string;
+ hint?: string;
+}) {
+ return (
+ <Card title={hint}>
+ <CardContent className="pt-6 pb-5">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2">
+ <Icon className="h-3.5 w-3.5" />
+ {label}
+ </div>
+ <div className="flex items-baseline justify-between gap-2">
+ <div className="text-2xl font-semibold tabular-nums">
+ {value}
+ {suffix && (
+ <span className="text-sm font-normal text-muted-foreground ml-0.5">{suffix}</span>
+ )}
+ </div>
+ {change !== null && change !== undefined && change !== 0 && (
+ <span
+ className={cn(
+ 'flex items-center text-xs font-medium',
+ change > 0
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : change < 0
+ ? 'text-rose-600 dark:text-rose-400'
+ : 'text-muted-foreground',
+ )}
+ >
+ {change > 0 ? (
+ <TrendingUp className="h-3 w-3 mr-0.5" />
+ ) : change < 0 ? (
+ <TrendingDown className="h-3 w-3 mr-0.5" />
+ ) : null}
+ {change > 0 ? '+' : ''}
+ {change}
+ {suffix === '%' ? 'pts' : ''}
+ </span>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
+// ─── Visibility trend chart ───────────────────────────────────────────────
+
+function VisibilityTrendChart({ data }: { data: VisibilityTrendPoint[] }) {
+ if (data.length === 0) {
+ return (
+ <div className="flex h-[260px] items-center justify-center text-sm text-muted-foreground">
+ No data yet for this topic.
+ </div>
+ );
+ }
+ return (
+ <ChartContainer height={260}>
+ {(width) => <DynamicVisibilityTrendChart width={width} data={data} />}
+ </ChartContainer>
+ );
+}
+
+// ─── Page ────────────────────────────────────────────────────────────────
+
+export default function TopicDetailPage({ params }: { params: Promise<{ id: string }> }) {
+ const { id: topicId } = use(params);
+ const router = useRouter();
+ const activeBrandId = useBrandStore((s) => s.activeBrandId);
+
+ const [topic, setTopic] = useState<Topic | null>(null);
+ const [summary, setSummary] = useState<InsightsSummary | null>(null);
+ const [trend, setTrend] = useState<VisibilityTrendPoint[]>([]);
+ const [sov, setSov] = useState<ShareOfVoiceData | null>(null);
+ const [competitors, setCompetitors] = useState<CompetitorComparisonData | null>(null);
+ const [results, setResults] = useState<PromptResultWithText[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const loadData = useCallback(async () => {
+ if (!activeBrandId || !topicId) return;
+ setLoading(true);
+ setError(null);
+ try {
+ // One server action (#312): Next.js runs server actions sequentially, so
+ // the old six-call Promise.all paid the sum of all six. This is one round
+ // trip whose body runs the work in a real server-side Promise.all.
+ const detail = await getTopicDetail(activeBrandId, topicId);
+ setTopic(detail.topic);
+ setSummary(detail.summary);
+ setTrend(detail.trend);
+ setSov(detail.sov);
+ setCompetitors(detail.competitors);
+ setResults(detail.results);
+ } catch (err) {
+ console.error('Failed to load topic detail', err);
+ setError(err instanceof Error ? err.message : 'Failed to load this topic');
+ toast.error('Failed to load this topic');
+ } finally {
+ setLoading(false);
+ }
+ }, [activeBrandId, topicId]);
+
+ useEffect(() => {
+ loadData();
+ }, [loadData]);
+
+ if (!activeBrandId) {
+ return (
+ <div className="flex h-[60vh] items-center justify-center">
+ <Card className="max-w-md">
+ <CardContent className="pt-6 text-center">
+ <h2 className="text-base font-semibold">No brand selected</h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ Select a brand from the top switcher first.
+ </p>
+ </CardContent>
+ </Card>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex h-[60vh] items-center justify-center">
+ <Card className="max-w-md">
+ <CardContent className="pt-6 text-center">
+ <AlertCircle className="mx-auto h-9 w-9 text-destructive/60" />
+ <h2 className="mt-3 text-base font-semibold">Couldn&apos;t load this topic</h2>
+ <p className="mt-1 text-sm text-muted-foreground">{error}</p>
+ <Button onClick={loadData} className="mt-4 gap-2" size="sm" variant="outline">
+ <RotateCw className="h-3.5 w-3.5" />
+ Retry
+ </Button>
+ </CardContent>
+ </Card>
+ </div>
+ );
+ }
+
+ // Top/weak prompts — aggregate by prompt_id
+ const promptRollup = new Map<string, { promptText: string; totalScore: number; count: number }>();
+ for (const r of results) {
+ const ex = promptRollup.get(r.promptId) ?? {
+ promptText: r.promptText,
+ totalScore: 0,
+ count: 0,
+ };
+ ex.totalScore += r.visibilityScore;
+ ex.count += 1;
+ promptRollup.set(r.promptId, ex);
+ }
+ const promptList = [...promptRollup.entries()].map(([id, v]) => ({
+ id,
+ text: v.promptText,
+ avg: Math.round(v.totalScore / v.count),
+ runs: v.count,
+ }));
+ const topPrompts = [...promptList].sort((a, b) => b.avg - a.avg).slice(0, 5);
+ const weakPrompts = [...promptList].sort((a, b) => a.avg - b.avg).slice(0, 5);
+
+ // Headline metric (#493): the topic-scoped prompt-level visibility rate.
+ // getCompetitorComparison already computes it under the topic filter with
+ // the same-denominator rule, so the own-brand entry carries rate, X/Y
+ // counts and the rate's point change.
+ const ownBrand = competitors?.brands.find((b) => b.isOwnBrand) ?? null;
+
+ return (
+ <div className="space-y-6">
+ {/* Header */}
+ <div>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => router.push('/dashboard/prompts/topics')}
+ className="mb-2 -ml-2 text-muted-foreground"
+ >
+ <ArrowLeft className="h-4 w-4 mr-1" />
+ Topics
+ </Button>
+ {loading && !topic ? (
+ <Skeleton className="h-8 w-64" />
+ ) : topic ? (
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">{topic.name}</h1>
+ </div>
+ ) : (
+ <h1 className="text-2xl font-bold">Topic not found</h1>
+ )}
+ </div>
+
+ {/* KPI strip */}
+ {loading ? (
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-[104px]" />
+ ))}
+ </div>
+ ) : summary ? (
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
+ <KpiCard
+ icon={Eye}
+ label="Visibility"
+ value={ownBrand?.score ?? 0}
+ change={ownBrand?.scoreChange ?? null}
+ hint={
+ ownBrand
+ ? `Mentioned in ${ownBrand.mentionAnswers} answers · cited in ${ownBrand.citationAnswers} · appeared in ${ownBrand.visiblePrompts} of ${ownBrand.promptCount} prompts`
+ : undefined
+ }
+ />
+ <KpiCard
+ icon={Zap}
+ label="Brand mentions"
+ value={summary.totalMentions.toLocaleString()}
+ change={summary.mentionsChange}
+ />
+ <KpiCard
+ icon={Quote}
+ label="Citations"
+ value={summary.totalCitations.toLocaleString()}
+ change={summary.citationsChange}
+ />
+ <KpiCard
+ icon={BarChart3}
+ label="Positive sentiment"
+ value={summary.positiveSentimentPct}
+ change={summary.sentimentChange}
+ suffix="%"
+ />
+ </div>
+ ) : null}
+
+ {/* Trend + SoV platform */}
+ <div className="grid gap-4 lg:grid-cols-3">
+ <Card className="lg:col-span-2">
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Visibility trend</CardTitle>
+ <p className="text-xs text-muted-foreground">
+ Daily average visibility for this topic vs. competitor average
+ </p>
+ </CardHeader>
+ <CardContent>
+ {loading ? <Skeleton className="h-[260px]" /> : <VisibilityTrendChart data={trend} />}
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Share of voice by platform</CardTitle>
+ <p className="text-xs text-muted-foreground">Brand vs. competitors on answer engines</p>
+ </CardHeader>
+ <CardContent>
+ {loading ? (
+ <Skeleton className="h-[260px]" />
+ ) : sov && sov.byPlatform.length > 0 ? (
+ <ShareOfVoicePlatformChart data={sov.byPlatform} overallSov={sov.overallSov} />
+ ) : (
+ <div className="flex h-[260px] items-center justify-center text-sm text-muted-foreground">
+ No platform data yet.
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+
+ {/* Competitor table + prompts */}
+ <div className="grid gap-4 lg:grid-cols-2">
+ {/* Competitors */}
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium flex items-center gap-2">
+ <Users className="h-4 w-4" />
+ Competitor comparison
+ </CardTitle>
+ <p className="text-xs text-muted-foreground">
+ Your brand vs. direct competitors on this topic
+ </p>
+ </CardHeader>
+ <CardContent>
+ {loading ? (
+ <Skeleton className="h-[200px]" />
+ ) : competitors && competitors.brands.length > 0 ? (
+ <ul className="divide-y">
+ {competitors.brands.slice(0, 6).map((c, i) => (
+ <li
+ key={c.name}
+ className={cn(
+ 'flex items-center gap-3 py-2',
+ c.isOwnBrand && 'bg-primary/5 -mx-3 px-3 rounded',
+ )}
+ title={`Appeared in ${c.visiblePrompts} of ${c.promptCount} prompts · avg score ${c.avgVisibilityScore}%`}
+ >
+ <span className="w-5 text-xs text-muted-foreground tabular-nums text-right">
+ {i + 1}
+ </span>
+ <span className="flex-1 text-sm font-medium truncate">
+ {c.name}
+ {c.isOwnBrand && (
+ <span className="ml-1.5 text-[10px] font-medium text-primary">YOU</span>
+ )}
+ </span>
+ <span className="text-sm tabular-nums w-10 text-right">{c.score ?? '—'}</span>
+ {c.scoreChange !== null && (
+ <span
+ className={cn(
+ 'text-xs tabular-nums w-12 text-right',
+ c.scoreChange > 0
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : c.scoreChange < 0
+ ? 'text-rose-600 dark:text-rose-400'
+ : 'text-muted-foreground',
+ )}
+ >
+ {c.scoreChange > 0 ? '+' : ''}
+ {c.scoreChange}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-sm text-muted-foreground py-10 text-center">
+ No competitor mentions yet.
+ </p>
+ )}
+ </CardContent>
+ </Card>
+
+ {/* Top / Weak prompts */}
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Prompt performance</CardTitle>
+ <p className="text-xs text-muted-foreground">
+ Best & worst performing prompts in this topic (last 50 runs)
+ </p>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {loading ? (
+ <>
+ <Skeleton className="h-24" />
+ <Skeleton className="h-24" />
+ </>
+ ) : promptList.length === 0 ? (
+ <p className="text-sm text-muted-foreground py-6 text-center">
+ No prompt results yet.
+ </p>
+ ) : (
+ <>
+ <div>
+ <div className="flex items-center gap-2 text-xs font-medium text-emerald-600 dark:text-emerald-400 mb-2">
+ <TrendingUp className="h-3 w-3" />
+ Top performers
+ </div>
+ <ul className="space-y-1.5">
+ {topPrompts.map((p) => (
+ <li key={p.id} className="flex items-center gap-2 text-sm">
+ <Badge variant="outline" className="text-[10px] shrink-0">
+ {p.avg}%
+ </Badge>
+ <span className="flex-1 truncate">{p.text}</span>
+ <span className="text-xs text-muted-foreground">{p.runs} runs</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ <div>
+ <div className="flex items-center gap-2 text-xs font-medium text-rose-600 dark:text-rose-400 mb-2">
+ <TrendingDown className="h-3 w-3" />
+ Needs improvement
+ </div>
+ <ul className="space-y-1.5">
+ {weakPrompts.map((p) => (
+ <li key={p.id} className="flex items-center gap-2 text-sm">
+ <Badge variant="outline" className="text-[10px] shrink-0">
+ {p.avg}%
+ </Badge>
+ <span className="flex-1 truncate">{p.text}</span>
+ <span className="text-xs text-muted-foreground">{p.runs} runs</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ <div className="pt-2 border-t">
+ <Link
+ href={`/dashboard/insights?topic=${topicId}`}
+ className="text-xs text-primary hover:underline"
+ >
+ View all prompt results for this topic →
+ </Link>
+ </div>
+ </>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/topic_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/[id]/topic_charts.tsx
similarity index 100%
rename from web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/topic_charts.tsx
rename to web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/[id]/topic_charts.tsx
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/page.tsx
new file mode 100644
index 000000000..393972618
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/page.tsx
@@ -0,0 +1,3 @@
+// The Prompts page, opened on its Topics view. It reads the view from the
+// route, so the sidebar submenu and the in-page tabs stay in sync.
+export { default } from '../page';
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx
index 80bf75007..268962767 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx
@@ -1,479 +1,7 @@
-'use client';
+import { redirect } from 'next/navigation';
-import { useCallback, useEffect, useRef, useState, use } from 'react';
-import { toast } from 'sonner';
-import { Link, useRouter } from '@/i18n/navigation';
-import { useBrandStore } from '@/stores/use-brand-store';
-import {
- getTopicDetail,
- type InsightsSummary,
- type VisibilityTrendPoint,
- type ShareOfVoiceData,
- type CompetitorComparisonData,
- type PromptResultWithText,
-} from '@/lib/actions/tracking';
-import type { Topic } from '@/types';
-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
-import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
-import { Skeleton } from '@/components/ui/skeleton';
-import {
- AlertCircle,
- ArrowLeft,
- BarChart3,
- Eye,
- Quote,
- RotateCw,
- TrendingDown,
- TrendingUp,
- Zap,
- Users,
-} from 'lucide-react';
-import { ShareOfVoicePlatformChart } from '../../insights/_charts';
-import { cn } from '@/lib/utils';
-import dynamic from 'next/dynamic';
-const DynamicVisibilityTrendChart = dynamic(
- () => import('./topic_charts').then((m) => m.VisibilityTrendChartView),
- {
- ssr: false,
- loading: () => <Skeleton className="h-[260px] w-full" />,
- },
-);
-
-function ChartContainer({
- height,
- children,
-}: {
- height: number;
- children: (width: number) => React.ReactNode;
-}) {
- const ref = useRef<HTMLDivElement>(null);
- const [width, setWidth] = useState(0);
-
- useEffect(() => {
- const el = ref.current;
- if (!el) return;
- const update = () => setWidth(el.clientWidth);
- update();
- const ro = new ResizeObserver(update);
- ro.observe(el);
- return () => ro.disconnect();
- }, []);
-
- return (
- <div ref={ref} style={{ width: '100%', height }}>
- {width > 0 && children(width)}
- </div>
- );
-}
-
-// ─── KPI Card ────────────────────────────────────────────────────────────
-
-function KpiCard({
- icon: Icon,
- label,
- value,
- change,
- suffix,
- hint,
-}: {
- icon: React.ComponentType<{ className?: string }>;
- label: string;
- value: string | number;
- change?: number | null;
- suffix?: string;
- hint?: string;
-}) {
- return (
- <Card title={hint}>
- <CardContent className="pt-6 pb-5">
- <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2">
- <Icon className="h-3.5 w-3.5" />
- {label}
- </div>
- <div className="flex items-baseline justify-between gap-2">
- <div className="text-2xl font-semibold tabular-nums">
- {value}
- {suffix && (
- <span className="text-sm font-normal text-muted-foreground ml-0.5">{suffix}</span>
- )}
- </div>
- {change !== null && change !== undefined && change !== 0 && (
- <span
- className={cn(
- 'flex items-center text-xs font-medium',
- change > 0
- ? 'text-emerald-600 dark:text-emerald-400'
- : change < 0
- ? 'text-rose-600 dark:text-rose-400'
- : 'text-muted-foreground',
- )}
- >
- {change > 0 ? (
- <TrendingUp className="h-3 w-3 mr-0.5" />
- ) : change < 0 ? (
- <TrendingDown className="h-3 w-3 mr-0.5" />
- ) : null}
- {change > 0 ? '+' : ''}
- {change}
- {suffix === '%' ? 'pts' : ''}
- </span>
- )}
- </div>
- </CardContent>
- </Card>
- );
-}
-
-// ─── Visibility trend chart ───────────────────────────────────────────────
-
-function VisibilityTrendChart({ data }: { data: VisibilityTrendPoint[] }) {
- if (data.length === 0) {
- return (
- <div className="flex h-[260px] items-center justify-center text-sm text-muted-foreground">
- No data yet for this topic.
- </div>
- );
- }
- return (
- <ChartContainer height={260}>
- {(width) => <DynamicVisibilityTrendChart width={width} data={data} />}
- </ChartContainer>
- );
-}
-
-// ─── Page ────────────────────────────────────────────────────────────────
-
-export default function TopicDetailPage({ params }: { params: Promise<{ id: string }> }) {
- const { id: topicId } = use(params);
- const router = useRouter();
- const activeBrandId = useBrandStore((s) => s.activeBrandId);
-
- const [topic, setTopic] = useState<Topic | null>(null);
- const [summary, setSummary] = useState<InsightsSummary | null>(null);
- const [trend, setTrend] = useState<VisibilityTrendPoint[]>([]);
- const [sov, setSov] = useState<ShareOfVoiceData | null>(null);
- const [competitors, setCompetitors] = useState<CompetitorComparisonData | null>(null);
- const [results, setResults] = useState<PromptResultWithText[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
-
- const loadData = useCallback(async () => {
- if (!activeBrandId || !topicId) return;
- setLoading(true);
- setError(null);
- try {
- // One server action (#312): Next.js runs server actions sequentially, so
- // the old six-call Promise.all paid the sum of all six. This is one round
- // trip whose body runs the work in a real server-side Promise.all.
- const detail = await getTopicDetail(activeBrandId, topicId);
- setTopic(detail.topic);
- setSummary(detail.summary);
- setTrend(detail.trend);
- setSov(detail.sov);
- setCompetitors(detail.competitors);
- setResults(detail.results);
- } catch (err) {
- console.error('Failed to load topic detail', err);
- setError(err instanceof Error ? err.message : 'Failed to load this topic');
- toast.error('Failed to load this topic');
- } finally {
- setLoading(false);
- }
- }, [activeBrandId, topicId]);
-
- useEffect(() => {
- loadData();
- }, [loadData]);
-
- if (!activeBrandId) {
- return (
- <div className="flex h-[60vh] items-center justify-center">
- <Card className="max-w-md">
- <CardContent className="pt-6 text-center">
- <h2 className="text-base font-semibold">No brand selected</h2>
- <p className="mt-1 text-sm text-muted-foreground">
- Select a brand from the top switcher first.
- </p>
- </CardContent>
- </Card>
- </div>
- );
- }
-
- if (error) {
- return (
- <div className="flex h-[60vh] items-center justify-center">
- <Card className="max-w-md">
- <CardContent className="pt-6 text-center">
- <AlertCircle className="mx-auto h-9 w-9 text-destructive/60" />
- <h2 className="mt-3 text-base font-semibold">Couldn&apos;t load this topic</h2>
- <p className="mt-1 text-sm text-muted-foreground">{error}</p>
- <Button onClick={loadData} className="mt-4 gap-2" size="sm" variant="outline">
- <RotateCw className="h-3.5 w-3.5" />
- Retry
- </Button>
- </CardContent>
- </Card>
- </div>
- );
- }
-
- // Top/weak prompts — aggregate by prompt_id
- const promptRollup = new Map<string, { promptText: string; totalScore: number; count: number }>();
- for (const r of results) {
- const ex = promptRollup.get(r.promptId) ?? {
- promptText: r.promptText,
- totalScore: 0,
- count: 0,
- };
- ex.totalScore += r.visibilityScore;
- ex.count += 1;
- promptRollup.set(r.promptId, ex);
- }
- const promptList = [...promptRollup.entries()].map(([id, v]) => ({
- id,
- text: v.promptText,
- avg: Math.round(v.totalScore / v.count),
- runs: v.count,
- }));
- const topPrompts = [...promptList].sort((a, b) => b.avg - a.avg).slice(0, 5);
- const weakPrompts = [...promptList].sort((a, b) => a.avg - b.avg).slice(0, 5);
-
- // Headline metric (#493): the topic-scoped prompt-level visibility rate.
- // getCompetitorComparison already computes it under the topic filter with
- // the same-denominator rule, so the own-brand entry carries rate, X/Y
- // counts and the rate's point change.
- const ownBrand = competitors?.brands.find((b) => b.isOwnBrand) ?? null;
-
- return (
- <div className="space-y-6">
- {/* Header */}
- <div>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => router.push('/dashboard/topics')}
- className="mb-2 -ml-2 text-muted-foreground"
- >
- <ArrowLeft className="h-4 w-4 mr-1" />
- Topics
- </Button>
- {loading && !topic ? (
- <Skeleton className="h-8 w-64" />
- ) : topic ? (
- <div>
- <h1 className="text-2xl font-bold tracking-tight">{topic.name}</h1>
- </div>
- ) : (
- <h1 className="text-2xl font-bold">Topic not found</h1>
- )}
- </div>
-
- {/* KPI strip */}
- {loading ? (
- <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-[104px]" />
- ))}
- </div>
- ) : summary ? (
- <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <KpiCard
- icon={Eye}
- label="Visibility"
- value={ownBrand?.score ?? 0}
- change={ownBrand?.scoreChange ?? null}
- hint={
- ownBrand
- ? `Mentioned in ${ownBrand.mentionAnswers} answers · cited in ${ownBrand.citationAnswers} · appeared in ${ownBrand.visiblePrompts} of ${ownBrand.promptCount} prompts`
- : undefined
- }
- />
- <KpiCard
- icon={Zap}
- label="Brand mentions"
- value={summary.totalMentions.toLocaleString()}
- change={summary.mentionsChange}
- />
- <KpiCard
- icon={Quote}
- label="Citations"
- value={summary.totalCitations.toLocaleString()}
- change={summary.citationsChange}
- />
- <KpiCard
- icon={BarChart3}
- label="Positive sentiment"
- value={summary.positiveSentimentPct}
- change={summary.sentimentChange}
- suffix="%"
- />
- </div>
- ) : null}
-
- {/* Trend + SoV platform */}
- <div className="grid gap-4 lg:grid-cols-3">
- <Card className="lg:col-span-2">
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">Visibility trend</CardTitle>
- <p className="text-xs text-muted-foreground">
- Daily average visibility for this topic vs. competitor average
- </p>
- </CardHeader>
- <CardContent>
- {loading ? <Skeleton className="h-[260px]" /> : <VisibilityTrendChart data={trend} />}
- </CardContent>
- </Card>
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">Share of voice by platform</CardTitle>
- <p className="text-xs text-muted-foreground">Brand vs. competitors on answer engines</p>
- </CardHeader>
- <CardContent>
- {loading ? (
- <Skeleton className="h-[260px]" />
- ) : sov && sov.byPlatform.length > 0 ? (
- <ShareOfVoicePlatformChart data={sov.byPlatform} overallSov={sov.overallSov} />
- ) : (
- <div className="flex h-[260px] items-center justify-center text-sm text-muted-foreground">
- No platform data yet.
- </div>
- )}
- </CardContent>
- </Card>
- </div>
-
- {/* Competitor table + prompts */}
- <div className="grid gap-4 lg:grid-cols-2">
- {/* Competitors */}
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium flex items-center gap-2">
- <Users className="h-4 w-4" />
- Competitor comparison
- </CardTitle>
- <p className="text-xs text-muted-foreground">
- Your brand vs. direct competitors on this topic
- </p>
- </CardHeader>
- <CardContent>
- {loading ? (
- <Skeleton className="h-[200px]" />
- ) : competitors && competitors.brands.length > 0 ? (
- <ul className="divide-y">
- {competitors.brands.slice(0, 6).map((c, i) => (
- <li
- key={c.name}
- className={cn(
- 'flex items-center gap-3 py-2',
- c.isOwnBrand && 'bg-primary/5 -mx-3 px-3 rounded',
- )}
- title={`Appeared in ${c.visiblePrompts} of ${c.promptCount} prompts · avg score ${c.avgVisibilityScore}%`}
- >
- <span className="w-5 text-xs text-muted-foreground tabular-nums text-right">
- {i + 1}
- </span>
- <span className="flex-1 text-sm font-medium truncate">
- {c.name}
- {c.isOwnBrand && (
- <span className="ml-1.5 text-[10px] font-medium text-primary">YOU</span>
- )}
- </span>
- <span className="text-sm tabular-nums w-10 text-right">{c.score ?? '—'}</span>
- {c.scoreChange !== null && (
- <span
- className={cn(
- 'text-xs tabular-nums w-12 text-right',
- c.scoreChange > 0
- ? 'text-emerald-600 dark:text-emerald-400'
- : c.scoreChange < 0
- ? 'text-rose-600 dark:text-rose-400'
- : 'text-muted-foreground',
- )}
- >
- {c.scoreChange > 0 ? '+' : ''}
- {c.scoreChange}
- </span>
- )}
- </li>
- ))}
- </ul>
- ) : (
- <p className="text-sm text-muted-foreground py-10 text-center">
- No competitor mentions yet.
- </p>
- )}
- </CardContent>
- </Card>
-
- {/* Top / Weak prompts */}
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">Prompt performance</CardTitle>
- <p className="text-xs text-muted-foreground">
- Best & worst performing prompts in this topic (last 50 runs)
- </p>
- </CardHeader>
- <CardContent className="space-y-4">
- {loading ? (
- <>
- <Skeleton className="h-24" />
- <Skeleton className="h-24" />
- </>
- ) : promptList.length === 0 ? (
- <p className="text-sm text-muted-foreground py-6 text-center">
- No prompt results yet.
- </p>
- ) : (
- <>
- <div>
- <div className="flex items-center gap-2 text-xs font-medium text-emerald-600 dark:text-emerald-400 mb-2">
- <TrendingUp className="h-3 w-3" />
- Top performers
- </div>
- <ul className="space-y-1.5">
- {topPrompts.map((p) => (
- <li key={p.id} className="flex items-center gap-2 text-sm">
- <Badge variant="outline" className="text-[10px] shrink-0">
- {p.avg}%
- </Badge>
- <span className="flex-1 truncate">{p.text}</span>
- <span className="text-xs text-muted-foreground">{p.runs} runs</span>
- </li>
- ))}
- </ul>
- </div>
- <div>
- <div className="flex items-center gap-2 text-xs font-medium text-rose-600 dark:text-rose-400 mb-2">
- <TrendingDown className="h-3 w-3" />
- Needs improvement
- </div>
- <ul className="space-y-1.5">
- {weakPrompts.map((p) => (
- <li key={p.id} className="flex items-center gap-2 text-sm">
- <Badge variant="outline" className="text-[10px] shrink-0">
- {p.avg}%
- </Badge>
- <span className="flex-1 truncate">{p.text}</span>
- <span className="text-xs text-muted-foreground">{p.runs} runs</span>
- </li>
- ))}
- </ul>
- </div>
- <div className="pt-2 border-t">
- <Link
- href={`/dashboard/insights?topic=${topicId}`}
- className="text-xs text-primary hover:underline"
- >
- View all prompt results for this topic →
- </Link>
- </div>
- </>
- )}
- </CardContent>
- </Card>
- </div>
- </div>
- );
+// A topic's page moved under Prompts with the Topics view (/dashboard/prompts/topics).
+export default async function TopicRedirect({ params }: { params: Promise<{ id: string }> }) {
+ const { id } = await params;
+ redirect(`/dashboard/prompts/topics/${encodeURIComponent(id)}`);
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.test.ts
new file mode 100644
index 000000000..782baf9c7
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.test.ts
@@ -0,0 +1,28 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const redirect = vi.fn();
+vi.mock('next/navigation', () => ({
+ redirect: (url: string) => redirect(url),
+}));
+
+import TopicsPage from './page';
+import TopicRedirect from './[id]/page';
+
+describe('the old Topics routes', () => {
+ beforeEach(() => redirect.mockClear());
+
+ it('sends /dashboard/topics to the Prompts area’s Topics tab', () => {
+ TopicsPage();
+ expect(redirect).toHaveBeenCalledWith('/dashboard/prompts/topics');
+ });
+
+ it('sends a topic’s old page to its page under Prompts', async () => {
+ await TopicRedirect({ params: Promise.resolve({ id: 'topic-1' }) });
+ expect(redirect).toHaveBeenCalledWith('/dashboard/prompts/topics/topic-1');
+ });
+
+ it('keeps an odd id inside its own path segment', async () => {
+ await TopicRedirect({ params: Promise.resolve({ id: 'a/b?c' }) });
+ expect(redirect).toHaveBeenCalledWith('/dashboard/prompts/topics/a%2Fb%3Fc');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
index bcccf8273..80fe0e802 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
@@ -1,778 +1,7 @@
-'use client';
-
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useTranslations } from 'next-intl';
-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 { customUtcWindow } from '@/lib/topic-trend';
-import { DateRangeFilter } from '@/components/filters/date-range-filter';
-import {
- DEFAULT_PROMPT_RANGE_PRESET,
- PROMPT_RANGE_PRESETS,
- resolvePromptRange,
- type PromptRangePreset,
-} from '@/config/prompt-options';
-import { TopicSuggestionsCard } from './_suggestions-card';
-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
-import { createTopic } from '@/lib/actions/topic';
-import { toast } from 'sonner';
-import { Input } from '@/components/ui/input';
-import { Loader2, Plus } from 'lucide-react';
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from '@/components/ui/table';
-import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@/components/ui/dialog';
-import { Skeleton } from '@/components/ui/skeleton';
-import { Badge } from '@/components/ui/badge';
-import { Button, buttonVariants } from '@/components/ui/button';
-import {
- AlertCircle,
- ArrowRight,
- ChevronDown,
- ChevronUp,
- Download,
- Flame,
- Layers,
- Minus,
- RotateCw,
- Settings2,
- Tag,
- TrendingDown,
- TrendingUp,
- Trophy,
-} from 'lucide-react';
-import { cn } from '@/lib/utils';
-import { toCsv } from '@/lib/csv';
-import { formatRelative } from '@/lib/format-relative';
-import { compareNullsLast, type SortDir } from '../prompts/prompt-sort';
-
-// ─── Helpers ─────────────────────────────────────────────────────────────
-
-function visibilityBarColor(score: number) {
- if (score >= 75) return 'bg-emerald-500';
- if (score >= 50) return 'bg-amber-500';
- if (score >= 25) return 'bg-orange-500';
- return 'bg-rose-500';
-}
-
-function visibilityTextColor(score: number) {
- if (score >= 75) return 'text-emerald-600 dark:text-emerald-400';
- if (score >= 50) return 'text-amber-600 dark:text-amber-400';
- if (score >= 25) return 'text-orange-600 dark:text-orange-400';
- return 'text-rose-600 dark:text-rose-400';
-}
-
-const TOPIC_EXPORT_HEADERS = [
- 'topic',
- 'prompt_count',
- 'visibility_rate',
- 'visible_prompts',
- 'active_prompts',
- 'visibility_change',
- 'total_mentions',
- 'total_citations',
- 'share_of_voice',
- 'top_competitor',
- 'top_competitor_sov',
- 'last_run_at',
-];
-
-// ─── Sparkline ───────────────────────────────────────────────────────────
-
-function Sparkline({ points }: { points: number[] }) {
- if (!points.length) return null;
- const width = 80;
- const height = 24;
- const max = Math.max(...points, 1);
- const min = Math.min(...points);
- const range = max - min || 1;
- const step = width / Math.max(points.length - 1, 1);
-
- const path = points
- .map((p, i) => {
- const x = i * step;
- const y = height - ((p - min) / range) * height;
- return `${i === 0 ? 'M' : 'L'}${x.toFixed(2)},${y.toFixed(2)}`;
- })
- .join(' ');
-
- const last = points[points.length - 1];
- const first = points[0];
- const trendUp = last >= first;
-
- return (
- <svg width={width} height={height} className="inline-block">
- <path
- d={path}
- fill="none"
- strokeWidth={1.5}
- className={trendUp ? 'stroke-emerald-500' : 'stroke-rose-500'}
- />
- </svg>
- );
-}
-
-// ─── KPI Card ────────────────────────────────────────────────────────────
-
-function KpiCard({
- icon: Icon,
- label,
- value,
- sub,
- tone = 'neutral',
-}: {
- icon: React.ComponentType<{ className?: string }>;
- label: string;
- value: string | number;
- sub?: string;
- tone?: 'neutral' | 'positive' | 'negative' | 'warning';
-}) {
- const toneClasses: Record<string, string> = {
- neutral: 'text-foreground',
- positive: 'text-emerald-600 dark:text-emerald-400',
- negative: 'text-rose-600 dark:text-rose-400',
- warning: 'text-amber-600 dark:text-amber-400',
- };
- return (
- <Card>
- <CardContent className="pt-6 pb-5">
- <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2">
- <Icon className="h-3.5 w-3.5" />
- {label}
- </div>
- <div className={cn('text-2xl font-semibold tabular-nums', toneClasses[tone])}>{value}</div>
- {sub && <p className="text-xs text-muted-foreground mt-1 truncate">{sub}</p>}
- </CardContent>
- </Card>
- );
-}
-
-// ─── Sortable leaderboard columns ─────────────────────────────────────────
-
-type TopicSortKey = 'prompts' | 'visibility' | 'sov' | 'mentions' | 'citations' | 'lastRun';
-
-/**
- * Clickable header that toggles asc⇄desc for its column and marks the active
- * sort with a chevron. Mirrors the Prompts page's SortableHead (#597).
- */
-function SortableHead({
- children,
- className,
- sortKey,
- activeSort,
- dir,
- onSort,
-}: {
- children: React.ReactNode;
- className?: string;
- sortKey: TopicSortKey;
- activeSort: TopicSortKey;
- dir: SortDir;
- onSort: (key: TopicSortKey) => void;
-}) {
- const active = activeSort === sortKey;
- return (
- <TableHead
- className={className}
- aria-sort={active ? (dir === 'asc' ? 'ascending' : 'descending') : 'none'}
- >
- <button
- type="button"
- onClick={() => onSort(sortKey)}
- aria-label={`Sort by ${typeof children === 'string' ? children : sortKey}`}
- className={cn(
- 'inline-flex items-center gap-1 transition-colors hover:text-foreground',
- active ? 'text-foreground' : 'text-muted-foreground',
- )}
- >
- {children}
- {active &&
- (dir === 'asc' ? (
- <ChevronUp className="h-3.5 w-3.5" />
- ) : (
- <ChevronDown className="h-3.5 w-3.5" />
- ))}
- </button>
- </TableHead>
- );
-}
-
-// ─── Page ────────────────────────────────────────────────────────────────
+import { redirect } from 'next/navigation';
+// Topics moved into the Prompts area, as its Topics tab. Links to the old
+// route (bookmarks, shared links, older builds) land there.
export default function TopicsPage() {
- const t = useTranslations('topics');
- const common = useTranslations('common');
- const activeBrandId = useBrandStore((s) => s.activeBrandId);
- 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);
- const [error, setError] = useState<string | null>(null);
- const [isAdding, setIsAdding] = useState(false);
- const [newName, setNewName] = useState('');
- const [open, setOpen] = useState(false);
- // Default matches the previous hard-coded order (#597): visibility descending.
- const [sortKey, setSortKey] = useState<TopicSortKey>('visibility');
- const [sortDir, setSortDir] = useState<SortDir>('desc');
- // The window the table covers, as on the Prompts page; opens on 24 hours.
- const [rangePreset, setRangePreset] = useState<PromptRangePreset>(DEFAULT_PROMPT_RANGE_PRESET);
- const [customFrom, setCustomFrom] = useState('');
- const [customTo, setCustomTo] = useState('');
- // A custom range is a window only once a bound is entered.
- const range = useMemo(
- () =>
- rangePreset === 'custom' && !customFrom && !customTo
- ? null
- : resolvePromptRange(rangePreset, { from: customFrom, to: customTo }),
- [rangePreset, customFrom, customTo],
- );
- // Only the latest request may fill the table: a slow 90-day read must not
- // land after the 24-hour one picked since.
- const requestRef = useRef(0);
-
- const handleSort = useCallback(
- (key: TopicSortKey) => {
- setSortDir((prevDir) => (sortKey === key && prevDir === 'desc' ? 'asc' : 'desc'));
- setSortKey(key);
- },
- [sortKey],
- );
-
- const loadData = useCallback(async () => {
- if (!activeBrandId) {
- setTopics([]);
- setLoading(false);
- return;
- }
- if (!range) return;
- const request = ++requestRef.current;
- setLoading(true);
- setError(null);
- try {
- const window =
- rangePreset === 'custom'
- ? customUtcWindow(customFrom, customTo, range)
- : { from: range.from, to: range.to };
- const data = await getTopicsOverview(activeBrandId, window);
- if (request !== requestRef.current) return;
- setTopics(data.topics);
- setUnassignedPromptCount(data.unassignedPromptCount);
- } catch (err) {
- if (request !== requestRef.current) return;
- console.error('Failed to load topics overview', err);
- setError(err instanceof Error ? err.message : t('loadError'));
- toast.error(t('loadError'));
- } finally {
- if (request === requestRef.current) setLoading(false);
- }
- }, [activeBrandId, range, rangePreset, customFrom, customTo, t]);
-
- useEffect(() => {
- loadData();
- }, [loadData]);
-
- const sortedTopics = useMemo(() => {
- const valueOf = (row: TopicOverviewRow): number | null => {
- switch (sortKey) {
- case 'prompts':
- return row.promptCount;
- case 'visibility':
- return row.visibilityRate;
- case 'sov':
- return row.shareOfVoice;
- case 'mentions':
- return row.totalMentions;
- case 'citations':
- return row.totalCitations;
- case 'lastRun':
- return row.lastRunAt ? new Date(row.lastRunAt).getTime() : null;
- }
- };
- return [...topics].sort((a, b) => compareNullsLast(valueOf(a), valueOf(b), sortDir));
- }, [topics, sortKey, sortDir]);
-
- const kpis = useMemo(() => {
- if (topics.length === 0) return null;
- const withData = topics.filter((t) => t.visibilityRate > 0);
- if (withData.length === 0) {
- return {
- total: topics.length,
- best: null as TopicOverviewRow | null,
- weakest: null as TopicOverviewRow | null,
- gainer: null as TopicOverviewRow | null,
- };
- }
- const best = [...withData].sort((a, b) => b.visibilityRate - a.visibilityRate)[0];
- const weakest = [...withData].sort((a, b) => a.visibilityRate - b.visibilityRate)[0];
- const withChange = topics.filter((t) => t.visibilityChange !== null);
- const gainer = withChange.length
- ? [...withChange].sort((a, b) => (b.visibilityChange ?? 0) - (a.visibilityChange ?? 0))[0]
- : null;
-
- return {
- total: topics.length,
- best,
- weakest,
- gainer,
- };
- }, [topics]);
-
- const canExport = !loading && topics.length > 0;
-
- const handleExportCsv = useCallback(() => {
- if (!canExport) return;
-
- const rows = topics.map((t) => ({
- topic: t.name,
- prompt_count: t.promptCount,
- visibility_rate: t.visibilityRate,
- visible_prompts: t.visiblePrompts,
- active_prompts: t.activePrompts,
- visibility_change: t.visibilityChange ?? '',
- total_mentions: t.totalMentions,
- total_citations: t.totalCitations,
- share_of_voice: t.shareOfVoice,
- top_competitor: t.topCompetitor?.name ?? '',
- top_competitor_sov: t.topCompetitor?.sov ?? '',
- last_run_at: t.lastRunAt ?? '',
- }));
-
- const csv = toCsv(rows, TOPIC_EXPORT_HEADERS);
- const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
- const date = new Date().toISOString().slice(0, 10);
- const slug = activeBrand?.slug ?? 'brand';
-
- link.href = url;
- link.download = `ansvisor_${slug}_topics_${rangePreset}_${date}.csv`;
- link.click();
-
- URL.revokeObjectURL(url);
- }, [activeBrand?.slug, canExport, rangePreset, topics]);
-
- if (!activeBrandId) {
- return (
- <div className="flex h-[60vh] items-center justify-center">
- <Card className="max-w-md">
- <CardContent className="pt-6 text-center">
- <Tag className="mx-auto h-10 w-10 text-muted-foreground/50" />
- <h2 className="mt-3 text-base font-semibold">{t('noBrandTitle')}</h2>
- <p className="mt-1 text-sm text-muted-foreground">{t('noBrandBody')}</p>
- </CardContent>
- </Card>
- </div>
- );
- }
-
- const handleAddTopic = async () => {
- if (isAdding) return;
- const name = newName.trim();
- if (!name) return;
- if (topics.some((t) => t.name.toLowerCase() === name.toLowerCase())) {
- toast.error(t('topicAlreadyExists'));
- return;
- }
- setIsAdding(true);
- try {
- const added = await createTopic(activeBrandId, name);
- await loadData();
- setNewName('');
- setOpen(false);
- toast.success(t('topicAdded', { name: added.name }));
- } catch (err) {
- toast.error(err instanceof Error ? err.message : t('failedToAddTopic'));
- } finally {
- setIsAdding(false);
- }
- };
-
- return (
- <div className="space-y-6">
- {/* Header */}
- <div className="flex items-center justify-between gap-4 flex-wrap">
- <div>
- <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
- <p className="text-muted-foreground text-sm">{t('description')}</p>
- </div>
- <div className="flex items-center gap-2">
- <span title={!canExport ? t('exportHint') : undefined}>
- <Button
- type="button"
- variant="outline"
- size="sm"
- className="gap-2"
- onClick={handleExportCsv}
- disabled={!canExport}
- >
- <Download className="h-4 w-4" />
- {common('exportCsv')}
- </Button>
- </span>
- <Link
- href={`/dashboard/brands/${activeBrandId}/topics`}
- className={buttonVariants({ variant: 'outline', size: 'sm' })}
- >
- <Settings2 className="h-4 w-4" />
- {t('manageTopics')}
- </Link>
- {canManage && (
- <>
- <Button size="sm" onClick={() => setOpen(true)}>
- <Plus className="mr-2 h-4 w-4" />
- {t('addTopic')}
- </Button>
- <Dialog
- open={open}
- onOpenChange={(value) => {
- setOpen(value);
- if (!value) {
- setNewName('');
- }
- }}
- >
- <DialogContent className="sm:max-w-sm">
- <DialogHeader>
- <DialogTitle>{t('addTopic')}</DialogTitle>
- <DialogDescription>{t('addTopicDescription')}</DialogDescription>
- </DialogHeader>
- <div className="flex gap-2">
- <Input
- placeholder="e.g. Industry, Comparison..."
- value={newName}
- onChange={(e) => setNewName(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && newName.trim() && handleAddTopic()}
- className="flex-1"
- />
- </div>
- <DialogFooter>
- <DialogClose render={<Button variant="outline" />}>
- {common('cancel')}
- </DialogClose>
- <Button
- variant="default"
- onClick={handleAddTopic}
- disabled={isAdding || !newName.trim()}
- className="gap-1.5 shrink-0"
- >
- {isAdding ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Plus className="h-4 w-4" />
- )}
- {t('addTopic')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </>
- )}
- </div>
- </div>
-
- <DateRangeFilter
- value={rangePreset}
- presets={PROMPT_RANGE_PRESETS}
- onChange={setRangePreset}
- from={customFrom}
- to={customTo}
- onFromChange={setCustomFrom}
- onToChange={setCustomTo}
- />
-
- {/* KPIs */}
- {loading ? (
- <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-[104px]" />
- ))}
- </div>
- ) : kpis ? (
- <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <KpiCard
- icon={Layers}
- label={t('kpi.trackedTopics')}
- value={kpis.total}
- sub={
- unassignedPromptCount > 0
- ? t('kpi.unassignedPrompts', { count: unassignedPromptCount })
- : t('kpi.allCategorised')
- }
- />
- <KpiCard
- icon={Trophy}
- label={t('kpi.bestPerformer')}
- value={kpis.best ? kpis.best.visibilityRate : '—'}
- sub={kpis.best?.name ?? t('kpi.noDataYet')}
- tone="positive"
- />
- <KpiCard
- icon={TrendingDown}
- label={t('kpi.biggestGap')}
- value={kpis.weakest ? kpis.weakest.visibilityRate : '—'}
- sub={kpis.weakest?.name ?? t('kpi.noDataYet')}
- tone="warning"
- />
- <KpiCard
- icon={Flame}
- label={t('kpi.topMover')}
- value={
- kpis.gainer && kpis.gainer.visibilityChange !== null
- ? t('ptsChange', {
- value: `${kpis.gainer.visibilityChange > 0 ? '+' : ''}${kpis.gainer.visibilityChange.toFixed(1)}`,
- })
- : '—'
- }
- sub={kpis.gainer?.name ?? t('kpi.notEnoughData')}
- tone={
- kpis.gainer?.visibilityChange && kpis.gainer.visibilityChange >= 0
- ? 'positive'
- : 'negative'
- }
- />
- </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">
- <CardTitle className="text-sm font-medium">{t('leaderboardTitle')}</CardTitle>
- <p className="text-xs text-muted-foreground">{t('leaderboardHint')}</p>
- </CardHeader>
- <CardContent className="p-0">
- {loading ? (
- <div className="p-6 space-y-2">
- {Array.from({ length: 5 }).map((_, i) => (
- <Skeleton key={i} className="h-12" />
- ))}
- </div>
- ) : error ? (
- <div className="py-14 text-center text-sm">
- <AlertCircle className="mx-auto h-9 w-9 text-destructive/60" />
- <p className="mt-2 font-medium">{t('loadError')}</p>
- <Button
- className="mt-4 gap-2"
- size="sm"
- variant="outline"
- onClick={() => void loadData()}
- >
- <RotateCw className="h-4 w-4" />
- {common('retry')}
- </Button>
- </div>
- ) : topics.length === 0 ? (
- <div className="py-14 text-center text-sm text-muted-foreground">
- <Tag className="mx-auto h-9 w-9 text-muted-foreground/40" />
- <p className="mt-2">{t('emptyTitle')}</p>
- <p className="text-xs">{t('emptyBody')}</p>
- {canManage && (
- <Button className="mt-4" onClick={() => setOpen(true)}>
- <Plus className="mr-2 h-4 w-4" />
- {t('addTopic')}
- </Button>
- )}
- </div>
- ) : (
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="pl-6">{t('columns.topic')}</TableHead>
- <SortableHead
- className="text-right"
- sortKey="prompts"
- activeSort={sortKey}
- dir={sortDir}
- onSort={handleSort}
- >
- {t('columns.prompts')}
- </SortableHead>
- <SortableHead
- sortKey="visibility"
- activeSort={sortKey}
- dir={sortDir}
- onSort={handleSort}
- >
- {t('columns.visibility')}
- </SortableHead>
- <SortableHead
- className="text-right"
- sortKey="sov"
- activeSort={sortKey}
- dir={sortDir}
- onSort={handleSort}
- >
- {t('columns.sov')}
- </SortableHead>
- <SortableHead
- className="text-right"
- sortKey="mentions"
- activeSort={sortKey}
- dir={sortDir}
- onSort={handleSort}
- >
- {t('columns.mentions')}
- </SortableHead>
- <SortableHead
- className="text-right"
- sortKey="citations"
- activeSort={sortKey}
- dir={sortDir}
- onSort={handleSort}
- >
- {t('columns.citations')}
- </SortableHead>
- <TableHead>{t('columns.trend')}</TableHead>
- <TableHead>{t('columns.topCompetitor')}</TableHead>
- <SortableHead
- className="text-right"
- sortKey="lastRun"
- activeSort={sortKey}
- dir={sortDir}
- onSort={handleSort}
- >
- {t('columns.lastRun')}
- </SortableHead>
- <TableHead className="pr-6 text-right w-[40px]" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {sortedTopics.map((topic) => (
- <TableRow key={topic.id} className="group hover:bg-muted/50">
- <TableCell className="pl-6 font-medium text-sm">
- <Link href={`/dashboard/topics/${topic.id}`} className="hover:underline">
- {topic.name}
- </Link>
- </TableCell>
- <TableCell className="text-right tabular-nums text-sm">
- {topic.promptCount}
- </TableCell>
- <TableCell className="min-w-[160px]">
- {topic.activePrompts > 0 ? (
- <div
- className="flex items-center gap-2"
- title={t('appearedIn', {
- visible: topic.visiblePrompts,
- active: topic.activePrompts,
- })}
- >
- <span
- className={cn(
- 'text-sm font-semibold tabular-nums w-11',
- visibilityTextColor(topic.visibilityRate),
- )}
- >
- {topic.visibilityRate}
- </span>
- <div className="h-1.5 flex-1 max-w-[90px] rounded-full bg-muted overflow-hidden">
- <div
- className={cn(
- 'h-full rounded-full',
- visibilityBarColor(topic.visibilityRate),
- )}
- style={{
- width: `${Math.min(100, topic.visibilityRate)}%`,
- }}
- />
- </div>
- </div>
- ) : (
- <span className="text-xs text-muted-foreground">—</span>
- )}
- </TableCell>
- <TableCell className="text-right tabular-nums text-sm">
- {topic.shareOfVoice > 0 ? `${topic.shareOfVoice}%` : '—'}
- </TableCell>
- <TableCell className="text-right tabular-nums text-sm">
- {topic.totalMentions.toLocaleString()}
- </TableCell>
- <TableCell className="text-right tabular-nums text-sm">
- {topic.totalCitations.toLocaleString()}
- </TableCell>
- <TableCell>
- {/* Under two days there is no line, only the change. */}
- {topic.trendSparkline.some((v) => v > 0) ||
- topic.visibilityChange !== null ? (
- <div className="flex items-center gap-2">
- {topic.trendSparkline.some((v) => v > 0) && (
- <Sparkline points={topic.trendSparkline} />
- )}
- {topic.visibilityChange !== null && topic.visibilityChange !== 0 && (
- <span
- className={cn(
- 'text-xs font-medium tabular-nums',
- topic.visibilityChange > 0
- ? 'text-emerald-600 dark:text-emerald-400'
- : 'text-rose-600 dark:text-rose-400',
- )}
- >
- {topic.visibilityChange > 0 ? (
- <TrendingUp className="h-3 w-3 inline mr-0.5" />
- ) : (
- <TrendingDown className="h-3 w-3 inline mr-0.5" />
- )}
- {t('ptsChange', {
- value: Math.abs(topic.visibilityChange).toFixed(1),
- })}
- </span>
- )}
- {topic.visibilityChange === 0 && (
- <Minus className="h-3 w-3 text-muted-foreground" />
- )}
- </div>
- ) : (
- <span className="text-xs text-muted-foreground">—</span>
- )}
- </TableCell>
- <TableCell>
- {topic.topCompetitor ? (
- <Badge variant="outline" className="text-[10px]">
- {topic.topCompetitor.name} · {topic.topCompetitor.sov}%
- </Badge>
- ) : (
- <span className="text-xs text-muted-foreground">—</span>
- )}
- </TableCell>
- <TableCell className="text-right text-xs text-muted-foreground">
- {formatRelative(topic.lastRunAt, common)}
- </TableCell>
- <TableCell className="pr-6 text-right">
- <Link
- href={`/dashboard/topics/${topic.id}`}
- className="inline-flex opacity-0 group-hover:opacity-100 transition-opacity"
- aria-label={t('openDetails')}
- >
- <ArrowRight className="h-4 w-4 text-muted-foreground" />
- </Link>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- )}
- </CardContent>
- </Card>
- </div>
- );
+ redirect('/dashboard/prompts/topics');
}
diff --git a/web/src/components/action-center/topic-gap-context.tsx b/web/src/components/action-center/topic-gap-context.tsx
index 5e7333f7c..ddb85ebf5 100644
--- a/web/src/components/action-center/topic-gap-context.tsx
+++ b/web/src/components/action-center/topic-gap-context.tsx
@@ -31,7 +31,7 @@ export function TopicGapContext({ payload }: { payload: Record<string, unknown>
<span>{topicName}</span>
{topicId && (
<Link
- href={`/dashboard/topics/${topicId}`}
+ href={`/dashboard/prompts/topics/${topicId}`}
className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
>
{t('openTopic')}
diff --git a/web/src/components/action-center/topic-opportunity-context.tsx b/web/src/components/action-center/topic-opportunity-context.tsx
index d680b2e19..62d90f00d 100644
--- a/web/src/components/action-center/topic-opportunity-context.tsx
+++ b/web/src/components/action-center/topic-opportunity-context.tsx
@@ -41,7 +41,7 @@ export function TopicOpportunityContext({ payload }: { payload: Record<string, u
<span>{topicName}</span>
{topicId && (
<Link
- href={`/dashboard/topics/${topicId}`}
+ href={`/dashboard/prompts/topics/${topicId}`}
className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
>
{t('openTopic')}
diff --git a/web/src/components/layout/mobile-nav.tsx b/web/src/components/layout/mobile-nav.tsx
index 3a5bfec5d..7b9d9c678 100644
--- a/web/src/components/layout/mobile-nav.tsx
+++ b/web/src/components/layout/mobile-nav.tsx
@@ -158,7 +158,7 @@ export function MobileNav() {
<span
className={cn(
'block rounded-md px-3 py-1.5 text-sm transition-colors',
- pathname === child.href
+ pathname === child.href || pathname.startsWith(`${child.href}/`)
? 'font-medium text-primary'
: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
)}
diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsx
index 3c679ca12..53f11c455 100644
--- a/web/src/components/layout/sidebar.tsx
+++ b/web/src/components/layout/sidebar.tsx
@@ -405,7 +405,10 @@ export function Sidebar() {
{submenuOpen && (
<ul id={submenuId} className="mt-0.5 ml-[18px] space-y-0.5 border-l pl-2">
{item.children.map((child) => {
- const childActive = pathname === child.href;
+ // A view's own pages count too: a topic's page
+ // sits under Topics.
+ const childActive =
+ pathname === child.href || pathname.startsWith(`${child.href}/`);
return (
<li key={child.href}>
<Link
diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.ts
index 178a41672..24a5e577b 100644
--- a/web/src/config/dashboard.ts
+++ b/web/src/config/dashboard.ts
@@ -10,7 +10,6 @@ import {
Quote,
ShoppingBag,
Sparkles,
- Tag,
Target,
} from 'lucide-react';
import type { Feature } from '@/config/plans';
@@ -80,15 +79,12 @@ export const dashboardNav: NavGroup[] = [
children: [
{ title: 'Tracked Prompts', href: '/dashboard/prompts/tracked' },
{ title: 'Prompt Suggestions', href: '/dashboard/prompts/suggestions' },
+ // Was the Topics page (/dashboard/topics, which redirects here).
+ { title: 'Topics', href: '/dashboard/prompts/topics' },
{ title: 'Query Fan-outs', href: '/dashboard/prompts/fan-outs' },
{ title: 'Prompts Insights', href: '/dashboard/prompts/insights' },
],
},
- {
- title: 'Topics',
- href: '/dashboard/topics',
- icon: Tag,
- },
// Mentions & Sentiment (MS-05): beside Citations, its sibling concept.
{
title: 'Mentions',
diff --git a/web/src/lib/actions/topic-suggestions.ts b/web/src/lib/actions/topic-suggestions.ts
index 2d534cbfb..cd239d82b 100644
--- a/web/src/lib/actions/topic-suggestions.ts
+++ b/web/src/lib/actions/topic-suggestions.ts
@@ -125,6 +125,6 @@ export async function acceptTopicSuggestion(suggestionId: string): Promise<{ top
console.error('[topic-suggestions] accept ack failed:', await ack.text().catch(() => ''));
}
- revalidatePath('/dashboard/topics');
+ revalidatePath('/dashboard/prompts/topics');
return { topicId: topic.id };
}
diff --git a/web/src/lib/dashboard-navigation.test.ts b/web/src/lib/dashboard-navigation.test.ts
index 376e66255..b8210176a 100644
--- a/web/src/lib/dashboard-navigation.test.ts
+++ b/web/src/lib/dashboard-navigation.test.ts
@@ -22,6 +22,22 @@ describe('getDashboardNavLabel', () => {
}
});
+ // Topics moved into Prompts as one of its views, under the suggestions;
+ // /dashboard/topics redirects there.
+ it('lists Topics under Prompts, after Prompt Suggestions, and not as its own item', () => {
+ const items = dashboardNav.flatMap((group) => group.items);
+ const prompts = items.find((item) => item.title === 'Prompts')!;
+ expect(prompts.children?.map((c) => c.title)).toEqual([
+ 'Tracked Prompts',
+ 'Prompt Suggestions',
+ 'Topics',
+ 'Query Fan-outs',
+ 'Prompts Insights',
+ ]);
+ expect(prompts.children?.[2].href).toBe('/dashboard/prompts/topics');
+ expect(items.some((item) => item.href === '/dashboard/topics')).toBe(false);
+ });
+
it('uses the brands namespace only for Brands', () => {
expect(getDashboardNavLabel('Brands', translateNav, translateBrands)).toBe('brands.title');
expect(getDashboardNavLabel('Shopping', translateNav, translateBrands)).toBe('nav.shopping');
diff --git a/web/src/lib/dashboard-navigation.ts b/web/src/lib/dashboard-navigation.ts
index 290392198..23c28eed7 100644
--- a/web/src/lib/dashboard-navigation.ts
+++ b/web/src/lib/dashboard-navigation.ts
@@ -16,9 +16,9 @@ export const dashboardNavLabelKeys: Record<string, NavLabelKey> = {
Prompts: { namespace: 'nav', key: 'prompts' },
'Tracked Prompts': { namespace: 'nav', key: 'trackedPrompts' },
'Prompt Suggestions': { namespace: 'nav', key: 'promptSuggestions' },
+ Topics: { namespace: 'nav', key: 'topics' },
'Query Fan-outs': { namespace: 'nav', key: 'queryFanouts' },
'Prompts Insights': { namespace: 'nav', key: 'promptsInsights' },
- Topics: { namespace: 'nav', key: 'topics' },
'Content Optimization': { namespace: 'nav', key: 'content' },
'Site Audit': { namespace: 'nav', key: 'audit' },
Citations: { namespace: 'nav', key: 'citations' },
diff --git a/web/src/lib/prompts-routes.test.ts b/web/src/lib/prompts-routes.test.ts
index aaca992e6..4f2c9b06b 100644
--- a/web/src/lib/prompts-routes.test.ts
+++ b/web/src/lib/prompts-routes.test.ts
@@ -17,13 +17,15 @@ describe('sectionFromPath', () => {
tab: 'all',
view: 'suggestions',
});
+ expect(sectionFromPath('/dashboard/prompts/topics')?.tab).toBe('topics');
expect(sectionFromPath('/dashboard/prompts/fan-outs')?.tab).toBe('fanout');
expect(sectionFromPath('/dashboard/prompts/insights')?.tab).toBe('insights');
});
- test('is null off the four routes (the base path, a prompt detail page)', () => {
+ test('is null off the five routes (the base path, a prompt or topic detail page)', () => {
expect(sectionFromPath('/dashboard/prompts')).toBeNull();
expect(sectionFromPath('/dashboard/prompts/8a1c-uuid')).toBeNull();
+ expect(sectionFromPath('/dashboard/prompts/topics/8a1c-uuid')).toBeNull();
});
});
@@ -31,6 +33,7 @@ describe('sectionFor', () => {
test('maps the in-page tabs to the routes', () => {
expect(sectionFor('all', 'tracked').href).toBe('/dashboard/prompts/tracked');
expect(sectionFor('all', 'suggestions').href).toBe('/dashboard/prompts/suggestions');
+ expect(sectionFor('topics', 'suggestions').href).toBe('/dashboard/prompts/topics');
expect(sectionFor('fanout', 'suggestions').href).toBe('/dashboard/prompts/fan-outs');
expect(sectionFor('insights', 'tracked').href).toBe('/dashboard/prompts/insights');
});
diff --git a/web/src/lib/prompts-routes.ts b/web/src/lib/prompts-routes.ts
index 02247d3df..ba5e46bf7 100644
--- a/web/src/lib/prompts-routes.ts
+++ b/web/src/lib/prompts-routes.ts
@@ -1,15 +1,16 @@
/**
- * The Prompts area's four views and their routes (PROMPT-001). The sidebar's
+ * The Prompts area's five views and their routes (PROMPT-001). The sidebar's
* Prompts submenu links to them, and the page's own tabs keep the URL on the
- * matching route, so the two always show the same view.
+ * matching route, so the two always show the same view. Topics used to be
+ * its own page at /dashboard/topics, which redirects here.
*/
-export type PromptsTab = 'all' | 'fanout' | 'insights';
+export type PromptsTab = 'all' | 'topics' | 'fanout' | 'insights';
export type PromptsListView = 'tracked' | 'suggestions';
export interface PromptsSection {
/** The route's last segment. */
- slug: 'tracked' | 'suggestions' | 'fan-outs' | 'insights';
+ slug: 'tracked' | 'suggestions' | 'topics' | 'fan-outs' | 'insights';
href: string;
tab: PromptsTab;
/** The Tracked / Suggestions switch; only meaningful on the Prompts tab. */
@@ -21,11 +22,12 @@ export const PROMPTS_BASE = '/dashboard/prompts';
export const PROMPTS_SECTIONS: readonly PromptsSection[] = [
{ slug: 'tracked', href: `${PROMPTS_BASE}/tracked`, tab: 'all', view: 'tracked' },
{ slug: 'suggestions', href: `${PROMPTS_BASE}/suggestions`, tab: 'all', view: 'suggestions' },
+ { slug: 'topics', href: `${PROMPTS_BASE}/topics`, tab: 'topics', view: 'tracked' },
{ slug: 'fan-outs', href: `${PROMPTS_BASE}/fan-outs`, tab: 'fanout', view: 'tracked' },
{ slug: 'insights', href: `${PROMPTS_BASE}/insights`, tab: 'insights', view: 'tracked' },
];
-/** The section a pathname (without locale prefix) is on; null off the four routes. */
+/** The section a pathname (without locale prefix) is on; null off the five routes. */
export function sectionFromPath(pathname: string): PromptsSection | null {
const path = pathname.replace(/\/+$/, '');
return PROMPTS_SECTIONS.find((s) => s.href === path) ?? null;
@@ -33,13 +35,15 @@ export function sectionFromPath(pathname: string): PromptsSection | null {
/** The route for a tab and list view, as the page's tabs set them. */
export function sectionFor(tab: PromptsTab, view: PromptsListView): PromptsSection {
- if (tab === 'fanout') return PROMPTS_SECTIONS[2];
- if (tab === 'insights') return PROMPTS_SECTIONS[3];
- return view === 'suggestions' ? PROMPTS_SECTIONS[1] : PROMPTS_SECTIONS[0];
+ const bySlug = (slug: PromptsSection['slug']) => PROMPTS_SECTIONS.find((s) => s.slug === slug)!;
+ if (tab === 'topics') return bySlug('topics');
+ if (tab === 'fanout') return bySlug('fan-outs');
+ if (tab === 'insights') return bySlug('insights');
+ return bySlug(view === 'suggestions' ? 'suggestions' : 'tracked');
}
/**
- * Query params that carry over when moving between the four sections — the
+ * Query params that carry over when moving between the five sections — the
* date range and location stay; the tab and view are in the path now, and a
* prompt-specific panel or sort belongs to the table it was opened from.
*/