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): add a Positive Sentiment KPI (#1128)

Cihan8d600f378421
diff --git a/server/src/lib/action-center/from-mentions.js b/server/src/lib/action-center/from-mentions.js
index a9f109026..9eb0f38d5 100644
--- a/server/src/lib/action-center/from-mentions.js
+++ b/server/src/lib/action-center/from-mentions.js
@@ -20,7 +20,7 @@ import { planTasks } from './tasks/plan.js';
export const MENTION_ACTION_KIND = 'mention_review';
const ACTIVE = ['new', 'in_progress', 'on_hold'];
-const KPI_KEYS = ['mentions', 'ai_visibility'];
+const KPI_KEYS = ['mentions', 'ai_visibility', 'positive_sentiment'];
/** At most a page of the Mentions table at once. */
export const MAX_MENTIONS = 100;
/** The answers quoted on the action. */
diff --git a/server/src/lib/action-center/from-mentions.test.js b/server/src/lib/action-center/from-mentions.test.js
index ad08aa0be..22135ac77 100644
--- a/server/src/lib/action-center/from-mentions.test.js
+++ b/server/src/lib/action-center/from-mentions.test.js
@@ -101,7 +101,7 @@ describe('sendMentionsToActionCenter', () => {
category: 'protect',
kind: 'mention_review',
impact: 'medium',
- kpi_keys: ['mentions', 'ai_visibility'],
+ kpi_keys: ['mentions', 'ai_visibility', 'positive_sentiment'],
baseline: { mentions: 3, positive: 1, negative: 1, netSentiment: 0 },
// r4 isn't a mention, so it doesn't change which action these answers find.
dedup_key: mentionDedupKey(['r1', 'r2', 'r3']),
diff --git a/web/messages/en.json b/web/messages/en.json
index 9868f7226..ec6ff5abb 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -213,6 +213,10 @@
"name": "AI Referral Traffic",
"description": "Visits arriving from AI platforms"
},
+ "positive_sentiment": {
+ "name": "Positive Sentiment",
+ "description": "Positive share of the AI responses naming you"
+ },
"competitor_lead": {
"name": "Lead over top competitor",
"description": "Your visibility minus the strongest competitor's on the same prompts, in points"
diff --git a/web/src/components/action-center/kpi-table.tsx b/web/src/components/action-center/kpi-table.tsx
index 69dabd55c..5b0490963 100644
--- a/web/src/components/action-center/kpi-table.tsx
+++ b/web/src/components/action-center/kpi-table.tsx
@@ -10,6 +10,7 @@ import {
Pencil,
PieChart,
Quote,
+ Smile,
TrendingDown,
TrendingUp,
Trash2,
@@ -48,6 +49,7 @@ const KPI_ICONS: Record<KpiKey, React.ComponentType<{ className?: string }>> = {
mentions: MessageSquare,
share_of_voice: PieChart,
ai_referral_traffic: MousePointerClick,
+ positive_sentiment: Smile,
};
/**
diff --git a/web/src/lib/actions/kpis.test.ts b/web/src/lib/actions/kpis.test.ts
new file mode 100644
index 000000000..784b09747
--- /dev/null
+++ b/web/src/lib/actions/kpis.test.ts
@@ -0,0 +1,121 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { DEFAULT_KPI_SET, KPI_KEYS, KPI_REGISTRY, KPI_TEMPLATES } from '@/lib/kpis/registry';
+
+/**
+ * The Positive Sentiment KPI (AC): Insights' Positive sentiment card as an
+ * Action Center KPI — the positive share of the answers naming the brand, its
+ * change in points, and a daily sparkline that leaves out days without a
+ * mention rather than drawing them as 0%.
+ */
+
+let definitions: unknown[] = [];
+// One insights_aggregates_daily row per day, by p_day_from.
+let dailyRows: Record<string, Record<string, number>> = {};
+const rpcCalls: Record<string, unknown>[] = [];
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ from: () => {
+ const q = {
+ select: () => q,
+ eq: async () => ({ data: definitions, error: null }),
+ };
+ return q;
+ },
+ rpc: async (...call: [string, Record<string, unknown>]) => {
+ const args = call[1];
+ rpcCalls.push(args);
+ return { data: dailyRows[String(args.p_day_from)] ?? {}, error: null };
+ },
+ })),
+}));
+
+const getInsightsSummary = vi.fn();
+vi.mock('./tracking', () => ({
+ getInsightsSummary: (...args: unknown[]) => getInsightsSummary(...args),
+ getShareOfVoiceData: vi.fn(),
+ getVisibilityRateTrend: vi.fn(),
+}));
+vi.mock('./traffic', () => ({ getTrafficSummary: vi.fn(), getTrafficTrend: vi.fn() }));
+
+const { getKpiSnapshots } = await import('./kpis');
+
+const DAY_MS = 86_400_000;
+const daysAgo = (n: number) => new Date(Date.now() - n * DAY_MS).toISOString().slice(0, 10);
+
+beforeEach(() => {
+ definitions = [];
+ dailyRows = {};
+ rpcCalls.length = 0;
+ getInsightsSummary.mockReset();
+});
+
+describe('the Positive Sentiment KPI', () => {
+ it('is listed last, under Mentions, and makes Brand Monitoring a usable template', () => {
+ expect(KPI_KEYS.at(-1)).toBe('positive_sentiment');
+ expect(DEFAULT_KPI_SET.at(-1)).toBe('positive_sentiment');
+ expect(KPI_REGISTRY.positive_sentiment).toMatchObject({
+ category: 'mentions',
+ unit: 'percent',
+ direction: 'higher_is_better',
+ });
+ expect(KPI_TEMPLATES.brand_monitoring).toEqual(['mentions', 'positive_sentiment']);
+ });
+
+ it("reads Insights' positive share and its change in points, with a sparkline of the days named", async () => {
+ definitions = [
+ { kpi_key: 'positive_sentiment', target: 50, timeframe: 'monthly', is_active: true },
+ ];
+ getInsightsSummary.mockResolvedValue({
+ positiveSentimentPct: 40,
+ sentimentChange: 6,
+ totalMentions: 107,
+ totalCitations: 0,
+ });
+ dailyRows = {
+ [daysAgo(6)]: { positive_count: 3, mentioning_results: 4 },
+ // daysAgo(5): no answer named the brand.
+ [daysAgo(4)]: { positive_count: 1, mentioning_results: 3 },
+ [daysAgo(0)]: { positive_count: 0, mentioning_results: 2 },
+ };
+
+ const { configured, kpis } = await getKpiSnapshots('b1');
+
+ expect(configured).toBe(true);
+ expect(kpis).toHaveLength(1);
+ expect(kpis[0]).toMatchObject({
+ key: 'positive_sentiment',
+ category: 'mentions',
+ unit: 'percent',
+ value: 40,
+ change: 6,
+ changeKind: 'points',
+ target: 50,
+ progress: 80,
+ });
+ expect(kpis[0].trend).toEqual([
+ { date: daysAgo(6), value: 75 },
+ { date: daysAgo(4), value: 33 },
+ { date: daysAgo(0), value: 0 },
+ ]);
+ // One rollup read per day of the sparkline, shared with Mentions and Citations.
+ expect(rpcCalls).toHaveLength(7);
+ });
+
+ it('comes after the other KPIs in the table', async () => {
+ definitions = [
+ { kpi_key: 'positive_sentiment', target: 50, timeframe: 'monthly', is_active: true },
+ { kpi_key: 'mentions', target: 100, timeframe: 'monthly', is_active: true },
+ ];
+ getInsightsSummary.mockResolvedValue({
+ positiveSentimentPct: 40,
+ sentimentChange: null,
+ totalMentions: 107,
+ mentionsChange: 25,
+ totalCitations: 0,
+ });
+ const { kpis } = await getKpiSnapshots('b1');
+ expect(kpis.map((k) => k.key)).toEqual(['mentions', 'positive_sentiment']);
+ expect(kpis[1].change).toBeNull();
+ });
+});
diff --git a/web/src/lib/actions/kpis.ts b/web/src/lib/actions/kpis.ts
index 3aa1ebd06..0f9296054 100644
--- a/web/src/lib/actions/kpis.ts
+++ b/web/src/lib/actions/kpis.ts
@@ -118,7 +118,8 @@ async function fetchWindowMetrics(
const days = windowOverride ?? { dayFrom: daysAgo(windowDays - 1), dayTo: utcToday() };
const trendFrom = daysAgo(TREND_DAYS - 1);
- const wantsInsights = keys.has('citations') || keys.has('mentions');
+ const wantsInsights =
+ keys.has('citations') || keys.has('mentions') || keys.has('positive_sentiment');
const [visibility, insights, sov, traffic, trafficTrend, dailyTotals] = await Promise.all([
keys.has('ai_visibility') ? getVisibilityRateTrend(brandId, { days }) : null,
@@ -138,7 +139,8 @@ async function fetchWindowMetrics(
: null,
// Mentions/citations have window aggregates but no daily-series RPC, so
// the 7-point sparkline is seven one-day aggregates in parallel. Each is
- // a rollup read returning one JSON row; both KPIs share the same seven.
+ // a rollup read returning one JSON row; the KPIs read from the answers'
+ // rollups (mentions, citations, positive sentiment) share the same seven.
wantsInsights ? fetchDailyInsightTotals(brandId) : null,
]);
@@ -159,11 +161,18 @@ async function fetchDailyInsightTotals(brandId: string) {
p_day_to: day,
});
if (error) throw new Error(error.message);
- const agg = (data ?? {}) as { total_mentions?: number; total_citations?: number };
+ const agg = (data ?? {}) as {
+ total_mentions?: number;
+ total_citations?: number;
+ positive_count?: number;
+ mentioning_results?: number;
+ };
return {
date: day,
mentions: Number(agg.total_mentions ?? 0),
citations: Number(agg.total_citations ?? 0),
+ positive: Number(agg.positive_count ?? 0),
+ mentioning: Number(agg.mentioning_results ?? 0),
};
}),
);
@@ -210,6 +219,20 @@ function buildSnapshot(
trend = metrics.dailyTotals.map((d) => ({ date: d.date, value: d.mentions }));
break;
}
+ case 'positive_sentiment': {
+ if (!metrics.insights || !metrics.dailyTotals) return null;
+ // Insights' Positive sentiment card: the positive share of the answers
+ // naming the brand, its change in points.
+ value = metrics.insights.positiveSentimentPct;
+ change = metrics.insights.sentimentChange;
+ changeKind = 'points';
+ // A day without an answer naming the brand has no share; it is left
+ // out rather than drawn as 0%.
+ trend = metrics.dailyTotals
+ .filter((d) => d.mentioning > 0)
+ .map((d) => ({ date: d.date, value: Math.round((d.positive * 100) / d.mentioning) }));
+ break;
+ }
case 'share_of_voice': {
if (!metrics.sov) return null;
value = metrics.sov.overallSov;
diff --git a/web/src/lib/kpis/registry.ts b/web/src/lib/kpis/registry.ts
index 8e69f33a2..f8941095c 100644
--- a/web/src/lib/kpis/registry.ts
+++ b/web/src/lib/kpis/registry.ts
@@ -16,7 +16,8 @@ export type KpiKey =
| 'citations'
| 'mentions'
| 'share_of_voice'
- | 'ai_referral_traffic';
+ | 'ai_referral_traffic'
+ | 'positive_sentiment';
export type KpiCategory = 'visibility' | 'citations' | 'mentions' | 'traffic' | 'content';
@@ -87,6 +88,17 @@ export const KPI_REGISTRY: Record<KpiKey, KpiMeta> = {
source: 'tracking',
defaultTarget: 100,
},
+ // The positive share of the answers naming the brand, as Insights'
+ // Positive sentiment card: sentiment is read over mentions, so it files
+ // under them.
+ positive_sentiment: {
+ key: 'positive_sentiment',
+ category: 'mentions',
+ unit: 'percent',
+ direction: 'higher_is_better',
+ source: 'tracking',
+ defaultTarget: 50,
+ },
};
export const KPI_KEYS = Object.keys(KPI_REGISTRY) as KpiKey[];
@@ -105,6 +117,7 @@ export const DEFAULT_KPI_SET: KpiKey[] = [
'mentions',
'share_of_voice',
'ai_referral_traffic',
+ 'positive_sentiment',
];
export type KpiTemplateKey =
@@ -116,8 +129,8 @@ export type KpiTemplateKey =
/**
* Templates are presets over the registry, nothing more — picking one checks
* a set of KPIs and seeds their default targets. A template with no
- * computable KPIs yet (content, brand monitoring) renders disabled in the
- * drawer rather than being hidden: the roadmap is allowed to show.
+ * computable KPIs yet (content) renders disabled in the drawer rather than
+ * being hidden: the roadmap is allowed to show.
*
* AI Search Visibility is deliberately the four answer-engine KPIs, not the
* whole registry: referral traffic measures what arrives at the site, not
@@ -127,7 +140,7 @@ export type KpiTemplateKey =
export const KPI_TEMPLATES: Record<KpiTemplateKey, KpiKey[]> = {
ai_search_visibility: ['ai_visibility', 'citations', 'mentions', 'share_of_voice'],
content_performance: [],
- brand_monitoring: [],
+ brand_monitoring: ['mentions', 'positive_sentiment'],
custom: [],
};