Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(mentions): add the Mentions overview tab (#1116)
Cihancab6f2b47966
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 6b3c1532f..c6c5fea81 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3011,7 +3011,87 @@"search": "Search","searchPlaceholder": "Search prompts, brands, phrases…"},- "comingSoon": "This view is on its way: its figures and charts arrive with the next updates."+ "comingSoon": "This view is on its way: its figures and charts arrive with the next updates.",+ "overview": {+ "sectionLabel": "Mentions overview",+ "loadError": "Couldn't load the overview. Try again in a moment.",+ "unavailable": "Mention figures aren't available yet. They appear once the mentions data has been prepared.",+ "pickDates": "Choose a start or end date to see the overview.",+ "empty": "No tracked responses in this period. Try a longer range or clear the filters.",+ "headline": {+ "label": "Summary",+ "net": "Net sentiment is <b>{net}</b>.",+ "netChange": "Net sentiment is <b>{net}</b> (<tone>{change}</tone> vs the previous {period}).",+ "netLowSample": "Net sentiment is <b>{net}</b> (low sample: {count, plural, one {# mention} other {# mentions}}).",+ "noMentions": "AI didn't name {brand} in the tracked responses of this period.",+ "moverDown": "Most of the drop is on <b>{platform} ({change})</b>.",+ "moverUp": "Most of the rise is on <b>{platform} ({change})</b>.",+ "companionsOne": "AI usually names {brand} next to <b>{first}</b>.",+ "companionsTwo": "AI usually names {brand} next to <b>{first}</b> and <b>{second}</b>.",+ "period": "{days, plural, one {day} other {# days}}",+ "period24h": "24 hours",+ "basis": "Built from aggregates with a fixed template, no LLM call · {range} · {answers, plural, one {# tracked response} other {# tracked responses}} · {mentions, plural, one {# mention} other {# mentions}}"+ },+ "kpi": {+ "totalMentions": "Total mentions",+ "totalMentionsTip": "Responses that name {brand} at least once. A response naming you twice counts once.",+ "totalMentionsSub": "responses naming {brand}",+ "mentionRate": "Mention rate",+ "mentionRateTip": "The share of tracked responses that name {brand}.",+ "mentionRateSub": "of {count} tracked responses",+ "promptsWithMentions": "Prompts with mentions",+ "promptsWithMentionsTip": "Prompts with at least one response naming {brand} in this period.",+ "promptsWithMentionsSub": "of {count} tracked prompts",+ "netSentiment": "Net sentiment",+ "netSentimentTip": "Positive minus negative share of the responses naming {brand}, from −100 to +100. Neutral mentions count in the total.",+ "sampleTip": "{count, plural, one {Based on # tracked response} other {Based on # tracked responses}} in this period.",+ "sampleTipNamed": "{count, plural, one {Based on # response naming {brand}} other {Based on # responses naming {brand}}} in this period.",+ "splitLabel": "{positive} positive, {neutral} neutral, {negative} negative",+ "lowSample": "{count, plural, one {Low sample · # response} other {Low sample · # responses}}"+ },+ "sentiment": {+ "positive": "Positive",+ "neutral": "Neutral",+ "negative": "Negative"+ },+ "trend": {+ "title": "Mentions & sentiment over time",+ "metricLabel": "Trend metric",+ "mentions": "Mentions",+ "rate": "Mention rate",+ "net": "Net sentiment",+ "tooltipResponses": "{count, plural, one {# response} other {# responses}}",+ "tooltipMentions": "{count, plural, one {# mention} other {# mentions}}",+ "lowSample": "Low sample",+ "tooShort": "The trend needs a range of at least two days."+ },+ "platforms": {+ "title": "By AI platform",+ "tableLabel": "Mentions and sentiment by AI platform",+ "platform": "Platform",+ "mentions": "Mentions",+ "rate": "Rate",+ "sentiment": "Sentiment",+ "net": "Net",+ "lowSample": "Low sample",+ "negativeNet": "negative net sentiment",+ "disagree": "Platforms disagree: {high} is {highNet} but {low} is {lowNet}."+ },+ "competitors": {+ "title": "Competitor framing",+ "description": "How often AI names each brand, and how often in the same responses as you.",+ "tableLabel": "Mentions of your brand and competitors",+ "brand": "Brand",+ "mentions": "Mentions",+ "rate": "Rate",+ "sentiment": "Sentiment",+ "net": "Net",+ "sameAnswer": "Same answer as you",+ "you": "You",+ "ownSentimentOnly": "Sentiment is measured for your brand only.",+ "none": "No competitors yet. Add them on the Competitors page to compare."+ }+ }},"competitors": {"title": "Competitors",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsxindex 0b0992826..2563472db 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx@@ -163,12 +163,14 @@ interface MetricCardProps {sub?: React.ReactNode;spark?: (number | null)[] | null;quota?: { used: number; limit: number; label: string } | null;+ /** In place of the sparkline, like Mentions' sentiment split. */+ footer?: React.ReactNode;onClick?: () => void;clickLabel?: string;}/** One KPI card, as in the v2 mockup: label, value with its change, a line of context, a sparkline. */-function MetricCard({+export function MetricCard({label,tooltip,icon: Icon,@@ -177,6 +179,7 @@ function MetricCard({sub,spark,quota,+ footer,onClick,clickLabel,}: MetricCardProps) {@@ -233,7 +236,9 @@ function MetricCard({)}</div><div className="truncate text-xs text-muted-foreground">{sub}</div>- {quota ? (+ {footer ? (+ footer+ ) : quota ? (<QuotaBar used={quota.used} limit={quota.limit} label={quota.label} />) : (<Sparkline values={spark ?? []} bad={delta?.tone === 'bad'} />diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_competitor-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_competitor-table.tsxnew file mode 100644index 000000000..33db07f79--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_competitor-table.tsx@@ -0,0 +1,106 @@+'use client';++import { useLocale, useTranslations } from 'next-intl';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { cn } from '@/lib/utils';+import { numberFormat } from '@/lib/number-format';+import { wholeNet } from '@/lib/mentions-headline';+import {+ isLowSample,+ mentionRate,+ sentimentSplit,+ type MentionsOverview,+} from '@/lib/mentions-overview';+import { signedValue, TONE_TEXT } from '../insights/kpi-format';+import { SentimentSplitBar } from './_sentiment-split';++/**+ * "Competitor framing" (MS-06): your brand, then each competitor with its+ * mentions, its rate over the same responses, and how many of those name you+ * too. Sentiment is stored toward your brand only, so a competitor's tone+ * stays "—" until it is measured; the strength and weakness columns come+ * with the themes.+ */+export function CompetitorTable({+ overview,+ brand,+ className,+}: {+ overview: Pick<MentionsOverview, 'current' | 'competitors'>;+ brand: string;+ className?: string;+}) {+ const t = useTranslations('mentions.overview.competitors');+ const locale = useLocale();+ const f = numberFormat(locale);+ const { current: cur } = overview;+ const ownRate = mentionRate(cur);+ const split = sentimentSplit(cur);+ const net = wholeNet(cur);+ const rateOf = (mentions: number) => (cur.answers > 0 ? (mentions * 100) / cur.answers : null);+ const competitors = [...overview.competitors].sort((a, b) => b.mentions - a.mentions);+ const pct = (n: number | null) => (n === null ? '—' : f.percent(n, 1));+ const dash = <span className="text-muted-foreground">—</span>;++ return (+ <Card className={className}>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ <p className="text-xs text-muted-foreground">{t('description')}</p>+ </CardHeader>+ <CardContent className="overflow-x-auto">+ <table className="w-full min-w-[640px] text-sm" aria-label={t('tableLabel')}>+ <thead>+ <tr className="border-b text-[11px] uppercase tracking-wide text-muted-foreground">+ <th className="py-2 pr-3 text-left font-medium">{t('brand')}</th>+ <th className="w-24 px-2 py-2 text-right font-medium">{t('mentions')}</th>+ <th className="w-20 px-2 py-2 text-right font-medium">{t('rate')}</th>+ <th className="w-40 px-2 py-2 text-left font-medium">{t('sentiment')}</th>+ <th className="w-16 px-2 py-2 text-right font-medium">{t('net')}</th>+ <th className="w-40 py-2 pl-2 text-right font-medium">{t('sameAnswer')}</th>+ </tr>+ </thead>+ <tbody>+ <tr className="border-b bg-muted/40 last:border-b-0">+ <td className="py-2.5 pr-3 font-semibold">+ <span className="inline-flex items-center gap-2">+ {brand}+ <span className="rounded-md bg-muted px-1.5 py-px text-[11px] font-medium text-muted-foreground">+ {t('you')}+ </span>+ </span>+ </td>+ <td className="px-2 py-2.5 text-right tabular-nums">{f.number(cur.mentions)}</td>+ <td className="px-2 py-2.5 text-right tabular-nums">{pct(ownRate)}</td>+ <td className="px-2 py-2.5">{split ? <SentimentSplitBar split={split} /> : dash}</td>+ <td+ className={cn(+ 'px-2 py-2.5 text-right font-semibold tabular-nums',+ net === null || isLowSample(cur)+ ? 'text-muted-foreground'+ : TONE_TEXT[net > 0 ? 'good' : net < 0 ? 'bad' : 'neutral'],+ )}+ >+ {net === null ? '—' : signedValue(net, locale)}+ </td>+ <td className="py-2.5 pl-2 text-right">{dash}</td>+ </tr>+ {competitors.map((c) => (+ <tr key={c.competitorId} className="border-b last:border-b-0">+ <td className="py-2.5 pr-3">{c.name}</td>+ <td className="px-2 py-2.5 text-right tabular-nums">{f.number(c.mentions)}</td>+ <td className="px-2 py-2.5 text-right tabular-nums">{pct(rateOf(c.mentions))}</td>+ <td className="px-2 py-2.5">{dash}</td>+ <td className="px-2 py-2.5 text-right">{dash}</td>+ <td className="py-2.5 pl-2 text-right tabular-nums">{f.number(c.coMentions)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ <p className="mt-3 text-xs text-muted-foreground">+ {competitors.length === 0 ? t('none') : t('ownSentimentOnly')}+ </p>+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsxnew file mode 100644index 000000000..e2b489801--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx@@ -0,0 +1,98 @@+'use client';++import { useLocale, useTranslations } from 'next-intl';+import { cn } from '@/lib/utils';+import { mentionPlatformLabel, mentionsHeadline } from '@/lib/mentions-headline';+import type { MentionsOverview } from '@/lib/mentions-overview';+import {+ arrowChange,+ dayLabel,+ signedChange,+ signedValue,+ TONE_TEXT,+} from '../insights/kpi-format';++/** "Oct 16, 9:40 AM": the 24h view's bounds, in local time. */+function momentLabel(value: string, locale: string): string {+ return new Date(value).toLocaleString(locale, {+ month: 'short',+ day: 'numeric',+ hour: 'numeric',+ minute: '2-digit',+ });+}++/**+ * The Overview's summary line (MS-06), as in the mockup: net sentiment and+ * its change, the platform behind most of it, and the brands AI names you+ * beside. Written from the aggregates by a fixed template, never an LLM, and+ * says so with the window and the responses it rests on.+ */+export function Headline({ overview, brand }: { overview: MentionsOverview; brand: string }) {+ const t = useTranslations('mentions.overview.headline');+ const locale = useLocale();+ const { net, lowSample, netChange, mover, companions } = mentionsHeadline(overview);+ const { window: w, current } = overview;+ const b = (chunks: React.ReactNode) => <b className="font-semibold">{chunks}</b>;++ const period = w.source === 'answers' ? t('period24h') : t('period', { days: w.days });+ const change = arrowChange(netChange, locale);+ const range =+ w.source === 'answers'+ ? `${momentLabel(w.from, locale)} – ${momentLabel(w.to, locale)}`+ : `${dayLabel(w.dayFrom, locale)} – ${dayLabel(w.dayTo, locale)}`;++ return (+ <section+ aria-label={t('label')}+ className="rounded-xl border border-l-[3px] border-l-foreground bg-card px-4 py-3 text-sm"+ >+ <p>+ {net === null+ ? t('noMentions', { brand })+ : change+ ? t.rich('netChange', {+ net: signedValue(net, locale),+ change: change.text,+ period,+ b,+ tone: (chunks) => (+ <span className={cn('font-medium', TONE_TEXT[change.tone])}>{chunks}</span>+ ),+ })+ : lowSample+ ? t.rich('netLowSample', {+ net: signedValue(net, locale),+ count: current.mentions,+ b,+ })+ : t.rich('net', { net: signedValue(net, locale), b })}+ {mover && (+ <>+ {' '}+ {t.rich(mover.change < 0 ? 'moverDown' : 'moverUp', {+ platform: mentionPlatformLabel(mover.platform),+ change: signedChange(mover.change, locale),+ b,+ })}+ </>+ )}+ {companions.length > 0 && (+ <>+ {' '}+ {companions.length === 1+ ? t.rich('companionsOne', { brand, first: companions[0], b })+ : t.rich('companionsTwo', { brand, first: companions[0], second: companions[1], b })}+ </>+ )}+ </p>+ <p className="mt-1 text-xs text-muted-foreground">+ {t('basis', {+ range,+ answers: current.answers,+ mentions: current.mentions,+ })}+ </p>+ </section>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview-kpis.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview-kpis.tsxnew file mode 100644index 000000000..dfdd135eb--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview-kpis.tsx@@ -0,0 +1,132 @@+'use client';++import { useLocale, useTranslations } from 'next-intl';+import { Layers, MessageCircle, Percent, Smile } from 'lucide-react';+import { numberFormat } from '@/lib/number-format';+import { wholeNet } from '@/lib/mentions-headline';+import {+ isLowSample,+ LOW_SAMPLE_MENTIONS,+ mentionRate,+ mentionTrend,+ relativeChange,+ sentimentSplit,+ type MentionsOverview,+} from '@/lib/mentions-overview';+import { MetricCard } from '../insights/_kpi-cards';+import { signedValue, upIsGood } from '../insights/kpi-format';+import { SentimentLegend, SentimentSplitBar } from './_sentiment-split';++/** A share as a bar where the Insights cards draw their sparkline. */+function ShareBar({ value, label }: { value: number; label: string }) {+ return (+ <div+ role="img"+ aria-label={label}+ className="my-[9px] h-1.5 overflow-hidden rounded-full bg-muted"+ >+ <div className="h-full rounded-full bg-foreground/60" style={{ width: `${value}%` }} />+ </div>+ );+}++/**+ * The Overview's KPI cards (MS-06), as in the mockup: Total mentions, Mention+ * rate, Prompts with mentions and Net sentiment with its split and n. Each+ * change is against the window of the same length before; a rate taken over+ * fewer than 20 responses is a "Low sample" and shows no change.+ */+export function OverviewKpis({ overview, brand }: { overview: MentionsOverview; brand: string }) {+ const t = useTranslations('mentions.overview.kpi');+ const locale = useLocale();+ const f = numberFormat(locale);+ const { current: cur, previous: prev } = overview;+ const trend = mentionTrend(overview);+ const round = (n: number | null, digits = 0) =>+ n === null ? null : Math.round(n * 10 ** digits) / 10 ** digits;++ const rate = mentionRate(cur);+ const prevRate = mentionRate(prev);+ const lowAnswers = cur.answers < LOW_SAMPLE_MENTIONS;+ const net = wholeNet(cur);+ const prevNet = wholeNet(prev);+ const split = sentimentSplit(cur);+ const promptShare = cur.prompts > 0 ? (cur.promptsWithMentions * 100) / cur.prompts : 0;++ return (+ <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">+ <MetricCard+ label={t('totalMentions')}+ tooltip={t('totalMentionsTip', { brand })}+ icon={MessageCircle}+ value={f.number(cur.mentions)}+ delta={upIsGood(round(relativeChange(cur.mentions, prev.mentions)), {+ percent: true,+ locale,+ })}+ sub={t('totalMentionsSub', { brand })}+ spark={trend.map((d) => d.mentions)}+ />+ <MetricCard+ label={t('mentionRate')}+ tooltip={`${t('mentionRateTip', { brand })} ${t('sampleTip', { count: cur.answers })}`}+ icon={Percent}+ value={rate === null ? '—' : f.percent(rate, 1)}+ delta={+ lowAnswers || rate === null || prevRate === null+ ? null+ : upIsGood(round(rate - prevRate, 1), { locale })+ }+ sub={+ rate !== null && lowAnswers+ ? t('lowSample', { count: cur.answers })+ : t('mentionRateSub', { count: f.number(cur.answers) })+ }+ spark={trend.map((d) => d.rate)}+ />+ <MetricCard+ label={t('promptsWithMentions')}+ tooltip={t('promptsWithMentionsTip', { brand })}+ icon={Layers}+ value={f.number(cur.promptsWithMentions)}+ delta={upIsGood(round(relativeChange(cur.promptsWithMentions, prev.promptsWithMentions)), {+ percent: true,+ locale,+ })}+ sub={t('promptsWithMentionsSub', { count: f.number(cur.prompts) })}+ footer={+ <ShareBar+ value={promptShare}+ label={`${f.number(cur.promptsWithMentions)} ${t('promptsWithMentionsSub', {+ count: f.number(cur.prompts),+ })}`}+ />+ }+ />+ <MetricCard+ label={t('netSentiment')}+ tooltip={`${t('netSentimentTip', { brand })} ${t('sampleTipNamed', {+ count: cur.mentions,+ brand,+ })}`}+ icon={Smile}+ value={net === null ? '—' : signedValue(net, locale)}+ delta={+ isLowSample(cur) || net === null || prevNet === null+ ? null+ : upIsGood(net - prevNet, { locale })+ }+ sub={+ split === null ? null : isLowSample(cur) ? (+ t('lowSample', { count: cur.mentions })+ ) : (+ <SentimentLegend split={split} />+ )+ }+ footer={+ split ? <SentimentSplitBar split={split} className="my-[9px]" /> : <div className="h-6" />+ }+ />+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.test.tsxnew file mode 100644index 000000000..4d5ee11ec--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.test.tsx@@ -0,0 +1,294 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import { DEFAULT_MENTIONS_FILTERS } from '@/lib/mentions-filters';+import type { MentionPlatformRow, MentionsOverview, MentionTotals } from '@/lib/mentions-overview';+import { CompetitorTable } from './_competitor-table';+import { Headline } from './_headline';+import { MentionsOverviewTab } from './_overview';+import { OverviewKpis } from './_overview-kpis';+import { PlatformTable } from './_platform-table';++const getMentionsOverview = vi.fn();+vi.mock('@/lib/actions/mentions', () => ({+ getMentionsOverview: (...args: unknown[]) => getMentionsOverview(...args),+}));+// The chart is loaded on demand and measured; its card is not what these tests read.+vi.mock('./_trend-card', () => ({ TrendCard: () => null }));++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const totals = (over: Partial<MentionTotals>): MentionTotals => ({+ answers: 0,+ mentions: 0,+ occurrences: 0,+ positive: 0,+ negative: 0,+ positionSum: 0,+ positionCount: 0,+ prompts: 0,+ promptsWithMentions: 0,+ lastAnswerAt: null,+ ...over,+});++const platform = (+ id: string,+ now: [number, number, number, number],+ before: [number, number, number, number] = [0, 0, 0, 0],+): MentionPlatformRow => ({+ platform: id,+ answers: now[0],+ mentions: now[1],+ positive: now[2],+ negative: now[3],+ previous: { answers: before[0], mentions: before[1], positive: before[2], negative: before[3] },+});++// The mockup's story: net +34, down 6, most of it on Gemini, usually beside+// Profound and Peec AI.+const overview: MentionsOverview = {+ window: {+ from: '2026-09-17T09:00:00Z',+ to: '2026-10-17T09:00:00Z',+ days: 30,+ source: 'days',+ dayFrom: '2026-09-18',+ dayTo: '2026-10-17',+ },+ current: totals({+ answers: 400,+ mentions: 100,+ positive: 48,+ negative: 14,+ prompts: 20,+ promptsWithMentions: 15,+ }),+ previous: totals({+ answers: 400,+ mentions: 80,+ positive: 40,+ negative: 8,+ prompts: 20,+ promptsWithMentions: 12,+ }),+ platforms: [+ platform('chatgpt-web', [100, 50, 30, 3], [100, 50, 30, 3]),+ platform('gemini-web', [100, 50, 15, 18], [100, 50, 16, 10]),+ platform('claude', [40, 10, 5, 0]),+ platform('grok-web', [0, 0, 0, 0], [10, 5, 1, 1]),+ ],+ daily: [],+ competitors: [+ { competitorId: 'o', name: 'Otterly AI', mentions: 120, coMentions: 31, previousMentions: 0 },+ { competitorId: 'p', name: 'Profound', mentions: 260, coMentions: 41, previousMentions: 0 },+ { competitorId: 'e', name: 'Peec AI', mentions: 90, coMentions: 36, previousMentions: 0 },+ ],+};++let container: HTMLDivElement;+let root: Root;++function render(node: React.ReactNode) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ {node}+ </NextIntlClientProvider>,+ );+ });+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ getMentionsOverview.mockReset();+ vi.useRealTimers();+});++describe('Headline', () => {+ it('writes the summary from the figures, and says what it is built from', () => {+ render(<Headline overview={overview} brand="Ansvisor" />);+ const [summary, basis] = container.querySelectorAll('p');+ expect(summary.textContent).toBe(+ 'Net sentiment is +34 (↓ 6 vs the previous 30 days). Most of the drop is on ' ++ 'Gemini (−18). AI usually names Ansvisor next to Profound and Peec AI.',+ );+ expect(basis.textContent).toBe(+ 'Built from aggregates with a fixed template, no LLM call · Sep 18 – Oct 17 · ' ++ '400 tracked responses · 100 mentions',+ );+ });++ it('marks a net taken over fewer than 20 mentions as a low sample, with no change', () => {+ render(+ <Headline+ overview={{+ ...overview,+ current: totals({ answers: 2, mentions: 2, negative: 1 }),+ competitors: [],+ }}+ brand="Ansvisor"+ />,+ );+ expect(container.querySelector('p')?.textContent).toBe(+ 'Net sentiment is −50 (low sample: 2 mentions).',+ );+ });++ it('says so when the brand was never named', () => {+ render(+ <Headline overview={{ ...overview, current: totals({ answers: 12 }) }} brand="Ansvisor" />,+ );+ expect(container.querySelector('p')?.textContent).toBe(+ "AI didn't name Ansvisor in the tracked responses of this period.",+ );+ });+});++describe('OverviewKpis', () => {+ it('shows each figure with its change and context', () => {+ render(<OverviewKpis overview={overview} brand="Ansvisor" />);+ const text = container.textContent;+ expect(text).toContain('100+25%');+ expect(text).toContain('responses naming Ansvisor');+ expect(text).toContain('25.0%+5');+ expect(text).toContain('of 400 tracked responses');+ expect(text).toContain('15+25%');+ expect(text).toContain('of 20 tracked prompts');+ expect(text).toContain('+34−6');+ expect(text).toContain('n=100');+ });++ it('marks net sentiment over fewer than 20 mentions as a low sample, without a change', () => {+ render(+ <OverviewKpis+ overview={{+ ...overview,+ current: totals({ answers: 400, mentions: 12, positive: 6, negative: 1 }),+ }}+ brand="Ansvisor"+ />,+ );+ expect(container.textContent).toContain('Low sample · 12 responses');+ expect(container.textContent).toContain('+42');+ expect(container.textContent).not.toContain('+42−');+ });+});++describe('PlatformTable', () => {+ it('lists the platforms answering now, tints a negative one and notes the disagreement', () => {+ render(<PlatformTable rows={overview.platforms} />);+ const rows = [...container.querySelectorAll('tbody tr')];+ expect(rows.map((r) => r.querySelector('td')?.textContent)).toEqual([+ 'ChatGPT',+ 'Gemini (negative net sentiment)',+ 'Claude',+ ]);+ expect(rows[1].className).toContain('bg-red-50');+ expect(rows[1].textContent).toContain('−6↓ 18');+ // Claude's 10 mentions are too few to judge: no colour, no change.+ expect(rows[2].textContent).toContain('+50Low sample');+ expect(container.textContent).toContain('Platforms disagree: ChatGPT is +54 but Gemini is −6.');+ });+});++describe('CompetitorTable', () => {+ it('puts you first, then competitors by mentions, with sentiment only for you', () => {+ render(<CompetitorTable overview={overview} brand="Ansvisor" />);+ const rows = [...container.querySelectorAll('tbody tr')].map((r) =>+ [...r.querySelectorAll('td')].map((td) => td.textContent),+ );+ expect(rows[0]).toEqual(['AnsvisorYou', '100', '25.0%', '', '+34', '—']);+ expect(rows.slice(1)).toEqual([+ ['Profound', '260', '65.0%', '—', '—', '41'],+ ['Otterly AI', '120', '30.0%', '—', '—', '31'],+ ['Peec AI', '90', '22.5%', '—', '—', '36'],+ ]);+ expect(container.textContent).toContain('Sentiment is measured for your brand only.');+ });+});++describe('MentionsOverviewTab', () => {+ it('reads the overview once the filters settle and shows it', async () => {+ vi.useFakeTimers();+ getMentionsOverview.mockResolvedValue(overview);+ render(+ <MentionsOverviewTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,+ );+ expect(getMentionsOverview).not.toHaveBeenCalled();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(getMentionsOverview).toHaveBeenCalledTimes(1);+ expect(getMentionsOverview.mock.calls[0][0]).toBe('b1');+ expect(container.textContent).toContain('Net sentiment is +34');+ });++ it('says a read failed, and shows the skeleton again once a newer one is on its way', async () => {+ vi.useFakeTimers();+ getMentionsOverview.mockRejectedValueOnce(new Error('offline'));+ render(+ <MentionsOverviewTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(container.textContent).toBe("Couldn't load the overview. Try again in a moment.");++ render(+ <MentionsOverviewTab+ brandId="b1"+ brand="Ansvisor"+ filters={{ ...DEFAULT_MENTIONS_FILTERS, range: '7d' }}+ />,+ );+ expect(container.textContent).toBe('');+ expect(container.querySelector('[aria-hidden]')).not.toBeNull();+ });++ it('asks for dates on a custom range without any', () => {+ render(+ <MentionsOverviewTab+ brandId="b1"+ brand="Ansvisor"+ filters={{ ...DEFAULT_MENTIONS_FILTERS, range: 'custom' }}+ />,+ );+ expect(container.textContent).toBe('Choose a start or end date to see the overview.');+ expect(getMentionsOverview).not.toHaveBeenCalled();+ });++ it('says when the period has no tracked responses, or the figures are unavailable', async () => {+ vi.useFakeTimers();+ getMentionsOverview.mockResolvedValueOnce({ ...overview, current: totals({}) });+ render(+ <MentionsOverviewTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(container.textContent).toBe(+ 'No tracked responses in this period. Try a longer range or clear the filters.',+ );++ getMentionsOverview.mockResolvedValueOnce(null);+ render(<MentionsOverviewTab brandId="b2" brand="Other" filters={DEFAULT_MENTIONS_FILTERS} />);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(container.textContent).toContain("Mention figures aren't available yet.");+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.tsxnew file mode 100644index 000000000..1d7499f49--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.tsx@@ -0,0 +1,123 @@+'use client';++import { useEffect, useMemo, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Card, CardContent } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';+import { getMentionsOverview } from '@/lib/actions/mentions';+import { mentionsQuery, type MentionsFilters } from '@/lib/mentions-filters';+import type { MentionsOverview } from '@/lib/mentions-overview';+import { cn } from '@/lib/utils';+import { CompetitorTable } from './_competitor-table';+import { Headline } from './_headline';+import { OverviewKpis } from './_overview-kpis';+import { PlatformTable } from './_platform-table';+import { TrendCard } from './_trend-card';++/** Typing in the search box reads once it pauses, not on every key. */+const READ_DELAY_MS = 250;++type Loaded =+ | { brandId: string; key: string; status: 'ok'; overview: MentionsOverview | null }+ | { brandId: string; key: string; status: 'error' };++function Message({ children }: { children: React.ReactNode }) {+ return (+ <Card>+ <CardContent className="py-10 text-center text-sm text-muted-foreground">+ {children}+ </CardContent>+ </Card>+ );+}++/**+ * The Overview tab (MS-06), top-down as in the mockup: the summary line, the+ * KPI cards, the trend beside the platform table, and the competitor+ * framing. One read per filter change; a newer change wins over a read+ * still on its way.+ */+export function MentionsOverviewTab({+ brandId,+ brand,+ filters,+}: {+ brandId: string;+ brand: string;+ filters: MentionsFilters;+}) {+ const t = useTranslations('mentions.overview');+ const query = useMemo(() => mentionsQuery(filters), [filters]);+ const key = query ? JSON.stringify([brandId, query]) : null;+ const [loaded, setLoaded] = useState<Loaded | null>(null);++ useEffect(() => {+ if (!key || !query) return;+ let cancelled = false;+ const timer = setTimeout(() => {+ getMentionsOverview(brandId, query)+ .then((overview) => {+ if (!cancelled) setLoaded({ brandId, key, status: 'ok', overview });+ })+ .catch(() => {+ if (!cancelled) setLoaded({ brandId, key, status: 'error' });+ });+ }, READ_DELAY_MS);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [brandId, key, query]);++ if (!query) return <Message>{t('pickDates')}</Message>;+ // Another brand's figures are never shown under this one's name.+ if (!loaded || loaded.brandId !== brandId) return <OverviewSkeleton />;+ if (loaded.status === 'error') {+ // A failed read gives way to the skeleton once a newer one is on its way.+ return loaded.key === key ? <Message>{t('loadError')}</Message> : <OverviewSkeleton />;+ }+ if (!loaded.overview) return <Message>{t('unavailable')}</Message>;++ const overview = loaded.overview;+ // The last read stays on screen, dimmed, while a newer one is on its way.+ const stale = loaded.key !== key;+ return (+ <section+ aria-label={t('sectionLabel')}+ aria-busy={stale}+ className={cn('flex flex-col gap-3 transition-opacity', stale && 'opacity-60')}+ >+ {overview.current.answers === 0 ? (+ <Message>{t('empty')}</Message>+ ) : (+ <>+ <Headline overview={overview} brand={brand} />+ <OverviewKpis overview={overview} brand={brand} />+ {/* Each card keeps its own height: the table grows with the platforms. */}+ <div className="grid items-start gap-3 xl:grid-cols-2">+ <TrendCard overview={overview} />+ <PlatformTable rows={overview.platforms} />+ </div>+ <CompetitorTable overview={overview} brand={brand} />+ </>+ )}+ </section>+ );+}++function OverviewSkeleton() {+ return (+ <div className="flex flex-col gap-3" aria-hidden>+ <Skeleton className="h-[72px] w-full rounded-xl" />+ <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">+ {[0, 1, 2, 3].map((i) => (+ <Skeleton key={i} className="h-[124px] rounded-xl" />+ ))}+ </div>+ <div className="grid gap-3 xl:grid-cols-2">+ <Skeleton className="h-[300px] rounded-xl" />+ <Skeleton className="h-[300px] rounded-xl" />+ </div>+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_platform-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_platform-table.tsxnew file mode 100644index 000000000..17eab0c4b--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_platform-table.tsx@@ -0,0 +1,144 @@+'use client';++import { useLocale, useTranslations } from 'next-intl';+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { cn } from '@/lib/utils';+import { numberFormat } from '@/lib/number-format';+import {+ mentionPlatformLabel,+ platformDisagreement,+ platformNetChange,+ wholeNet,+} from '@/lib/mentions-headline';+import {+ isLowSample,+ mentionRate,+ sentimentSplit,+ type MentionPlatformRow,+} from '@/lib/mentions-overview';+import { arrowChange, signedValue, TONE_TEXT } from '../insights/kpi-format';+import { SentimentSplitBar } from './_sentiment-split';++/**+ * "By AI platform" (MS-06), as in the mockup: per platform, Mentions, Mention+ * rate, the sentiment split and Net sentiment with its change. A platform+ * with negative net sentiment is tinted, and a note says when platforms+ * disagree. Fewer than 20 mentions is a "Low sample": no change, no tint.+ */+export function PlatformTable({+ rows,+ className,+}: {+ rows: MentionPlatformRow[];+ className?: string;+}) {+ const t = useTranslations('mentions.overview.platforms');+ const locale = useLocale();+ const f = numberFormat(locale);+ // Platforms answered only in the window before have nothing to show now.+ const shown = rows.filter((r) => r.answers > 0);+ const disagreement = platformDisagreement(shown);++ return (+ <Card className={className}>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ </CardHeader>+ <CardContent className="overflow-x-auto">+ <table className="w-full min-w-[480px] text-sm" aria-label={t('tableLabel')}>+ <thead>+ <tr className="border-b text-[11px] uppercase tracking-wide text-muted-foreground">+ <th className="py-2 pr-3 text-left font-medium">{t('platform')}</th>+ <th className="w-20 px-2 py-2 text-right font-medium">{t('mentions')}</th>+ <th className="w-16 px-2 py-2 text-right font-medium">{t('rate')}</th>+ <th className="w-[30%] px-2 py-2 text-left font-medium">{t('sentiment')}</th>+ <th className="w-24 py-2 pl-2 text-right font-medium">{t('net')}</th>+ </tr>+ </thead>+ <tbody>+ {shown.map((row) => {+ const rate = mentionRate(row);+ const split = sentimentSplit(row);+ const net = wholeNet(row);+ const low = isLowSample(row);+ const change = arrowChange(platformNetChange(row), locale);+ const negative = !low && net !== null && net < 0;+ return (+ <tr+ key={row.platform}+ className={cn(+ 'border-b last:border-b-0',+ negative && 'bg-red-50 dark:bg-red-950/30',+ )}+ >+ <td className="py-2.5 pr-3 font-medium">+ <span className="inline-flex items-center gap-2 whitespace-nowrap">+ <AIProviderAvatar+ provider={resolveAIProvider(row.platform, row.platform)}+ className="h-5 w-5"+ />+ {mentionPlatformLabel(row.platform)}+ </span>+ {negative && <span className="sr-only"> ({t('negativeNet')})</span>}+ </td>+ <td className="px-2 py-2.5 text-right tabular-nums">{f.number(row.mentions)}</td>+ <td className="px-2 py-2.5 text-right tabular-nums">+ {rate === null ? '—' : f.percent(rate, 0)}+ </td>+ <td className="px-2 py-2.5">+ {split ? (+ <SentimentSplitBar split={split} />+ ) : (+ <span className="text-muted-foreground">—</span>+ )}+ </td>+ <td className="py-2.5 pl-2 text-right tabular-nums">+ {net === null ? (+ <span className="text-muted-foreground">—</span>+ ) : (+ <span className="inline-flex flex-col items-end leading-tight">+ <span+ className={cn(+ 'font-semibold',+ low+ ? 'text-muted-foreground'+ : TONE_TEXT[net > 0 ? 'good' : net < 0 ? 'bad' : 'neutral'],+ )}+ >+ {signedValue(net, locale)}+ {change && (+ <span+ className={cn('ml-1 text-[11px] font-medium', TONE_TEXT[change.tone])}+ >+ {change.text}+ </span>+ )}+ </span>+ {low && (+ <span className="whitespace-nowrap text-[11px] text-muted-foreground">+ {t('lowSample')}+ </span>+ )}+ </span>+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ {disagreement && (+ <p className="mt-3 rounded-md border border-dashed bg-muted/40 px-3 py-2 text-xs text-muted-foreground">+ {t('disagree', {+ high: mentionPlatformLabel(disagreement.high.platform),+ highNet: signedValue(disagreement.high.net, locale),+ low: mentionPlatformLabel(disagreement.low.platform),+ lowNet: signedValue(disagreement.low.net, locale),+ })}+ </p>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_sentiment-split.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_sentiment-split.tsxnew file mode 100644index 000000000..0ebbb1b10--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_sentiment-split.tsx@@ -0,0 +1,60 @@+'use client';++import { useLocale, useTranslations } from 'next-intl';+import { cn } from '@/lib/utils';+import { numberFormat } from '@/lib/number-format';+import type { sentimentSplit } from '@/lib/mentions-overview';++type Split = NonNullable<ReturnType<typeof sentimentSplit>>;++/** Each tone's colour, in both themes; neutral stays grey and is never dropped. */+const TONE_FILL = {+ positive: 'bg-emerald-500 dark:bg-emerald-400',+ neutral: 'bg-muted-foreground/30',+ negative: 'bg-red-500 dark:bg-red-400',+} as const;++const TONES = ['positive', 'neutral', 'negative'] as const;++/** The mentions' tone as one bar: positive, neutral, negative (spec §6). */+export function SentimentSplitBar({ split, className }: { split: Split; className?: string }) {+ const t = useTranslations('mentions.overview.kpi');+ const f = numberFormat(useLocale());+ return (+ <div+ role="img"+ aria-label={t('splitLabel', {+ positive: f.percent(split.positive, 0),+ neutral: f.percent(split.neutral, 0),+ negative: f.percent(split.negative, 0),+ })}+ className={cn('flex h-1.5 overflow-hidden rounded-full bg-muted', className)}+ >+ {TONES.map((tone) => (+ <span+ key={tone}+ className={cn('h-full', TONE_FILL[tone])}+ style={{ width: `${split[tone]}%` }}+ />+ ))}+ </div>+ );+}++/** The bar's legend: each tone's share, then n, the mentions behind them. */+export function SentimentLegend({ split }: { split: Split }) {+ const t = useTranslations('mentions.overview.sentiment');+ const f = numberFormat(useLocale());+ return (+ <span className="inline-flex items-center gap-2.5">+ {TONES.map((tone) => (+ <span key={tone} className="inline-flex items-center gap-1" title={t(tone)}>+ <span aria-hidden className={cn('h-2 w-2 rounded-[2px]', TONE_FILL[tone])} />+ <span className="sr-only">{t(tone)}</span>+ {f.percent(split[tone], 0)}+ </span>+ ))}+ <span>n={f.number(split.n)}</span>+ </span>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-card.tsxnew file mode 100644index 000000000..1d165d6b7--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-card.tsx@@ -0,0 +1,76 @@+'use client';++import { useState } from 'react';+import dynamic from 'next/dynamic';+import { useTranslations } from 'next-intl';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';+import { cn } from '@/lib/utils';+import { mentionTrend, type MentionsOverview } from '@/lib/mentions-overview';+import type { TrendMetric } from './_trend-chart';++const MentionTrendChart = dynamic(() => import('./_trend-chart').then((m) => m.MentionTrendChart), {+ ssr: false,+ loading: () => <Skeleton className="h-[220px] w-full" />,+});++const METRICS: TrendMetric[] = ['mentions', 'rate', 'net'];++/**+ * "Mentions & sentiment over time" (MS-06): Mentions, Mention rate or Net+ * sentiment per day. The 24h view is read from the answers, not whole days,+ * so it has no trend to draw.+ */+export function TrendCard({+ overview,+ className,+}: {+ overview: MentionsOverview;+ className?: string;+}) {+ const t = useTranslations('mentions.overview.trend');+ const [metric, setMetric] = useState<TrendMetric>('mentions');+ const days = mentionTrend(overview);+ const drawable = overview.window.source === 'days' && days.length >= 2;++ return (+ <Card className={className}>+ <CardHeader className="flex flex-row flex-wrap items-center justify-between gap-2 pb-2">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ {drawable && (+ <div+ className="flex overflow-hidden rounded-md border"+ role="group"+ aria-label={t('metricLabel')}+ >+ {METRICS.map((m) => (+ <button+ key={m}+ type="button"+ onClick={() => setMetric(m)}+ aria-pressed={metric === m}+ className={cn(+ 'px-3 py-1.5 text-xs font-medium transition-colors',+ metric === m+ ? 'bg-primary text-primary-foreground'+ : 'bg-card text-foreground hover:bg-muted',+ )}+ >+ {t(m)}+ </button>+ ))}+ </div>+ )}+ </CardHeader>+ <CardContent>+ {drawable ? (+ <MentionTrendChart days={days} metric={metric} />+ ) : (+ <div className="flex h-[220px] items-center justify-center text-sm text-muted-foreground">+ {t('tooShort')}+ </div>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-chart.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-chart.tsxnew file mode 100644index 000000000..cee240c90--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-chart.tsx@@ -0,0 +1,156 @@+'use client';++import { useEffect, useRef, useState } from 'react';+import { useLocale, useTranslations } from 'next-intl';+import { Area, AreaChart, CartesianGrid, ReferenceLine, Tooltip, XAxis, YAxis } from 'recharts';+import { numberFormat } from '@/lib/number-format';+import { LOW_SAMPLE_MENTIONS, type MentionTrendDay } from '@/lib/mentions-overview';+import { dayLabel, signedValue } from '../insights/kpi-format';++export type TrendMetric = 'mentions' | 'rate' | 'net';++// Measured with a ResizeObserver (same approach as insights/_charts.tsx).+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>+ );+}++const HEIGHT = 220;+const STROKE = '#6366f1';++/**+ * The Overview's trend (MS-06): one metric per day over the window. A day+ * without responses has no rate and a day without mentions no net sentiment;+ * the line joins over them. Each point's tooltip gives its n, marked "Low+ * sample" under 20.+ */+export function MentionTrendChart({+ days,+ metric,+}: {+ days: MentionTrendDay[];+ metric: TrendMetric;+}) {+ const t = useTranslations('mentions.overview.trend');+ const locale = useLocale();+ const f = numberFormat(locale);+ const value = (n: number) =>+ metric === 'net'+ ? signedValue(Math.round(n), locale)+ : metric === 'rate'+ ? f.percent(n, 1)+ : f.number(n);++ return (+ <ChartContainer height={HEIGHT}>+ {(width) => (+ <AreaChart+ width={width}+ height={HEIGHT}+ data={days}+ margin={{ top: 8, right: 8, left: -16, bottom: 0 }}+ >+ <defs>+ <linearGradient id="mentionsTrendFill" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={STROKE} stopOpacity={0.18} />+ <stop offset="95%" stopColor={STROKE} stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid strokeDasharray="3 3" className="stroke-border" vertical={false} />+ <XAxis+ dataKey="day"+ tickFormatter={(day: string) => dayLabel(day, locale)}+ minTickGap={24}+ tick={{ fontSize: 11 }}+ tickLine={false}+ axisLine={false}+ className="fill-muted-foreground"+ />+ <YAxis+ // A rate's axis ends at the next ten above its peak, never past 100.+ domain={+ metric === 'net'+ ? [-100, 100]+ : metric === 'rate'+ ? [0, (max: number) => Math.min(100, Math.ceil(max / 10) * 10 || 10)]+ : [0, 'auto']+ }+ ticks={metric === 'net' ? [-100, -50, 0, 50, 100] : undefined}+ allowDecimals={false}+ tickFormatter={(v: number) =>+ metric === 'net'+ ? signedValue(v, locale)+ : metric === 'rate'+ ? f.percent(v, 0)+ : f.number(v)+ }+ tick={{ fontSize: 11 }}+ tickLine={false}+ axisLine={false}+ className="fill-muted-foreground"+ />+ {metric === 'net' && <ReferenceLine y={0} className="stroke-muted-foreground/40" />}+ <Tooltip+ isAnimationActive={false}+ content={({ active, payload }) => {+ const d = active ? (payload?.[0]?.payload as MentionTrendDay | undefined) : undefined;+ if (!d) return null;+ const v = d[metric];+ // A rate is taken over the day's responses, net sentiment over its mentions.+ const n = metric === 'net' ? d.mentions : d.answers;+ return (+ <div className="rounded-lg border bg-background px-3 py-2 text-xs shadow-md">+ <p className="mb-1 font-medium text-foreground">{dayLabel(d.day, locale)}</p>+ <p className="font-medium text-foreground tabular-nums">+ {v === null ? '—' : value(v)}+ </p>+ <p className="text-muted-foreground">+ {metric === 'net'+ ? t('tooltipMentions', { count: n })+ : t('tooltipResponses', { count: n })}+ {metric !== 'mentions' && n > 0 && n < LOW_SAMPLE_MENTIONS && (+ <> · {t('lowSample')}</>+ )}+ </p>+ </div>+ );+ }}+ />+ <Area+ type="monotone"+ dataKey={metric}+ stroke={STROKE}+ strokeWidth={2}+ fill={metric === 'net' ? 'none' : 'url(#mentionsTrendFill)'}+ connectNulls+ dot={false}+ activeDot={{ r: 4 }}+ isAnimationActive={false}+ />+ </AreaChart>+ )}+ </ChartContainer>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsxindex d6d41a695..f07208faf 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx@@ -19,6 +19,7 @@ import { writeUrlParams } from '@/lib/url-state';import { useBrandStore } from '@/stores/use-brand-store';import type { Topic } from '@/types';import { MentionsFilterBar } from './_filter-bar';+import { MentionsOverviewTab } from './_overview';/*** Mentions & Sentiment (MS-05): where AI mentions the brand, how it describes@@ -31,6 +32,9 @@ import { MentionsFilterBar } from './_filter-bar';export default function MentionsPage() {const t = useTranslations('mentions');const activeBrandId = useBrandStore((s) => s.activeBrandId);+ const brandName = useBrandStore(+ (s) => s.brands.find((b) => b.id === s.activeBrandId)?.name ?? '',+ );const [tab, setTab] = useState<MentionsTab>(DEFAULT_MENTIONS_TAB);const [filters, setFilters] = useState<MentionsFilters>(DEFAULT_MENTIONS_FILTERS);@@ -101,7 +105,13 @@ export default function MentionsPage() {/></div>- {MENTIONS_TABS.map((id) => (+ <TabsContent value="overview" className="mt-4">+ {/* Read once the URL's filters are in, so the first read is the right one. */}+ {urlRead && (+ <MentionsOverviewTab brandId={activeBrandId} brand={brandName} filters={filters} />+ )}+ </TabsContent>+ {MENTIONS_TABS.filter((id) => id !== 'overview').map((id) => (<TabsContent key={id} value={id} className="mt-4"><Card><CardContent className="py-10 text-center text-sm text-muted-foreground">diff --git a/web/src/lib/mentions-headline.test.ts b/web/src/lib/mentions-headline.test.tsnew file mode 100644index 000000000..68aee0be8--- /dev/null+++ b/web/src/lib/mentions-headline.test.ts@@ -0,0 +1,167 @@+import { describe, expect, it } from 'vitest';+import {+ mentionPlatformLabel,+ mentionsHeadline,+ platformDisagreement,+ platformNetChange,+} from './mentions-headline';+import type { MentionPlatformRow, MentionsOverview, MentionTotals } from './mentions-overview';++const totals = (over: Partial<MentionTotals>): MentionTotals => ({+ answers: 0,+ mentions: 0,+ occurrences: 0,+ positive: 0,+ negative: 0,+ positionSum: 0,+ positionCount: 0,+ prompts: 0,+ promptsWithMentions: 0,+ lastAnswerAt: null,+ ...over,+});++const platform = (+ id: string,+ now: [number, number, number],+ before: [number, number, number] = [0, 0, 0],+): MentionPlatformRow => ({+ platform: id,+ answers: now[0],+ mentions: now[0],+ positive: now[1],+ negative: now[2],+ previous: { answers: before[0], mentions: before[0], positive: before[1], negative: before[2] },+});++const overview = (over: Partial<MentionsOverview>): MentionsOverview => ({+ window: { from: '', to: '', days: 30, source: 'days', dayFrom: '', dayTo: '' },+ current: totals({}),+ previous: totals({}),+ platforms: [],+ daily: [],+ competitors: [],+ ...over,+});++describe('mentionsHeadline', () => {+ it('states the net sentiment, its change, the platform behind it and the usual companions', () => {+ const h = mentionsHeadline(+ overview({+ // Net +34 now (48% − 14%), +40 before: down 6.+ current: totals({ mentions: 100, positive: 48, negative: 14 }),+ previous: totals({ mentions: 100, positive: 50, negative: 10 }),+ platforms: [+ // ChatGPT: +60 → +60. Gemini: +12 → −6, down 18. Claude: up.+ platform('chatgpt-web', [40, 26, 2], [40, 26, 2]),+ platform('gemini-web', [50, 15, 18], [50, 16, 10]),+ platform('claude', [30, 20, 2], [30, 15, 3]),+ ],+ competitors: [+ {+ competitorId: 'p',+ name: 'Profound',+ mentions: 900,+ coMentions: 412,+ previousMentions: 0,+ },+ {+ competitorId: 'o',+ name: 'Otterly AI',+ mentions: 400,+ coMentions: 131,+ previousMentions: 0,+ },+ {+ competitorId: 'e',+ name: 'Peec AI',+ mentions: 500,+ coMentions: 286,+ previousMentions: 0,+ },+ ],+ }),+ );+ expect(h.net).toBe(34);+ expect(h.netChange).toBe(-6);+ expect(h.mover).toEqual({ platform: 'gemini-web', change: -18 });+ expect(h.companions).toEqual(['Profound', 'Peec AI']);+ });++ it('names no mover when the change is flat or no platform has enough mentions', () => {+ const flat = mentionsHeadline(+ overview({+ current: totals({ mentions: 20, positive: 10, negative: 2 }),+ previous: totals({ mentions: 20, positive: 10, negative: 2 }),+ platforms: [platform('gemini-web', [10, 1, 5], [10, 5, 1])],+ }),+ );+ expect(flat.netChange).toBe(0);+ expect(flat.mover).toBeNull();+ });++ it('has no figures for a window without mentions', () => {+ const h = mentionsHeadline(overview({}));+ expect(h).toEqual({+ net: null,+ lowSample: true,+ netChange: null,+ mover: null,+ companions: [],+ });+ });++ it('gives no change from or to a low sample', () => {+ const h = mentionsHeadline(+ overview({+ current: totals({ mentions: 2, positive: 0, negative: 1 }),+ previous: totals({ mentions: 40, positive: 20, negative: 0 }),+ }),+ );+ expect(h).toMatchObject({ net: -50, lowSample: true, netChange: null, mover: null });+ expect(+ mentionsHeadline(+ overview({+ current: totals({ mentions: 40, positive: 20, negative: 0 }),+ previous: totals({ mentions: 2, positive: 0, negative: 1 }),+ }),+ ),+ ).toMatchObject({ net: 50, lowSample: false, netChange: null });+ });+});++describe('platformNetChange', () => {+ it('needs 20 mentions in both windows', () => {+ expect(platformNetChange(platform('claude', [20, 10, 0], [20, 5, 0]))).toBe(25);+ expect(platformNetChange(platform('claude', [19, 10, 0], [20, 5, 0]))).toBeNull();+ });+});++describe('platformDisagreement', () => {+ it('flags platforms 40 points apart or more', () => {+ expect(+ platformDisagreement([+ platform('chatgpt-web', [50, 30, 3]), // +54+ platform('gemini-web', [50, 15, 18]), // −6+ platform('claude', [10, 0, 10]), // low sample: left out+ ]),+ ).toEqual({+ high: { platform: 'chatgpt-web', net: 54 },+ low: { platform: 'gemini-web', net: -6 },+ });+ });++ it('stays quiet when they roughly agree or only one can be compared', () => {+ expect(+ platformDisagreement([platform('chatgpt-web', [50, 30, 3]), platform('claude', [50, 25, 5])]),+ ).toBeNull();+ expect(platformDisagreement([platform('chatgpt-web', [50, 30, 3])])).toBeNull();+ });+});++describe('mentionPlatformLabel', () => {+ it('names the tracked platforms and keeps any other id', () => {+ expect(mentionPlatformLabel('gemini-web')).toBe('Gemini');+ expect(mentionPlatformLabel('new-engine')).toBe('new-engine');+ });+});diff --git a/web/src/lib/mentions-headline.ts b/web/src/lib/mentions-headline.tsnew file mode 100644index 000000000..2a6b205e5--- /dev/null+++ b/web/src/lib/mentions-headline.ts@@ -0,0 +1,110 @@+import { PLATFORM_LABELS } from '@/config/platform-labels';+import { POSITION_PLATFORMS } from '@/lib/prompt-positions';+import {+ isLowSample,+ LOW_SAMPLE_MENTIONS,+ netSentiment,+ type MentionPlatformRow,+ type MentionsOverview,+} from '@/lib/mentions-overview';++/** A platform id as the filter bar names it ("gemini-web" → "Gemini"). */+export function mentionPlatformLabel(platform: string): string {+ return (+ POSITION_PLATFORMS.find((p) => p.id === platform)?.label ??+ PLATFORM_LABELS[platform] ??+ platform+ );+}++/** Net sentiment in whole points, as the page shows it; null with no mentions. */+export function wholeNet(t: Parameters<typeof netSentiment>[0]): number | null {+ const net = netSentiment(t);+ return net === null ? null : Math.round(net);+}++/**+ * What the Overview's summary line (MS-06) says, chosen from the aggregates by+ * a fixed template, never an LLM: the net sentiment and its change, the+ * platform that moved it most, and the brands AI names you beside most often.+ * The page words it; this picks the facts.+ */+export interface MentionsHeadline {+ /** The window's net sentiment in whole points; null with no mentions. */+ net: number | null;+ /** Fewer than 20 mentions: the net is shown as a low sample, without a change. */+ lowSample: boolean;+ /** Against the window before; null when either is a low sample. */+ netChange: number | null;+ /** The platform whose net moved most the same way, when both windows have enough mentions. */+ mover: { platform: string; change: number } | null;+ /** Up to two competitors AI names in the same answers as you, most often first. */+ companions: string[];+}++export function mentionsHeadline(o: MentionsOverview): MentionsHeadline {+ const net = wholeNet(o.current);+ const previous = wholeNet(o.previous);+ const lowSample = isLowSample(o.current);+ // Like the KPI cards: no change from or to a low sample.+ const netChange =+ net !== null && previous !== null && !lowSample && !isLowSample(o.previous)+ ? net - previous+ : null;++ let mover: MentionsHeadline['mover'] = null;+ if (netChange !== null && netChange !== 0) {+ for (const row of o.platforms) {+ const change = platformNetChange(row);+ if (change === null || Math.sign(change) !== Math.sign(netChange)) continue;+ if (!mover || Math.abs(change) > Math.abs(mover.change)) {+ mover = { platform: row.platform, change };+ }+ }+ }++ // Named beside you only when you were named at all.+ const companions =+ o.current.mentions > 0+ ? o.competitors+ .filter((c) => c.coMentions > 0)+ .sort((a, b) => b.coMentions - a.coMentions)+ .slice(0, 2)+ .map((c) => c.name)+ : [];++ return { net, lowSample, netChange, mover, companions };+}++/**+ * A platform's net sentiment change against the window before, only when both+ * windows have enough mentions to say so (fewer than 20 is a low sample).+ */+export function platformNetChange(row: MentionPlatformRow): number | null {+ if (row.mentions < LOW_SAMPLE_MENTIONS || row.previous.mentions < LOW_SAMPLE_MENTIONS) {+ return null;+ }+ const now = wholeNet(row);+ const before = wholeNet(row.previous);+ return now !== null && before !== null ? now - before : null;+}++/** Platforms whose net sentiment differs by at least this many points disagree. */+export const PLATFORM_DISAGREEMENT_POINTS = 40;++/**+ * The most and least favourable platforms when they disagree (spec §6:+ * "ChatGPT is +54 but Gemini is −6"); null when they don't, or when fewer+ * than two have enough mentions to compare.+ */+export function platformDisagreement(+ rows: MentionPlatformRow[],+): { high: { platform: string; net: number }; low: { platform: string; net: number } } | null {+ const nets = rows+ .filter((r) => r.mentions >= LOW_SAMPLE_MENTIONS)+ .map((r) => ({ platform: r.platform, net: wholeNet(r) as number }));+ if (nets.length < 2) return null;+ const high = nets.reduce((a, b) => (b.net > a.net ? b : a));+ const low = nets.reduce((a, b) => (b.net < a.net ? b : a));+ return high.net - low.net >= PLATFORM_DISAGREEMENT_POINTS ? { high, low } : null;+}diff --git a/web/src/lib/mentions-overview.test.ts b/web/src/lib/mentions-overview.test.tsindex d1118c4ce..09d6090e4 100644--- a/web/src/lib/mentions-overview.test.ts+++ b/web/src/lib/mentions-overview.test.ts@@ -3,13 +3,22 @@ import {averagePosition,isLowSample,mentionRate,+ mentionTrend,netSentiment,parseMentionsOverview,+ relativeChange,sentimentSplit,} from './mentions-overview';const raw = {- window: { from: '2026-09-17T06:00:00Z', to: '2026-10-17T06:00:00Z', days: 30, source: 'days' },+ window: {+ from: '2026-09-17T06:00:00Z',+ to: '2026-10-17T06:00:00Z',+ days: 30,+ source: 'days',+ day_from: '2026-09-18',+ day_to: '2026-10-17',+ },current: {answers: 107,mentions: 107,@@ -56,6 +65,8 @@ describe('parseMentionsOverview', () => {to: '2026-10-17T06:00:00Z',days: 30,source: 'days',+ dayFrom: '2026-09-18',+ dayTo: '2026-10-17',});expect(o.current).toMatchObject({answers: 107,@@ -130,3 +141,35 @@ describe('the Overview metrics', () => {expect(averagePosition({ positionSum: 0, positionCount: 0 })).toBeNull();});});++describe('relativeChange', () => {+ it('is the change in percent, and null with nothing before', () => {+ expect(relativeChange(112, 100)).toBe(12);+ expect(relativeChange(90, 120)).toBe(-25);+ expect(relativeChange(5, 0)).toBeNull();+ });+});++describe('mentionTrend', () => {+ it('lists every day of the window, a day without answers as zero', () => {+ const trend = mentionTrend({+ window: {+ from: '',+ to: '',+ days: 3,+ source: 'days',+ dayFrom: '2026-10-15',+ dayTo: '2026-10-17',+ },+ daily: [+ { day: '2026-10-15', answers: 10, mentions: 4, positive: 2, negative: 1 },+ { day: '2026-10-17', answers: 5, mentions: 0, positive: 0, negative: 0 },+ ],+ });+ expect(trend).toEqual([+ { day: '2026-10-15', answers: 10, mentions: 4, rate: 40, net: 25 },+ { day: '2026-10-16', answers: 0, mentions: 0, rate: null, net: null },+ { day: '2026-10-17', answers: 5, mentions: 0, rate: 0, net: null },+ ]);+ });+});diff --git a/web/src/lib/mentions-overview.ts b/web/src/lib/mentions-overview.tsindex d28585d29..780c52de6 100644--- a/web/src/lib/mentions-overview.ts+++ b/web/src/lib/mentions-overview.ts@@ -63,6 +63,9 @@ export interface MentionsOverview {days: number;/** Under two days the answers were read directly; longer windows read whole UTC days. */source: 'answers' | 'days';+ /** The UTC days the window covers, `YYYY-MM-DD`. */+ dayFrom: string;+ dayTo: string;};current: MentionTotals;previous: MentionTotals;@@ -118,6 +121,8 @@ export function parseMentionsOverview(raw: unknown): MentionsOverview | null {to: String(w.to ?? ''),days: num(w, 'days'),source: w.source === 'answers' ? 'answers' : 'days',+ dayFrom: String(w.day_from ?? ''),+ dayTo: String(w.day_to ?? ''),},current: totals(r.current as Raw | null),previous: totals(r.previous as Raw | null),@@ -194,3 +199,45 @@ export function isLowSample(t: Pick<Counts, 'mentions'>): boolean {export function averagePosition(t: Pick<MentionTotals, 'positionSum' | 'positionCount'>) {return t.positionCount > 0 ? t.positionSum / t.positionCount : null;}++/** A count's change against the window before, in percent; null when there was nothing before. */+export function relativeChange(current: number, previous: number): number | null {+ return previous > 0 ? ((current - previous) * 100) / previous : null;+}++/** One day of the trend: the mentions, and the rates when the day has answers to take them over. */+export interface MentionTrendDay {+ day: string;+ answers: number;+ mentions: number;+ /** Null on a day without answers. */+ rate: number | null;+ /** Null on a day without mentions. */+ net: number | null;+}++/**+ * The window's days in order, a day without answers included as zero (the+ * function returns only days that have some), so the trend's axis is even.+ */+export function mentionTrend(o: Pick<MentionsOverview, 'window' | 'daily'>): MentionTrendDay[] {+ const byDay = new Map(o.daily.map((d) => [d.day, d]));+ const days: string[] = [];+ const from = Date.parse(`${o.window.dayFrom}T00:00:00Z`);+ const to = Date.parse(`${o.window.dayTo}T00:00:00Z`);+ if (Number.isFinite(from) && Number.isFinite(to)) {+ for (let t = from; t <= to; t += 86_400_000) days.push(new Date(t).toISOString().slice(0, 10));+ } else {+ days.push(...byDay.keys());+ }+ return days.map((day) => {+ const d = byDay.get(day) ?? { day, answers: 0, mentions: 0, positive: 0, negative: 0 };+ return {+ day,+ answers: d.answers,+ mentions: d.mentions,+ rate: mentionRate(d),+ net: netSentiment(d),+ };+ });+}