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): show the Perception tab (#1124)
Cihan38c6808b1b59
diff --git a/web/messages/en.json b/web/messages/en.jsonindex cb5e4fe88..80a55d509 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -5216,7 +5216,6 @@"search": "Search","searchPlaceholder": "Search prompts…"},- "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.",@@ -5433,6 +5432,47 @@"kpiChange": "{label}: {value} ({change})","net": "{net} · {split} (n={count})"}+ },+ "perception": {+ "sectionLabel": "Perception",+ "loadError": "Couldn't load the perception figures. Try again in a moment.",+ "unavailable": "Perception isn't available yet. It appears once the mentions data has been prepared.",+ "pickDates": "Choose a start or end date to see the perception figures.",+ "noMentions": "AI didn't name {brand} in the tracked responses of this period.",+ "method": "Terms come from the sentences that name each brand, by rule (no LLM). A sentence naming two brands lends its words to both.",+ "terms": {+ "title": "What AI associates with {brand}",+ "note": "Words and phrases next to your brand, by responses",+ "tableLabel": "Terms AI uses next to your brand",+ "responses": "{count, plural, one {# response} other {# responses}}",+ "share": "{share} of responses naming {brand}",+ "none": "No terms yet. They appear once this period's responses have been prepared."+ },+ "shape": {+ "title": "Brand shape: you vs top competitors",+ "chartLabel": "Share of the responses naming each brand, on the attributes that tell them apart",+ "notEnough": "The shape needs at least three attributes and one competitor named in this period."+ },+ "gap": {+ "title": "Biggest gap",+ "unplaced": "“{term}”: {competitor} in {competitorShare} of the responses naming it; AI doesn't use it for {brand}.",+ "ranked": "“{term}”: {competitor} in {competitorShare} of the responses naming it; {brand} in {brandShare} (#{rank})."+ },+ "heatmap": {+ "title": "Brand × attribute",+ "note": "Share of the responses naming each brand",+ "tableLabel": "Each attribute's share of the responses naming each brand",+ "attribute": "Attribute",+ "you": "You",+ "none": "No attributes yet for this period."+ },+ "coMentions": {+ "title": "Frequently mentioned with",+ "tableLabel": "Competitors named in the same responses as you",+ "note": "The trend shows whether the AI's consideration set around you is changing.",+ "responses": "{count, plural, one {# response} other {# responses}}",+ "none": "No competitor is named in the same responses as you in this period."+ }}},"competitors": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_brand-shape-chart.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_brand-shape-chart.tsxnew file mode 100644index 000000000..edcf42016--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_brand-shape-chart.tsx@@ -0,0 +1,113 @@+'use client';++import { useEffect, useRef, useState } from 'react';+import { useLocale } from 'next-intl';+import { PolarAngleAxis, PolarGrid, PolarRadiusAxis, Radar, RadarChart, Tooltip } from 'recharts';+import { numberFormat } from '@/lib/number-format';++// 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 = 280;++export interface ShapeSeries {+ key: string;+ name: string;+ color: string;+}++/**+ * "Brand shape" (MS-09): each brand's share of the responses naming it, on the attributes+ * that tell them apart, one outline per brand. The axis ends at the next ten+ * above the highest share, so a low-share set still fills the chart.+ */+export function BrandShapeChart({+ data,+ series,+}: {+ /** One row per attribute: { attribute, [series key]: share } */+ data: Record<string, string | number | null>[];+ series: ShapeSeries[];+}) {+ const f = numberFormat(useLocale());+ const top = Math.max(10, ...data.flatMap((row) => series.map((s) => Number(row[s.key] ?? 0))));+ const domainTop = Math.min(100, Math.ceil(top / 10) * 10);++ return (+ <ChartContainer height={HEIGHT}>+ {(width) => (+ <RadarChart width={width} height={HEIGHT} data={data} outerRadius="72%">+ <PolarGrid className="stroke-border" />+ {/* No axis line: the grid draws the outline, and the class's fill would cover the shapes. */}+ <PolarAngleAxis+ dataKey="attribute"+ tick={{ fontSize: 11 }}+ axisLine={false}+ className="fill-muted-foreground"+ />+ <PolarRadiusAxis domain={[0, domainTop]} tick={false} axisLine={false} />+ <Tooltip+ isAnimationActive={false}+ content={({ active, payload, label }) => {+ if (!active || !payload?.length) return null;+ return (+ <div className="rounded-lg border bg-background px-3 py-2 text-xs shadow-md">+ <p className="mb-1 font-medium text-foreground">{label}</p>+ {payload.map((entry) => (+ <div key={String(entry.dataKey)} className="flex items-center gap-2">+ <span+ className="inline-block h-2 w-2 shrink-0 rounded-full"+ style={{ backgroundColor: String(entry.color) }}+ />+ <span className="text-muted-foreground">{entry.name}:</span>+ <span className="font-medium text-foreground tabular-nums">+ {typeof entry.value === 'number' ? f.percent(entry.value, 0) : '—'}+ </span>+ </div>+ ))}+ </div>+ );+ }}+ />+ {series.map((s) => (+ <Radar+ key={s.key}+ name={s.name}+ dataKey={s.key}+ stroke={s.color}+ fill={s.color}+ fillOpacity={0.12}+ strokeWidth={2}+ isAnimationActive={false}+ />+ ))}+ </RadarChart>+ )}+ </ChartContainer>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_brand-shape.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_brand-shape.tsxnew file mode 100644index 000000000..f73f4b117--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_brand-shape.tsx@@ -0,0 +1,86 @@+'use client';++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 { attributeShares, biggestGap, type MentionsPerception } from '@/lib/mentions-perception';+import { GapNote } from './_perception-cards';+import type { ShapeSeries } from './_brand-shape-chart';++const BrandShapeChart = dynamic(+ () => import('./_brand-shape-chart').then((m) => m.BrandShapeChart),+ { ssr: false, loading: () => <Skeleton className="h-[280px] w-full" /> },+);++/** The radar compares you with up to this many competitors (spec §9). */+const RADAR_COMPETITORS = 3;+/**+ * Your brand in ink, as the rest of the Mentions page draws it (#1217,+ * #1220); the competitors in hues that aren't the brand's or violet.+ */+const BRAND_STROKE = 'var(--primary)';+const COMPETITOR_STROKES = ['#f97316', '#0d9488', '#ef4444'];+/** A shape needs at least this many attributes to have one. */+const MIN_ATTRIBUTES = 3;++/**+ * "Brand shape: you vs top competitors" (MS-09): a radar of the brand and its+ * three most mentioned competitors on the attributes that tell them apart,+ * in the Insights trend's colors, with the biggest gap beneath it.+ */+export function BrandShapeCard({+ perception,+ brand,+ className,+}: {+ perception: MentionsPerception;+ brand: string;+ className?: string;+}) {+ const t = useTranslations('mentions.perception.shape');+ const entities = perception.entities.slice(0, RADAR_COMPETITORS + 1);+ const rows = attributeShares({ ...perception, entities });+ const series: ShapeSeries[] = entities.map((e, i) => ({+ key: `e${i}`,+ name: e.isBrand ? brand : e.name,+ color: e.isBrand ? BRAND_STROKE : COMPETITOR_STROKES[(i - 1) % COMPETITOR_STROKES.length],+ }));+ const data = rows.map((row) => ({+ attribute: row.term,+ ...Object.fromEntries(row.shares.map((share, i) => [`e${i}`, share])),+ }));+ const drawable = rows.length >= MIN_ATTRIBUTES && entities.length >= 2;+ // Among the brands drawn, so the note never names one the radar doesn't show.+ const gap = biggestGap({ ...perception, entities });++ return (+ <Card className={className}>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ </CardHeader>+ <CardContent className="space-y-3">+ {drawable ? (+ <figure aria-label={t('chartLabel')}>+ <BrandShapeChart data={data} series={series} />+ <figcaption className="flex flex-wrap justify-center gap-3 text-xs text-muted-foreground">+ {series.map((s) => (+ <span key={s.key} className="inline-flex items-center gap-1.5">+ <span+ aria-hidden+ className="inline-block h-2 w-2 rounded-full"+ style={{ backgroundColor: s.color }}+ />+ {s.name}+ </span>+ ))}+ </figcaption>+ </figure>+ ) : (+ <p className="text-sm text-muted-foreground">{t('notEnough')}</p>+ )}+ {gap && <GapNote gap={gap} brand={brand} />}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception-cards.tsxnew file mode 100644index 000000000..a3c0197aa--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception-cards.tsx@@ -0,0 +1,245 @@+'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 {+ attributeShares,+ changeOf,+ shareOf,+ type MentionsPerception,+ type PerceptionGap,+} from '@/lib/mentions-perception';+import { TONE_TEXT, upIsGood } from '../insights/kpi-format';++/** A count's change against the window before, as "+12%"; neutral in tone, since more isn't better here. */+function Change({ now, before }: { now: number; before: number }) {+ const locale = useLocale();+ const raw = changeOf(now, before);+ const change = upIsGood(raw === null ? null : Math.round(raw), { percent: true, locale });+ if (!change) return <span className="text-muted-foreground">—</span>;+ return <span className={TONE_TEXT.neutral}>{change.text}</span>;+}++function Bar({ value, max }: { value: number; max: number }) {+ return (+ <span className="block h-1.5 overflow-hidden rounded-full bg-muted">+ <span+ className="block h-full rounded-full bg-foreground/60"+ style={{ width: `${max > 0 ? (value / max) * 100 : 0}%` }}+ />+ </span>+ );+}++/**+ * "What AI associates with you" (MS-09): the brand's top terms, each with+ * the responses it comes in, its share of the responses naming the brand and its change+ * against the window before.+ */+export function TermsCard({+ perception,+ brand,+ className,+}: {+ perception: MentionsPerception;+ brand: string;+ className?: string;+}) {+ const t = useTranslations('mentions.perception.terms');+ const f = numberFormat(useLocale());+ const mentions = perception.entities.find((e) => e.isBrand)?.mentions ?? 0;+ const max = Math.max(0, ...perception.brandTerms.map((term) => term.answers));++ return (+ <Card className={className}>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{t('title', { brand })}</CardTitle>+ <p className="text-xs text-muted-foreground">{t('note')}</p>+ </CardHeader>+ <CardContent>+ {perception.brandTerms.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('none')}</p>+ ) : (+ <table className="w-full text-sm" aria-label={t('tableLabel')}>+ <tbody>+ {perception.brandTerms.map((term) => {+ const share = shareOf(term.answers, mentions);+ return (+ <tr key={term.term} className="border-b last:border-b-0">+ <td className="py-1.5 pr-3 font-medium">{term.term}</td>+ <td className="w-[40%] px-2 py-1.5">+ <Bar value={term.answers} max={max} />+ </td>+ <td+ className="w-24 px-2 py-1.5 text-right text-xs text-muted-foreground tabular-nums"+ title={+ share === null+ ? undefined+ : t('share', { share: f.percent(share, 0), brand })+ }+ >+ {t('responses', { count: term.answers })}+ </td>+ <td className="w-14 py-1.5 pl-2 text-right text-xs tabular-nums">+ <Change now={term.answers} before={term.previousAnswers} />+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ )}+ </CardContent>+ </Card>+ );+}++/**+ * "Brand × attribute" (MS-09): each attribute's share of each brand's+ * mentions, the brand and up to four competitors, the cell shaded by share.+ */+export function HeatmapCard({+ perception,+ className,+}: {+ perception: MentionsPerception;+ className?: string;+}) {+ const t = useTranslations('mentions.perception.heatmap');+ const f = numberFormat(useLocale());+ const rows = attributeShares(perception);++ 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('note')}</p>+ </CardHeader>+ <CardContent className="overflow-x-auto">+ {rows.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('none')}</p>+ ) : (+ <table className="w-full min-w-[420px] 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('attribute')}</th>+ {perception.entities.map((e) => (+ <th key={e.entity} className="px-2 py-2 text-center font-medium">+ <span className="line-clamp-2 normal-case tracking-normal">+ {e.isBrand ? t('you') : e.name}+ </span>+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.map((row) => (+ <tr key={row.term} className="border-b last:border-b-0">+ <td className="py-1.5 pr-3 font-medium">{row.term}</td>+ {row.shares.map((share, i) => (+ <td+ key={perception.entities[i].entity}+ className="px-2 py-1.5 text-center text-xs tabular-nums"+ // The share as a neutral tint (the brand has no colour on this+ // page, only ink), readable on both themes.+ style={+ share+ ? {+ backgroundColor: `rgba(120, 113, 108, ${Math.min(0.45, share / 150)})`,+ }+ : undefined+ }+ >+ {share === null ? '—' : f.percent(share, 0)}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </CardContent>+ </Card>+ );+}++/**+ * "Frequently mentioned with" (MS-09): the competitors AI names in the same+ * responses as the brand, and the change against the window before (is the+ * AI's consideration set around you changing?).+ */+export function CoMentionsCard({+ perception,+ className,+}: {+ perception: MentionsPerception;+ className?: string;+}) {+ const t = useTranslations('mentions.perception.coMentions');+ const shown = perception.coMentions.filter((c) => c.coMentions > 0);+ const max = Math.max(0, ...shown.map((c) => c.coMentions));++ return (+ <Card className={className}>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ </CardHeader>+ <CardContent className="space-y-3">+ {shown.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('none')}</p>+ ) : (+ <table className="w-full text-sm" aria-label={t('tableLabel')}>+ <tbody>+ {shown.map((c) => (+ <tr key={c.competitorId} className="border-b last:border-b-0">+ <td className="py-1.5 pr-3 font-medium">{c.name}</td>+ <td className="w-[45%] px-2 py-1.5">+ <Bar value={c.coMentions} max={max} />+ </td>+ <td className="w-24 px-2 py-1.5 text-right text-xs text-muted-foreground tabular-nums">+ {t('responses', { count: c.coMentions })}+ </td>+ <td className="w-14 py-1.5 pl-2 text-right text-xs tabular-nums">+ <Change now={c.coMentions} before={c.previousCoMentions} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ <p className="text-xs text-muted-foreground">{t('note')}</p>+ </CardContent>+ </Card>+ );+}++/** The biggest gap (spec §9): where a competitor is associated and you are not. */+export function GapNote({ gap, brand }: { gap: PerceptionGap; brand: string }) {+ const t = useTranslations('mentions.perception.gap');+ const f = numberFormat(useLocale());+ const values = {+ term: gap.term,+ competitor: gap.competitor,+ competitorShare: f.percent(gap.competitorShare, 0),+ brand,+ };+ return (+ <p+ className={cn(+ 'rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900',+ 'dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200',+ )}+ >+ <b className="font-semibold">{t('title')}: </b>+ {gap.brandRank === null+ ? t('unplaced', values)+ : t('ranked', {+ ...values,+ brandShare: f.percent(gap.brandShare, 0),+ rank: gap.brandRank,+ })}+ </p>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsxnew file mode 100644index 000000000..483aa464e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsx@@ -0,0 +1,295 @@+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 { MentionsPerception } from '@/lib/mentions-perception';+import { BrandShapeCard } from './_brand-shape';+import { MentionsPerceptionTab } from './_perception';+import { CoMentionsCard, GapNote, HeatmapCard, TermsCard } from './_perception-cards';++const getMentionsPerception = vi.fn();+vi.mock('@/lib/actions/mentions', () => ({+ getMentionsPerception: (...args: unknown[]) => getMentionsPerception(...args),+}));+// The radar is loaded on demand and measured; these tests read what it is given.+vi.mock('next/dynamic', () => ({+ default: () =>+ function Radar({ series }: { series: { name: string; color: string }[] }) {+ return <div data-testid="radar">{series.map((s) => `${s.name} ${s.color}`).join(', ')}</div>;+ },+}));++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const entity = (entity: string, name: string, mentions: number) => ({+ entity,+ name,+ isBrand: entity === 'brand',+ mentions,+ previousMentions: 0,+});++const values = (brand: number, profound: number, peec: number, otterly: number) => [+ { entity: 'brand', answers: brand },+ { entity: 'p', answers: profound },+ { entity: 'e', answers: peec },+ { entity: 'o', answers: otterly },+];++// Profound owns "enterprise", which AI uses for Ansvisor in 10% of its mentions.+const perception: MentionsPerception = {+ window: { from: '2026-09-17T09:00:00Z', to: '2026-10-17T09:00:00Z', days: 30 },+ entities: [+ entity('brand', 'Ansvisor', 50),+ entity('p', 'Profound', 80),+ entity('e', 'Peec AI', 40),+ entity('o', 'Otterly AI', 20),+ entity('s', 'Scrunch', 0),+ ],+ brandTerms: [+ { term: 'visibility tracking', answers: 20, previousAnswers: 10 },+ { term: 'api', answers: 10, previousAnswers: 10 },+ { term: 'pricing', answers: 5, previousAnswers: 0 },+ ],+ attributes: [+ { term: 'enterprise', values: values(5, 48, 4, 0) },+ { term: 'visibility tracking', values: values(20, 16, 8, 2) },+ { term: 'open source', values: values(0, 0, 12, 1) },+ ],+ coMentions: [+ { competitorId: 'p', name: 'Profound', coMentions: 30, previousCoMentions: 20 },+ { competitorId: 'e', name: 'Peec AI', coMentions: 0, previousCoMentions: 5 },+ { competitorId: 'o', name: 'Otterly AI', coMentions: 12, previousCoMentions: 12 },+ ],+};++let container: HTMLDivElement;+let root: Root;++function render(node: React.ReactNode) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ {node}+ </NextIntlClientProvider>,+ );+ });+}++const cells = (row: Element) => [...row.querySelectorAll('th, td')].map((c) => c.textContent);++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ getMentionsPerception.mockReset();+ vi.useRealTimers();+});++describe('TermsCard', () => {+ it("lists the brand's terms with their responses, share and change", () => {+ render(<TermsCard perception={perception} brand="Ansvisor" />);+ expect(container.textContent).toContain('What AI associates with Ansvisor');+ const rows = [...container.querySelectorAll('tbody tr')];+ expect(rows.map(cells)).toEqual([+ ['visibility tracking', '', '20 responses', '+100%'],+ ['api', '', '10 responses', '±0'],+ // Nothing before to compare with.+ ['pricing', '', '5 responses', '—'],+ ]);+ expect(rows[0].querySelectorAll('td')[2].getAttribute('title')).toBe(+ '40% of responses naming Ansvisor',+ );+ });++ it('says when there are no terms yet', () => {+ render(<TermsCard perception={{ ...perception, brandTerms: [] }} brand="Ansvisor" />);+ expect(container.textContent).toContain('No terms yet.');+ });+});++describe('HeatmapCard', () => {+ it("shows each attribute's share of each brand's mentions, shaded by share", () => {+ render(<HeatmapCard perception={perception} />);+ const rows = [...container.querySelectorAll('tr')];+ expect(rows.map(cells)).toEqual([+ ['Attribute', 'You', 'Profound', 'Peec AI', 'Otterly AI', 'Scrunch'],+ ['enterprise', '10%', '60%', '10%', '0%', '—'],+ ['visibility tracking', '40%', '20%', '20%', '10%', '—'],+ ['open source', '0%', '0%', '30%', '5%', '—'],+ ]);+ const [, , profound, , otterly] = [...rows[1].querySelectorAll('td')] as HTMLElement[];+ expect(profound.style.backgroundColor).toBe('rgba(120, 113, 108, 0.4)');+ expect(otterly.style.backgroundColor).toBe('');+ });+});++describe('CoMentionsCard', () => {+ it('lists the competitors named beside the brand, leaving out the ones never named', () => {+ render(<CoMentionsCard perception={perception} />);+ expect([...container.querySelectorAll('tbody tr')].map(cells)).toEqual([+ ['Profound', '', '30 responses', '+50%'],+ ['Otterly AI', '', '12 responses', '±0'],+ ]);+ });++ it('says when no competitor is named beside the brand', () => {+ render(<CoMentionsCard perception={{ ...perception, coMentions: [] }} />);+ expect(container.textContent).toContain('No competitor is named in the same responses');+ });+});++describe('GapNote', () => {+ it("names the brand's place, or says AI never uses the term for it", () => {+ const gap = {+ term: 'enterprise',+ competitor: 'Profound',+ competitorShare: 60,+ brandShare: 10,+ brandRank: 2,+ };+ render(<GapNote gap={gap} brand="Ansvisor" />);+ expect(container.textContent).toBe(+ 'Biggest gap: “enterprise”: Profound in 60% of the responses naming it; Ansvisor in 10% (#2).',+ );++ render(<GapNote gap={{ ...gap, brandShare: 0, brandRank: null }} brand="Ansvisor" />);+ expect(container.textContent).toBe(+ "Biggest gap: “enterprise”: Profound in 60% of the responses naming it; AI doesn't use it for Ansvisor.",+ );+ });+});++describe('BrandShapeCard', () => {+ it('draws the brand and its top three competitors, with the biggest gap beneath', () => {+ render(<BrandShapeCard perception={perception} brand="Ansvisor" />);+ expect(container.querySelector('[data-testid="radar"]')?.textContent).toBe(+ // Your brand in ink, as the rest of the page; no violet.+ 'Ansvisor var(--primary), Profound #f97316, Peec AI #0d9488, Otterly AI #ef4444',+ );+ expect(container.querySelector('figcaption')?.textContent).toBe(+ 'AnsvisorProfoundPeec AIOtterly AI',+ );+ expect(container.textContent).toContain(+ 'Biggest gap: “enterprise”: Profound in 60% of the responses naming it; Ansvisor in 10% (#2).',+ );+ });++ it('takes the gap among the brands drawn, not a fifth one off the radar', () => {+ render(+ <BrandShapeCard+ perception={{+ ...perception,+ entities: [...perception.entities.slice(0, 4), entity('s', 'Scrunch', 40)],+ attributes: [+ ...perception.attributes,+ { term: 'agencies', values: [{ entity: 's', answers: 36 }] },+ ],+ }}+ brand="Ansvisor"+ />,+ );+ expect(container.textContent).toContain('Biggest gap: “enterprise”: Profound');+ });++ it('says so when there are too few attributes for a shape', () => {+ render(+ <BrandShapeCard+ perception={{ ...perception, attributes: perception.attributes.slice(0, 2) }}+ brand="Ansvisor"+ />,+ );+ expect(container.querySelector('[data-testid="radar"]')).toBeNull();+ expect(container.textContent).toContain('The shape needs at least three attributes');+ });+});++describe('MentionsPerceptionTab', () => {+ it('reads the perception once the filters settle and shows it', async () => {+ vi.useFakeTimers();+ getMentionsPerception.mockResolvedValue(perception);+ render(+ <MentionsPerceptionTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,+ );+ expect(getMentionsPerception).not.toHaveBeenCalled();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(getMentionsPerception).toHaveBeenCalledTimes(1);+ expect(getMentionsPerception.mock.calls[0][0]).toBe('b1');+ expect(container.textContent).toContain('What AI associates with Ansvisor');+ expect(container.textContent).toContain('Frequently mentioned with');+ expect(container.textContent).toContain('by rule (no LLM)');+ });++ it('says a read failed, and shows the skeleton again once a newer one is on its way', async () => {+ vi.useFakeTimers();+ getMentionsPerception.mockRejectedValueOnce(new Error('offline'));+ render(+ <MentionsPerceptionTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(container.textContent).toBe(+ "Couldn't load the perception figures. Try again in a moment.",+ );++ render(+ <MentionsPerceptionTab+ 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(+ <MentionsPerceptionTab+ brandId="b1"+ brand="Ansvisor"+ filters={{ ...DEFAULT_MENTIONS_FILTERS, range: 'custom' }}+ />,+ );+ expect(container.textContent).toBe('Choose a start or end date to see the perception figures.');+ expect(getMentionsPerception).not.toHaveBeenCalled();+ });++ it('says when the brand was never named, or the figures are unavailable', async () => {+ vi.useFakeTimers();+ getMentionsPerception.mockResolvedValueOnce({+ ...perception,+ entities: [entity('brand', 'Ansvisor', 0), ...perception.entities.slice(1)],+ });+ render(+ <MentionsPerceptionTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(container.textContent).toBe(+ "AI didn't name Ansvisor in the tracked responses of this period.",+ );++ getMentionsPerception.mockResolvedValueOnce(null);+ render(<MentionsPerceptionTab brandId="b2" brand="Other" filters={DEFAULT_MENTIONS_FILTERS} />);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(container.textContent).toContain("Perception isn't available yet.");+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsxnew file mode 100644index 000000000..62c76ea8a--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsx@@ -0,0 +1,113 @@+'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 { getMentionsPerception } from '@/lib/actions/mentions';+import { mentionsQuery, type MentionsFilters } from '@/lib/mentions-filters';+import type { MentionsPerception } from '@/lib/mentions-perception';+import { cn } from '@/lib/utils';+import { BrandShapeCard } from './_brand-shape';+import { CoMentionsCard, HeatmapCard, TermsCard } from './_perception-cards';++/** 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'; perception: MentionsPerception | 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 Perception tab (MS-09), as in the mockup: what AI associates with the+ * brand and the brand's shape against its competitors, then the brand ×+ * attribute heat map and the competitors named beside it. One read per+ * filter change; a newer change wins over a read still on its way.+ */+export function MentionsPerceptionTab({+ brandId,+ brand,+ filters,+}: {+ brandId: string;+ brand: string;+ filters: MentionsFilters;+}) {+ const t = useTranslations('mentions.perception');+ 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(() => {+ getMentionsPerception(brandId, query)+ .then((perception) => {+ if (!cancelled) setLoaded({ brandId, key, status: 'ok', perception });+ })+ .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>;+ if (!loaded || loaded.brandId !== brandId) return <PerceptionSkeleton />;+ if (loaded.status === 'error') {+ return loaded.key === key ? <Message>{t('loadError')}</Message> : <PerceptionSkeleton />;+ }+ if (!loaded.perception) return <Message>{t('unavailable')}</Message>;++ const perception = loaded.perception;+ const stale = loaded.key !== key;+ const mentions = perception.entities.find((e) => e.isBrand)?.mentions ?? 0;++ return (+ <section+ aria-label={t('sectionLabel')}+ aria-busy={stale}+ className={cn('flex flex-col gap-3 transition-opacity', stale && 'opacity-60')}+ >+ {mentions === 0 ? (+ <Message>{t('noMentions', { brand })}</Message>+ ) : (+ <>+ <div className="grid items-start gap-3 xl:grid-cols-2">+ <TermsCard perception={perception} brand={brand} />+ <BrandShapeCard perception={perception} brand={brand} />+ </div>+ <div className="grid items-start gap-3 xl:grid-cols-2">+ <HeatmapCard perception={perception} />+ <CoMentionsCard perception={perception} />+ </div>+ <p className="text-xs text-muted-foreground">{t('method')}</p>+ </>+ )}+ </section>+ );+}++function PerceptionSkeleton() {+ return (+ <div className="grid gap-3 xl:grid-cols-2" aria-hidden>+ {[0, 1, 2, 3].map((i) => (+ <Skeleton key={i} className="h-[300px] rounded-xl" />+ ))}+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsxindex 1a863b52c..347c278d6 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx@@ -2,7 +2,6 @@import { useEffect, useMemo, useState } from 'react';import { useTranslations } from 'next-intl';-import { Card, CardContent } from '@/components/ui/card';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import { getCompetitors } from '@/lib/actions/competitor';import { getTopics } from '@/lib/actions/topic';@@ -23,6 +22,7 @@ import { MentionsFilterBar } from './_filter-bar';import { MentionsHeaderActions } from './_header-actions';import { MentionsListTab } from './_mentions-tab';import { MentionsOverviewTab } from './_overview';+import { MentionsPerceptionTab } from './_perception';import { useMentionsExport } from './_use-mentions-export';/**@@ -150,11 +150,9 @@ export default function MentionsPage() {)}</TabsContent><TabsContent value="perception" className="mt-4">- <Card>- <CardContent className="py-10 text-center text-sm text-muted-foreground">- {t('comingSoon')}- </CardContent>- </Card>+ {urlRead && (+ <MentionsPerceptionTab brandId={activeBrandId} brand={brandName} filters={filters} />+ )}</TabsContent></Tabs></div>diff --git a/web/src/lib/mentions-perception.test.ts b/web/src/lib/mentions-perception.test.tsindex f57263f6e..05b1d237e 100644--- a/web/src/lib/mentions-perception.test.ts+++ b/web/src/lib/mentions-perception.test.ts@@ -110,6 +110,24 @@ describe('biggestGap', () => {expect(biggestGap(p)).toMatchObject({ competitorShare: 80, brandShare: 10, brandRank: 2 });});+ it('leaves out shares taken over fewer than 20 mentions', () => {+ const p = parseMentionsPerception(raw)!;+ const few = (brand: number, competitor: number): MentionsPerception => ({+ ...p,+ entities: [+ { ...p.entities[0], mentions: brand },+ { ...p.entities[1], mentions: competitor },+ ],+ });+ // Crema Club's 30 "fast delivery" answers over 19 mentions; then the brand on 19.+ expect(biggestGap(few(100, 19))).toBeNull();+ expect(biggestGap(few(19, 50))).toBeNull();+ expect(biggestGap(few(20, 50))).toMatchObject({+ term: 'fast delivery',+ competitor: 'Crema Club',+ });+ });+it('is null when no competitor leads by 20 points', () => {const p: MentionsPerception = {...parseMentionsPerception(raw)!,diff --git a/web/src/lib/mentions-perception.ts b/web/src/lib/mentions-perception.tsindex bcc295a90..c7eb55643 100644--- a/web/src/lib/mentions-perception.ts+++ b/web/src/lib/mentions-perception.ts@@ -1,4 +1,4 @@-import { relativeChange } from '@/lib/mentions-overview';+import { LOW_SAMPLE_MENTIONS, relativeChange } from '@/lib/mentions-overview';/*** The Mentions & Sentiment Perception tab's figures (MS-09), as@@ -130,13 +130,15 @@ export interface PerceptionGap {/*** The biggest gap (spec §9): the attribute where a competitor is most* strongly associated and the brand least, by the widest margin, at least- * GAP_POINTS. Null when no competitor leads anything by that much.+ * GAP_POINTS. Null when no competitor leads anything by that much. Shares+ * taken over fewer than LOW_SAMPLE_MENTIONS mentions are left out, as the+ * Overview does: one answer would otherwise read as 100%.*/export function biggestGap(p: Pick<MentionsPerception, 'entities' | 'attributes'>,): PerceptionGap | null {const brandIndex = p.entities.findIndex((e) => e.isBrand);- if (brandIndex < 0) return null;+ if (brandIndex < 0 || p.entities[brandIndex].mentions < LOW_SAMPLE_MENTIONS) return null;let best: PerceptionGap | null = null;let bestMargin = GAP_POINTS;for (const row of attributeShares(p)) {@@ -144,6 +146,7 @@ export function biggestGap(for (let i = 0; i < row.shares.length; i++) {const share = row.shares[i];if (i === brandIndex || share === null || share - brandShare < bestMargin) continue;+ if (p.entities[i].mentions < LOW_SAMPLE_MENTIONS) continue;bestMargin = share - brandShare;const placed = row.shares.filter((s): s is number => s !== null && s > 0);best = {