Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(insights): send the biggest topic gap to the Action Center (#1045)
Cihan4a949ea5c42c
diff --git a/server/src/lib/action-center/from-topic-gap.js b/server/src/lib/action-center/from-topic-gap.jsnew file mode 100644index 000000000..3fcea80a5--- /dev/null+++ b/server/src/lib/action-center/from-topic-gap.js@@ -0,0 +1,220 @@+/**+ * "Send biggest gap to Actions" (VIS-010): the Insights heat map's topic+ * where a competitor leads you most, sent as a Compete action.+ *+ * The person picks the topic and the competitor; the scores are worked out+ * again here from the same rollups the heat map reads (00137), so the action+ * states the gap as Ansvisor measures it, not as a client says it is. The+ * work is C04's (close_topic_coverage_gap) plan, measured afterwards on the+ * topic's prompts like a content opportunity (basket-metrics.js).+ */++import supabaseAdmin from '../../config/supabase.js';+import { computeAiVisibilityScore } from '../../config/visibility-score.js';+import { resolveBrandSources } from './sources.js';+import { planTasks } from './tasks/plan.js';++export const TOPIC_GAP_ACTION_KIND = 'topic_competitor_gap';++const ACTIVE = ['new', 'in_progress', 'on_hold'];+/** Under this many answers a topic shows "Low sample" on the heat map, and isn't sent. */+const LOW_SAMPLE_ANSWERS = 20;+const KPI_KEYS = ['ai_visibility', 'share_of_voice'];++/** C04's plan: the same work, sent by a person instead of raised by a signal. */+export const TOPIC_GAP_TASKS = [+ 'analyze_topic_gap',+ 'analyze_competitor_visibility',+ 'analyze_competitor_content',+ 'cluster_prompts',+ 'map_prompts_to_content',+ 'identify_content_gaps',+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },+ 'validate_topic_sov',+ 'measure_action_outcome',+];++function httpError(message, status) {+ const err = new Error(message);+ err.status = status;+ return err;+}++const num = (v) => Number(v ?? 0);++/** An entity's Visibility in a topic, over the brand's answers there (as the heat map scores it). */+function score(answers, components) {+ const positions = num(components?.position_count);+ return (+ computeAiVisibilityScore({+ answers,+ mentionAnswers: num(components?.mention_answers),+ citationAnswers: num(components?.citation_answers),+ positionFactor: positions > 0 ? num(components?.sum_inv_position) / positions : null,+ }) ?? 0+ );+}++/**+ * Your score, the competitor's and the gap between them in one topic of an+ * insights_topic_competitors_daily payload. A competitor never named in the+ * topic scores 0.+ */+export function topicGapScores(topic, competitorId) {+ const answers = num(topic.answers);+ const competitor = (topic.competitors || []).find((c) => c.competitor_id === competitorId);+ const you = score(answers, topic);+ const them = score(answers, competitor);+ return { answers, you, them, gap: Math.round((them - you) * 10) / 10 };+}++/** How much a gap matters: 20+ points is high, 10+ medium. */+export function topicGapImpact(gap) {+ if (gap >= 20) return 'high';+ if (gap >= 10) return 'medium';+ return 'low';+}++/**+ * Creates the Compete action, or returns the open one if this topic was+ * already sent: one gap action per topic at a time, even if another+ * competitor has taken the lead since.+ *+ * @param {{ id: string, name: string, brand_id: string }} topic - checked against the caller's org+ * @param {{ competitorId: string, dayFrom?: string, dayTo?: string, models?: string[],+ * region?: string, userId: string }} opts - the heat map's window and filters+ * @returns {Promise<{ actionId: string, actionNo: number, created: boolean }>}+ */+export async function sendTopicGapToActionCenter(+ topic,+ { competitorId, dayFrom, dayTo, models, region, userId },+) {+ const brandId = topic.brand_id;++ const { data: competitor } = await supabaseAdmin+ .from('competitors')+ .select('id, name')+ .eq('id', competitorId)+ .eq('brand_id', brandId)+ .maybeSingle();+ if (!competitor) throw httpError('Competitor not found', 404);++ const dedupKey = `topic_gap:${topic.id}`;+ const openAction = async () => {+ const { data } = await supabaseAdmin+ .from('actions')+ .select('id, action_no')+ .eq('brand_id', brandId)+ .eq('dedup_key', dedupKey)+ .in('status', ACTIVE)+ .maybeSingle();+ return data;+ };+ const open = await openAction();+ if (open) return { actionId: open.id, actionNo: Number(open.action_no), created: false };++ const { data: map, error: mapErr } = await supabaseAdmin.rpc('insights_topic_competitors_daily', {+ p_brand_id: brandId,+ p_day_from: dayFrom ?? null,+ p_day_to: dayTo ?? null,+ p_models: models?.length ? models : null,+ p_region: region || null,+ });+ if (mapErr) throw new Error(mapErr.message);+ const row = map?.complete ? (map.topics || []).find((t) => t.topic_id === topic.id) : null;+ if (!row) throw httpError('No answers for this topic in the selected range', 409);+ const { answers, you, them, gap } = topicGapScores(row, competitor.id);+ // The heat map's rule, kept here too: the server decides what is sent.+ if (answers < LOW_SAMPLE_ANSWERS) {+ throw httpError('Too few answers in this topic to measure a gap', 409);+ }+ if (gap <= 0) throw httpError('The competitor does not lead this topic', 409);++ // The prompts it is measured on (basket-metrics.js), fixed at send time so+ // moving a prompt to another topic later doesn't change what it's judged by.+ const { data: prompts, error: promptsErr } = await supabaseAdmin+ .from('prompts')+ .select('id, text, prompt_sets!inner(brand_id)')+ .eq('topic_id', topic.id)+ .eq('prompt_sets.brand_id', brandId);+ if (promptsErr) throw new Error(promptsErr.message);++ const payload = {+ source: TOPIC_GAP_ACTION_KIND,+ topicId: topic.id,+ topicName: topic.name,+ competitorId: competitor.id,+ competitorName: competitor.name,+ // Library task titles name the competitor from this list (tasks/plan.js).+ competitorNames: [competitor.name],+ yourScore: you,+ competitorScore: them,+ gap,+ window: { dayFrom: dayFrom ?? null, dayTo: dayTo ?? null },+ promptIds: (prompts || []).map((p) => p.id),+ targetEntity: 'prompts',+ targetCount: (prompts || []).length,+ targets: (prompts || []).slice(0, 50).map((p) => p.text),+ };++ const { data: action, error } = await supabaseAdmin+ .from('actions')+ .insert({+ brand_id: brandId,+ category: 'compete',+ kind: TOPIC_GAP_ACTION_KIND,+ definition_version: 1,+ impact: topicGapImpact(gap),+ payload,+ kpi_keys: KPI_KEYS,+ baseline: { yourScore: you, competitorScore: them, gap },+ dedup_key: dedupKey,+ })+ .select('id, action_no')+ .single();+ if (error) {+ // Two sends at once: the other one opened it (the open-action dedup index, 00084).+ if (error.code === '23505') {+ const winner = await openAction();+ if (winner) {+ return { actionId: winner.id, actionNo: Number(winner.action_no), created: false };+ }+ }+ throw new Error(error.message);+ }++ const sources = await resolveBrandSources(brandId);+ const plan = planTasks(+ { id: TOPIC_GAP_ACTION_KIND, tasks: TOPIC_GAP_TASKS },+ { sources, payload },+ );+ const { error: tasksErr } = await supabaseAdmin.from('action_tasks').insert(+ plan.map((item) => ({+ action_id: action.id,+ position: item.position,+ task_key: item.taskKey,+ task_version: item.version,+ mode: item.mode,+ permission: item.permission,+ depends_on: item.dependsOn,+ title_params: item.titleParams,+ status: 'todo',+ })),+ );+ if (tasksErr) throw new Error(tasksErr.message);++ await supabaseAdmin.from('action_events').insert({+ action_id: action.id,+ event: 'created',+ actor_id: userId,+ data: {+ source: TOPIC_GAP_ACTION_KIND,+ topicId: topic.id,+ competitorId: competitor.id,+ gap,+ taskCount: plan.length,+ },+ });++ return { actionId: action.id, actionNo: Number(action.action_no), created: true };+}diff --git a/server/src/lib/action-center/from-topic-gap.test.js b/server/src/lib/action-center/from-topic-gap.test.jsnew file mode 100644index 000000000..3a3c42546--- /dev/null+++ b/server/src/lib/action-center/from-topic-gap.test.js@@ -0,0 +1,228 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * sendTopicGapToActionCenter (VIS-010): the heat map's biggest gap as a+ * Compete action. These pin that the gap is measured again on the server,+ * that a topic and competitor already sent return the open action, and that+ * the action carries C04's tasks and a person's "created" event.+ */++let db;++function table(name) {+ const state = { name, filters: {}, op: 'select', row: null };+ const result = () => {+ if (state.op === 'insert') {+ db.inserts.push({ table: name, row: state.row });+ if (name === 'actions') {+ return db.insertError+ ? { data: null, error: db.insertError }+ : { data: { id: 'act-1', action_no: 61 }, error: null };+ }+ return { data: null, error: null };+ }+ return { data: db.rows[name]?.(state.filters) ?? null, error: null };+ };+ const chain = {+ select: () => chain,+ insert: (row) => {+ state.op = 'insert';+ state.row = row;+ return chain;+ },+ eq: (col, val) => {+ state.filters[col] = val;+ return chain;+ },+ in: (col, val) => {+ state.filters[col] = val;+ return chain;+ },+ maybeSingle: async () => result(),+ single: async () => result(),+ then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),+ };+ return chain;+}++vi.mock('../../config/supabase.js', () => ({+ default: {+ from: (name) => table(name),+ rpc: async (fn, args) => {+ db.rpcCalls.push({ fn, args });+ return { data: db.map, error: null };+ },+ },+}));+vi.mock('./sources.js', () => ({+ resolveBrandSources: async () => new Set(['tracking', 'competitors', 'topics']),+}));++const { sendTopicGapToActionCenter, topicGapImpact, topicGapScores } =+ await import('./from-topic-gap.js');++const topic = { id: 't1', name: 'AI Rank Tracker', brand_id: 'b1' };++const topicRow = (you, them) => ({+ topic_id: 't1',+ answers: 100,+ mention_answers: you,+ citation_answers: 0,+ sum_inv_position: 0,+ position_count: 0,+ competitors: [+ {+ competitor_id: 'c1',+ mention_answers: them,+ citation_answers: 0,+ sum_inv_position: 0,+ position_count: 0,+ },+ ],+});++beforeEach(() => {+ db = {+ inserts: [],+ rpcCalls: [],+ insertError: null,+ map: { complete: true, topics: [topicRow(20, 60)] },+ rows: {+ competitors: (f) =>+ f.id === 'c1' && f.brand_id === 'b1' ? { id: 'c1', name: 'Peec AI' } : null,+ actions: () => null,+ prompts: () => [+ { id: 'p1', text: 'best ai rank tracker' },+ { id: 'p2', text: 'ai rank tracker pricing' },+ ],+ },+ };+});++describe('topicGapScores', () => {+ it('scores both over your answers and gives the gap', () => {+ // 0.6 × 20% = 12.0 and 0.6 × 60% = 36.0 (no citations or positions).+ expect(topicGapScores(topicRow(20, 60), 'c1')).toEqual({+ answers: 100,+ you: 12,+ them: 36,+ gap: 24,+ });+ });++ it('scores a competitor never named in the topic 0', () => {+ expect(topicGapScores(topicRow(20, 60), 'c9').them).toBe(0);+ });+});++describe('topicGapImpact', () => {+ it('is high from 20 points, medium from 10', () => {+ expect([25, 20, 12, 10, 3].map(topicGapImpact)).toEqual([+ 'high',+ 'high',+ 'medium',+ 'medium',+ 'low',+ ]);+ });+});++describe('sendTopicGapToActionCenter', () => {+ const send = (extra = {}) =>+ sendTopicGapToActionCenter(topic, {+ competitorId: 'c1',+ dayFrom: '2026-09-15',+ dayTo: '2026-10-14',+ userId: 'u1',+ ...extra,+ });++ it('opens a Compete action with the gap measured on the server', async () => {+ const result = await send({ models: ['gpt-4o'], region: 'US' });++ expect(result).toEqual({ actionId: 'act-1', actionNo: 61, created: true });+ expect(db.rpcCalls[0]).toEqual({+ fn: 'insights_topic_competitors_daily',+ args: {+ p_brand_id: 'b1',+ p_day_from: '2026-09-15',+ p_day_to: '2026-10-14',+ p_models: ['gpt-4o'],+ p_region: 'US',+ },+ });++ const action = db.inserts.find((i) => i.table === 'actions').row;+ expect(action).toMatchObject({+ brand_id: 'b1',+ category: 'compete',+ kind: 'topic_competitor_gap',+ impact: 'high',+ dedup_key: 'topic_gap:t1',+ kpi_keys: ['ai_visibility', 'share_of_voice'],+ baseline: { yourScore: 12, competitorScore: 36, gap: 24 },+ });+ expect(action.payload).toMatchObject({+ topicName: 'AI Rank Tracker',+ competitorName: 'Peec AI',+ competitorNames: ['Peec AI'],+ gap: 24,+ promptIds: ['p1', 'p2'],+ targetEntity: 'prompts',+ targetCount: 2,+ });+ });++ it('plans C04’s tasks and records who sent it', async () => {+ await send();++ const tasks = db.inserts.find((i) => i.table === 'action_tasks').row;+ expect(tasks.map((t) => t.task_key)).toEqual([+ 'analyze_topic_gap',+ 'analyze_competitor_visibility',+ 'analyze_competitor_content',+ 'cluster_prompts',+ 'map_prompts_to_content',+ 'identify_content_gaps',+ 'optimize_content',+ 'validate_topic_sov',+ 'measure_action_outcome',+ ]);+ expect(tasks.every((t) => t.action_id === 'act-1' && t.status === 'todo')).toBe(true);+ expect(db.inserts.find((i) => i.table === 'action_events').row).toMatchObject({+ action_id: 'act-1',+ event: 'created',+ actor_id: 'u1',+ });+ });++ it('returns the open action for a topic already sent, whoever leads it now', async () => {+ db.rows.actions = (f) =>+ f.dedup_key === 'topic_gap:t1' ? { id: 'act-0', action_no: 58 } : null;++ expect(await send()).toEqual({ actionId: 'act-0', actionNo: 58, created: false });+ expect(db.inserts).toEqual([]);+ });++ it('refuses a competitor that is not the brand’s', async () => {+ await expect(send({ competitorId: 'c9' })).rejects.toMatchObject({ status: 404 });+ expect(db.inserts).toEqual([]);+ });++ it('refuses a topic the competitor does not lead', async () => {+ db.map = { complete: true, topics: [topicRow(60, 20)] };+ await expect(send()).rejects.toMatchObject({ status: 409 });+ expect(db.inserts).toEqual([]);+ });++ it('refuses a topic with too few answers to measure', async () => {+ db.map = { complete: true, topics: [{ ...topicRow(2, 12), answers: 15 }] };+ await expect(send()).rejects.toMatchObject({ status: 409, message: /Too few answers/ });+ expect(db.inserts).toEqual([]);+ });++ it('refuses before the rollups are backfilled', async () => {+ db.map = { complete: false, topics: [topicRow(20, 60)] };+ await expect(send()).rejects.toMatchObject({ status: 409 });+ });+});diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex 9072f45c7..c3b38ea15 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -236,8 +236,13 @@ export async function validateAction(action, { now = new Date() } = {}) {// An action sent from a content opportunity is measured on its own prompts// and pages; the brand-wide numbers would bury a single piece of content.- // An Improve action (PROMPT-004) likewise, on its one prompt.- if (action.kind === 'content_opportunity' || action.kind === 'prompt_improve') {+ // An Improve action (PROMPT-004) likewise, on its one prompt, and a topic+ // gap sent from Insights (VIS-010) on the topic's prompts.+ if (+ action.kind === 'content_opportunity' ||+ action.kind === 'prompt_improve' ||+ action.kind === 'topic_competitor_gap'+ ) {const scope = await basketScope(action);const [before, after] = await Promise.all([measureBasket(action.brand_id, scope, beforeWindow.from, beforeWindow.to),diff --git a/server/src/routes/topics-gap-action.test.js b/server/src/routes/topics-gap-action.test.jsnew file mode 100644index 000000000..36d4d7096--- /dev/null+++ b/server/src/routes/topics-gap-action.test.js@@ -0,0 +1,138 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for "Send biggest gap to Actions" (VIS-010):+ * POST /api/topics/:id/gap-action. The action itself is tested in+ * from-topic-gap.test.js; what shows up only here is what the route lets+ * through: ids in the format seeded data uses, a body that matches, a topic+ * that exists, and a caller from the topic's organization.+ */++const assertBrandAccess = vi.fn();+const sendTopicGapToActionCenter = vi.fn();+let topicRow = null;++let server;+let baseUrl;++async function startApp() {+ vi.resetModules();+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess }));+ vi.doMock('../lib/action-center/from-topic-gap.js', () => ({ sendTopicGapToActionCenter }));+ vi.doMock('../lib/plan-guard.js', () => ({ requireFeature: () => (req, res, next) => next() }));+ vi.doMock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));+ vi.doMock('../lib/web-research.js', () => ({ webResearch: vi.fn() }));+ vi.doMock('../lib/logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };+ return { default: logger, logger };+ });+ // The topic lookup is the only table the route reads.+ vi.doMock('../config/supabase.js', () => {+ const chain = new Proxy(+ {},+ {+ get: (_t, op) =>+ op === 'maybeSingle' ? async () => ({ data: topicRow, error: null }) : () => chain,+ },+ );+ return { default: { from: () => chain } };+ });++ const { default: router } = await import('./topics.js');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/topics', router);++ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/topics`;+}++// Seeded ids aren't RFC 4122 versions; the route must still take them.+const TOPIC = '77777777-7777-7777-7777-777777777701';+const COMPETITOR = '99999999-9999-9999-9999-999999999901';++const post = (topicId, body) =>+ fetch(`${baseUrl}/${topicId}/gap-action`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ vi.clearAllMocks();+ topicRow = { id: TOPIC, name: 'AI Rank Tracker', brand_id: 'b1' };+ assertBrandAccess.mockResolvedValue({});+ sendTopicGapToActionCenter.mockResolvedValue({ actionId: 'a1', actionNo: 61, created: true });+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /api/topics/:id/gap-action', () => {+ it('sends the topic with the heat map’s window and filters', async () => {+ const res = await post(TOPIC, {+ competitorId: COMPETITOR,+ dayFrom: '2026-09-15',+ dayTo: '2026-10-14',+ models: ['gpt-4o'],+ region: 'US',+ });++ expect(res.status).toBe(201);+ expect(await res.json()).toEqual({ actionId: 'a1', actionNo: 61, created: true });+ expect(assertBrandAccess).toHaveBeenCalledWith('b1', 'u1');+ expect(sendTopicGapToActionCenter).toHaveBeenCalledWith(topicRow, {+ competitorId: COMPETITOR,+ dayFrom: '2026-09-15',+ dayTo: '2026-10-14',+ models: ['gpt-4o'],+ region: 'US',+ userId: 'u1',+ });+ });++ it('answers 200 with the open action when it was already sent', async () => {+ sendTopicGapToActionCenter.mockResolvedValue({ actionId: 'a0', actionNo: 58, created: false });+ const res = await post(TOPIC, { competitorId: COMPETITOR });+ expect(res.status).toBe(200);+ });++ it('rejects a malformed topic id or body before reading anything', async () => {+ expect((await post('not-an-id', { competitorId: COMPETITOR })).status).toBe(400);+ expect((await post(TOPIC, { competitorId: 'nope' })).status).toBe(400);+ expect((await post(TOPIC, { competitorId: COMPETITOR, dayFrom: 'Sep 15' })).status).toBe(400);+ expect(assertBrandAccess).not.toHaveBeenCalled();+ expect(sendTopicGapToActionCenter).not.toHaveBeenCalled();+ });++ it('answers 404 for a topic that does not exist', async () => {+ topicRow = null;+ expect((await post(TOPIC, { competitorId: COMPETITOR })).status).toBe(404);+ expect(sendTopicGapToActionCenter).not.toHaveBeenCalled();+ });++ it('refuses a caller from another organization', async () => {+ assertBrandAccess.mockRejectedValue(Object.assign(new Error('Unauthorized'), { status: 403 }));+ expect((await post(TOPIC, { competitorId: COMPETITOR })).status).toBe(403);+ expect(sendTopicGapToActionCenter).not.toHaveBeenCalled();+ });++ it('passes the action’s own status through, e.g. a gap that closed', async () => {+ sendTopicGapToActionCenter.mockRejectedValue(+ Object.assign(new Error('The competitor does not lead this topic'), { status: 409 }),+ );+ const res = await post(TOPIC, { competitorId: COMPETITOR });+ expect(res.status).toBe(409);+ expect((await res.json()).details).toBe('The competitor does not lead this topic');+ });+});diff --git a/server/src/routes/topics.js b/server/src/routes/topics.jsindex 2a549be20..5b092dc99 100644--- a/server/src/routes/topics.js+++ b/server/src/routes/topics.js@@ -9,6 +9,7 @@ import { withRetry } from '../lib/retry.js';import { webResearch } from '../lib/web-research.js';import logger from '../lib/logger.js';import { getLanguageName } from '../lib/languages.js';+import { sendTopicGapToActionCenter } from '../lib/action-center/from-topic-gap.js';const router = Router();@@ -414,4 +415,55 @@ router.post('/suggestions/:id/accept', async (req, res) => {}});+const DAY = /^\d{4}-\d{2}-\d{2}$/;+const gapActionSchema = z.object({+ // guid, not uuid: seeded ids (e.g. the demo's) aren't RFC 4122 versions.+ competitorId: z.guid(),+ // The heat map's window and filters, so the gap is measured as it was shown.+ dayFrom: z.string().regex(DAY).optional(),+ dayTo: z.string().regex(DAY).optional(),+ models: z.array(z.string().min(1).max(100)).max(50).optional(),+ region: z.string().min(1).max(10).optional(),+});++/**+ * POST /api/topics/:id/gap-action+ * Body: { competitorId, dayFrom?, dayTo?, models?, region? }+ *+ * "Send biggest gap to Actions" on Insights (VIS-010): a Compete action to+ * close the topic's gap with the competitor leading it. Sending the same+ * topic and competitor again returns the action already open.+ */+router.post('/:id/gap-action', async (req, res) => {+ try {+ if (!z.guid().safeParse(req.params.id).success) {+ return res.status(400).json({ error: 'Invalid topic id' });+ }+ const parsed = gapActionSchema.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });+ }+ const { data: topic } = await supabaseAdmin+ .from('topics')+ .select('id, name, brand_id')+ .eq('id', req.params.id)+ .maybeSingle();+ if (!topic) return res.status(404).json({ error: 'Topic not found' });+ await assertBrandAccess(topic.brand_id, req.user.id);++ const result = await sendTopicGapToActionCenter(topic, {+ ...parsed.data,+ userId: req.user.id,+ });+ return res.status(result.created ? 201 : 200).json(result);+ } catch (error) {+ const status = error.status || 500;+ req.log.error({ err: error }, 'topic gap action error');+ return res.status(status).json({+ error: 'Failed to send to the Action Center',+ details: error.message,+ });+ }+});+export default router;diff --git a/web/messages/en.json b/web/messages/en.jsonindex 10b54107f..f63bbc499 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -776,6 +776,16 @@"note": "Before is the 7 days before this action was sent. The latest 7 days are re-read daily while the action is open and for 30 days after it's completed. A position counts as changed when it moves at least 0.5.","noteFinal": "The 7 days before this action was sent, next to the 7 days ending 30 days after it was completed. A position counts as changed when it moves at least 0.5."}+ },+ "noSignalsTopicGap": "This action was sent from Insights' Topics vs competitors, so it has no detection signals. Its evidence is the topic and scores on the Overview tab.",+ "topicGap": {+ "source": "Source",+ "sourceValue": "Insights › Topics vs competitors",+ "openTopic": "Open topic",+ "topic": "Topic",+ "scores": "Visibility when sent",+ "you": "You",+ "gap": "{gap} pts behind"}}},@@ -1177,6 +1187,12 @@"titleGeneric": "Improve a prompt's position","description": "Sent from the Prompts Improve tab: platform-specific changes to get the brand mentioned earlier and cited for one prompt.","goal": "Get the brand mentioned early and cited for this prompt on the platforms it covers."+ },+ "topic_competitor_gap": {+ "title": "Close the {gap}-pt gap with {competitor} in {topic}",+ "titleGeneric": "Close a topic gap with a competitor",+ "description": "Sent from Insights: a competitor leads one of your topics on Visibility.",+ "goal": "Lead the topic, or close most of the gap."}},"actionTasks": {@@ -1818,7 +1834,15 @@"lowSample": "Low sample","openTopic": "Open {topic}","showAll": "Show all {count}",- "showLess": "Show less"+ "showLess": "Show less",+ "sendGap": "Send biggest gap to Actions",+ "sendGapTitle": "Open a Compete action for {topic}, where {competitor} leads you by {gap} pts",+ "noGap": "No topic where a competitor leads you",+ "sent": "AC-{no} sent to the Action Center",+ "alreadySent": "Already in the Action Center as AC-{no}",+ "sendFailed": "Couldn't send to the Action Center.",+ "openAction": "Open",+ "gapChanged": "The gap changed since the page loaded. Refresh to see the latest."}},"topics": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsxindex 76c3cfc09..38ed686a8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx@@ -2,10 +2,14 @@import { useState } from 'react';import { useTranslations } from 'next-intl';-import { Link } from '@/i18n/navigation';+import { ArrowRight } from 'lucide-react';+import { toast } from 'sonner';+import { Link, useRouter } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';+import { sendTopicGapToActionCenter, type TopicGapWindow } from '@/lib/actions/topic';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { cn } from '@/lib/utils';-import { heatShade, topicHeatmap, type TopicCompetitors } from '@/lib/insights-topics';+import { biggestGap, heatShade, topicHeatmap, type TopicCompetitors } from '@/lib/insights-topics';import { TONE_TEXT } from './kpi-format';/** Rows shown before "Show all". */@@ -36,14 +40,19 @@ const SHADES = [export function TopicHeatmap({topics,columns,+ window,className,}: {topics: TopicCompetitors[];/** You first, then the competitors on the trend: `'you'` or a competitor id. */columns: { key: string; name: string }[];+ /** The window and filters the map was loaded with, for "Send biggest gap". */+ window: TopicGapWindow;className?: string;}) {const t = useTranslations('insights.topicMap');+ const router = useRouter();+ const [sending, setSending] = useState(false);// Expanded for this data only: another brand or range starts folded.const [expandedFor, setExpandedFor] = useState<TopicCompetitors[] | null>(null);const expanded = expandedFor === topics;@@ -56,11 +65,69 @@ export function TopicHeatmap({// The tones spread over the scores of every row, so folding doesn't shift them.const named = rows.flatMap((r) => r.scores).filter((v) => v > 0);const [low, high] = [Math.min(...named), Math.max(...named)];+ const target = biggestGap(rows);+ const targetCompetitor = target && columns.find((c) => c.key === target.leader)?.name;++ const sendBiggestGap = async () => {+ if (!target) return;+ setSending(true);+ try {+ const result = await sendTopicGapToActionCenter(target.topicId, target.leader, window);+ if ('error' in result) {+ // The page's numbers can be older than the server's: a newer run may+ // have closed the gap since it loaded.+ if (result.code === 'stale') toast.error(t('gapChanged'));+ else toast.error(t('sendFailed'), { description: result.error });+ return;+ }+ toast.success(+ result.created+ ? t('sent', { no: result.actionNo })+ : t('alreadySent', { no: result.actionNo }),+ {+ action: {+ label: t('openAction'),+ onClick: () =>+ router.push(`/dashboard/action-center/actions?action=${result.actionId}`),+ },+ },+ );+ } catch {+ toast.error(t('sendFailed'));+ } finally {+ setSending(false);+ }+ };return (<Card className={className}><CardHeader className="pb-2">- <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ {/* The hint sits on a wrapper: a disabled button shows no tooltip. */}+ <span+ title={+ target+ ? t('sendGapTitle', {+ topic: target.name,+ competitor: targetCompetitor ?? '',+ gap: Math.abs(target.gap!).toFixed(1),+ })+ : t('noGap')+ }+ >+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5 text-xs"+ disabled={!target || sending}+ onClick={sendBiggestGap}+ >+ <ArrowRight className="h-3.5 w-3.5" aria-hidden />+ {t('sendGap')}+ </Button>+ </span>+ </div></CardHeader><CardContent className="overflow-x-auto">{/* Fixed layout: every brand column gets the same width, as in the mockup. */}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex 64ad2bd3e..ce5df7972 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -1485,6 +1485,12 @@ export default function InsightsPage() {topicCompetitors.length > 0 && (<TopicHeatmaptopics={topicCompetitors}+ window={{+ dayFrom: loadedFilters?.days?.dayFrom,+ dayTo: loadedFilters?.days?.dayTo,+ model: loadedFilters?.model,+ region: loadedFilters?.region,+ }}columns={trendLines(rateTrend.entities, rateTrend.points, rateTrend.pinned).map((line) => ({ key: line.key, name: line.name }),)}diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex f89f0463d..80901bf3d 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -60,6 +60,7 @@ import { ImpactDots, isSuperseded, SignalStatusBadge } from './signal-table';import { ActionIcon } from './action-table';import { OpportunityContext } from './opportunity-context';import { ImproveContext } from './improve-context';+import { TopicGapContext } from './topic-gap-context';import { ImproveOutcomeCard } from './improve-outcome-card';import { improvePlatformLabels } from '@/lib/improve-outcome';import { cn } from '@/lib/utils';@@ -263,6 +264,8 @@ export function ActionDrawer({)}<ImproveContext payload={action.payload ?? {}} /></>+ ) : action.kind === 'topic_competitor_gap' ? (+ <TopicGapContext payload={action.payload ?? {}} />) : opportunityId ? (<OpportunityContextopportunityId={opportunityId}@@ -340,9 +343,11 @@ export function ActionDrawer({<p className="text-xs text-muted-foreground">{action.kind === 'prompt_improve'? t('drawer.noSignalsImprove')- : opportunityId- ? t('drawer.noSignalsOpportunity')- : t('drawer.noSignals')}+ : action.kind === 'topic_competitor_gap'+ ? t('drawer.noSignalsTopicGap')+ : opportunityId+ ? t('drawer.noSignalsOpportunity')+ : t('drawer.noSignals')}</p>)}{detail.signals.map((signal) => {diff --git a/web/src/components/action-center/topic-gap-context.tsx b/web/src/components/action-center/topic-gap-context.tsxnew file mode 100644index 000000000..5e7333f7c--- /dev/null+++ b/web/src/components/action-center/topic-gap-context.tsx@@ -0,0 +1,59 @@+'use client';++import { useTranslations } from 'next-intl';+import { ExternalLink } from 'lucide-react';+import { Link } from '@/i18n/navigation';++/**+ * What a topic gap sent from Insights is about (VIS-010): its source, the+ * topic with a link to it, and the two scores when it was sent. Copied onto+ * the action at send time, so it still reads after the scores move.+ */+export function TopicGapContext({ payload }: { payload: Record<string, unknown> }) {+ const t = useTranslations('actionCenter.actionsPage.drawer.topicGap');+ const topicId = typeof payload.topicId === 'string' ? payload.topicId : null;+ const topicName = typeof payload.topicName === 'string' ? payload.topicName : null;+ const competitor = typeof payload.competitorName === 'string' ? payload.competitorName : null;+ const you = typeof payload.yourScore === 'number' ? payload.yourScore : null;+ const them = typeof payload.competitorScore === 'number' ? payload.competitorScore : null;+ const gap = typeof payload.gap === 'number' ? payload.gap : null;++ return (+ <section className="space-y-3">+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('source')}</p>+ <p className="mt-1">{t('sourceValue')}</p>+ </div>+ {topicName && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('topic')}</p>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <span>{topicName}</span>+ {topicId && (+ <Link+ href={`/dashboard/topics/${topicId}`}+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"+ >+ {t('openTopic')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ )}+ </div>+ </div>+ )}+ {you !== null && them !== null && competitor && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('scores')}</p>+ <p className="mt-1 tabular-nums">+ {t('you')} {you.toFixed(1)} · {competitor} {them.toFixed(1)}+ {gap !== null && (+ <span className="ml-2 text-xs text-muted-foreground">+ {t('gap', { gap: gap.toFixed(1) })}+ </span>+ )}+ </p>+ </div>+ )}+ </section>+ );+}diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex ba74e48d9..4d28c4b90 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -1,5 +1,12 @@import { describe, expect, it } from 'vitest';-import { actionGoal, actionTexts, eventTaskText, humanizeKind, taskText } from './display';+import {+ actionContextTags,+ actionGoal,+ actionTexts,+ eventTaskText,+ humanizeKind,+ taskText,+} from './display';import { ACTION_KINDS } from './registry';import type { ActionItem } from '@/lib/actions/action-center';import messages from '../../../messages/en.json';@@ -40,8 +47,21 @@ describe('actionTexts', () => {expect(() => actionGoal(kind, t)).not.toThrow();});- it('holds copy for all sixty-two definitions, opportunity and Improve actions', () => {- expect(ACTION_KINDS).toHaveLength(64);+ it('holds copy for all sixty-two definitions, opportunity, Improve and topic gap actions', () => {+ expect(ACTION_KINDS).toHaveLength(65);+ });++ it('names a topic gap after its topic, competitor and gap (VIS-010)', () => {+ const payload = { topicName: 'AI Rank Tracker', competitorName: 'Peec AI', gap: 26.5 };+ expect(actionTexts(action({ kind: 'topic_competitor_gap', payload }), t).title).toBe(+ 'Close the 26.5-pt gap with Peec AI in AI Rank Tracker',+ );+ // Sent by a person: no "0 signals" chip.+ const tags = actionContextTags(+ action({ kind: 'topic_competitor_gap', payload, signalCount: 0 }),+ (key: string) => key,+ );+ expect(tags).not.toContain('tags.signals');});it('names an Improve action after its prompt, with its own why and goal', () => {diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 547e9864b..5e5b78ec4 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -78,6 +78,23 @@ export function actionTexts(description: typeof p.why === 'string' && p.why ? p.why : t(`${action.kind}.description`),};}+ // A topic gap sent from Insights (VIS-010) names the topic, the competitor+ // and the gap it was sent with.+ if (+ action.kind === 'topic_competitor_gap' &&+ typeof p.topicName === 'string' &&+ typeof p.competitorName === 'string' &&+ typeof p.gap === 'number'+ ) {+ return {+ title: t(`${action.kind}.title`, {+ gap: p.gap.toFixed(1),+ competitor: p.competitorName,+ topic: p.topicName,+ }),+ description: t(`${action.kind}.description`),+ };+ }const targets = targetLabel(p, t);return {title: targets ? t(`${action.kind}.title`, { targets }) : t(`${action.kind}.titleGeneric`),@@ -121,15 +138,22 @@ export function actionGoal(return isActionKind(kind) ? t(`${kind}.goal`) : t('unknown.goal');}+/** Kinds a person sends rather than a definition raises. */+const PERSON_SENT_KINDS: string[] = [+ 'content_opportunity',+ 'prompt_improve',+ 'topic_competitor_gap',+];+/** Compact evidence chips under the title: signal count plus the kind's own* count (pages, prompts, competitors). */export function actionContextTags(action: ActionItem, t: Translator): string[] {- // Actions a person sent (a content opportunity, an Improve set) have no- // detection signals by design; "0 signals" would read as missing evidence.- const tags =- action.kind === 'content_opportunity' || action.kind === 'prompt_improve'- ? []- : [t('tags.signals', { count: action.signalCount })];+ // Actions a person sent (a content opportunity, an Improve set, a topic+ // gap) have no detection signals by design; "0 signals" would read as+ // missing evidence.+ const tags = PERSON_SENT_KINDS.includes(action.kind)+ ? []+ : [t('tags.signals', { count: action.signalCount })];const count = num(action.payload ?? {}, 'targetCount');const entity = str(action.payload ?? {}, 'targetEntity');if (count > 0 && entity) tags.push(t(`tags.${entity}`, { count }));diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex 53e5c9b8e..8c4b83f4a 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -104,7 +104,9 @@ export type ActionKind =// Sent by a person from a content opportunity, not raised by a definition.| 'content_opportunity'// Sent by a person from the Prompts Positions panel's Improve tab (PROMPT-004).- | 'prompt_improve';+ | 'prompt_improve'+ // Sent by a person from Insights' Topics vs competitors (VIS-010).+ | 'topic_competitor_gap';export type TaskStatus =| 'todo'@@ -220,6 +222,7 @@ export const ACTION_KINDS: readonly ActionKind[] = ['create_content_for_competitor_gaps','content_opportunity','prompt_improve',+ 'topic_competitor_gap',];/**diff --git a/web/src/lib/actions/topic.ts b/web/src/lib/actions/topic.tsindex 1f0bbabfd..58421e198 100644--- a/web/src/lib/actions/topic.ts+++ b/web/src/lib/actions/topic.ts@@ -2,6 +2,7 @@import { createClient } from '@/lib/supabase/server';import { computeAiVisibilityScore } from '@/lib/visibility-score';+import { API_BASE_URL } from '@/config/api';import type { Topic } from '@/types';function mapTopicRow(row: Record<string, unknown>): Topic {@@ -406,3 +407,61 @@ export async function deleteTopic(topicId: string): Promise<void> {const { error } = await supabase.from('topics').delete().eq('id', topicId);if (error) throw new Error(error.message);}++/** The window and filters a heat map's gap was shown for (VIS-010). */+export interface TopicGapWindow {+ dayFrom?: string;+ dayTo?: string;+ /** The page's AI Model filter: model slugs, comma-separated. */+ model?: string;+ region?: string;+}++/**+ * "Send biggest gap to Actions" (VIS-010): a Compete action to close the+ * topic's gap with the competitor leading it. The server measures the gap+ * again over the same window; the same topic and competitor sent again+ * return the open action.+ */+export async function sendTopicGapToActionCenter(+ topicId: string,+ competitorId: string,+ window: TopicGapWindow,+): Promise<+ | { actionId: string; actionNo: number; created: boolean }+ // 'stale': the server measured no gap over that window any more (409).+ | { error: string; code?: 'stale' }+> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'Not authenticated' };++ const models = window.model+ ?.split(',')+ .map((m) => m.trim())+ .filter(Boolean);+ const res = await fetch(`${API_BASE_URL}/api/topics/${topicId}/gap-action`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({+ competitorId,+ dayFrom: window.dayFrom,+ dayTo: window.dayTo,+ models: models?.length ? models : undefined,+ region: window.region || undefined,+ }),+ });++ // Returned, not thrown: a thrown error's message is masked in production.+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ const error = body.details || body.error || `Server error: ${res.status}`;+ return res.status === 409 ? { error, code: 'stale' } : { error };+ }+ return res.json();+}diff --git a/web/src/lib/insights-topics.test.ts b/web/src/lib/insights-topics.test.tsindex 9cb3d0a74..30e30313f 100644--- a/web/src/lib/insights-topics.test.ts+++ b/web/src/lib/insights-topics.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import { computeAiVisibilityScore } from './visibility-score';import {+ biggestGap,heatShade,parseTopicCompetitors,topicHeatmap,@@ -77,8 +78,33 @@ describe('topicHeatmap', () => {});});+describe('biggestGap', () => {+ it('picks the topic you trail by the most, against its leader', () => {+ const rows = topicHeatmap(+ [+ topic('lead', 100, 80, { a: 50 }),+ topic('small-gap', 100, 40, { a: 50, b: 45 }),+ topic('big-gap', 100, 10, { a: 30, b: 70 }),+ topic('few', 10, 0, { a: 9 }),+ ],+ ['you', 'a', 'b'],+ );++ expect(biggestGap(rows)).toMatchObject({ topicId: 'big-gap', leader: 'b' });+ });++ it('sends nothing when you lead everywhere or the samples are too small', () => {+ const rows = topicHeatmap(+ [topic('lead', 100, 80, { a: 50 }), topic('few', 10, 0, { a: 9 })],+ ['you', 'a'],+ );+ expect(biggestGap(rows)).toBeNull();+ });+});+describe('heatShade', () => {it('spreads the tones over the scores in view', () => {+ // A table of 50s to 80s still reads in steps.// Quarters of the range: 50–57.5, 57.5–65, 65–72.5, 72.5–80.expect([50, 56, 62, 70, 80].map((v) => heatShade(v, 50, 80))).toEqual([1, 1, 2, 3, 4]);expect([12, 48.6].map((v) => heatShade(v, 12, 48.6))).toEqual([1, 4]);diff --git a/web/src/lib/insights-topics.ts b/web/src/lib/insights-topics.tsindex 4449ccf23..34a609a71 100644--- a/web/src/lib/insights-topics.ts+++ b/web/src/lib/insights-topics.ts@@ -119,6 +119,17 @@ export function topicHeatmap(topics: TopicCompetitors[], columns: string[]): Hea);}+/**+ * The row "Send biggest gap to Actions" sends: the topic you trail by the+ * most, against the competitor leading it. Topics you lead or with too few+ * answers are never sent. Null when no competitor leads you anywhere.+ */+export function biggestGap(rows: HeatmapRow[]): HeatmapRow | null {+ return rows+ .filter((r) => r.status === 'behind' && r.leader !== 'you')+ .reduce<HeatmapRow | null>((worst, r) => (!worst || r.gap! < worst.gap! ? r : worst), null);+}+/*** A cell's shade, light to dark, by where its score sits between the lowest* and highest non-zero score in view. The map compares, so its tones spread