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(action-center): group copies of one signal and count them once (#1059)

Cihan9b412280f2fb
diff --git a/supabase/migrations/00141_signal_groups.sql b/supabase/migrations/00141_signal_groups.sql
new file mode 100644
index 000000000..d09022bef
--- /dev/null
+++ b/supabase/migrations/00141_signal_groups.sql
@@ -0,0 +1,170 @@
+-- Signal groups: count copies of one finding once (AC-002).
+--
+-- A brand can track the same prompt text several times, in different topics
+-- or with different locations, and the detectors write one signal per
+-- prompt. On production one pass wrote ten identical "Citations lost for
+-- '…'" rows, and every card counted all ten. The Signals list now shows such
+-- copies as one row, so the cards count them as one too.
+--
+-- signal_group_key names the group a signal belongs to: signals of one kind,
+-- about one prompt text (case, spacing and the closing "?" ignored), found in
+-- one pass. Signals not about a prompt are their own group. The web list has
+-- the same rule in web/src/lib/signals/group.ts; change both together.
+--
+-- signals_summary is 00080's, counting groups instead of rows. A group is
+-- detected when its first copy was, high impact when any copy is, and
+-- resolved only once every copy is, on the day the last one was: a finding
+-- with copies still open has not been resolved.
+--
+-- signals_new_count is the Action Center tab badge, the untriaged groups.
+
+create or replace function public.signal_group_key(
+ p_id uuid,
+ p_kind text,
+ p_detected_at timestamptz,
+ p_payload jsonb
+) returns text
+language sql
+stable
+set search_path = public
+as $$
+ select case
+ when jsonb_typeof(p_payload -> 'promptId') = 'string'
+ and jsonb_typeof(p_payload -> 'promptText') = 'string'
+ then p_kind || '|'
+ || lower(regexp_replace(
+ btrim(regexp_replace(p_payload ->> 'promptText', '[ \t\n\r\f\v]+', ' ', 'g')),
+ '[ ?.!]+$', ''))
+ || '|' || (extract(epoch from p_detected_at) * 1000)::bigint::text
+ else p_id::text
+ end;
+$$;
+
+create or replace function public.signals_summary(
+ p_brand_id uuid,
+ p_from timestamptz,
+ p_to timestamptz
+) returns jsonb
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ with bounds as (
+ select p_from as cur_from, p_to as cur_to,
+ p_from - (p_to - p_from) as prev_from, p_from as prev_to
+ ),
+ groups as (
+ select
+ public.signal_group_key(id, kind, detected_at, payload) as group_key,
+ min(detected_at) as detected_at,
+ case when bool_and(resolved_at is not null) then max(resolved_at) end as resolved_at,
+ bool_or(impact = 'high') as important,
+ -- One kind per group, so one category and one set of sources.
+ min(category) as category,
+ min(source) as source
+ from public.signals
+ where brand_id = p_brand_id
+ group by 1
+ ),
+ active as (
+ select * from groups, bounds
+ where detected_at < cur_to
+ and (resolved_at is null or resolved_at >= cur_from)
+ ),
+ prev_active as (
+ select * from groups, bounds
+ where detected_at < prev_to
+ and (resolved_at is null or resolved_at >= prev_from)
+ ),
+ days as (
+ select generate_series(
+ (select cur_from from bounds)::date,
+ (select cur_to from bounds)::date - 1,
+ interval '1 day'
+ )::date as day
+ )
+ select jsonb_build_object(
+ 'total', (select count(*) from active),
+ 'prev_total', (select count(*) from prev_active),
+ 'important', (select count(*) from active where important),
+ 'prev_important', (select count(*) from prev_active where important),
+ 'new', (
+ select count(*) from groups, bounds
+ where detected_at >= cur_from and detected_at < cur_to
+ ),
+ 'prev_new', (
+ select count(*) from groups, bounds
+ where detected_at >= prev_from and detected_at < prev_to
+ ),
+ 'resolved', (
+ select count(*) from groups, bounds
+ where resolved_at >= cur_from and resolved_at < cur_to
+ ),
+ 'prev_resolved', (
+ select count(*) from groups, bounds
+ where resolved_at >= prev_from and resolved_at < prev_to
+ ),
+ 'by_day_active', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(g.group_key) as cnt
+ from days d
+ left join groups g
+ on g.detected_at::date <= d.day
+ and (g.resolved_at is null or g.resolved_at::date >= d.day)
+ group by d.day
+ ) t
+ ),
+ 'by_day_important', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(g.group_key) as cnt
+ from days d
+ left join groups g
+ on g.important
+ and g.detected_at::date <= d.day
+ and (g.resolved_at is null or g.resolved_at::date >= d.day)
+ group by d.day
+ ) t
+ ),
+ 'by_day_new', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(g.group_key) as cnt
+ from days d
+ left join groups g on g.detected_at::date = d.day
+ group by d.day
+ ) t
+ ),
+ 'by_day_resolved', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(g.group_key) as cnt
+ from days d
+ left join groups g on g.resolved_at::date = d.day
+ group by d.day
+ ) t
+ ),
+ 'by_category', (
+ select coalesce(jsonb_object_agg(category, cnt), '{}'::jsonb)
+ from (select category, count(*) as cnt from active group by 1) c
+ ),
+ 'by_source', (
+ select coalesce(jsonb_object_agg(src, cnt), '{}'::jsonb)
+ from (select unnest(source) as src, count(*) as cnt from active group by 1) s
+ )
+ );
+$$;
+
+create or replace function public.signals_new_count(p_brand_id uuid)
+returns integer
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ select count(distinct public.signal_group_key(id, kind, detected_at, payload))::integer
+ from public.signals
+ where brand_id = p_brand_id and status = 'new';
+$$;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index bafd6a44c..c3f9be966 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -17472,6 +17472,180 @@ grant execute on function public.fanout_coverage_by_platform(timestamptz, timest
comment on function public.fanout_coverage_by_platform(timestamptz, timestamptz) is
'Answers and answers with observed query fan-out per platform in [p_since, p_until), across all brands (00140). Read by the daily health report.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00141_signal_groups.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Signal groups: count copies of one finding once (AC-002).
+--
+-- A brand can track the same prompt text several times, in different topics
+-- or with different locations, and the detectors write one signal per
+-- prompt. On production one pass wrote ten identical "Citations lost for
+-- '…'" rows, and every card counted all ten. The Signals list now shows such
+-- copies as one row, so the cards count them as one too.
+--
+-- signal_group_key names the group a signal belongs to: signals of one kind,
+-- about one prompt text (case, spacing and the closing "?" ignored), found in
+-- one pass. Signals not about a prompt are their own group. The web list has
+-- the same rule in web/src/lib/signals/group.ts; change both together.
+--
+-- signals_summary is 00080's, counting groups instead of rows. A group is
+-- detected when its first copy was, high impact when any copy is, and
+-- resolved only once every copy is, on the day the last one was: a finding
+-- with copies still open has not been resolved.
+--
+-- signals_new_count is the Action Center tab badge, the untriaged groups.
+
+create or replace function public.signal_group_key(
+ p_id uuid,
+ p_kind text,
+ p_detected_at timestamptz,
+ p_payload jsonb
+) returns text
+language sql
+stable
+set search_path = public
+as $$
+ select case
+ when jsonb_typeof(p_payload -> 'promptId') = 'string'
+ and jsonb_typeof(p_payload -> 'promptText') = 'string'
+ then p_kind || '|'
+ || lower(regexp_replace(
+ btrim(regexp_replace(p_payload ->> 'promptText', '[ \t\n\r\f\v]+', ' ', 'g')),
+ '[ ?.!]+$', ''))
+ || '|' || (extract(epoch from p_detected_at) * 1000)::bigint::text
+ else p_id::text
+ end;
+$$;
+
+create or replace function public.signals_summary(
+ p_brand_id uuid,
+ p_from timestamptz,
+ p_to timestamptz
+) returns jsonb
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ with bounds as (
+ select p_from as cur_from, p_to as cur_to,
+ p_from - (p_to - p_from) as prev_from, p_from as prev_to
+ ),
+ groups as (
+ select
+ public.signal_group_key(id, kind, detected_at, payload) as group_key,
+ min(detected_at) as detected_at,
+ case when bool_and(resolved_at is not null) then max(resolved_at) end as resolved_at,
+ bool_or(impact = 'high') as important,
+ -- One kind per group, so one category and one set of sources.
+ min(category) as category,
+ min(source) as source
+ from public.signals
+ where brand_id = p_brand_id
+ group by 1
+ ),
+ active as (
+ select * from groups, bounds
+ where detected_at < cur_to
+ and (resolved_at is null or resolved_at >= cur_from)
+ ),
+ prev_active as (
+ select * from groups, bounds
+ where detected_at < prev_to
+ and (resolved_at is null or resolved_at >= prev_from)
+ ),
+ days as (
+ select generate_series(
+ (select cur_from from bounds)::date,
+ (select cur_to from bounds)::date - 1,
+ interval '1 day'
+ )::date as day
+ )
+ select jsonb_build_object(
+ 'total', (select count(*) from active),
+ 'prev_total', (select count(*) from prev_active),
+ 'important', (select count(*) from active where important),
+ 'prev_important', (select count(*) from prev_active where important),
+ 'new', (
+ select count(*) from groups, bounds
+ where detected_at >= cur_from and detected_at < cur_to
+ ),
+ 'prev_new', (
+ select count(*) from groups, bounds
+ where detected_at >= prev_from and detected_at < prev_to
+ ),
+ 'resolved', (
+ select count(*) from groups, bounds
+ where resolved_at >= cur_from and resolved_at < cur_to
+ ),
+ 'prev_resolved', (
+ select count(*) from groups, bounds
+ where resolved_at >= prev_from and resolved_at < prev_to
+ ),
+ 'by_day_active', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(g.group_key) as cnt
+ from days d
+ left join groups g
+ on g.detected_at::date <= d.day
+ and (g.resolved_at is null or g.resolved_at::date >= d.day)
+ group by d.day
+ ) t
+ ),
+ 'by_day_important', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(g.group_key) as cnt
+ from days d
+ left join groups g
+ on g.important
+ and g.detected_at::date <= d.day
+ and (g.resolved_at is null or g.resolved_at::date >= d.day)
+ group by d.day
+ ) t
+ ),
+ 'by_day_new', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(g.group_key) as cnt
+ from days d
+ left join groups g on g.detected_at::date = d.day
+ group by d.day
+ ) t
+ ),
+ 'by_day_resolved', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(g.group_key) as cnt
+ from days d
+ left join groups g on g.resolved_at::date = d.day
+ group by d.day
+ ) t
+ ),
+ 'by_category', (
+ select coalesce(jsonb_object_agg(category, cnt), '{}'::jsonb)
+ from (select category, count(*) as cnt from active group by 1) c
+ ),
+ 'by_source', (
+ select coalesce(jsonb_object_agg(src, cnt), '{}'::jsonb)
+ from (select unnest(source) as src, count(*) as cnt from active group by 1) s
+ )
+ );
+$$;
+
+create or replace function public.signals_new_count(p_brand_id uuid)
+returns integer
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ select count(distinct public.signal_group_key(id, kind, detected_at, payload))::integer
+ from public.signals
+ where brand_id = p_brand_id and status = 'new';
+$$;
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00147_insights_same_prompts_definer.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index 8903ac1bb..8c6d44d23 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -265,6 +265,13 @@
"platforms": "Tracked on {names}",
"locations": "Tracked in {names}"
},
+ "grouped": {
+ "badge": "×{count} grouped",
+ "toggle": "{count} grouped signals, one per prompt",
+ "topic": "In {topic}",
+ "noTopic": "No topic",
+ "countsNote": "Copies of one finding count once: the same prompt text, found in the same run, tracked as several prompts."
+ },
"status": {
"new": "New",
"acknowledged": "Acknowledged",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx
index e92cbb0e0..f4ea6ed93 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx
@@ -4,7 +4,16 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
import dynamic from 'next/dynamic';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
-import { AlertCircle, Download, Radar, Search, TrendingDown, TrendingUp, X } from 'lucide-react';
+import {
+ AlertCircle,
+ Download,
+ Info,
+ Radar,
+ Search,
+ TrendingDown,
+ TrendingUp,
+ X,
+} from 'lucide-react';
import { useBrandStore } from '@/stores/use-brand-store';
import type { Brand } from '@/types';
import {
@@ -26,6 +35,7 @@ import {
} from '@/lib/signals/registry';
import { signalAffected, signalTexts } from '@/lib/signals/display';
import { isOnPlatform, locationName, platformName } from '@/lib/signals/names';
+import { groupSignals } from '@/lib/signals/group';
import { getAIProviderDisplayName, type AIProviderKey } from '@/components/ai-provider-avatar';
import { ActionCenterTabs } from '@/components/action-center/action-center-tabs';
import { isSuperseded, SignalTable } from '@/components/action-center/signal-table';
@@ -167,7 +177,7 @@ function SignalsContent({ brand }: { brand: Brand }) {
}, [urlRead, datePreset, category, impact, status, source, platform, search]);
const [selected, setSelected] = useState<Signal | null>(null);
- const [busyId, setBusyId] = useState<string | null>(null);
+ const [busyIds, setBusyIds] = useState<ReadonlySet<string>>(new Set());
// The open drawer lives in the URL (?signal=<id>), mirroring the Actions
// page: back from a prompt page — or a refresh — restores it, and the
@@ -284,13 +294,18 @@ function SignalsContent({ brand }: { brand: Brand }) {
URL.revokeObjectURL(url);
}, [brand.slug, visible, tTexts, tCategories, t]);
+ // The list shows copies of one finding as one row, and the counts follow.
+ const groups = useMemo(() => groupSignals(visible), [visible]);
+ const allGroups = useMemo(() => groupSignals(signals ?? []), [signals]);
+
const categoryCounts = useMemo(() => {
const counts = new Map<SignalCategory, number>();
- for (const signal of signals ?? []) {
- counts.set(signal.category, (counts.get(signal.category) ?? 0) + 1);
+ for (const { signals: members } of allGroups) {
+ const category = members[0].category;
+ counts.set(category, (counts.get(category) ?? 0) + 1);
}
return counts;
- }, [signals]);
+ }, [allGroups]);
// One sparkline series per card, over the window's days (capped at 30
// points so 90d stays legible at sparkline size).
@@ -317,6 +332,9 @@ function SignalsContent({ brand }: { brand: Brand }) {
return `${fmt(utcDay(windowDays * 2 - 1))} – ${fmt(utcDay(windowDays))}`;
}, [windowDays]);
+ const countsNote =
+ allGroups.length < (signals?.length ?? 0) ? t('grouped.countsNote') : undefined;
+
const hasActiveFilters =
category !== 'all' ||
impact !== 'all' ||
@@ -334,12 +352,23 @@ function SignalsContent({ brand }: { brand: Brand }) {
setSearch('');
};
- const handleStatusChange = async (signal: Signal, nextStatus: SignalStatus) => {
- setBusyId(signal.id);
+ // One signal from its drawer or row, or every copy a group's menu applies to.
+ const handleStatusChange = async (targets: Signal[], nextStatus: SignalStatus) => {
+ const ids = new Set(targets.map((signal) => signal.id));
+ const withBusy = (on: boolean) =>
+ setBusyIds((prev) => {
+ const next = new Set(prev);
+ for (const id of ids) {
+ if (on) next.add(id);
+ else next.delete(id);
+ }
+ return next;
+ });
+ withBusy(true);
try {
- await updateSignalStatus(brand.id, signal.id, nextStatus);
+ await updateSignalStatus(brand.id, [...ids], nextStatus);
const patch = (s: Signal) =>
- s.id === signal.id
+ ids.has(s.id)
? {
...s,
status: nextStatus,
@@ -347,11 +376,11 @@ function SignalsContent({ brand }: { brand: Brand }) {
}
: s;
setSignals((prev) => (prev ?? []).map(patch));
- setSelected((prev) => (prev && prev.id === signal.id ? patch(prev) : prev));
+ setSelected((prev) => (prev && ids.has(prev.id) ? patch(prev) : prev));
} catch {
toast.error(t('statusChangeFailed'));
} finally {
- setBusyId(null);
+ withBusy(false);
}
};
@@ -404,6 +433,7 @@ function SignalsContent({ brand }: { brand: Brand }) {
prev={summary.prevTotal}
rangeLabel={prevRangeLabel}
spark={sparkSeries(summary.byDayActive)}
+ note={countsNote}
/>
<SummaryCard
label={t('cards.important')}
@@ -411,6 +441,7 @@ function SignalsContent({ brand }: { brand: Brand }) {
prev={summary.prevImportant}
rangeLabel={prevRangeLabel}
spark={sparkSeries(summary.byDayImportant)}
+ note={countsNote}
/>
<SummaryCard
label={t('cards.new')}
@@ -418,6 +449,7 @@ function SignalsContent({ brand }: { brand: Brand }) {
prev={summary.prevNew}
rangeLabel={prevRangeLabel}
spark={sparkSeries(summary.byDayNew)}
+ note={countsNote}
/>
<SummaryCard
label={t('cards.resolved')}
@@ -425,6 +457,7 @@ function SignalsContent({ brand }: { brand: Brand }) {
prev={summary.prevResolved}
rangeLabel={prevRangeLabel}
spark={sparkSeries(summary.byDayResolved)}
+ note={countsNote}
/>
<AvgImpactCard summary={summary} days={windowDays} />
</div>
@@ -434,7 +467,7 @@ function SignalsContent({ brand }: { brand: Brand }) {
<div className="flex flex-wrap items-center gap-2">
<CategoryPill
label={t('allSignals')}
- count={signals?.length ?? 0}
+ count={allGroups.length}
isActive={category === 'all'}
onClick={() => setCategory('all')}
/>
@@ -447,6 +480,12 @@ function SignalsContent({ brand }: { brand: Brand }) {
onClick={() => setCategory(key)}
/>
))}
+ {countsNote && (
+ <span className="flex items-center text-muted-foreground" title={countsNote}>
+ <Info className="h-3.5 w-3.5" aria-hidden="true" />
+ <span className="sr-only">{countsNote}</span>
+ </span>
+ )}
</div>
<div
className="flex h-8 overflow-hidden rounded-md border"
@@ -531,10 +570,11 @@ function SignalsContent({ brand }: { brand: Brand }) {
{visible.length > 0 ? (
<SignalTable
- signals={visible}
+ groups={groups}
onSelect={selectSignal}
- onStatusChange={(signal, next) => void handleStatusChange(signal, next)}
- busyId={busyId}
+ onStatusChange={(targets, next) => void handleStatusChange(targets, next)}
+ busyIds={busyIds}
+ selectedId={selected?.id ?? null}
/>
) : (
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center">
@@ -550,8 +590,8 @@ function SignalsContent({ brand }: { brand: Brand }) {
onOpenChange={(open) => {
if (!open) selectSignal(null);
}}
- onStatusChange={(signal, next) => void handleStatusChange(signal, next)}
- isBusy={busyId === selected?.id}
+ onStatusChange={(signal, next) => void handleStatusChange([signal], next)}
+ isBusy={selected ? busyIds.has(selected.id) : false}
/>
</div>
);
@@ -563,19 +603,30 @@ function SummaryCard({
prev,
rangeLabel,
spark,
+ note,
}: {
label: string;
value: number;
prev: number;
rangeLabel: string;
spark: KpiTrendPoint[];
+ /** Why the count may be lower than the rows behind it. */
+ note?: string;
}) {
const t = useTranslations('actionCenter.signalsPage');
const change = prev > 0 ? Math.round(((value - prev) / prev) * 100) : null;
return (
<Card>
<CardContent className="p-4">
- <p className="text-xs font-medium text-muted-foreground">{label}</p>
+ <p className="flex items-center gap-1 text-xs font-medium text-muted-foreground">
+ {label}
+ {note && (
+ <span title={note}>
+ <Info className="h-3 w-3" aria-hidden="true" />
+ <span className="sr-only">{note}</span>
+ </span>
+ )}
+ </p>
<div className="mt-1 flex items-end justify-between gap-2">
<span className="text-2xl font-bold tabular-nums">{value}</span>
{spark.length > 1 && (
diff --git a/web/src/components/action-center/action-export-buttons.test.tsx b/web/src/components/action-center/action-export-buttons.test.tsx
index 64d3fbd1b..8a7dedd9f 100644
--- a/web/src/components/action-center/action-export-buttons.test.tsx
+++ b/web/src/components/action-center/action-export-buttons.test.tsx
@@ -105,7 +105,7 @@ const detail = {
payload: {},
kpiKeys: [],
actionId: 'a1',
- where: { platforms: ['gemini-web'], regions: [] },
+ where: { platforms: ['gemini-web'], regions: [], topics: [] },
},
],
events: [
diff --git a/web/src/components/action-center/signal-table.test.tsx b/web/src/components/action-center/signal-table.test.tsx
index c268438c7..98061b17e 100644
--- a/web/src/components/action-center/signal-table.test.tsx
+++ b/web/src/components/action-center/signal-table.test.tsx
@@ -1,9 +1,12 @@
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { NextIntlClientProvider } from 'next-intl';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../messages/en.json';
-import { SignalWhereLine } from './signal-table';
+import type { Signal } from '@/lib/signals/map';
+import { groupSignals } from '@/lib/signals/group';
+import { NO_WHERE } from '@/lib/signals/where';
+import { SignalTable, SignalWhereLine } from './signal-table';
(
globalThis as typeof globalThis & {
@@ -49,6 +52,7 @@ describe('SignalWhereLine', () => {
'grok-web',
],
regions: ['US', 'GB', 'DE'],
+ topics: [],
}}
/>,
);
@@ -70,12 +74,105 @@ describe('SignalWhereLine', () => {
it('says nothing when Affected already names the one place, or there is none', () => {
render(
<SignalWhereLine
- where={{ platforms: ['gemini-web'], regions: [] }}
+ where={{ platforms: ['gemini-web'], regions: [], topics: [] }}
besides={['Gemini', null]}
/>,
);
expect(container.textContent).toBe('');
- render(<SignalWhereLine where={{ platforms: [], regions: [] }} />);
+ render(<SignalWhereLine where={NO_WHERE} />);
expect(container.textContent).toBe('');
});
});
+
+const TEXT = 'Which specialty coffee subscriptions ship internationally?';
+const copy = (id: string, topic: string, status: Signal['status']): Signal => ({
+ id,
+ category: 'citation',
+ kind: 'lost_citations',
+ impact: 'high',
+ status,
+ source: ['ai_results'],
+ detectedAt: '2026-10-13T05:47:00+00:00',
+ lastDetectedAt: '2026-10-13T05:47:00+00:00',
+ resolvedAt: null,
+ previousValue: null,
+ currentValue: null,
+ changeValue: null,
+ payload: { promptId: `p-${id}`, promptText: TEXT },
+ kpiKeys: [],
+ actionId: null,
+ where: { platforms: ['chatgpt-web'], regions: ['US'], topics: [topic] },
+});
+
+describe('SignalTable groups', () => {
+ const copies = [copy('a', 'Coffee subscriptions', 'new'), copy('b', 'Gifts', 'resolved')];
+
+ it('shows copies as one row that opens onto each copy, and acts on the open ones', () => {
+ const onSelect = vi.fn();
+ const onStatusChange = vi.fn();
+ render(
+ <SignalTable
+ groups={groupSignals(copies)}
+ onSelect={onSelect}
+ onStatusChange={onStatusChange}
+ busyIds={new Set()}
+ />,
+ );
+ const rows = () => container.querySelectorAll('tbody tr');
+ expect(rows().length).toBe(1);
+ expect(container.textContent).toContain('×2 grouped');
+ expect(container.textContent).toContain('2 prompts');
+
+ const toggle = container.querySelector<HTMLButtonElement>('button[aria-expanded]')!;
+ act(() => toggle.click());
+ expect(toggle.getAttribute('aria-expanded')).toBe('true');
+ expect(rows().length).toBe(3);
+ expect(rows()[1].textContent).toContain('In Coffee subscriptions');
+ expect(rows()[2].textContent).toContain('In Gifts');
+
+ // A copy opens its own drawer.
+ act(() => (rows()[2] as HTMLElement).click());
+ expect(onSelect).toHaveBeenCalledWith(copies[1]);
+ });
+
+ it('opens the group of a copy selected from elsewhere, such as an action link', () => {
+ render(
+ <SignalTable
+ groups={groupSignals(copies)}
+ onSelect={vi.fn()}
+ onStatusChange={vi.fn()}
+ busyIds={new Set()}
+ selectedId="b"
+ />,
+ );
+ expect(container.querySelectorAll('tbody tr').length).toBe(3);
+ });
+
+ it("resolves a group's open copies from its menu and leaves the resolved one alone", async () => {
+ const onStatusChange = vi.fn();
+ render(
+ <SignalTable
+ groups={groupSignals(copies)}
+ onSelect={vi.fn()}
+ onStatusChange={onStatusChange}
+ busyIds={new Set()}
+ />,
+ );
+ const trigger = container.querySelector<HTMLButtonElement>(
+ 'button[aria-label="Actions for this signal"]',
+ )!;
+ await act(async () => {
+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ trigger.click();
+ });
+ const items = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ expect(items.map((item) => item.textContent)).toEqual([
+ 'Acknowledge',
+ 'Mark resolved',
+ 'Dismiss',
+ 'Reopen',
+ ]);
+ await act(async () => items[1].click());
+ expect(onStatusChange).toHaveBeenCalledWith([copies[0]], 'resolved');
+ });
+});
diff --git a/web/src/components/action-center/signal-table.tsx b/web/src/components/action-center/signal-table.tsx
index 060a842fb..c4ff3d822 100644
--- a/web/src/components/action-center/signal-table.tsx
+++ b/web/src/components/action-center/signal-table.tsx
@@ -1,9 +1,11 @@
'use client';
+import { useState } from 'react';
import { useTranslations } from 'next-intl';
import {
BarChart3,
Check,
+ ChevronRight,
Eye,
Gauge,
Link2,
@@ -51,6 +53,7 @@ import {
import { signalAffected, signalTexts } from '@/lib/signals/display';
import { locationName, platformFamily, platformName } from '@/lib/signals/names';
import type { SignalWhere } from '@/lib/signals/where';
+import { groupStatus, groupWhere, type SignalGroup } from '@/lib/signals/group';
import { formatRelative } from '@/lib/format-relative';
import { cn } from '@/lib/utils';
@@ -267,21 +270,128 @@ export function SignalWhereLine({
);
}
-export function SignalTable({
+/**
+ * The row menu: each choice acts on the signals it applies to, so a group's
+ * menu resolves its open copies and leaves the resolved ones alone. For one
+ * signal it is that signal's own menu.
+ */
+function SignalMenu({
signals,
- onSelect,
onStatusChange,
- busyId,
+ disabled,
}: {
signals: Signal[];
+ onStatusChange: (signals: Signal[], status: SignalStatus) => void;
+ disabled: boolean;
+}) {
+ const t = useTranslations('actionCenter.signalsPage');
+ const fresh = signals.filter((s) => s.status === 'new');
+ const open = signals.filter((s) => s.status === 'new' || s.status === 'acknowledged');
+ const closed = signals.filter((s) => s.status === 'resolved' || s.status === 'dismissed');
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className="rounded p-1 text-muted-foreground hover:bg-muted disabled:pointer-events-none disabled:opacity-50"
+ disabled={disabled}
+ aria-label={t('menu.label')}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {fresh.length > 0 && (
+ <DropdownMenuItem onClick={() => onStatusChange(fresh, 'acknowledged')}>
+ <Eye className="h-4 w-4" />
+ {t('menu.acknowledge')}
+ </DropdownMenuItem>
+ )}
+ {open.length > 0 && (
+ <>
+ <DropdownMenuItem onClick={() => onStatusChange(open, 'resolved')}>
+ <Check className="h-4 w-4" />
+ {t('menu.resolve')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => onStatusChange(open, 'dismissed')}>
+ <X className="h-4 w-4" />
+ {t('menu.dismiss')}
+ </DropdownMenuItem>
+ </>
+ )}
+ {closed.length > 0 && (
+ <DropdownMenuItem onClick={() => onStatusChange(closed, 'new')}>
+ <RotateCcw className="h-4 w-4" />
+ {t('menu.reopen')}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function DetectedCell({ iso }: { iso: string }) {
+ const tCommon = useTranslations('common');
+ const detected = new Date(iso);
+ return (
+ <TableCell>
+ <p className="text-xs tabular-nums">
+ {detected.toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ })}
+ {', '}
+ {detected.toLocaleTimeString('en-US', {
+ hour: 'numeric',
+ minute: '2-digit',
+ })}
+ </p>
+ <p className="text-xs text-muted-foreground">{detectedLabel(iso, tCommon)}</p>
+ </TableCell>
+ );
+}
+
+/**
+ * The signals list, one row per group (lib/signals/group.ts). A group of
+ * copies leads with its newest signal and a "×N grouped" toggle; opened, it
+ * lists each copy with the topic and place that tell it apart, and each copy
+ * opens its own drawer and keeps its own status.
+ */
+export function SignalTable({
+ groups,
+ onSelect,
+ onStatusChange,
+ busyIds,
+ selectedId = null,
+}: {
+ groups: SignalGroup[];
onSelect: (signal: Signal) => void;
- onStatusChange: (signal: Signal, status: SignalStatus) => void;
- busyId: string | null;
+ onStatusChange: (signals: Signal[], status: SignalStatus) => void;
+ busyIds: ReadonlySet<string>;
+ /** The signal open in the drawer; its group opens so its row can be seen. */
+ selectedId?: string | null;
}) {
const t = useTranslations('actionCenter.signalsPage');
const tTexts = useTranslations('actionCenter.signalTexts');
const tCategories = useTranslations('actionCenter.signalCategories');
- const tCommon = useTranslations('common');
+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set());
+
+ // A drawer opened from a link (an action's evidence) can name a copy inside
+ // a closed group; open that group once, when the selection arrives.
+ const [revealed, setRevealed] = useState<string | null>(null);
+ if (selectedId !== revealed) {
+ setRevealed(selectedId);
+ const holder = groups.find(
+ (g) => g.signals.length > 1 && g.signals.some((s) => s.id === selectedId),
+ );
+ if (holder && !expanded.has(holder.key)) setExpanded(new Set(expanded).add(holder.key));
+ }
+
+ const toggle = (key: string) =>
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+ const isBusy = (signals: Signal[]) => signals.some((s) => busyIds.has(s.id));
return (
<div className="overflow-x-auto rounded-lg border">
@@ -301,107 +411,128 @@ export function SignalTable({
</TableRow>
</TableHeader>
<TableBody>
- {signals.map((signal) => {
- const texts = signalTexts(signal, tTexts);
- const affected = signalAffected(signal, t);
- const stateKey = SIGNAL_KINDS[signal.kind].stateKey;
- const detected = new Date(signal.detectedAt);
- return (
- <TableRow key={signal.id} className="cursor-pointer" onClick={() => onSelect(signal)}>
+ {groups.flatMap(({ key, signals }) => {
+ const lead = signals[0];
+ const isGroup = signals.length > 1;
+ const isOpen = isGroup && expanded.has(key);
+ const texts = signalTexts(lead, tTexts);
+ const affected = signalAffected(lead, t);
+ const stateKey = SIGNAL_KINDS[lead.kind].stateKey;
+ const status = isGroup ? groupStatus(signals) : lead.status;
+ const superseded = signals.every(isSuperseded);
+ const where = isGroup ? groupWhere(signals) : lead.where;
+ // Copies are one prompt text tracked as several prompts.
+ const affectedLabel = isGroup
+ ? t('affected.prompts', { count: signals.length })
+ : affected.label;
+
+ const rows = [
+ <TableRow
+ key={key}
+ className="cursor-pointer"
+ onClick={() => (isGroup ? toggle(key) : onSelect(lead))}
+ >
<TableCell className="max-w-[360px]">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-muted/40">
- <SignalKindIcon kind={signal.kind} category={signal.category} />
+ <SignalKindIcon kind={lead.kind} category={lead.category} />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-medium">{texts.title}</p>
<p className="truncate text-xs text-muted-foreground">{texts.description}</p>
+ {isGroup && (
+ <button
+ type="button"
+ aria-expanded={isOpen}
+ aria-label={t('grouped.toggle', { count: signals.length })}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggle(key);
+ }}
+ className="mt-1 inline-flex items-center gap-1 rounded-full border bg-background px-2 py-0.5 text-[11px] font-medium text-muted-foreground hover:bg-muted hover:text-foreground"
+ >
+ <ChevronRight
+ className={cn('h-3 w-3 transition-transform', isOpen && 'rotate-90')}
+ aria-hidden="true"
+ />
+ {t('grouped.badge', { count: signals.length })}
+ </button>
+ )}
</div>
</div>
</TableCell>
<TableCell>
- <p className="text-xs font-medium">{tCategories(signal.category)}</p>
+ <p className="text-xs font-medium">{tCategories(lead.category)}</p>
<p className={cn('text-xs', STATE_TEXT[stateKey] ?? 'text-muted-foreground')}>
{t(`states.${stateKey}`)}
</p>
</TableCell>
<TableCell>
<div className="flex items-center gap-1.5">
- <span className="text-xs">{t(`impact.${signal.impact}`)}</span>
- <ImpactDots impact={signal.impact} />
+ <span className="text-xs">{t(`impact.${lead.impact}`)}</span>
+ <ImpactDots impact={lead.impact} />
</div>
</TableCell>
<TableCell>
- <SourceList sources={signal.source} />
+ <SourceList sources={lead.source} />
</TableCell>
<TableCell className="max-w-[180px]">
- <p className="text-xs font-medium">{affected.label}</p>
+ <p className="text-xs font-medium">{affectedLabel}</p>
{affected.detail && (
<p className="truncate text-xs text-muted-foreground">{affected.detail}</p>
)}
- <SignalWhereLine
- where={signal.where}
- besides={[affected.label, affected.detail]}
- />
+ <SignalWhereLine where={where} besides={[affectedLabel, affected.detail]} />
</TableCell>
+ <DetectedCell iso={lead.detectedAt} />
<TableCell>
- <p className="text-xs tabular-nums">
- {detected.toLocaleDateString('en-US', {
- month: 'short',
- day: 'numeric',
- })}
- {', '}
- {detected.toLocaleTimeString('en-US', {
- hour: 'numeric',
- minute: '2-digit',
- })}
- </p>
- <p className="text-xs text-muted-foreground">
- {detectedLabel(signal.detectedAt, tCommon)}
- </p>
- </TableCell>
- <TableCell>
- <SignalStatusBadge status={signal.status} superseded={isSuperseded(signal)} />
+ <SignalStatusBadge status={status} superseded={superseded} />
</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}>
- <DropdownMenu>
- <DropdownMenuTrigger
- className="rounded p-1 text-muted-foreground hover:bg-muted disabled:pointer-events-none disabled:opacity-50"
- disabled={busyId === signal.id}
- aria-label={t('menu.label')}
- >
- <MoreHorizontal className="h-4 w-4" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- {signal.status === 'new' && (
- <DropdownMenuItem onClick={() => onStatusChange(signal, 'acknowledged')}>
- <Eye className="h-4 w-4" />
- {t('menu.acknowledge')}
- </DropdownMenuItem>
- )}
- {(signal.status === 'new' || signal.status === 'acknowledged') && (
- <>
- <DropdownMenuItem onClick={() => onStatusChange(signal, 'resolved')}>
- <Check className="h-4 w-4" />
- {t('menu.resolve')}
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onStatusChange(signal, 'dismissed')}>
- <X className="h-4 w-4" />
- {t('menu.dismiss')}
- </DropdownMenuItem>
- </>
- )}
- {(signal.status === 'resolved' || signal.status === 'dismissed') && (
- <DropdownMenuItem onClick={() => onStatusChange(signal, 'new')}>
- <RotateCcw className="h-4 w-4" />
- {t('menu.reopen')}
- </DropdownMenuItem>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
+ <SignalMenu
+ signals={signals}
+ onStatusChange={onStatusChange}
+ disabled={isBusy(signals)}
+ />
</TableCell>
- </TableRow>
- );
+ </TableRow>,
+ ];
+
+ if (isOpen) {
+ for (const signal of signals) {
+ const topic = signal.where.topics[0];
+ rows.push(
+ <TableRow
+ key={signal.id}
+ className="cursor-pointer bg-muted/30"
+ onClick={() => onSelect(signal)}
+ >
+ <TableCell className="max-w-[360px]">
+ <p className="truncate pl-11 text-xs">
+ {topic ? t('grouped.topic', { topic }) : t('grouped.noTopic')}
+ </p>
+ </TableCell>
+ <TableCell />
+ <TableCell />
+ <TableCell />
+ <TableCell className="max-w-[180px]">
+ <SignalWhereLine where={signal.where} />
+ </TableCell>
+ <TableCell />
+ <TableCell>
+ <SignalStatusBadge status={signal.status} superseded={isSuperseded(signal)} />
+ </TableCell>
+ <TableCell onClick={(e) => e.stopPropagation()}>
+ <SignalMenu
+ signals={[signal]}
+ onStatusChange={onStatusChange}
+ disabled={busyIds.has(signal.id)}
+ />
+ </TableCell>
+ </TableRow>,
+ );
+ }
+ }
+ return rows;
})}
</TableBody>
</Table>
diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.ts
index 1b9addc8e..16be7175f 100644
--- a/web/src/lib/action-center/export.test.ts
+++ b/web/src/lib/action-center/export.test.ts
@@ -47,7 +47,7 @@ const signal: Signal = {
payload: {},
kpiKeys: [],
actionId: 'a1',
- where: { platforms: ['chatgpt-web', 'gemini-web'], regions: ['US'] },
+ where: { platforms: ['chatgpt-web', 'gemini-web'], regions: ['US'], topics: [] },
};
const detail = {
diff --git a/web/src/lib/actions/signals.ts b/web/src/lib/actions/signals.ts
index 74b7b81de..2cb515cbb 100644
--- a/web/src/lib/actions/signals.ts
+++ b/web/src/lib/actions/signals.ts
@@ -78,7 +78,9 @@ async function getPromptPlaces(
for (let from = 0; ; from += 1000) {
const { data, error } = await supabase
.from('prompts')
- .select('id, platforms, regions, topic_id, is_active, prompt_sets!inner(brand_id)')
+ .select(
+ 'id, platforms, regions, topic_id, is_active, prompt_sets!inner(brand_id), topics(name)',
+ )
.eq('prompt_sets.brand_id', brandId)
.order('id')
.range(from, from + 999);
@@ -87,10 +89,13 @@ async function getPromptPlaces(
return new Map();
}
for (const row of data ?? []) {
+ // The generated types read the topic join as a list; it is one topic.
+ const topic = row.topics as { name: string } | { name: string }[] | null;
places.set(row.id, {
platforms: row.platforms ?? [],
regions: row.regions ?? [],
topicId: row.topic_id,
+ topic: (Array.isArray(topic) ? topic[0]?.name : topic?.name) ?? null,
isActive: row.is_active,
});
}
@@ -166,29 +171,30 @@ export async function getSignalsSummary(
};
}
-/** Count of untriaged signals, for the Action Center tab badge. A head
- * count query — no rows transferred, immune to the row cap. */
+/**
+ * Untriaged signals for the Action Center tab badge, counted the way the list
+ * shows them: copies of one finding count once (signals_new_count, 00141).
+ * One number back, immune to the row cap.
+ */
export async function getNewSignalCount(brandId: string): Promise<number> {
const supabase = await createClient();
- const { count, error } = await supabase
- .from('signals')
- .select('id', { count: 'exact', head: true })
- .eq('brand_id', brandId)
- .eq('status', 'new');
+ const { data, error } = await supabase.rpc('signals_new_count', { p_brand_id: brandId });
if (error) throw new Error(error.message);
- return count ?? 0;
+ return Number(data ?? 0);
}
/**
- * Triage: any org member can move a signal through its lifecycle (RLS
- * enforces membership). Resolving stamps resolved_at; leaving the resolved
- * state clears it so the summary's "Resolved" count stays truthful.
+ * Triage: any org member can move signals through their lifecycle (RLS
+ * enforces membership). Several at once for a group's menu, which acts on
+ * every copy. Resolving stamps resolved_at; leaving the resolved state
+ * clears it so the summary's "Resolved" count stays truthful.
*/
export async function updateSignalStatus(
brandId: string,
- signalId: string,
+ signalIds: string[],
status: SignalStatus,
): Promise<void> {
+ if (signalIds.length === 0) return;
const supabase = await createClient();
const { error } = await supabase
.from('signals')
@@ -198,7 +204,7 @@ export async function updateSignalStatus(
updated_at: new Date().toISOString(),
})
.eq('brand_id', brandId)
- .eq('id', signalId);
+ .in('id', signalIds);
if (error) throw new Error(error.message);
}
diff --git a/web/src/lib/signals/group.test.ts b/web/src/lib/signals/group.test.ts
new file mode 100644
index 000000000..70ff20805
--- /dev/null
+++ b/web/src/lib/signals/group.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+import type { Signal } from './map';
+import { NO_WHERE } from './where';
+import { groupSignals, groupStatus, groupWhere, promptTextKey, signalGroupKey } from './group';
+
+const signal = (over: Partial<Signal>): Signal => ({
+ id: 's1',
+ category: 'citation',
+ kind: 'lost_citations',
+ impact: 'high',
+ status: 'new',
+ source: ['ai_results'],
+ detectedAt: '2026-10-08T10:53:00+00:00',
+ lastDetectedAt: '2026-10-08T10:53:00+00:00',
+ resolvedAt: null,
+ previousValue: null,
+ currentValue: null,
+ changeValue: null,
+ payload: {},
+ kpiKeys: [],
+ actionId: null,
+ where: NO_WHERE,
+ ...over,
+});
+
+const TEXT =
+ 'Which tools track AI search visibility and answer engine optimization performance over time?';
+const lost = (id: string, over: Partial<Signal> = {}) =>
+ signal({ id, payload: { promptId: `p-${id}`, promptText: TEXT }, ...over });
+
+describe('promptTextKey', () => {
+ it('ignores case, spacing and the closing punctuation', () => {
+ expect(promptTextKey(TEXT)).toBe(promptTextKey(` ${TEXT.toLowerCase().replace('?', '')} `));
+ expect(promptTextKey('Best AI\nrank tracker?!')).toBe('best ai rank tracker');
+ expect(promptTextKey('Best AI rank tracker')).not.toBe(promptTextKey('Best AEO rank tracker'));
+ });
+});
+
+describe('signalGroupKey', () => {
+ it('puts copies of one prompt text, of one kind, from one pass together', () => {
+ const a = lost('a');
+ expect(signalGroupKey(lost('b', { detectedAt: '2026-10-08T10:53:00.000Z' }))).toBe(
+ signalGroupKey(a),
+ );
+ expect(signalGroupKey(lost('c', { detectedAt: '2026-10-09T10:53:00Z' }))).not.toBe(
+ signalGroupKey(a),
+ );
+ expect(signalGroupKey(lost('d', { kind: 'prompt_gain' }))).not.toBe(signalGroupKey(a));
+ });
+
+ it('leaves a signal that is not about a prompt on its own', () => {
+ expect(signalGroupKey(signal({ id: 'x', payload: { domain: 'yotpo.com' } }))).toBe('x');
+ // A prompt text without the prompt is a first citation's context, not its subject.
+ expect(signalGroupKey(signal({ id: 'y', payload: { promptText: TEXT, url: '/a' } }))).toBe('y');
+ });
+});
+
+describe('groupSignals', () => {
+ it('keeps the list order and gathers each group under its first signal', () => {
+ const groups = groupSignals([
+ lost('a'),
+ signal({ id: 'x' }),
+ lost('b', { payload: { promptId: 'p-b', promptText: TEXT.toLowerCase() } }),
+ ]);
+ expect(groups.map((g) => g.signals.map((s) => s.id))).toEqual([['a', 'b'], ['x']]);
+ });
+});
+
+describe('groupStatus and groupWhere', () => {
+ it('shows a group as open while any copy is', () => {
+ expect(groupStatus([lost('a', { status: 'resolved' }), lost('b')])).toBe('new');
+ expect(
+ groupStatus([lost('a', { status: 'dismissed' }), lost('b', { status: 'resolved' })]),
+ ).toBe('resolved');
+ });
+
+ it('joins the places of every copy', () => {
+ expect(
+ groupWhere([
+ lost('a', { where: { platforms: ['chatgpt-web'], regions: ['US'], topics: ['AEO'] } }),
+ lost('b', { where: { platforms: ['gemini-web'], regions: ['US'], topics: ['GEO'] } }),
+ ]),
+ ).toEqual({
+ platforms: ['chatgpt-web', 'gemini-web'],
+ regions: ['US'],
+ topics: ['AEO', 'GEO'],
+ });
+ });
+});
diff --git a/web/src/lib/signals/group.ts b/web/src/lib/signals/group.ts
new file mode 100644
index 000000000..af97c1d6f
--- /dev/null
+++ b/web/src/lib/signals/group.ts
@@ -0,0 +1,66 @@
+import type { Signal } from './map';
+import type { SignalStatus } from './registry';
+import { mergeWhere, type SignalWhere } from './where';
+
+/**
+ * Signals that read as one row (AC-002).
+ *
+ * A brand can track the same prompt text several times, in different topics
+ * or with different locations, and the detectors write one signal per prompt.
+ * On production one pass wrote ten identical "Citations lost for '…'" rows,
+ * which looked like duplicates and inflated every count. Signals of one kind,
+ * about one prompt text, found in one pass are therefore one group: one row
+ * in the list, one in every count. Each signal stays its own row underneath,
+ * with its own status.
+ *
+ * The rule has a twin in SQL, public.signal_group_key (00141), which the
+ * summary cards and the tab badge count with. Change both together.
+ */
+
+/** A prompt text as the group compares it: case, spacing and the closing "?" ignored. */
+export function promptTextKey(text: string): string {
+ // ASCII whitespace only, exactly as the SQL twin's character class does.
+ return text
+ .replace(/[ \t\n\r\f\v]+/g, ' ')
+ .replace(/^ | $/g, '')
+ .replace(/[ ?.!]+$/, '')
+ .toLowerCase();
+}
+
+export function signalGroupKey(
+ signal: Pick<Signal, 'id' | 'kind' | 'detectedAt' | 'payload'>,
+): string {
+ const { promptId, promptText } = signal.payload ?? {};
+ if (typeof promptId === 'string' && typeof promptText === 'string') {
+ return `${signal.kind}|${promptTextKey(promptText)}|${Date.parse(signal.detectedAt)}`;
+ }
+ return signal.id;
+}
+
+export interface SignalGroup {
+ key: string;
+ /** In the order given (newest first); the first one leads the row. */
+ signals: Signal[];
+}
+
+export function groupSignals(signals: Signal[]): SignalGroup[] {
+ const groups = new Map<string, Signal[]>();
+ for (const signal of signals) {
+ const key = signalGroupKey(signal);
+ const members = groups.get(key);
+ if (members) members.push(signal);
+ else groups.set(key, [signal]);
+ }
+ return [...groups.entries()].map(([key, members]) => ({ key, signals: members }));
+}
+
+// Open before closed, so a group with one untriaged copy still asks for triage.
+const STATUS_ORDER: readonly SignalStatus[] = ['new', 'acknowledged', 'resolved', 'dismissed'];
+
+export function groupStatus(signals: Signal[]): SignalStatus {
+ return STATUS_ORDER.find((status) => signals.some((s) => s.status === status)) ?? 'new';
+}
+
+export function groupWhere(signals: Signal[]): SignalWhere {
+ return mergeWhere(signals.map((signal) => signal.where));
+}
diff --git a/web/src/lib/signals/where.test.ts b/web/src/lib/signals/where.test.ts
index d6fcb4d74..3f3bc6fc0 100644
--- a/web/src/lib/signals/where.test.ts
+++ b/web/src/lib/signals/where.test.ts
@@ -1,23 +1,46 @@
import { describe, expect, it } from 'vitest';
-import { NO_WHERE, signalWhere, type PromptPlace } from './where';
+import { NO_WHERE, mergeWhere, signalWhere, type PromptPlace } from './where';
+
+const place = (over: Partial<PromptPlace>): PromptPlace => ({
+ platforms: [],
+ regions: [],
+ topicId: null,
+ topic: null,
+ isActive: true,
+ ...over,
+});
const prompts = new Map<string, PromptPlace>([
[
'p1',
- { platforms: ['chatgpt-web', 'google-aio'], regions: ['US'], topicId: 't1', isActive: true },
+ place({
+ platforms: ['chatgpt-web', 'google-aio'],
+ regions: ['US'],
+ topicId: 't1',
+ topic: 'AEO',
+ }),
],
[
'p2',
- {
+ place({
platforms: ['chatgpt-web', 'chatgpt-shopping'],
regions: ['US', 'GB'],
topicId: 't1',
- isActive: true,
- },
+ topic: 'AEO',
+ }),
],
- ['p3', { platforms: ['gemini-web'], regions: [], topicId: 't2', isActive: true }],
+ ['p3', place({ platforms: ['gemini-web'], topicId: 't2', topic: 'GEO' })],
// Paused: still a prompt's own place, but no longer part of its topic's measure.
- ['p4', { platforms: ['grok-web'], regions: ['DE'], topicId: 't1', isActive: false }],
+ [
+ 'p4',
+ place({
+ platforms: ['grok-web'],
+ regions: ['DE'],
+ topicId: 't1',
+ topic: 'AEO',
+ isActive: false,
+ }),
+ ],
]);
describe('signalWhere', () => {
@@ -25,17 +48,20 @@ describe('signalWhere', () => {
expect(signalWhere({ entity: 'platforms', platform: 'gemini-web' }, prompts)).toEqual({
platforms: ['gemini-web'],
regions: [],
+ topics: [],
});
expect(signalWhere({ entity: 'regions', region: 'JP', bestRegion: 'US' }, prompts)).toEqual({
platforms: [],
regions: ['JP'],
+ topics: [],
});
});
- it("reads a prompt signal's place from its prompt", () => {
+ it("reads a prompt signal's place and topic from its prompt", () => {
expect(signalWhere({ promptId: 'p1', promptText: 'best tracker' }, prompts)).toEqual({
platforms: ['chatgpt-web', 'google-aio'],
regions: ['US'],
+ topics: ['AEO'],
});
});
@@ -43,16 +69,21 @@ describe('signalWhere', () => {
expect(signalWhere({ promptIds: ['p2', 'p1'] }, prompts)).toEqual({
platforms: ['chatgpt-web', 'google-aio'],
regions: ['US', 'GB'],
+ topics: ['AEO'],
});
expect(
signalWhere({ entity: 'prompts', targets: [{ id: 'p3' }, { id: 'p1' }] }, prompts),
- ).toEqual({ platforms: ['chatgpt-web', 'gemini-web', 'google-aio'], regions: ['US'] });
+ ).toEqual({
+ platforms: ['chatgpt-web', 'gemini-web', 'google-aio'],
+ regions: ['US'],
+ topics: ['AEO', 'GEO'],
+ });
});
it("reads a topic signal's place from the topic's tracked prompts, not its paused ones", () => {
expect(
signalWhere({ entity: 'topics', targets: [{ id: 't1', label: 'AEO' }] }, prompts),
- ).toEqual({ platforms: ['chatgpt-web', 'google-aio'], regions: ['US', 'GB'] });
+ ).toEqual({ platforms: ['chatgpt-web', 'google-aio'], regions: ['US', 'GB'], topics: ['AEO'] });
});
it('has no place for a competitor, a source domain, or a prompt it cannot find', () => {
@@ -64,6 +95,24 @@ describe('signalWhere', () => {
expect(signalWhere({ promptId: 'p4' }, prompts)).toEqual({
platforms: ['grok-web'],
regions: ['DE'],
+ topics: ['AEO'],
+ });
+ });
+});
+
+describe('mergeWhere', () => {
+ it('joins places, counting each once, the most shared first', () => {
+ expect(
+ mergeWhere([
+ { platforms: ['gemini-web', 'chatgpt-web'], regions: ['GB'], topics: ['AEO'] },
+ { platforms: ['chatgpt-web', 'chatgpt-web'], regions: ['US'], topics: ['GEO'] },
+ { platforms: ['chatgpt-web'], regions: ['US'], topics: ['AEO'] },
+ ]),
+ ).toEqual({
+ platforms: ['chatgpt-web', 'gemini-web'],
+ regions: ['US', 'GB'],
+ topics: ['AEO', 'GEO'],
});
+ expect(mergeWhere([])).toBe(NO_WHERE);
});
});
diff --git a/web/src/lib/signals/where.ts b/web/src/lib/signals/where.ts
index a5c99c834..65b1cbaae 100644
--- a/web/src/lib/signals/where.ts
+++ b/web/src/lib/signals/where.ts
@@ -14,9 +14,11 @@
export interface SignalWhere {
/** Platform or model slugs as stored (`gemini-web`, `gpt-5-6`), most common first. */
- platforms: string[];
+ platforms: readonly string[];
/** Location codes (`US`, `US-CA`), most common first. Empty when untargeted. */
- regions: string[];
+ regions: readonly string[];
+ /** The topics of the prompts it is about, by name; what tells copies of one prompt apart. */
+ topics: readonly string[];
}
/** Where one prompt is tracked, the topic it belongs to, and whether it still runs. */
@@ -24,10 +26,12 @@ export interface PromptPlace {
platforms: string[];
regions: string[];
topicId: string | null;
+ topic: string | null;
isActive: boolean;
}
-export const NO_WHERE: SignalWhere = { platforms: [], regions: [] };
+// Shared by every signal without a place; readonly, so no caller can fill it in.
+export const NO_WHERE: SignalWhere = { platforms: [], regions: [], topics: [] };
// Shopping answers never feed a signal (the detectors skip them), so the
// platform would only be noise beside the engines that did.
@@ -43,7 +47,7 @@ function targetIds(payload: Record<string, unknown>): string[] {
}
/** Values ordered by how many of the counted items carry them, then by name. */
-function byFrequency(values: string[]): string[] {
+function byFrequency(values: readonly string[]): string[] {
const counts = new Map<string, number>();
for (const value of values) counts.set(value, (counts.get(value) ?? 0) + 1);
return [...counts.entries()]
@@ -68,7 +72,7 @@ export function signalWhere(
const platform = str(payload.platform);
const region = str(payload.region);
if (platform || region) {
- return { platforms: platform ? [platform] : [], regions: region ? [region] : [] };
+ return { platforms: platform ? [platform] : [], regions: region ? [region] : [], topics: [] };
}
let places: PromptPlace[] = [];
@@ -85,11 +89,25 @@ export function signalWhere(
}
if (places.length === 0) return NO_WHERE;
- // Each prompt counts a platform once, so "most common" means most prompts.
+ return mergeWhere(
+ places.map((p) => ({
+ platforms: p.platforms.filter((x) => !IGNORED_PLATFORMS.has(x)),
+ regions: p.regions,
+ topics: p.topic ? [p.topic] : [],
+ })),
+ );
+}
+
+/**
+ * Several places as one: every platform, location and topic, the ones most
+ * of them share first. Each place counts a value once, so "most common"
+ * means most prompts, or most signals of a group.
+ */
+export function mergeWhere(wheres: SignalWhere[]): SignalWhere {
+ if (wheres.length === 0) return NO_WHERE;
return {
- platforms: byFrequency(
- places.flatMap((p) => [...new Set(p.platforms)].filter((x) => !IGNORED_PLATFORMS.has(x))),
- ),
- regions: byFrequency(places.flatMap((p) => [...new Set(p.regions)])),
+ platforms: byFrequency(wheres.flatMap((w) => [...new Set(w.platforms)])),
+ regions: byFrequency(wheres.flatMap((w) => [...new Set(w.regions)])),
+ topics: byFrequency(wheres.flatMap((w) => [...new Set(w.topics)])),
};
}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 89075e5ba..83e075525 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3416,6 +3416,10 @@ export type Database = {
Args: { p_brand_id: string; p_from: string; p_to: string }
Returns: Json
}
+ signals_new_count: {
+ Args: { p_brand_id: string }
+ Returns: number
+ }
topics_overview_aggregates: {
Args: { p_brand_id: string }
Returns: {