Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(mentions): add the Mentions table and the response drawer (#1117)

Cihan97f29cbc1c85
diff --git a/supabase/migrations/00158_mentions_list.sql b/supabase/migrations/00158_mentions_list.sql
new file mode 100644
index 000000000..8c5295c3d
--- /dev/null
+++ b/supabase/migrations/00158_mentions_list.sql
@@ -0,0 +1,251 @@
+-- ============================================================================
+-- 00158: The Mentions table's read (Mentions & Sentiment, MS-07)
+-- ============================================================================
+-- One row per answer that names the brand (a "mention", spec §5), newest
+-- first, a page at a time, with what the table and the response drawer's
+-- header show: the prompt and its topic, platform and model, country, date,
+-- sentiment, the brand's position among the brands named, and the
+-- competitors named in the same answer. The answer's text comes along so
+-- the server can cut the excerpt around the mention; the page never sees it.
+--
+-- The window is mentions_overview's (00157), so the table's total is the
+-- Overview's "Total mentions" for the same filters: under two days the
+-- exact instants, otherwise whole UTC days.
+--
+-- Filters, beside the page's (platform, region, topic, prompt search):
+-- p_sentiment 'positive' | 'neutral' | 'negative' (neutral is every
+-- mention that is neither, as in the rollups)
+-- p_competitor_id a competitor named in the same answer, or 'none' for
+-- answers naming no competitor
+-- Sorts: 'newest' (default), 'oldest', 'co_mentions' (most competitors named
+-- beside you first), 'negative' (negative, then neutral, then positive).
+-- Groups: 'prompt' or 'platform' put each group's rows together, the
+-- biggest group first, with the group's size on each row.
+--
+-- Security definer with the organization check made explicit, as
+-- mentions_overview: a caller outside the brand's organization gets null.
+
+-- The brand's mentions by time: about one answer in twelve names the brand,
+-- so the table reads those rows alone. On a large prompt_results, build it
+-- by hand first with `create index concurrently`, which doesn't hold back
+-- tracking's writes; this statement then finds it in place.
+create index if not exists idx_prompt_results_brand_mentions
+ on public.prompt_results (brand_id, created_at desc)
+ where mention_count > 0;
+
+create or replace function public.mentions_list(
+ p_brand_id uuid,
+ p_date_from timestamptz,
+ p_date_to timestamptz default null,
+ p_platform text default null,
+ p_region text default null,
+ p_topic_id uuid default null,
+ p_search text default null,
+ p_sentiment text default null,
+ p_competitor_id text default null,
+ p_sort text default 'newest',
+ p_group text default null,
+ p_limit integer default 100,
+ p_offset integer default 0
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set work_mem to '64MB'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_to timestamptz := coalesce(p_date_to, now());
+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));
+ v_days integer;
+ v_day_to date;
+ v_start timestamptz;
+ v_end timestamptz;
+ v_search text := nullif(btrim(lower(coalesce(p_search, ''))), '');
+ v_limit integer := least(greatest(coalesce(p_limit, 100), 1), 100);
+ v_offset integer := greatest(coalesce(p_offset, 0), 0);
+ v_group text := case when p_group in ('prompt', 'platform') then p_group end;
+ v_result jsonb;
+begin
+ if auth.role() is distinct from 'service_role' and not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ) then
+ return null;
+ end if;
+
+ -- The same window as mentions_overview's current one.
+ v_days := greatest(1, ceil(extract(epoch from v_to - v_from) / 86400.0 - 1.0 / 24)::integer);
+ if v_days < 2 then
+ v_start := v_from;
+ v_end := v_to + interval '1 microsecond';
+ else
+ v_day_to := (v_to at time zone 'utc')::date;
+ v_start := (v_day_to - (v_days - 1))::timestamp at time zone 'utc';
+ v_end := (v_day_to + 1)::timestamp at time zone 'utc';
+ end if;
+
+ with
+ prompts_in as (
+ select p.id, p.text, p.topic_id
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = p_brand_id
+ and (p_topic_id is null or p.topic_id = p_topic_id)
+ and (v_search is null or position(v_search in lower(p.text)) > 0)
+ ),
+ -- The brand's mentions in the window, read first, through the partial
+ -- index below, and only then joined to the prompts. Driven by the prompts
+ -- instead, the planner walks each prompt's whole history: 8.8 s for 30
+ -- days of the largest brand, against 0.2 s this way.
+ mention_rows as materialized (
+ select pr.id, pr.created_at, pr.prompt_id, pr.platform, pr.sentiment,
+ pr.competitor_mentions
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.mention_count > 0
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_start
+ and pr.created_at < v_end
+ and (p_platform is null or pr.platform = p_platform)
+ and (p_region is null or pr.region = p_region)
+ and (p_sentiment is null
+ or (p_sentiment in ('positive', 'negative') and pr.sentiment = p_sentiment)
+ or (p_sentiment = 'neutral'
+ and pr.sentiment is distinct from 'positive'
+ and pr.sentiment is distinct from 'negative'))
+ ),
+ hits as (
+ select m.id,
+ m.created_at,
+ m.prompt_id,
+ pi.text as prompt_text,
+ m.platform,
+ m.sentiment,
+ -- Competitors named beside you; the array lists every competitor,
+ -- named or not.
+ (select count(*)
+ from jsonb_array_elements(coalesce(m.competitor_mentions, '[]'::jsonb)) cm
+ where cm.value ? 'competitor_id'
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0) as co_count,
+ (p_competitor_id is not null and p_competitor_id <> 'none' and exists (
+ select 1
+ from jsonb_array_elements(coalesce(m.competitor_mentions, '[]'::jsonb)) cm
+ where cm.value->>'competitor_id' = p_competitor_id
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0)) as with_competitor
+ from mention_rows m
+ join prompts_in pi on pi.id = m.prompt_id
+ ),
+ filtered as (
+ select h.*,
+ case v_group
+ when 'prompt' then h.prompt_id::text
+ when 'platform' then h.platform
+ end as group_key
+ from hits h
+ where p_competitor_id is null
+ or (p_competitor_id = 'none' and h.co_count = 0)
+ or h.with_competitor
+ ),
+ grouped as (
+ select f.*,
+ case when v_group is not null
+ then count(*) over (partition by f.group_key) end as group_count
+ from filtered f
+ ),
+ page as (
+ select g.*
+ from grouped g
+ order by
+ case when v_group is not null then g.group_count end desc nulls last,
+ case when v_group = 'prompt' then lower(g.prompt_text) end,
+ g.group_key,
+ case when p_sort = 'negative' then
+ case g.sentiment when 'negative' then 0 when 'positive' then 2 else 1 end
+ end,
+ case when p_sort = 'co_mentions' then g.co_count end desc nulls last,
+ case when p_sort = 'oldest' then g.created_at end,
+ g.created_at desc,
+ g.id
+ limit v_limit
+ offset v_offset
+ ),
+ rows_out as (
+ select pg.*,
+ pr.model_used,
+ pr.region,
+ pr.mention_count,
+ pr.mention_position,
+ pr.mentioned_entity_count,
+ pr.response,
+ pi.topic_id,
+ t.name as topic_name,
+ coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'competitor_id', cm.value->>'competitor_id',
+ 'name', coalesce(co.name, cm.value->>'name'),
+ 'mention_position', cm.value->'mention_position')
+ order by (cm.value->>'mention_position')::int nulls last,
+ coalesce(co.name, cm.value->>'name'))
+ from jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ left join public.competitors co
+ on co.id::text = cm.value->>'competitor_id' and co.brand_id = p_brand_id
+ where cm.value ? 'competitor_id'
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0
+ ), '[]'::jsonb) as co_mentioned
+ from page pg
+ join public.prompt_results pr on pr.id = pg.id
+ join prompts_in pi on pi.id = pg.prompt_id
+ left join public.topics t on t.id = pi.topic_id
+ )
+ select jsonb_build_object(
+ 'total', (select count(*) from filtered),
+ 'prompts', (select count(distinct prompt_id) from filtered),
+ 'rows', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'id', r.id,
+ 'created_at', r.created_at,
+ 'prompt_id', r.prompt_id,
+ 'prompt_text', r.prompt_text,
+ 'topic_id', r.topic_id,
+ 'topic_name', r.topic_name,
+ 'platform', r.platform,
+ 'model_used', r.model_used,
+ 'region', r.region,
+ 'sentiment', r.sentiment,
+ 'mention_count', r.mention_count,
+ 'mention_position', r.mention_position,
+ 'mentioned_entity_count', r.mentioned_entity_count,
+ 'co_mentioned', r.co_mentioned,
+ 'response', r.response,
+ 'group_key', r.group_key,
+ 'group_count', r.group_count)
+ order by
+ case when v_group is not null then r.group_count end desc nulls last,
+ case when v_group = 'prompt' then lower(r.prompt_text) end,
+ r.group_key,
+ case when p_sort = 'negative' then
+ case r.sentiment when 'negative' then 0 when 'positive' then 2 else 1 end
+ end,
+ case when p_sort = 'co_mentions' then r.co_count end desc nulls last,
+ case when p_sort = 'oldest' then r.created_at end,
+ r.created_at desc,
+ r.id)
+ from rows_out r
+ ), '[]'::jsonb)
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke execute on function public.mentions_list(
+ uuid, timestamptz, timestamptz, text, text, uuid, text, text, text, text, text, integer, integer)
+ from public, anon;
+grant execute on function public.mentions_list(
+ uuid, timestamptz, timestamptz, text, text, uuid, text, text, text, text, text, integer, integer)
+ to authenticated, service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 3973d1c81..99978f31a 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -19962,3 +19962,258 @@ revoke execute on function public.mentions_overview(uuid, timestamptz, timestamp
grant execute on function public.mentions_overview(uuid, timestamptz, timestamptz, text, text, uuid, text)
to authenticated, service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00158_mentions_list.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00158: The Mentions table's read (Mentions & Sentiment, MS-07)
+-- ============================================================================
+-- One row per answer that names the brand (a "mention", spec §5), newest
+-- first, a page at a time, with what the table and the response drawer's
+-- header show: the prompt and its topic, platform and model, country, date,
+-- sentiment, the brand's position among the brands named, and the
+-- competitors named in the same answer. The answer's text comes along so
+-- the server can cut the excerpt around the mention; the page never sees it.
+--
+-- The window is mentions_overview's (00157), so the table's total is the
+-- Overview's "Total mentions" for the same filters: under two days the
+-- exact instants, otherwise whole UTC days.
+--
+-- Filters, beside the page's (platform, region, topic, prompt search):
+-- p_sentiment 'positive' | 'neutral' | 'negative' (neutral is every
+-- mention that is neither, as in the rollups)
+-- p_competitor_id a competitor named in the same answer, or 'none' for
+-- answers naming no competitor
+-- Sorts: 'newest' (default), 'oldest', 'co_mentions' (most competitors named
+-- beside you first), 'negative' (negative, then neutral, then positive).
+-- Groups: 'prompt' or 'platform' put each group's rows together, the
+-- biggest group first, with the group's size on each row.
+--
+-- Security definer with the organization check made explicit, as
+-- mentions_overview: a caller outside the brand's organization gets null.
+
+-- The brand's mentions by time: about one answer in twelve names the brand,
+-- so the table reads those rows alone. On a large prompt_results, build it
+-- by hand first with `create index concurrently`, which doesn't hold back
+-- tracking's writes; this statement then finds it in place.
+create index if not exists idx_prompt_results_brand_mentions
+ on public.prompt_results (brand_id, created_at desc)
+ where mention_count > 0;
+
+create or replace function public.mentions_list(
+ p_brand_id uuid,
+ p_date_from timestamptz,
+ p_date_to timestamptz default null,
+ p_platform text default null,
+ p_region text default null,
+ p_topic_id uuid default null,
+ p_search text default null,
+ p_sentiment text default null,
+ p_competitor_id text default null,
+ p_sort text default 'newest',
+ p_group text default null,
+ p_limit integer default 100,
+ p_offset integer default 0
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set work_mem to '64MB'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_to timestamptz := coalesce(p_date_to, now());
+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));
+ v_days integer;
+ v_day_to date;
+ v_start timestamptz;
+ v_end timestamptz;
+ v_search text := nullif(btrim(lower(coalesce(p_search, ''))), '');
+ v_limit integer := least(greatest(coalesce(p_limit, 100), 1), 100);
+ v_offset integer := greatest(coalesce(p_offset, 0), 0);
+ v_group text := case when p_group in ('prompt', 'platform') then p_group end;
+ v_result jsonb;
+begin
+ if auth.role() is distinct from 'service_role' and not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ) then
+ return null;
+ end if;
+
+ -- The same window as mentions_overview's current one.
+ v_days := greatest(1, ceil(extract(epoch from v_to - v_from) / 86400.0 - 1.0 / 24)::integer);
+ if v_days < 2 then
+ v_start := v_from;
+ v_end := v_to + interval '1 microsecond';
+ else
+ v_day_to := (v_to at time zone 'utc')::date;
+ v_start := (v_day_to - (v_days - 1))::timestamp at time zone 'utc';
+ v_end := (v_day_to + 1)::timestamp at time zone 'utc';
+ end if;
+
+ with
+ prompts_in as (
+ select p.id, p.text, p.topic_id
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = p_brand_id
+ and (p_topic_id is null or p.topic_id = p_topic_id)
+ and (v_search is null or position(v_search in lower(p.text)) > 0)
+ ),
+ -- The brand's mentions in the window, read first, through the partial
+ -- index below, and only then joined to the prompts. Driven by the prompts
+ -- instead, the planner walks each prompt's whole history: 8.8 s for 30
+ -- days of the largest brand, against 0.2 s this way.
+ mention_rows as materialized (
+ select pr.id, pr.created_at, pr.prompt_id, pr.platform, pr.sentiment,
+ pr.competitor_mentions
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.mention_count > 0
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_start
+ and pr.created_at < v_end
+ and (p_platform is null or pr.platform = p_platform)
+ and (p_region is null or pr.region = p_region)
+ and (p_sentiment is null
+ or (p_sentiment in ('positive', 'negative') and pr.sentiment = p_sentiment)
+ or (p_sentiment = 'neutral'
+ and pr.sentiment is distinct from 'positive'
+ and pr.sentiment is distinct from 'negative'))
+ ),
+ hits as (
+ select m.id,
+ m.created_at,
+ m.prompt_id,
+ pi.text as prompt_text,
+ m.platform,
+ m.sentiment,
+ -- Competitors named beside you; the array lists every competitor,
+ -- named or not.
+ (select count(*)
+ from jsonb_array_elements(coalesce(m.competitor_mentions, '[]'::jsonb)) cm
+ where cm.value ? 'competitor_id'
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0) as co_count,
+ (p_competitor_id is not null and p_competitor_id <> 'none' and exists (
+ select 1
+ from jsonb_array_elements(coalesce(m.competitor_mentions, '[]'::jsonb)) cm
+ where cm.value->>'competitor_id' = p_competitor_id
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0)) as with_competitor
+ from mention_rows m
+ join prompts_in pi on pi.id = m.prompt_id
+ ),
+ filtered as (
+ select h.*,
+ case v_group
+ when 'prompt' then h.prompt_id::text
+ when 'platform' then h.platform
+ end as group_key
+ from hits h
+ where p_competitor_id is null
+ or (p_competitor_id = 'none' and h.co_count = 0)
+ or h.with_competitor
+ ),
+ grouped as (
+ select f.*,
+ case when v_group is not null
+ then count(*) over (partition by f.group_key) end as group_count
+ from filtered f
+ ),
+ page as (
+ select g.*
+ from grouped g
+ order by
+ case when v_group is not null then g.group_count end desc nulls last,
+ case when v_group = 'prompt' then lower(g.prompt_text) end,
+ g.group_key,
+ case when p_sort = 'negative' then
+ case g.sentiment when 'negative' then 0 when 'positive' then 2 else 1 end
+ end,
+ case when p_sort = 'co_mentions' then g.co_count end desc nulls last,
+ case when p_sort = 'oldest' then g.created_at end,
+ g.created_at desc,
+ g.id
+ limit v_limit
+ offset v_offset
+ ),
+ rows_out as (
+ select pg.*,
+ pr.model_used,
+ pr.region,
+ pr.mention_count,
+ pr.mention_position,
+ pr.mentioned_entity_count,
+ pr.response,
+ pi.topic_id,
+ t.name as topic_name,
+ coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'competitor_id', cm.value->>'competitor_id',
+ 'name', coalesce(co.name, cm.value->>'name'),
+ 'mention_position', cm.value->'mention_position')
+ order by (cm.value->>'mention_position')::int nulls last,
+ coalesce(co.name, cm.value->>'name'))
+ from jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ left join public.competitors co
+ on co.id::text = cm.value->>'competitor_id' and co.brand_id = p_brand_id
+ where cm.value ? 'competitor_id'
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0
+ ), '[]'::jsonb) as co_mentioned
+ from page pg
+ join public.prompt_results pr on pr.id = pg.id
+ join prompts_in pi on pi.id = pg.prompt_id
+ left join public.topics t on t.id = pi.topic_id
+ )
+ select jsonb_build_object(
+ 'total', (select count(*) from filtered),
+ 'prompts', (select count(distinct prompt_id) from filtered),
+ 'rows', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'id', r.id,
+ 'created_at', r.created_at,
+ 'prompt_id', r.prompt_id,
+ 'prompt_text', r.prompt_text,
+ 'topic_id', r.topic_id,
+ 'topic_name', r.topic_name,
+ 'platform', r.platform,
+ 'model_used', r.model_used,
+ 'region', r.region,
+ 'sentiment', r.sentiment,
+ 'mention_count', r.mention_count,
+ 'mention_position', r.mention_position,
+ 'mentioned_entity_count', r.mentioned_entity_count,
+ 'co_mentioned', r.co_mentioned,
+ 'response', r.response,
+ 'group_key', r.group_key,
+ 'group_count', r.group_count)
+ order by
+ case when v_group is not null then r.group_count end desc nulls last,
+ case when v_group = 'prompt' then lower(r.prompt_text) end,
+ r.group_key,
+ case when p_sort = 'negative' then
+ case r.sentiment when 'negative' then 0 when 'positive' then 2 else 1 end
+ end,
+ case when p_sort = 'co_mentions' then r.co_count end desc nulls last,
+ case when p_sort = 'oldest' then r.created_at end,
+ r.created_at desc,
+ r.id)
+ from rows_out r
+ ), '[]'::jsonb)
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke execute on function public.mentions_list(
+ uuid, timestamptz, timestamptz, text, text, uuid, text, text, text, text, text, integer, integer)
+ from public, anon;
+grant execute on function public.mentions_list(
+ uuid, timestamptz, timestamptz, text, text, uuid, text, text, text, text, text, integer, integer)
+ to authenticated, service_role;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index c6c5fea81..3219b1e36 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3009,7 +3009,7 @@
"topic": "Topic",
"allTopics": "All topics",
"search": "Search",
- "searchPlaceholder": "Search prompts, brands, phrases…"
+ "searchPlaceholder": "Search prompts…"
},
"comingSoon": "This view is on its way: its figures and charts arrive with the next updates.",
"overview": {
@@ -3091,6 +3091,71 @@
"ownSentimentOnly": "Sentiment is measured for your brand only.",
"none": "No competitors yet. Add them on the Competitors page to compare."
}
+ },
+ "table": {
+ "sectionLabel": "Mentions table",
+ "tableLabel": "Answers that mention your brand",
+ "sentiment": "Sentiment",
+ "allSentiments": "All sentiments",
+ "coMentioned": "Co-mentioned",
+ "anyCompetitor": "Any or none",
+ "noCompetitor": "No competitor",
+ "groupBy": "Group by",
+ "noGrouping": "None",
+ "groupPrompt": "Prompt",
+ "groupPlatform": "Platform",
+ "sort": "Sort",
+ "sortNewest": "Newest",
+ "sortOldest": "Oldest",
+ "sortCoMentions": "Most co-mentions",
+ "sortNegative": "Most negative",
+ "summary": "{mentions, plural, one {# mention} other {# mentions}} · {prompts, plural, one {# prompt} other {# prompts}}",
+ "columns": {
+ "prompt": "Prompt",
+ "platform": "Platform",
+ "country": "Country",
+ "context": "Mention context",
+ "sentiment": "Sentiment",
+ "position": "Position",
+ "coMentioned": "Co-mentioned",
+ "topic": "Topic",
+ "date": "Date"
+ },
+ "positionOf": "#{position} of {count}",
+ "positionOnly": "#{position}",
+ "noSentiment": "Not rated",
+ "groupRow": "{label} · {count, plural, one {# mention} other {# mentions}}",
+ "openRow": "Open the answer to “{prompt}” on {platform}",
+ "empty": "No mentions match these filters. Try another sentiment or co-mention filter, or a longer range.",
+ "loadError": "Couldn't load the mentions. Try again in a moment.",
+ "unavailable": "The mentions table isn't available yet. It appears once the mentions data has been prepared.",
+ "pickDates": "Choose a start or end date to see the mentions."
+ },
+ "drawer": {
+ "label": "Answer detail",
+ "position": "Position #{position} of {count}",
+ "positionOnly": "Position #{position}",
+ "topic": "Topic: {topic}",
+ "viewPrompt": "View prompt",
+ "mention": "Mention",
+ "coMentioned": "Also named in this answer",
+ "noCoMentions": "No competitor is named in this answer.",
+ "competitorTone": "Competitors' tone isn't measured yet; the sentiment is toward your brand.",
+ "response": "Full AI response",
+ "stored": "stored, not regenerated",
+ "showResponse": "Show the response",
+ "hideResponse": "Hide the response",
+ "loading": "Loading the answer…",
+ "loadError": "Couldn't load this answer. Try again in a moment.",
+ "missing": "This answer is no longer stored.",
+ "citations": "Citations in this answer",
+ "noCitations": "This answer cites no sources.",
+ "copy": "Copy response",
+ "copied": "Response copied",
+ "copyFailed": "Couldn't copy the response. Select the text and copy it instead.",
+ "close": "Close",
+ "legendBrand": "Your brand",
+ "legendCompetitor": "Competitors"
}
},
"competitors": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_filter-bar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_filter-bar.tsx
index 3b45f81d1..cdd9d5aaa 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_filter-bar.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_filter-bar.tsx
@@ -21,8 +21,8 @@ const ALL = '__all__';
/**
* The filter bar every Mentions & Sentiment tab shares (MS-05): the date
- * range, AI platform, country, topic and a search over prompts, brands and
- * phrases. The brand is the app's active brand, chosen in the sidebar.
+ * range, AI platform, country, topic and a search over the prompts' text.
+ * The brand is the app's active brand, chosen in the sidebar.
*/
export function MentionsFilterBar({
filters,
@@ -110,7 +110,7 @@ export function MentionsFilterBar({
);
}
-function FilterSelect({
+export function FilterSelect({
label,
value,
items,
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mention-parts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mention-parts.tsx
new file mode 100644
index 000000000..9ef2e0d76
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mention-parts.tsx
@@ -0,0 +1,81 @@
+'use client';
+
+import { Children, cloneElement, isValidElement, type ReactNode } from 'react';
+import { useTranslations } from 'next-intl';
+import { Badge } from '@/components/ui/badge';
+import { cn } from '@/lib/utils';
+import { highlightSegments, type MentionKind } from '@/lib/mention-match';
+import type { Sentiment } from '@/types';
+
+/** The names an answer is highlighted by: your brand's (name, domains) and the competitors'. */
+export interface MentionNames {
+ brand: string[];
+ competitors: string[];
+}
+
+/** Your brand in violet, competitors in grey (spec §7), in both themes. */
+export const MARK_CLASS: Record<MentionKind, string> = {
+ brand:
+ 'rounded-sm bg-violet-100 px-0.5 font-medium text-violet-900 dark:bg-violet-500/25 dark:text-violet-100',
+ competitor: 'rounded-sm bg-muted px-0.5 text-foreground ring-1 ring-inset ring-border',
+};
+
+/** A text with the names in it marked. */
+export function Highlighted({ text, names }: { text: string; names: MentionNames }) {
+ return (
+ <>
+ {highlightSegments(text, names).map((segment, i) =>
+ segment.kind ? (
+ <mark key={i} className={MARK_CLASS[segment.kind]}>
+ {segment.text}
+ </mark>
+ ) : (
+ segment.text
+ ),
+ )}
+ </>
+ );
+}
+
+/**
+ * The same marks inside rendered markdown: every string child is split
+ * around the names, and elements are walked into (a link's label, a bold
+ * phrase), so a name is marked wherever the answer puts it.
+ */
+export function highlightChildren(children: ReactNode, names: MentionNames): ReactNode {
+ return Children.map(children, (child) => {
+ if (typeof child === 'string') return <Highlighted text={child} names={names} />;
+ if (isValidElement<{ children?: ReactNode }>(child) && child.props.children !== undefined) {
+ return cloneElement(child, undefined, highlightChildren(child.props.children, names));
+ }
+ return child;
+ });
+}
+
+const SENTIMENT_CLASS: Record<Sentiment, string> = {
+ positive: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',
+ neutral: '',
+ negative: 'border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300',
+};
+
+/** The answer's tone toward your brand, always written out, never colour alone (spec §15). */
+export function SentimentPill({
+ sentiment,
+ className,
+}: {
+ sentiment: Sentiment | null;
+ className?: string;
+}) {
+ const t = useTranslations('mentions');
+ if (!sentiment) {
+ return <span className="text-xs text-muted-foreground">{t('table.noSentiment')}</span>;
+ }
+ return (
+ <Badge
+ variant="outline"
+ className={cn('h-5 px-1.5 text-[11px] font-medium', SENTIMENT_CLASS[sentiment], className)}
+ >
+ {t(`overview.sentiment.${sentiment}`)}
+ </Badge>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
new file mode 100644
index 000000000..817200781
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
@@ -0,0 +1,233 @@
+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 { MentionRow, MentionsList } from '@/lib/mentions-list';
+import type { Competitor } from '@/types';
+import { MentionsListTab } from './_mentions-tab';
+
+const listMentions = vi.fn();
+const getMentionResponse = vi.fn();
+vi.mock('@/lib/actions/mentions', () => ({
+ listMentions: (...args: unknown[]) => listMentions(...args),
+ getMentionResponse: (...args: unknown[]) => getMentionResponse(...args),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const row = (over: Partial<MentionRow>): MentionRow => ({
+ id: 'r1',
+ createdAt: '2026-10-16T11:28:06Z',
+ promptId: 'p1',
+ promptText: 'Best espresso beans?',
+ topicId: 't1',
+ topicName: 'Beans',
+ platform: 'gemini-web',
+ model: 'gemini-2.5-flash',
+ region: 'DE',
+ sentiment: 'negative',
+ occurrences: 1,
+ position: 2,
+ brandsNamed: 3,
+ coMentioned: [{ competitorId: 'c1', name: 'Crema Club', position: 1 }],
+ excerpt: 'Crema Club is first; Acme Coffee is pricier.',
+ groupKey: null,
+ groupCount: null,
+ ...over,
+});
+
+const list = (over: Partial<MentionsList> = {}): MentionsList => ({
+ total: 2,
+ prompts: 1,
+ rows: [row({}), row({ id: 'r2', platform: 'claude', sentiment: 'positive', coMentioned: [] })],
+ brandTerms: ['Acme Coffee', 'acme.com'],
+ ...over,
+});
+
+const competitors: Competitor[] = [
+ { id: 'c1', brandId: 'b1', name: 'Crema Club', domain: 'cremaclub.com' },
+];
+
+let container: HTMLDivElement;
+let root: Root;
+
+function render(node: React.ReactNode) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ {node}
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+async function settle() {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ });
+}
+
+const tab = (props: Partial<React.ComponentProps<typeof MentionsListTab>> = {}) => (
+ <MentionsListTab
+ brandId="b1"
+ filters={DEFAULT_MENTIONS_FILTERS}
+ competitors={competitors}
+ brandDomains={['acme.com']}
+ showCountry={false}
+ {...props}
+ />
+);
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ window.history.replaceState(null, '', '/dashboard/mentions?tab=mentions');
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ listMentions.mockReset();
+ getMentionResponse.mockReset();
+ vi.useRealTimers();
+});
+
+describe('MentionsListTab', () => {
+ it('reads a page with the URL controls and lists the mentions with the names marked', async () => {
+ window.history.replaceState(
+ null,
+ '',
+ '/dashboard/mentions?tab=mentions&sentiment=negative&with=c1',
+ );
+ listMentions.mockResolvedValue(list());
+ render(tab());
+ await settle();
+
+ expect(listMentions).toHaveBeenCalledTimes(1);
+ const [brandId, , table, page] = listMentions.mock.calls[0];
+ expect([brandId, table, page]).toEqual([
+ 'b1',
+ { sentiment: 'negative', competitor: 'c1', sort: 'newest', group: '' },
+ 0,
+ ]);
+ expect(container.textContent).toContain('2 mentions · 1 prompt');
+
+ const rows = container.querySelectorAll('tbody tr[tabindex]');
+ expect(rows).toHaveLength(2);
+ expect(rows[0].textContent).toContain('Best espresso beans?');
+ expect(rows[0].textContent).toContain('Negative');
+ expect(rows[0].textContent).toContain('#2 of 3');
+ const marks = [...rows[0].querySelectorAll('mark')].map((m) => [m.textContent, m.className]);
+ expect(marks[0][0]).toBe('Crema Club');
+ expect(marks[0][1]).toContain('bg-muted');
+ expect(marks[1][0]).toBe('Acme Coffee');
+ expect(marks[1][1]).toContain('bg-violet-100');
+ expect(rows[1].textContent).toContain('—');
+ });
+
+ it('heads each group with its name and size', async () => {
+ window.history.replaceState(null, '', '/dashboard/mentions?tab=mentions&group=platform');
+ listMentions.mockResolvedValue(
+ list({
+ rows: [
+ row({ id: 'a', platform: 'gemini-web', groupKey: 'gemini-web', groupCount: 12 }),
+ row({ id: 'b', platform: 'gemini-web', groupKey: 'gemini-web', groupCount: 12 }),
+ row({ id: 'c', platform: 'claude', groupKey: 'claude', groupCount: 1 }),
+ ],
+ }),
+ );
+ render(tab());
+ await settle();
+ expect(
+ [...container.querySelectorAll('tbody td[colspan]')].map((td) => td.textContent),
+ ).toEqual(['Gemini · 12 mentions', 'Claude · 1 mention']);
+ });
+
+ it('opens the answer: header, excerpt, the full response marked, and typed citations', async () => {
+ listMentions.mockResolvedValue(list());
+ getMentionResponse.mockResolvedValue({
+ response:
+ '## Picks\n\n- **Acme Coffee** for [beans](https://acme.com/beans)\n- Crema Club for price',
+ citations: [
+ { url: 'https://www.acme.com/beans', title: 'Our beans', startIndex: 0, endIndex: 0 },
+ { url: 'https://cremaclub.com/x', title: '', startIndex: 0, endIndex: 0 },
+ { url: 'https://reddit.com/r/coffee', title: 'Thread', startIndex: 0, endIndex: 0 },
+ ],
+ });
+ render(tab());
+ await settle();
+
+ const first = container.querySelector('tbody tr[tabindex]') as HTMLElement;
+ await act(async () => {
+ first.click();
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(getMentionResponse).toHaveBeenCalledWith('b1', 'r1');
+
+ const drawer = document.body.querySelector('[role="dialog"]') as HTMLElement;
+ expect(drawer).not.toBeNull();
+ const text = drawer.textContent ?? '';
+ expect(text).toContain('Gemini · gemini-2.5-flash');
+ expect(text).toContain('Best espresso beans?');
+ expect(text).toContain('Position #2 of 3');
+ expect(text).toContain('Topic: Beans');
+ expect(drawer.querySelector('a[href="/dashboard/prompts/p1"]')).not.toBeNull();
+ expect(text).toContain('Crema Club#1');
+
+ // The answer's names are marked inside the rendered markdown, bold and list items included.
+ const listItems = [...drawer.querySelectorAll('li')].filter((li) => li.closest('.prose'));
+ expect(listItems[0].querySelector('strong mark')?.textContent).toBe('Acme Coffee');
+ expect(listItems[1].querySelector('mark')?.textContent).toBe('Crema Club');
+
+ expect(text).toContain('Citations in this answer (3)');
+ const cited = [...drawer.querySelectorAll('ul.divide-y li')].map((li) => li.textContent);
+ expect(cited[0]).toContain('You');
+ expect(cited[1]).toContain('cremaclub.com');
+ expect(cited[1]).toContain('Competitor');
+ expect(cited[2]).toContain('Forum');
+ });
+
+ it('keeps its page when a read fails, and says so', async () => {
+ listMentions.mockResolvedValueOnce(list({ total: 250 }));
+ render(tab());
+ await settle();
+ const next = [...container.querySelectorAll('button')].find((b) => b.textContent === 'Next');
+ listMentions.mockRejectedValueOnce(new Error('timeout'));
+ await act(async () => {
+ next?.click();
+ await vi.advanceTimersByTimeAsync(300);
+ });
+ expect(listMentions).toHaveBeenCalledTimes(2);
+ expect(listMentions.mock.calls[1][3]).toBe(1);
+ expect(container.textContent).toContain("Couldn't load the mentions.");
+ // No silent jump back to the first page.
+ await settle();
+ expect(listMentions).toHaveBeenCalledTimes(2);
+ });
+
+ it('says when nothing matches, and asks for dates on an empty custom range', async () => {
+ listMentions.mockResolvedValue(list({ total: 0, prompts: 0, rows: [] }));
+ render(tab());
+ await settle();
+ expect(container.textContent).toContain('No mentions match these filters.');
+
+ render(tab({ filters: { ...DEFAULT_MENTIONS_FILTERS, range: 'custom' } }));
+ await settle();
+ expect(container.textContent).toContain('Choose a start or end date to see the mentions.');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx
new file mode 100644
index 000000000..a1cdde938
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx
@@ -0,0 +1,249 @@
+'use client';
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { TablePager, usePagination } from '@/components/table-pager';
+import { Card, CardContent } from '@/components/ui/card';
+import { Skeleton } from '@/components/ui/skeleton';
+import { listMentions } from '@/lib/actions/mentions';
+import { mentionsQuery, type MentionsFilters } from '@/lib/mentions-filters';
+import {
+ DEFAULT_MENTIONS_TABLE,
+ MENTIONS_PAGE_SIZE,
+ NO_COMPETITOR,
+ mentionsTableParams,
+ readMentionsTable,
+ type MentionRow,
+ type MentionsList,
+ type MentionsTableState,
+} from '@/lib/mentions-list';
+import { writeUrlParams } from '@/lib/url-state';
+import { cn } from '@/lib/utils';
+import type { Competitor } from '@/types';
+import { FilterSelect } from './_filter-bar';
+import type { MentionNames } from './_mention-parts';
+import { MentionsTable } from './_mentions-table';
+import { ResponseDrawer } from './_response-drawer';
+
+/** Typing in the search box reads once it pauses, not on every key. */
+const READ_DELAY_MS = 250;
+const ANY = '__any__';
+
+type Loaded =
+ | { brandId: string; key: string; status: 'ok'; list: MentionsList | 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 Mentions tab (MS-07): the answers naming the brand, a page of 100 at
+ * a time, under the page's filters and the table's own (sentiment, a
+ * competitor named in the same answer, grouping, sort), which live in the
+ * URL too. A row opens the response drawer.
+ */
+export function MentionsListTab({
+ brandId,
+ filters,
+ competitors,
+ brandDomains,
+ showCountry,
+}: {
+ brandId: string;
+ filters: MentionsFilters;
+ competitors: Competitor[];
+ brandDomains: string[];
+ showCountry: boolean;
+}) {
+ const t = useTranslations('mentions.table');
+ const tSentiment = useTranslations('mentions.overview.sentiment');
+ const query = useMemo(() => mentionsQuery(filters), [filters]);
+
+ // The table's controls, read from the URL once after mount.
+ const [table, setTable] = useState<MentionsTableState>(DEFAULT_MENTIONS_TABLE);
+ const [urlRead, setUrlRead] = useState(false);
+ useEffect(() => {
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount
+ setTable(readMentionsTable(new URLSearchParams(window.location.search)));
+ setUrlRead(true);
+ }, []);
+ useEffect(() => {
+ if (urlRead) writeUrlParams(mentionsTableParams(table));
+ }, [urlRead, table]);
+ const patch = (next: Partial<MentionsTableState>) => setTable((prev) => ({ ...prev, ...next }));
+
+ const [loaded, setLoaded] = useState<Loaded | null>(null);
+ // The last read's total: a failed read keeps it, so the pager stays on its page.
+ const [total, setTotal] = useState(0);
+ // Back to the first page whenever the filters or the controls change.
+ const pager = usePagination(total, JSON.stringify([brandId, query, table]), MENTIONS_PAGE_SIZE);
+ const key = query && urlRead ? JSON.stringify([brandId, query, table, pager.page]) : null;
+
+ useEffect(() => {
+ if (!key || !query) return;
+ let cancelled = false;
+ const timer = setTimeout(() => {
+ listMentions(brandId, query, table, pager.page)
+ .then((list) => {
+ if (cancelled) return;
+ setLoaded({ brandId, key, status: 'ok', list });
+ setTotal(list?.total ?? 0);
+ })
+ .catch(() => {
+ if (!cancelled) setLoaded({ brandId, key, status: 'error' });
+ });
+ }, READ_DELAY_MS);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [brandId, key, query, table, pager.page]);
+
+ const [open, setOpen] = useState<MentionRow | null>(null);
+
+ // A new page starts at its first row: the table scrolls inside its own box.
+ const tableBox = useRef<HTMLDivElement>(null);
+ const shownPage = loaded?.status === 'ok' ? loaded.key : null;
+ useEffect(() => {
+ const box = tableBox.current?.querySelector<HTMLElement>('[data-slot="table-container"]');
+ if (box) box.scrollTop = 0;
+ }, [shownPage]);
+
+ // Each read returns the brand's names afresh; only a change in them re-marks the text.
+ const brandKey = loaded?.status === 'ok' ? (loaded.list?.brandTerms ?? []).join('\n') : '';
+ const names = useMemo<MentionNames>(
+ () => ({
+ brand: brandKey ? brandKey.split('\n') : [],
+ competitors: competitors.flatMap((c) => [c.name, c.domain].filter(Boolean)),
+ }),
+ [brandKey, competitors],
+ );
+
+ const controls = (
+ <div className="flex flex-wrap items-end gap-3">
+ <FilterSelect
+ label={t('sentiment')}
+ value={table.sentiment || ANY}
+ items={[
+ { value: ANY, label: t('allSentiments') },
+ { value: 'positive', label: tSentiment('positive') },
+ { value: 'neutral', label: tSentiment('neutral') },
+ { value: 'negative', label: tSentiment('negative') },
+ ]}
+ onChange={(v) =>
+ patch({ sentiment: !v || v === ANY ? '' : (v as MentionsTableState['sentiment']) })
+ }
+ className="w-36"
+ />
+ <FilterSelect
+ label={t('coMentioned')}
+ value={table.competitor || ANY}
+ items={[
+ { value: ANY, label: t('anyCompetitor') },
+ { value: NO_COMPETITOR, label: t('noCompetitor') },
+ ...competitors.map((c) => ({ value: c.id, label: c.name })),
+ ]}
+ onChange={(v) => patch({ competitor: !v || v === ANY ? '' : v })}
+ className="w-44"
+ />
+ <FilterSelect
+ label={t('groupBy')}
+ value={table.group || ANY}
+ items={[
+ { value: ANY, label: t('noGrouping') },
+ { value: 'prompt', label: t('groupPrompt') },
+ { value: 'platform', label: t('groupPlatform') },
+ ]}
+ onChange={(v) =>
+ patch({ group: !v || v === ANY ? '' : (v as MentionsTableState['group']) })
+ }
+ className="w-32"
+ />
+ <FilterSelect
+ label={t('sort')}
+ value={table.sort}
+ items={[
+ { value: 'newest', label: t('sortNewest') },
+ { value: 'oldest', label: t('sortOldest') },
+ { value: 'co_mentions', label: t('sortCoMentions') },
+ { value: 'negative', label: t('sortNegative') },
+ ]}
+ onChange={(v) => patch({ sort: (v as MentionsTableState['sort']) || 'newest' })}
+ className="w-40"
+ />
+ {loaded?.status === 'ok' && loaded.list && (
+ <span className="ml-auto pb-1.5 text-xs text-muted-foreground tabular-nums">
+ {t('summary', { mentions: loaded.list.total, prompts: loaded.list.prompts })}
+ </span>
+ )}
+ </div>
+ );
+
+ let body: React.ReactNode;
+ if (!query) body = <Message>{t('pickDates')}</Message>;
+ else if (!loaded || loaded.brandId !== brandId) body = <TableSkeleton />;
+ else if (loaded.status === 'error')
+ body = loaded.key === key ? <Message>{t('loadError')}</Message> : <TableSkeleton />;
+ else if (!loaded.list) body = <Message>{t('unavailable')}</Message>;
+ else if (loaded.list.rows.length === 0) body = <Message>{t('empty')}</Message>;
+ else {
+ // The last page stays on screen, dimmed, while a newer one is on its way.
+ const stale = loaded.key !== key;
+ body = (
+ <Card
+ ref={tableBox}
+ className={cn('gap-0 overflow-hidden py-0 transition-opacity', stale && 'opacity-60')}
+ >
+ <MentionsTable
+ rows={loaded.list.rows}
+ names={names}
+ group={table.group}
+ showCountry={showCountry}
+ onOpen={setOpen}
+ />
+ <TablePager
+ page={pager.page}
+ totalPages={pager.totalPages}
+ total={total}
+ start={pager.start}
+ end={pager.end}
+ onPage={pager.setPage}
+ />
+ </Card>
+ );
+ }
+
+ return (
+ <section aria-label={t('sectionLabel')} className="flex flex-col gap-3">
+ {controls}
+ {body}
+ <ResponseDrawer
+ brandId={brandId}
+ row={open}
+ names={names}
+ domains={{
+ brand: brandDomains,
+ competitors: competitors.map((c) => c.domain).filter(Boolean),
+ }}
+ onClose={() => setOpen(null)}
+ />
+ </section>
+ );
+}
+
+function TableSkeleton() {
+ return (
+ <Card className="gap-2 p-4" aria-hidden>
+ {Array.from({ length: 8 }, (_, i) => (
+ <Skeleton key={i} className="h-10 w-full" />
+ ))}
+ </Card>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-table.tsx
new file mode 100644
index 000000000..344c684b7
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-table.tsx
@@ -0,0 +1,147 @@
+'use client';
+
+import { Fragment } from 'react';
+import { useLocale, useTranslations } from 'next-intl';
+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { mentionPlatformLabel } from '@/lib/mentions-headline';
+import type { MentionGroup, MentionRow } from '@/lib/mentions-list';
+import { formatRegionDisplay } from '@/lib/region';
+import { Highlighted, SentimentPill, type MentionNames } from './_mention-parts';
+
+/**
+ * The Mentions table (MS-07), as in the mockup: per answer naming the brand,
+ * the prompt (pinned while the table scrolls sideways, under a pinned
+ * header), platform, country, the passage around the mention with the names
+ * marked, sentiment, position, the competitors named beside you, topic and
+ * date. With grouping on, each group opens with its name and size. A row
+ * opens the answer.
+ */
+export function MentionsTable({
+ rows,
+ names,
+ group,
+ showCountry,
+ onOpen,
+}: {
+ rows: MentionRow[];
+ names: MentionNames;
+ group: MentionGroup | '';
+ showCountry: boolean;
+ onOpen: (row: MentionRow) => void;
+}) {
+ const t = useTranslations('mentions.table');
+ const locale = useLocale();
+ const columns = showCountry ? 9 : 8;
+ const day = (iso: string) =>
+ new Date(iso).toLocaleDateString(locale, { month: 'short', day: 'numeric' });
+
+ return (
+ <Table stickyHeader stickyFirstColumn aria-label={t('tableLabel')}>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="min-w-[220px] pl-4">{t('columns.prompt')}</TableHead>
+ <TableHead>{t('columns.platform')}</TableHead>
+ {showCountry && <TableHead>{t('columns.country')}</TableHead>}
+ <TableHead className="min-w-[320px]">{t('columns.context')}</TableHead>
+ <TableHead>{t('columns.sentiment')}</TableHead>
+ <TableHead>{t('columns.position')}</TableHead>
+ <TableHead className="min-w-[140px]">{t('columns.coMentioned')}</TableHead>
+ <TableHead>{t('columns.topic')}</TableHead>
+ <TableHead className="pr-4">{t('columns.date')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row, i) => {
+ const platform = mentionPlatformLabel(row.platform);
+ const opensGroup = group !== '' && row.groupKey !== rows[i - 1]?.groupKey;
+ return (
+ <Fragment key={row.id}>
+ {opensGroup && (
+ <TableRow className="hover:bg-transparent">
+ <TableCell
+ colSpan={columns}
+ className="bg-muted/60 py-1.5 pl-4 text-xs font-medium text-muted-foreground"
+ >
+ {t('groupRow', {
+ label: group === 'prompt' ? row.promptText : platform,
+ count: row.groupCount ?? 0,
+ })}
+ </TableCell>
+ </TableRow>
+ )}
+ <TableRow
+ tabIndex={0}
+ aria-label={t('openRow', { prompt: row.promptText, platform })}
+ className="cursor-pointer align-top hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:outline-none"
+ onClick={() => onOpen(row)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onOpen(row);
+ }
+ }}
+ >
+ <TableCell className="max-w-[260px] pl-4 whitespace-normal">
+ <span className="line-clamp-2 text-sm font-medium" title={row.promptText}>
+ {row.promptText}
+ </span>
+ </TableCell>
+ <TableCell>
+ <span className="inline-flex items-center gap-1.5 whitespace-nowrap text-sm">
+ <AIProviderAvatar
+ plain
+ provider={resolveAIProvider(row.platform, row.platform)}
+ className="h-4 w-4"
+ />
+ {platform}
+ </span>
+ </TableCell>
+ {showCountry && (
+ <TableCell className="whitespace-nowrap text-sm">
+ {row.region ? formatRegionDisplay(row.region) : '—'}
+ </TableCell>
+ )}
+ <TableCell className="max-w-[420px] whitespace-normal">
+ <span className="line-clamp-2 text-xs leading-relaxed text-muted-foreground">
+ <Highlighted text={row.excerpt} names={names} />
+ </span>
+ </TableCell>
+ <TableCell>
+ <SentimentPill sentiment={row.sentiment} />
+ </TableCell>
+ <TableCell className="whitespace-nowrap text-sm tabular-nums">
+ {row.position === null
+ ? '—'
+ : row.brandsNamed
+ ? t('positionOf', { position: row.position, count: row.brandsNamed })
+ : t('positionOnly', { position: row.position })}
+ </TableCell>
+ <TableCell className="max-w-[200px] whitespace-normal">
+ <span className="line-clamp-2 text-xs text-muted-foreground">
+ {row.coMentioned.length > 0
+ ? row.coMentioned.map((c) => c.name).join(', ')
+ : '—'}
+ </span>
+ </TableCell>
+ <TableCell className="max-w-[180px] whitespace-normal">
+ <span className="line-clamp-2 text-xs">{row.topicName ?? '—'}</span>
+ </TableCell>
+ <TableCell className="whitespace-nowrap pr-4 text-xs text-muted-foreground">
+ {day(row.createdAt)}
+ </TableCell>
+ </TableRow>
+ </Fragment>
+ );
+ })}
+ </TableBody>
+ </Table>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx
new file mode 100644
index 000000000..e36f6991d
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx
@@ -0,0 +1,340 @@
+'use client';
+
+import { useEffect, useMemo, useState, type ComponentProps, type ReactNode } from 'react';
+import { useLocale, useTranslations } from 'next-intl';
+import { ArrowUpRight, ChevronDown, Copy, ExternalLink } from 'lucide-react';
+import { toast } from 'sonner';
+import type { Components } from 'react-markdown';
+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Markdown } from '@/components/ui/markdown';
+import {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Link } from '@/i18n/navigation';
+import { getMentionResponse } from '@/lib/actions/mentions';
+import { classifyDomain, extractHostname, SOURCE_CATEGORY_LABELS } from '@/lib/citations/classify';
+import { stripEntityMarkup } from '@/lib/entity-markup';
+import { mentionPlatformLabel } from '@/lib/mentions-headline';
+import type { MentionRow } from '@/lib/mentions-list';
+import { formatRegionDisplay } from '@/lib/region';
+import { cn } from '@/lib/utils';
+import type { Citation } from '@/types';
+import {
+ Highlighted,
+ highlightChildren,
+ MARK_CLASS,
+ SentimentPill,
+ type MentionNames,
+} from './_mention-parts';
+
+type Loaded =
+ | { id: string; status: 'ok'; response: string; citations: Citation[] }
+ | { id: string; status: 'missing' | 'error' };
+
+function Section({
+ title,
+ aside,
+ children,
+}: {
+ title: string;
+ aside?: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <section className="space-y-2">
+ <h3 className="flex items-center gap-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
+ {title}
+ {aside}
+ </h3>
+ {children}
+ </section>
+ );
+}
+
+/**
+ * The response drawer (MS-08, read-only in V1): the answer's prompt,
+ * platform and model, country, date and time; its sentiment and the brand's
+ * position; the passage around the mention; the competitors named beside
+ * you; the full stored answer with your brand marked in violet and
+ * competitors in grey; and the sources it cites, typed as on the Citations
+ * page. Sending to the Action Center, suggesting content and correcting the
+ * sentiment come next.
+ */
+export function ResponseDrawer({
+ brandId,
+ row,
+ names,
+ domains,
+ onClose,
+}: {
+ brandId: string;
+ row: MentionRow | null;
+ names: MentionNames;
+ /** For typing the cited sources: your domains and the competitors'. */
+ domains: { brand: string[]; competitors: string[] };
+ onClose: () => void;
+}) {
+ const t = useTranslations('mentions.drawer');
+ const locale = useLocale();
+ const [loaded, setLoaded] = useState<Loaded | null>(null);
+ const [showResponse, setShowResponse] = useState(true);
+ const id = row?.id ?? null;
+
+ useEffect(() => {
+ if (!id) return;
+ let cancelled = false;
+ getMentionResponse(brandId, id)
+ .then((answer) => {
+ if (cancelled) return;
+ setLoaded(answer ? { id, status: 'ok', ...answer } : { id, status: 'missing' });
+ })
+ .catch(() => {
+ if (!cancelled) setLoaded({ id, status: 'error' });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, id]);
+
+ // A previous answer's text never shows under this one's header.
+ const answer = loaded && loaded.id === id ? loaded : null;
+ const response = answer?.status === 'ok' ? stripEntityMarkup(answer.response) : '';
+
+ // The marks inside the rendered answer; keyed below so new names re-render it.
+ const components = useMemo<Partial<Components>>(() => {
+ type Tag = 'p' | 'li' | 'td' | 'th' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'blockquote';
+ const mark = (Tag: Tag) => {
+ function Marked({ children, node, ...props }: ComponentProps<Tag> & { node?: unknown }) {
+ void node;
+ return <Tag {...(props as object)}>{highlightChildren(children, names)}</Tag>;
+ }
+ return Marked;
+ };
+ return {
+ p: mark('p'),
+ li: mark('li'),
+ td: mark('td'),
+ th: mark('th'),
+ h1: mark('h1'),
+ h2: mark('h2'),
+ h3: mark('h3'),
+ h4: mark('h4'),
+ h5: mark('h5'),
+ h6: mark('h6'),
+ blockquote: mark('blockquote'),
+ };
+ }, [names]);
+
+ const copy = async () => {
+ try {
+ if (!navigator.clipboard) throw new Error('Clipboard unavailable');
+ await navigator.clipboard.writeText(response);
+ toast.success(t('copied'));
+ } catch {
+ toast.error(t('copyFailed'));
+ }
+ };
+
+ const platform = row ? mentionPlatformLabel(row.platform) : '';
+ const when = row
+ ? new Date(row.createdAt).toLocaleString(locale, {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ })
+ : '';
+ const chip = 'inline-flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-0.5 text-xs';
+
+ return (
+ <Sheet open={row !== null} onOpenChange={(open) => !open && onClose()}>
+ <SheetContent
+ aria-label={t('label')}
+ className="flex flex-col gap-0 p-0 data-[side=right]:w-full data-[side=right]:sm:max-w-2xl"
+ >
+ {row && (
+ <>
+ <SheetHeader className="gap-2 border-b px-5 py-4 pr-12">
+ <SheetDescription className="flex flex-wrap items-center gap-1.5 text-foreground">
+ <span className={chip}>
+ <AIProviderAvatar
+ plain
+ provider={resolveAIProvider(row.platform, row.platform)}
+ className="h-4 w-4"
+ />
+ {row.model ? `${platform} · ${row.model}` : platform}
+ </span>
+ {row.region && <span className={chip}>{formatRegionDisplay(row.region)}</span>}
+ <span className={chip}>{when}</span>
+ </SheetDescription>
+ <SheetTitle className="text-base leading-snug break-words">
+ {row.promptText}
+ </SheetTitle>
+ <div className="flex flex-wrap items-center gap-1.5">
+ <SentimentPill sentiment={row.sentiment} />
+ {row.position !== null && (
+ <span className={chip}>
+ {row.brandsNamed
+ ? t('position', { position: row.position, count: row.brandsNamed })
+ : t('positionOnly', { position: row.position })}
+ </span>
+ )}
+ {row.topicName && (
+ <span className={chip}>{t('topic', { topic: row.topicName })}</span>
+ )}
+ <Link
+ href={`/dashboard/prompts/${row.promptId}`}
+ className="inline-flex items-center gap-0.5 text-xs font-medium text-primary hover:underline"
+ >
+ {t('viewPrompt')}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ </div>
+ </SheetHeader>
+
+ <div className="flex-1 space-y-6 overflow-y-auto px-5 py-4">
+ <Section title={t('mention')}>
+ <blockquote className="rounded-md border-l-2 border-violet-400 bg-muted/40 px-3 py-2 text-sm leading-relaxed">
+ <Highlighted text={row.excerpt} names={names} />
+ </blockquote>
+ <p className="flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground">
+ <mark className={MARK_CLASS.brand}>{t('legendBrand')}</mark>
+ <mark className={MARK_CLASS.competitor}>{t('legendCompetitor')}</mark>
+ </p>
+ </Section>
+
+ <Section title={t('coMentioned')}>
+ {row.coMentioned.length === 0 ? (
+ <p className="text-sm text-muted-foreground">{t('noCoMentions')}</p>
+ ) : (
+ <>
+ <ul className="flex flex-wrap gap-1.5">
+ {row.coMentioned.map((c) => (
+ <li key={c.competitorId} className={chip}>
+ {c.name}
+ {c.position !== null && (
+ <span className="text-muted-foreground">#{c.position}</span>
+ )}
+ </li>
+ ))}
+ </ul>
+ <p className="text-xs text-muted-foreground">{t('competitorTone')}</p>
+ </>
+ )}
+ </Section>
+
+ <Section
+ title={t('response')}
+ aside={
+ <span className="font-normal normal-case tracking-normal">({t('stored')})</span>
+ }
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ className="-ml-2 h-7 px-2 text-xs"
+ aria-expanded={showResponse}
+ onClick={() => setShowResponse((v) => !v)}
+ >
+ <ChevronDown
+ className={cn(
+ 'h-3.5 w-3.5 transition-transform',
+ !showResponse && '-rotate-90',
+ )}
+ />
+ {showResponse ? t('hideResponse') : t('showResponse')}
+ </Button>
+ {showResponse &&
+ (!answer ? (
+ <div className="space-y-2" aria-label={t('loading')}>
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-11/12" />
+ <Skeleton className="h-4 w-4/5" />
+ </div>
+ ) : answer.status === 'ok' ? (
+ <div className="prose prose-sm dark:prose-invert max-w-none">
+ <Markdown
+ key={`${row.id}:${names.brand.join('|')}:${names.competitors.join('|')}`}
+ components={components}
+ >
+ {response}
+ </Markdown>
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ {answer.status === 'missing' ? t('missing') : t('loadError')}
+ </p>
+ ))}
+ </Section>
+
+ {answer?.status === 'ok' && (
+ <Section title={`${t('citations')} (${answer.citations.length})`}>
+ {answer.citations.length === 0 ? (
+ <p className="text-sm text-muted-foreground">{t('noCitations')}</p>
+ ) : (
+ <ul className="divide-y rounded-md border">
+ {answer.citations.map((cite, i) => {
+ const host = extractHostname(cite.url) ?? cite.url;
+ const category = classifyDomain(host, {
+ brandDomains: domains.brand,
+ competitorDomains: domains.competitors,
+ });
+ return (
+ <li key={`${cite.url}-${i}`}>
+ <a
+ href={cite.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex items-start gap-3 px-3 py-2 text-sm transition-colors hover:bg-muted/50"
+ >
+ <ExternalLink className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate font-medium">
+ {cite.title || host}
+ </span>
+ <span className="block truncate text-xs text-muted-foreground">
+ {host}
+ </span>
+ </span>
+ <Badge
+ variant="outline"
+ className={cn(
+ 'h-5 shrink-0 px-1.5 text-[11px]',
+ category === 'you' &&
+ 'border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300',
+ )}
+ >
+ {SOURCE_CATEGORY_LABELS[category]}
+ </Badge>
+ </a>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </Section>
+ )}
+ </div>
+
+ <div className="flex items-center justify-between gap-2 border-t px-5 py-3">
+ <Button variant="outline" size="sm" onClick={copy} disabled={answer?.status !== 'ok'}>
+ <Copy className="h-3.5 w-3.5" />
+ {t('copy')}
+ </Button>
+ <SheetClose render={<Button variant="ghost" size="sm" />}>{t('close')}</SheetClose>
+ </div>
+ </>
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx
index f07208faf..52eb61799 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/page.tsx
@@ -1,9 +1,10 @@
'use client';
-import { useEffect, useState } from 'react';
+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';
import { getBrandFilterOptions } from '@/lib/actions/tracking';
import {
@@ -17,8 +18,9 @@ import {
} from '@/lib/mentions-filters';
import { writeUrlParams } from '@/lib/url-state';
import { useBrandStore } from '@/stores/use-brand-store';
-import type { Topic } from '@/types';
+import type { Competitor, Topic } from '@/types';
import { MentionsFilterBar } from './_filter-bar';
+import { MentionsListTab } from './_mentions-tab';
import { MentionsOverviewTab } from './_overview';
/**
@@ -32,8 +34,11 @@ import { MentionsOverviewTab } from './_overview';
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 activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId));
+ const brandName = activeBrand?.name ?? '';
+ const brandDomains = useMemo(
+ () => (activeBrand?.domains ?? []).map((d) => d.domain).filter(Boolean),
+ [activeBrand],
);
const [tab, setTab] = useState<MentionsTab>(DEFAULT_MENTIONS_TAB);
@@ -54,6 +59,7 @@ export default function MentionsPage() {
const [regions, setRegions] = useState<string[]>([]);
const [topics, setTopics] = useState<Topic[]>([]);
+ const [competitors, setCompetitors] = useState<Competitor[]>([]);
useEffect(() => {
if (!activeBrandId) return;
let cancelled = false;
@@ -67,6 +73,11 @@ export default function MentionsPage() {
if (!cancelled) setTopics(rows);
})
.catch(() => {});
+ getCompetitors(activeBrandId)
+ .then((rows) => {
+ if (!cancelled) setCompetitors(rows);
+ })
+ .catch(() => {});
return () => {
cancelled = true;
};
@@ -111,15 +122,24 @@ export default function MentionsPage() {
<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">
- {t('comingSoon')}
- </CardContent>
- </Card>
- </TabsContent>
- ))}
+ <TabsContent value="mentions" className="mt-4">
+ {urlRead && (
+ <MentionsListTab
+ brandId={activeBrandId}
+ filters={filters}
+ competitors={competitors}
+ brandDomains={brandDomains}
+ showCountry={regions.length > 1}
+ />
+ )}
+ </TabsContent>
+ <TabsContent value="perception" className="mt-4">
+ <Card>
+ <CardContent className="py-10 text-center text-sm text-muted-foreground">
+ {t('comingSoon')}
+ </CardContent>
+ </Card>
+ </TabsContent>
</Tabs>
</div>
);
diff --git a/web/src/lib/actions/mentions.test.ts b/web/src/lib/actions/mentions.test.ts
index b4ed20c01..e5ae48445 100644
--- a/web/src/lib/actions/mentions.test.ts
+++ b/web/src/lib/actions/mentions.test.ts
@@ -2,15 +2,28 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
let result: { data: unknown; error: { code?: string; message: string } | null };
const rpc = vi.fn(async () => result);
+// A table read: every filter call is recorded, and the read ends in maybeSingle.
+let tableResult: { data: unknown; error: { message: string } | null };
+const tableCalls: unknown[][] = [];
+const query = {
+ select: (...args: unknown[]) => (tableCalls.push(['select', ...args]), query),
+ eq: (...args: unknown[]) => (tableCalls.push(['eq', ...args]), query),
+ maybeSingle: async () => tableResult,
+};
+const from = vi.fn((table: string) => (tableCalls.push(['from', table]), query));
vi.mock('@/lib/supabase/server', () => ({
- createClient: vi.fn(async () => ({ rpc })),
+ createClient: vi.fn(async () => ({ rpc, from })),
}));
-import { getMentionsOverview } from './mentions';
+import { getMentionResponse, getMentionsOverview, listMentions } from './mentions';
+import { DEFAULT_MENTIONS_TABLE } from '@/lib/mentions-list';
beforeEach(() => {
rpc.mockClear();
+ from.mockClear();
+ tableCalls.length = 0;
result = { data: null, error: null };
+ tableResult = { data: null, error: null };
});
describe('getMentionsOverview', () => {
@@ -58,3 +71,119 @@ describe('getMentionsOverview', () => {
await expect(getMentionsOverview('b1', { from: 'f' })).rejects.toThrow('statement timeout');
});
});
+
+describe('listMentions', () => {
+ it('reads a page with the table controls and cuts each answer to its excerpt', async () => {
+ result = {
+ data: {
+ total: 214,
+ prompts: 12,
+ rows: [
+ {
+ id: 'r1',
+ created_at: '2026-10-16T11:28:06Z',
+ prompt_id: 'p1',
+ prompt_text: 'Best espresso beans?',
+ topic_id: 't1',
+ topic_name: 'Beans',
+ platform: 'gemini-web',
+ model_used: 'gemini-2.5-flash',
+ region: 'DE',
+ sentiment: 'negative',
+ mention_count: 2,
+ mention_position: 2,
+ mentioned_entity_count: 4,
+ co_mentioned: [{ competitor_id: 'c1', name: 'Crema Club', mention_position: 1 }],
+ response: 'Try **Crema Club** first. Acme Coffee is pricier.',
+ group_key: null,
+ group_count: null,
+ },
+ ],
+ },
+ error: null,
+ };
+ tableResult = {
+ data: { name: 'Acme Coffee', brand_domains: [{ domain: 'acme.com' }] },
+ error: null,
+ };
+ const list = await listMentions(
+ 'b1',
+ { from: '2026-10-10T00:00:00.000Z', platform: 'gemini-web' },
+ { ...DEFAULT_MENTIONS_TABLE, sentiment: 'negative', competitor: 'c1', sort: 'co_mentions' },
+ 2,
+ );
+ expect(rpc).toHaveBeenCalledWith('mentions_list', {
+ p_brand_id: 'b1',
+ p_date_from: '2026-10-10T00:00:00.000Z',
+ p_date_to: undefined,
+ p_platform: 'gemini-web',
+ p_region: undefined,
+ p_topic_id: undefined,
+ p_search: undefined,
+ p_sentiment: 'negative',
+ p_competitor_id: 'c1',
+ p_sort: 'co_mentions',
+ p_group: undefined,
+ p_limit: 100,
+ p_offset: 200,
+ });
+ expect(tableCalls).toContainEqual(['eq', 'id', 'b1']);
+ expect(list).toMatchObject({
+ total: 214,
+ prompts: 12,
+ brandTerms: ['Acme Coffee', 'acme.com'],
+ });
+ expect(list?.rows[0]).toEqual({
+ id: 'r1',
+ createdAt: '2026-10-16T11:28:06Z',
+ promptId: 'p1',
+ promptText: 'Best espresso beans?',
+ topicId: 't1',
+ topicName: 'Beans',
+ platform: 'gemini-web',
+ model: 'gemini-2.5-flash',
+ region: 'DE',
+ sentiment: 'negative',
+ occurrences: 2,
+ position: 2,
+ brandsNamed: 4,
+ coMentioned: [{ competitorId: 'c1', name: 'Crema Club', position: 1 }],
+ excerpt: 'Try Crema Club first. Acme Coffee is pricier.',
+ groupKey: null,
+ groupCount: null,
+ });
+ expect(list?.rows[0]).not.toHaveProperty('response');
+ });
+
+ it('is null before the migration has run, and throws on other errors', async () => {
+ result = { data: null, error: { code: 'PGRST202', message: 'not found' } };
+ await expect(listMentions('b1', { from: 'f' }, DEFAULT_MENTIONS_TABLE, 0)).resolves.toBeNull();
+ result = { data: null, error: { code: '57014', message: 'statement timeout' } };
+ await expect(listMentions('b1', { from: 'f' }, DEFAULT_MENTIONS_TABLE, 0)).rejects.toThrow(
+ 'statement timeout',
+ );
+ });
+});
+
+describe('getMentionResponse', () => {
+ it("reads the answer's text and citations within the brand", async () => {
+ tableResult = {
+ data: { response: 'Hello', citations: [{ url: 'https://a.com', title: 'A' }] },
+ error: null,
+ };
+ await expect(getMentionResponse('b1', 'r1')).resolves.toEqual({
+ response: 'Hello',
+ citations: [{ url: 'https://a.com', title: 'A' }],
+ });
+ expect(tableCalls).toEqual([
+ ['from', 'prompt_results'],
+ ['select', 'response, citations'],
+ ['eq', 'id', 'r1'],
+ ['eq', 'brand_id', 'b1'],
+ ]);
+ });
+
+ it("is null when the answer isn't readable", async () => {
+ await expect(getMentionResponse('b1', 'r1')).resolves.toBeNull();
+ });
+});
diff --git a/web/src/lib/actions/mentions.ts b/web/src/lib/actions/mentions.ts
index 8380bbda5..da52f46cf 100644
--- a/web/src/lib/actions/mentions.ts
+++ b/web/src/lib/actions/mentions.ts
@@ -1,8 +1,16 @@
'use server';
import { createClient } from '@/lib/supabase/server';
+import { mentionExcerpt } from '@/lib/mention-match';
import type { MentionsQuery } from '@/lib/mentions-filters';
+import {
+ MENTIONS_PAGE_SIZE,
+ parseMentionsList,
+ type MentionsList,
+ type MentionsTableState,
+} from '@/lib/mentions-list';
import { parseMentionsOverview, type MentionsOverview } from '@/lib/mentions-overview';
+import type { Citation } from '@/types';
/**
* The Mentions & Sentiment Overview's figures (MS-06) for a window and the
@@ -31,3 +39,73 @@ export async function getMentionsOverview(
if (error) throw new Error(error.message);
return parseMentionsOverview(data);
}
+
+/**
+ * A page of the Mentions table (MS-07): the answers naming the brand in the
+ * window, filtered, sorted and grouped as the table asks, from mentions_list
+ * (00158). Each answer's text is cut here to the passage around the brand's
+ * first mention, so the page receives excerpts only.
+ *
+ * Null as getMentionsOverview: no function yet (PGRST202), or no access.
+ */
+export async function listMentions(
+ brandId: string,
+ query: MentionsQuery,
+ table: MentionsTableState,
+ page: number,
+): Promise<MentionsList | null> {
+ const supabase = await createClient();
+ const [list, brand] = await Promise.all([
+ supabase.rpc('mentions_list', {
+ p_brand_id: brandId,
+ p_date_from: query.from,
+ p_date_to: query.to,
+ p_platform: query.platform,
+ p_region: query.region,
+ p_topic_id: query.topicId,
+ p_search: query.search,
+ p_sentiment: table.sentiment || undefined,
+ p_competitor_id: table.competitor || undefined,
+ p_sort: table.sort,
+ p_group: table.group || undefined,
+ p_limit: MENTIONS_PAGE_SIZE,
+ p_offset: Math.max(0, page) * MENTIONS_PAGE_SIZE,
+ }),
+ supabase.from('brands').select('name, brand_domains(domain)').eq('id', brandId).maybeSingle(),
+ ]);
+ if (list.error?.code === 'PGRST202') return null;
+ if (list.error) throw new Error(list.error.message);
+
+ // The names tracking matches the brand by: its name and its domains.
+ const row = brand.data as { name?: string; brand_domains?: { domain?: string }[] } | null;
+ const brandTerms = [
+ row?.name ?? '',
+ ...(row?.brand_domains ?? []).map((d) => d.domain ?? ''),
+ ].filter(Boolean);
+ const parsed = parseMentionsList(list.data, (response) => mentionExcerpt(response, brandTerms));
+ return parsed ? { ...parsed, brandTerms } : null;
+}
+
+/**
+ * One answer's stored text and citations, for the response drawer. Read as
+ * the caller, so row-level security limits it to their organization's
+ * answers; null when it isn't theirs or no longer exists.
+ */
+export async function getMentionResponse(
+ brandId: string,
+ resultId: string,
+): Promise<{ response: string; citations: Citation[] } | null> {
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('prompt_results')
+ .select('response, citations')
+ .eq('id', resultId)
+ .eq('brand_id', brandId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) return null;
+ return {
+ response: typeof data.response === 'string' ? data.response : '',
+ citations: Array.isArray(data.citations) ? (data.citations as unknown as Citation[]) : [],
+ };
+}
diff --git a/web/src/lib/mention-match.test.ts b/web/src/lib/mention-match.test.ts
new file mode 100644
index 000000000..4d9db0f10
--- /dev/null
+++ b/web/src/lib/mention-match.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+import { answerProse, highlightSegments, mentionExcerpt } from './mention-match';
+
+describe('answerProse', () => {
+ it('reads the answer as prose: link labels, no URLs, no markdown marks', () => {
+ expect(
+ answerProse(
+ '## Best picks\n\n- **[Acme](https://acme.com/x)** is great, see https://acme.com\n> `quoted`\n1. #1 pick',
+ ),
+ ).toBe('Best picks Acme is great, see quoted 1. #1 pick');
+ });
+});
+
+describe('mentionExcerpt', () => {
+ const long = (n: number) => Array.from({ length: n }, (_, i) => `word${i}`).join(' ');
+
+ it('quotes around the first mention, cut on whole words', () => {
+ const text = `${long(40)} and then Acme Coffee roasts well. ${long(40)}`;
+ const excerpt = mentionExcerpt(text, ['Acme Coffee', 'acme.com']);
+ expect(excerpt.startsWith('…word')).toBe(true);
+ expect(excerpt.endsWith('…')).toBe(true);
+ expect(excerpt).toContain('and then Acme Coffee roasts well.');
+ // Whole words only at both ends.
+ expect(excerpt).toMatch(/^…word\d+ /);
+ expect(excerpt).toMatch(/ word\d+…$/);
+ });
+
+ it('matches a whole word only, ignoring case, and not inside a URL', () => {
+ expect(mentionExcerpt('Acmeville is not it. Then ACME COFFEE.', ['Acme Coffee'])).toBe(
+ 'Acmeville is not it. Then ACME COFFEE.',
+ );
+ const text = `See https://acme.com/acme-coffee for ${long(60)} later acme.com appears`;
+ expect(mentionExcerpt(text, ['acme.com'])).toMatch(/later acme\.com appears$/);
+ });
+
+ it("opens with the answer's start when no name matches", () => {
+ const excerpt = mentionExcerpt(long(80), ['Acme']);
+ expect(excerpt.startsWith('word0 word1')).toBe(true);
+ expect(excerpt.endsWith('…')).toBe(true);
+ });
+});
+
+describe('highlightSegments', () => {
+ it('marks the brand and competitors, the longer name first', () => {
+ expect(
+ highlightSegments('Acme Coffee beats Acme Roasters and crema club.', {
+ brand: ['Acme Coffee'],
+ competitors: ['Crema Club', 'Acme Roasters'],
+ }),
+ ).toEqual([
+ { text: 'Acme Coffee', kind: 'brand' },
+ { text: ' beats ' },
+ { text: 'Acme Roasters', kind: 'competitor' },
+ { text: ' and ' },
+ { text: 'crema club', kind: 'competitor' },
+ { text: '.' },
+ ]);
+ });
+
+ it('leaves text without names whole', () => {
+ expect(highlightSegments('Nothing here', { brand: ['Acme'], competitors: [] })).toEqual([
+ { text: 'Nothing here' },
+ ]);
+ expect(highlightSegments('Text', { brand: [], competitors: [] })).toEqual([{ text: 'Text' }]);
+ });
+});
diff --git a/web/src/lib/mention-match.ts b/web/src/lib/mention-match.ts
new file mode 100644
index 000000000..e378a801f
--- /dev/null
+++ b/web/src/lib/mention-match.ts
@@ -0,0 +1,117 @@
+import { stripEntityMarkup } from '@/lib/entity-markup';
+
+/**
+ * Finding a brand's or competitor's name in an AI answer the way tracking
+ * counts it (server/src/lib/response-parser.js — keep the two in sync): a
+ * case-insensitive whole word, with a Unicode boundary only on a side where
+ * the name ends in a letter or number of a space-separated script, in the
+ * answer as its reader sees it (ChatGPT's entity tags read as their names,
+ * links as their labels, bare URLs dropped).
+ */
+
+const WORD_CHAR = /[\p{L}\p{N}_]/u;
+// Scripts written without spaces between words, and Korean, whose particles
+// attach to the noun: a name there is always flanked by other letters.
+const UNSPACED_SCRIPT =
+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u;
+
+function namePattern(term: string): string {
+ const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const needsBoundary = (ch: string) => WORD_CHAR.test(ch) && !UNSPACED_SCRIPT.test(ch);
+ const chars = [...term];
+ const before = needsBoundary(chars[0]) ? '(?<![\\p{L}\\p{N}_])' : '';
+ const after = needsBoundary(chars[chars.length - 1]) ? '(?![\\p{L}\\p{N}_])' : '';
+ return `${before}${escaped}${after}`;
+}
+
+/** One regex for several names, the longest first so "Acme Coffee" wins over "Acme". */
+function namesRegex(terms: string[]): RegExp | null {
+ const unique = [...new Set(terms.map((t) => t.trim()).filter(Boolean))].sort(
+ (a, b) => b.length - a.length,
+ );
+ return unique.length > 0 ? new RegExp(unique.map(namePattern).join('|'), 'giu') : null;
+}
+
+/** "[label](https://…)" → "label"; bare URLs dropped. */
+function stripUrls(text: string): string {
+ return text.replace(/\[([^\]]*)\]\([^)]+\)/g, '$1').replace(/https?:\/\/[^\s)>\]]+/g, '');
+}
+
+/**
+ * The answer as plain prose for a quote: names matched as tracking does, and
+ * markdown's own marks dropped (headings, quote and bullet marks at a line
+ * start, bold, code), whitespace collapsed. "#1 pick" or "A > B" stay.
+ */
+export function answerProse(response: string): string {
+ return stripUrls(stripEntityMarkup(response))
+ .replace(/^[ \t]*(?:#{1,6}[ \t]+|>[ \t]?|[-*+][ \t]+)/gm, '')
+ .replace(/\*\*|__|`/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+/** About this many characters of context each side of the name. */
+const EXCERPT_RADIUS = 110;
+
+/**
+ * The passage around the brand's first mention in an answer (spec §7,
+ * "Mention context"), cut on whole words with "…" where it was cut. Falls back
+ * to the answer's opening when no name matches (a rename since the answer).
+ */
+export function mentionExcerpt(response: string, brandTerms: string[]): string {
+ const prose = answerProse(response);
+ const match = namesRegex(brandTerms)?.exec(prose);
+ if (!match) return cut(prose, 0, EXCERPT_RADIUS * 2);
+ return cut(prose, match.index - EXCERPT_RADIUS, match.index + match[0].length + EXCERPT_RADIUS);
+}
+
+function cut(text: string, from: number, to: number): string {
+ let start = Math.max(0, from);
+ let end = Math.min(text.length, to);
+ // Move inward to the nearest space so no word is cut.
+ if (start > 0) {
+ const space = text.indexOf(' ', start);
+ start = space === -1 || space >= end ? start : space + 1;
+ }
+ if (end < text.length) {
+ const space = text.lastIndexOf(' ', end);
+ end = space > start ? space : end;
+ }
+ const body = text.slice(start, end).trim();
+ return `${start > 0 ? '…' : ''}${body}${end < text.length ? '…' : ''}`;
+}
+
+export type MentionKind = 'brand' | 'competitor';
+
+export interface TextSegment {
+ text: string;
+ /** Set on a name: the brand's or a competitor's. */
+ kind?: MentionKind;
+}
+
+/**
+ * A text split around the names in it, for highlighting: the brand's names
+ * and the competitors'. The longer name wins where two overlap, and a name
+ * on both lists counts as the brand's.
+ */
+export function highlightSegments(
+ text: string,
+ names: { brand: string[]; competitors: string[] },
+): TextSegment[] {
+ const brand = new Set(names.brand.map((n) => n.trim().toLowerCase()).filter(Boolean));
+ const regex = namesRegex([...names.brand, ...names.competitors]);
+ if (!regex || !text) return text ? [{ text }] : [];
+ const segments: TextSegment[] = [];
+ let last = 0;
+ for (const match of text.matchAll(regex)) {
+ const at = match.index ?? 0;
+ if (at > last) segments.push({ text: text.slice(last, at) });
+ segments.push({
+ text: match[0],
+ kind: brand.has(match[0].toLowerCase()) ? 'brand' : 'competitor',
+ });
+ last = at + match[0].length;
+ }
+ if (last < text.length) segments.push({ text: text.slice(last) });
+ return segments;
+}
diff --git a/web/src/lib/mentions-filters.ts b/web/src/lib/mentions-filters.ts
index 5f6f5168e..7936f972f 100644
--- a/web/src/lib/mentions-filters.ts
+++ b/web/src/lib/mentions-filters.ts
@@ -22,7 +22,7 @@ export interface MentionsFilters {
platform: string;
region: string;
topic: string;
- /** Free text over prompts, brands and phrases. */
+ /** Free text over the prompts' text, the same on every tab. */
q: string;
}
diff --git a/web/src/lib/mentions-list.test.ts b/web/src/lib/mentions-list.test.ts
new file mode 100644
index 000000000..664b8613b
--- /dev/null
+++ b/web/src/lib/mentions-list.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+import {
+ DEFAULT_MENTIONS_TABLE,
+ mentionsTableParams,
+ parseMentionsList,
+ readMentionsTable,
+} from './mentions-list';
+
+describe('the table controls in the URL', () => {
+ it('reads known values and falls back on anything else', () => {
+ expect(
+ readMentionsTable(
+ new URLSearchParams('sentiment=negative&with=c1&sort=co_mentions&group=platform'),
+ ),
+ ).toEqual({ sentiment: 'negative', competitor: 'c1', sort: 'co_mentions', group: 'platform' });
+ expect(
+ readMentionsTable(new URLSearchParams('sentiment=angry&sort=random&group=topic')),
+ ).toEqual(DEFAULT_MENTIONS_TABLE);
+ });
+
+ it('keeps defaults out of the URL', () => {
+ expect(mentionsTableParams(DEFAULT_MENTIONS_TABLE)).toEqual({
+ sentiment: null,
+ with: null,
+ sort: null,
+ group: null,
+ });
+ expect(
+ mentionsTableParams({
+ sentiment: 'neutral',
+ competitor: 'none',
+ sort: 'oldest',
+ group: 'prompt',
+ }),
+ ).toEqual({ sentiment: 'neutral', with: 'none', sort: 'oldest', group: 'prompt' });
+ });
+});
+
+describe('parseMentionsList', () => {
+ it('reads sparse rows safely and keeps unknown sentiments out', () => {
+ const list = parseMentionsList(
+ {
+ total: '3',
+ prompts: 1,
+ rows: [
+ {
+ id: 'r1',
+ created_at: '2026-10-16T00:00:00Z',
+ prompt_id: 'p1',
+ prompt_text: 'Q',
+ sentiment: 'mixed',
+ mention_count: 1,
+ mention_position: null,
+ co_mentioned: null,
+ response: 'text',
+ group_key: 'chatgpt-web',
+ group_count: 3,
+ },
+ ],
+ },
+ (response) => `excerpt of ${response}`,
+ );
+ expect(list?.total).toBe(3);
+ expect(list?.rows[0]).toMatchObject({
+ sentiment: null,
+ position: null,
+ brandsNamed: null,
+ topicName: null,
+ coMentioned: [],
+ excerpt: 'excerpt of text',
+ groupKey: 'chatgpt-web',
+ groupCount: 3,
+ });
+ });
+
+ it('is null when there is nothing to read', () => {
+ expect(parseMentionsList(null, () => '')).toBeNull();
+ });
+});
diff --git a/web/src/lib/mentions-list.ts b/web/src/lib/mentions-list.ts
new file mode 100644
index 000000000..513c9d148
--- /dev/null
+++ b/web/src/lib/mentions-list.ts
@@ -0,0 +1,147 @@
+import type { Sentiment } from '@/types';
+
+/**
+ * The Mentions tab's table (MS-07): one row per answer naming the brand, as
+ * mentions_list (00158) returns them a page at a time, and the table's own
+ * controls, kept in the URL beside the page's filters.
+ */
+
+export const MENTION_SENTIMENTS = ['positive', 'neutral', 'negative'] as const;
+export const MENTION_SORTS = ['newest', 'oldest', 'co_mentions', 'negative'] as const;
+export const MENTION_GROUPS = ['prompt', 'platform'] as const;
+
+export type MentionSentiment = (typeof MENTION_SENTIMENTS)[number];
+export type MentionSort = (typeof MENTION_SORTS)[number];
+export type MentionGroup = (typeof MENTION_GROUPS)[number];
+
+/** Answers naming no competitor, in the "Co-mentioned" filter. */
+export const NO_COMPETITOR = 'none';
+
+export interface MentionsTableState {
+ /** Empty for every sentiment. */
+ sentiment: MentionSentiment | '';
+ /** A competitor named in the same answer, NO_COMPETITOR, or empty for any. */
+ competitor: string;
+ sort: MentionSort;
+ /** Empty for no grouping. */
+ group: MentionGroup | '';
+}
+
+export const DEFAULT_MENTIONS_TABLE: MentionsTableState = {
+ sentiment: '',
+ competitor: '',
+ sort: 'newest',
+ group: '',
+};
+
+/** The table pages at 100 rows (spec §15). */
+export const MENTIONS_PAGE_SIZE = 100;
+
+const pick = <T extends string>(value: string | null, allowed: readonly T[]): T | '' =>
+ value !== null && (allowed as readonly string[]).includes(value) ? (value as T) : '';
+
+export function readMentionsTable(search: URLSearchParams): MentionsTableState {
+ return {
+ sentiment: pick(search.get('sentiment'), MENTION_SENTIMENTS),
+ competitor: search.get('with') ?? '',
+ sort: pick(search.get('sort'), MENTION_SORTS) || DEFAULT_MENTIONS_TABLE.sort,
+ group: pick(search.get('group'), MENTION_GROUPS),
+ };
+}
+
+/** The table's query params for writeUrlParams; defaults map to null. */
+export function mentionsTableParams(state: MentionsTableState): Record<string, string | null> {
+ return {
+ sentiment: state.sentiment || null,
+ with: state.competitor || null,
+ sort: state.sort === DEFAULT_MENTIONS_TABLE.sort ? null : state.sort,
+ group: state.group || null,
+ };
+}
+
+export interface MentionRow {
+ /** The answer's id (prompt_results). */
+ id: string;
+ createdAt: string;
+ promptId: string;
+ promptText: string;
+ topicId: string | null;
+ topicName: string | null;
+ platform: string;
+ model: string | null;
+ region: string | null;
+ sentiment: Sentiment | null;
+ /** Times the brand is named in the answer. */
+ occurrences: number;
+ /** The brand's place among the brands the answer names (1 = first), and how many it names. */
+ position: number | null;
+ brandsNamed: number | null;
+ /** Competitors named in the same answer, in the order they appear when known. */
+ coMentioned: { competitorId: string; name: string; position: number | null }[];
+ /** The passage around the brand's first mention. */
+ excerpt: string;
+ /** With grouping on: the row's group and the group's size over every page. */
+ groupKey: string | null;
+ groupCount: number | null;
+}
+
+export interface MentionsList {
+ /** Mentions over every page, and the prompts they answer. */
+ total: number;
+ prompts: number;
+ rows: MentionRow[];
+ /** The names the brand is matched by (name and domains), for highlighting. */
+ brandTerms: string[];
+}
+
+type Raw = Record<string, unknown>;
+const num = (value: unknown): number | null =>
+ value === null || value === undefined || value === '' || !Number.isFinite(Number(value))
+ ? null
+ : Number(value);
+const str = (value: unknown): string | null =>
+ typeof value === 'string' && value !== '' ? value : null;
+const SENTIMENTS: readonly string[] = MENTION_SENTIMENTS;
+
+/**
+ * The function's jsonb as the table's rows, each answer's text cut down to
+ * the excerpt by `excerptOf` (the page never receives the full text). Null
+ * when there is nothing to read (the caller isn't in the brand's organization).
+ */
+export function parseMentionsList(
+ raw: unknown,
+ excerptOf: (response: string) => string,
+): Omit<MentionsList, 'brandTerms'> | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const r = raw as Raw;
+ const rows = Array.isArray(r.rows) ? (r.rows as Raw[]) : [];
+ return {
+ total: num(r.total) ?? 0,
+ prompts: num(r.prompts) ?? 0,
+ rows: rows.map((row) => ({
+ id: String(row.id ?? ''),
+ createdAt: String(row.created_at ?? ''),
+ promptId: String(row.prompt_id ?? ''),
+ promptText: String(row.prompt_text ?? ''),
+ topicId: str(row.topic_id),
+ topicName: str(row.topic_name),
+ platform: String(row.platform ?? ''),
+ model: str(row.model_used),
+ region: str(row.region),
+ sentiment: SENTIMENTS.includes(String(row.sentiment)) ? (row.sentiment as Sentiment) : null,
+ occurrences: num(row.mention_count) ?? 0,
+ position: num(row.mention_position),
+ brandsNamed: num(row.mentioned_entity_count),
+ coMentioned: (Array.isArray(row.co_mentioned) ? (row.co_mentioned as Raw[]) : []).map(
+ (c) => ({
+ competitorId: String(c.competitor_id ?? ''),
+ name: String(c.name ?? ''),
+ position: num(c.mention_position),
+ }),
+ ),
+ excerpt: excerptOf(typeof row.response === 'string' ? row.response : ''),
+ groupKey: str(row.group_key),
+ groupCount: num(row.group_count),
+ })),
+ };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 0baa77342..1f3ff4291 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3272,6 +3272,24 @@ export type Database = {
}
Returns: Json
}
+ mentions_list: {
+ Args: {
+ p_brand_id: string
+ p_competitor_id?: string
+ p_date_from: string
+ p_date_to?: string
+ p_group?: string
+ p_limit?: number
+ p_offset?: number
+ p_platform?: string
+ p_region?: string
+ p_search?: string
+ p_sentiment?: string
+ p_sort?: string
+ p_topic_id?: string
+ }
+ Returns: Json
+ }
normalize_page_path: { Args: { p_url: string }; Returns: string }
import_prompts: {
Args: {