Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(mentions): send mentions to the Action Center and suggest content (#1118)
Cihanb8a71ce32d45
diff --git a/server/src/lib/action-center/from-mentions.js b/server/src/lib/action-center/from-mentions.jsnew file mode 100644index 000000000..a9f109026--- /dev/null+++ b/server/src/lib/action-center/from-mentions.js@@ -0,0 +1,216 @@+/**+ * "Send to Action Center" from the Mentions tab (MS-08): one or more AI+ * answers that name the brand, sent as one action to change how AI+ * describes it.+ *+ * The person picks the answers; what they say is read again here from+ * prompt_results, so the action states the platforms, prompts and sentiment+ * as tracking stored them, not as a client says they are. Only the excerpts+ * come from the caller (the web cuts them from the same answers). The work+ * is F08's plan (fix_brand_inconsistency), the one written for how AI+ * describes a brand, measured afterwards on the answers' prompts like any+ * person-sent action (basket-metrics.js).+ */++import { createHash } from 'node:crypto';+import supabaseAdmin from '../../config/supabase.js';+import { resolveBrandSources } from './sources.js';+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'];+/** At most a page of the Mentions table at once. */+export const MAX_MENTIONS = 100;+/** The answers quoted on the action. */+const EVIDENCE = 10;+const EXCERPT_MAX = 400;++/** F08's plan, without its entity-signal audit: the answers themselves are the evidence. */+export const MENTION_REVIEW_TASKS = [+ 'analyze_mention_context',+ 'analyze_citations',+ 'identify_target_pages',+ 'strengthen_entity_content',+ 'publish_content',+ 'validate_mentions',+ 'measure_action_outcome',+];++function httpError(message, status) {+ const err = new Error(message);+ err.status = status;+ return err;+}++/** One action per set of answers: the same answers sent again find it. */+export function mentionDedupKey(resultIds) {+ const digest = createHash('sha1')+ .update([...new Set(resultIds)].sort().join(','))+ .digest('hex');+ return `mentions:${digest.slice(0, 20)}`;+}++/** Negative answers make it Protect work; how many of them, how urgent. */+export function mentionActionWeight(answers) {+ const negative = answers.filter((a) => a.sentiment === 'negative').length;+ const share = answers.length > 0 ? negative / answers.length : 0;+ return {+ negative,+ category: negative > 0 ? 'protect' : 'growth',+ impact: share >= 0.5 ? 'high' : negative > 0 ? 'medium' : 'low',+ };+}++/**+ * The sentiment of the answers sent, as the action's baseline: positive and+ * negative counts and the net (%positive − %negative), neutral being the rest.+ */+export function mentionBaseline(answers) {+ const positive = answers.filter((a) => a.sentiment === 'positive').length;+ const negative = answers.filter((a) => a.sentiment === 'negative').length;+ const mentions = answers.length;+ return {+ mentions,+ positive,+ negative,+ netSentiment: mentions > 0 ? Math.round(((positive - negative) * 100) / mentions) : null,+ };+}++/**+ * Creates the action, or returns the open one if these answers were already+ * sent.+ *+ * @param {string} brandId - checked against the caller's org by the route+ * @param {{ resultIds: string[], excerpts?: Record<string, string>, userId: string }} opts+ * @returns {Promise<{ actionId: string, actionNo: number, created: boolean }>}+ */+export async function sendMentionsToActionCenter(brandId, { resultIds, excerpts = {}, userId }) {+ const ids = [...new Set(resultIds)].slice(0, MAX_MENTIONS);++ // The brand's own answers that name it; anything else sent is ignored.+ const { data: rows, error: rowsErr } = await supabaseAdmin+ .from('prompt_results')+ .select('id, prompt_id, platform, region, sentiment, mention_count, created_at, prompts(text)')+ .eq('brand_id', brandId)+ .in('id', ids);+ if (rowsErr) throw new Error(rowsErr.message);+ const answers = (rows || [])+ .filter((r) => Number(r.mention_count) > 0 && r.prompt_id)+ .sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));+ if (!answers.length) throw httpError('No answers naming the brand were found', 404);++ // Keyed on the answers found, so ids that aren't the brand's mentions+ // can't open a second action for the same answers.+ const dedupKey = mentionDedupKey(answers.map((a) => a.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 prompts = new Map();+ for (const a of answers) {+ if (!prompts.has(a.prompt_id)) prompts.set(a.prompt_id, a.prompts?.text ?? '');+ }+ const promptIds = [...prompts.keys()];+ const { negative, category, impact } = mentionActionWeight(answers);+ const excerptOf = (id) => {+ const text = typeof excerpts[id] === 'string' ? excerpts[id].trim() : '';+ return text.length > EXCERPT_MAX ? `${text.slice(0, EXCERPT_MAX - 1)}…` : text;+ };++ const payload = {+ source: MENTION_ACTION_KIND,+ mentionCount: answers.length,+ negativeCount: negative,+ promptCount: promptIds.length,+ // The title names the prompt when there is one.+ promptText: prompts.get(promptIds[0]) ?? '',+ platforms: [...new Set(answers.map((a) => a.platform))],+ resultIds: answers.map((a) => a.id),+ evidence: answers.slice(0, EVIDENCE).map((a) => ({+ resultId: a.id,+ promptText: prompts.get(a.prompt_id) ?? '',+ platform: a.platform,+ region: a.region ?? null,+ sentiment: a.sentiment ?? null,+ createdAt: a.created_at,+ excerpt: excerptOf(a.id),+ })),+ // Measured on these prompts once done (basket-metrics.js).+ promptIds,+ targetEntity: 'prompts',+ targetCount: promptIds.length,+ targets: [...prompts.values()].slice(0, 50),+ };++ const { data: action, error } = await supabaseAdmin+ .from('actions')+ .insert({+ brand_id: brandId,+ category,+ kind: MENTION_ACTION_KIND,+ definition_version: 1,+ impact,+ payload,+ kpi_keys: KPI_KEYS,+ baseline: mentionBaseline(answers),+ 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: MENTION_ACTION_KIND, tasks: MENTION_REVIEW_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: MENTION_ACTION_KIND,+ mentions: answers.length,+ prompts: promptIds.length,+ taskCount: plan.length,+ },+ });++ return { actionId: action.id, actionNo: Number(action.action_no), created: true };+}diff --git a/server/src/lib/action-center/from-mentions.test.js b/server/src/lib/action-center/from-mentions.test.jsnew file mode 100644index 000000000..ad08aa0be--- /dev/null+++ b/server/src/lib/action-center/from-mentions.test.js@@ -0,0 +1,179 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * sendMentionsToActionCenter (MS-08): answers chosen on the Mentions tab as+ * one action. These pin that the answers are read again on the server (only+ * the brand's own answers naming it count), that the same answers sent again+ * return the open action, and that the action carries the review plan, its+ * evidence, a sentiment baseline 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: 62 }, 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) } }));+vi.mock('./sources.js', () => ({ resolveBrandSources: async () => new Set(['tracking']) }));++const {+ MENTION_REVIEW_TASKS,+ mentionActionWeight,+ mentionBaseline,+ mentionDedupKey,+ sendMentionsToActionCenter,+} = await import('./from-mentions.js');++const answer = (id, over = {}) => ({+ id,+ prompt_id: 'p1',+ platform: 'gemini-web',+ region: 'US',+ sentiment: 'negative',+ mention_count: 1,+ created_at: `2026-10-1${id.slice(-1)}T10:00:00Z`,+ prompts: { text: 'Best espresso beans?' },+ ...over,+});++beforeEach(() => {+ db = {+ inserts: [],+ insertError: null,+ rows: {+ actions: () => null,+ prompt_results: () => [+ answer('r1'),+ answer('r2', { sentiment: 'positive', platform: 'claude' }),+ answer('r3', { prompt_id: 'p2', prompts: { text: 'Cheap coffee?' }, sentiment: 'neutral' }),+ // Doesn't name the brand: ignored.+ answer('r4', { mention_count: 0 }),+ ],+ },+ };+});++describe('sendMentionsToActionCenter', () => {+ it('creates a Protect action from the answers as tracking stored them', async () => {+ const result = await sendMentionsToActionCenter('b1', {+ resultIds: ['r1', 'r2', 'r3', 'r4'],+ excerpts: { r1: '…Acme Coffee is pricier than Crema Club…', r2: 'x'.repeat(500) },+ userId: 'u1',+ });+ expect(result).toEqual({ actionId: 'act-1', actionNo: 62, created: true });++ const action = db.inserts.find((i) => i.table === 'actions').row;+ expect(action).toMatchObject({+ brand_id: 'b1',+ category: 'protect',+ kind: 'mention_review',+ impact: 'medium',+ kpi_keys: ['mentions', 'ai_visibility'],+ 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']),+ });+ expect(action.payload).toMatchObject({+ source: 'mention_review',+ mentionCount: 3,+ negativeCount: 1,+ promptCount: 2,+ promptIds: ['p2', 'p1'],+ targetEntity: 'prompts',+ targetCount: 2,+ platforms: ['gemini-web', 'claude'],+ resultIds: ['r3', 'r2', 'r1'],+ });+ const evidence = action.payload.evidence;+ expect(evidence.map((e) => e.resultId)).toEqual(['r3', 'r2', 'r1']);+ expect(evidence[2].excerpt).toBe('…Acme Coffee is pricier than Crema Club…');+ expect(evidence[1].excerpt).toHaveLength(400);+ expect(evidence[0].excerpt).toBe('');++ const tasks = db.inserts.find((i) => i.table === 'action_tasks').row;+ expect(tasks.map((t) => t.task_key)).toEqual(MENTION_REVIEW_TASKS);+ const event = db.inserts.find((i) => i.table === 'action_events').row;+ expect(event).toMatchObject({ event: 'created', actor_id: 'u1' });+ });++ it('returns the open action when the same answers were sent', async () => {+ db.rows.actions = () => ({ id: 'act-9', action_no: 9 });+ await expect(+ sendMentionsToActionCenter('b1', { resultIds: ['r2', 'r1'], userId: 'u1' }),+ ).resolves.toEqual({ actionId: 'act-9', actionNo: 9, created: false });+ expect(db.inserts).toEqual([]);+ });++ it('refuses answers that are not the brand’s mentions', async () => {+ db.rows.prompt_results = () => [answer('r4', { mention_count: 0 })];+ await expect(+ sendMentionsToActionCenter('b1', { resultIds: ['r4'], userId: 'u1' }),+ ).rejects.toMatchObject({ status: 404 });+ });++ it('returns the winner when another send opened it first', async () => {+ db.insertError = { code: '23505', message: 'duplicate' };+ let reads = 0;+ db.rows.actions = () => (reads++ === 0 ? null : { id: 'act-7', action_no: 7 });+ await expect(+ sendMentionsToActionCenter('b1', { resultIds: ['r1'], userId: 'u1' }),+ ).resolves.toEqual({ actionId: 'act-7', actionNo: 7, created: false });+ });+});++describe('the action’s weight and baseline', () => {+ it('is Growth without negatives, high impact when most are negative', () => {+ const s = (sentiment) => ({ sentiment });+ expect(mentionActionWeight([s('positive'), s('neutral')])).toEqual({+ negative: 0,+ category: 'growth',+ impact: 'low',+ });+ expect(mentionActionWeight([s('negative'), s('neutral'), s('positive')]).impact).toBe('medium');+ expect(mentionActionWeight([s('negative'), s('positive')]).impact).toBe('high');+ expect(mentionBaseline([s('positive'), s('positive'), s('negative'), s('neutral')])).toEqual({+ mentions: 4,+ positive: 2,+ negative: 1,+ netSentiment: 25,+ });+ });++ it('keys the same answers the same way, in any order', () => {+ expect(mentionDedupKey(['b', 'a', 'a'])).toBe(mentionDedupKey(['a', 'b']));+ expect(mentionDedupKey(['a'])).not.toBe(mentionDedupKey(['a', 'b']));+ });+});diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex 86820c3c1..2fc4f9c2e 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -238,12 +238,13 @@ export async function validateAction(action, { now = new Date() } = {}) {// and pages; the brand-wide numbers would bury a single piece of content.// An Improve action (PROMPT-004) likewise, on its one prompt, and a topic// gap (VIS-010) or opportunity (VIS-011) sent from Insights on the topic's- // prompts.+ // prompts, and answers sent from Mentions (MS-08) on their prompts.if (action.kind === 'content_opportunity' ||action.kind === 'prompt_improve' ||action.kind === 'topic_competitor_gap' ||- action.kind === 'topic_opportunity'+ action.kind === 'topic_opportunity' ||+ action.kind === 'mention_review') {const scope = await basketScope(action);const [before, after] = await Promise.all([diff --git a/server/src/lib/action-center/validate.test.js b/server/src/lib/action-center/validate.test.jsindex 5a491c9ac..2de3ec7ae 100644--- a/server/src/lib/action-center/validate.test.js+++ b/server/src/lib/action-center/validate.test.js@@ -195,6 +195,24 @@ describe('validateAction', () => {expect(patch.validation.beforeWindow.to < patch.validation.afterWindow.from).toBe(true);});+ it("measures answers sent from Mentions on their prompts' basket", async () => {+ const writes = mockWrites();+ rpc.mockResolvedValue({ data: {}, error: null });++ await validateAction(+ action({+ kind: 'mention_review',+ kpi_keys: ['mentions'],+ payload: { promptIds: ['p1', 'p2'] },+ }),+ { now: NOW },+ );++ expect(rpc).toHaveBeenCalledWith('opportunity_basket_metrics', expect.anything());+ const patch = writes.updated.find((w) => w.table === 'actions').patch;+ expect(patch.validation.scope).toEqual({ kind: 'basket', prompts: 2, pages: 0 });+ });+it('records the verdict on the action trail', async () => {const writes = mockWrites();rpc.mockResolvedValue({ data: { total_citations: 10 }, error: null });diff --git a/server/src/routes/index.js b/server/src/routes/index.jsindex 4f07286e6..146fbeb8e 100644--- a/server/src/routes/index.js+++ b/server/src/routes/index.js@@ -8,6 +8,7 @@ import topicRoutes from './topics.js';import auditRoutes from './audits.js';import reportRoutes from './reports.js';import integrationRoutes from './integrations.js';+import mentionRoutes from './mentions.js';import brandRoutes from './brands.js';import actionCenterRoutes from './action-center.js';@@ -22,6 +23,7 @@ router.use('/topics', topicRoutes);router.use('/audits', auditRoutes);router.use('/reports', reportRoutes);router.use('/integrations', integrationRoutes);+router.use('/mentions', mentionRoutes);router.use('/brands', brandRoutes);router.use('/action-center', actionCenterRoutes);diff --git a/server/src/routes/mentions-action.test.js b/server/src/routes/mentions-action.test.jsnew file mode 100644index 000000000..472f6bd8a--- /dev/null+++ b/server/src/routes/mentions-action.test.js@@ -0,0 +1,93 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for "Send to Action Center" on the Mentions tab (MS-08):+ * POST /api/mentions/action. The action itself is tested in+ * from-mentions.test.js; what shows up only here is what the route lets+ * through: ids in the format seeded data uses, a body that matches, and a+ * caller from the brand's organization.+ */++const assertBrandAccess = vi.fn();+const sendMentionsToActionCenter = vi.fn();++let server;+let baseUrl;++async function startApp() {+ vi.resetModules();+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess }));+ vi.doMock('../lib/action-center/from-mentions.js', () => ({+ MAX_MENTIONS: 100,+ sendMentionsToActionCenter,+ }));++ const { default: router } = await import('./mentions.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/mentions', router);++ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/mentions`;+}++// Seeded ids aren't RFC 4122 versions; the route must still take them.+const BRAND = '33333333-3333-3333-3333-333333333333';+const R1 = '780b5130-567e-8aef-eb44-505221a56152';++const post = (body) =>+ fetch(`${baseUrl}/action`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ assertBrandAccess.mockReset().mockResolvedValue({});+ sendMentionsToActionCenter.mockReset();+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /api/mentions/action', () => {+ it('sends the answers for a member and says whether it was created', async () => {+ sendMentionsToActionCenter.mockResolvedValue({ actionId: 'a1', actionNo: 62, created: true });+ const res = await post({ brandId: BRAND, resultIds: [R1], excerpts: { [R1]: '…Acme…' } });+ expect(res.status).toBe(201);+ expect(await res.json()).toEqual({ actionId: 'a1', actionNo: 62, created: true });+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');+ expect(sendMentionsToActionCenter).toHaveBeenCalledWith(BRAND, {+ resultIds: [R1],+ excerpts: { [R1]: '…Acme…' },+ userId: 'u1',+ });++ sendMentionsToActionCenter.mockResolvedValue({ actionId: 'a1', actionNo: 62, created: false });+ expect((await post({ brandId: BRAND, resultIds: [R1] })).status).toBe(200);+ });++ it('rejects a body without answers or with bad ids', async () => {+ expect((await post({ brandId: BRAND, resultIds: [] })).status).toBe(400);+ expect((await post({ brandId: 'nope', resultIds: [R1] })).status).toBe(400);+ expect((await post({ brandId: BRAND, resultIds: Array(101).fill(R1) })).status).toBe(400);+ expect(sendMentionsToActionCenter).not.toHaveBeenCalled();+ });++ it('refuses a caller outside the brand’s organization', async () => {+ assertBrandAccess.mockRejectedValue(Object.assign(new Error('Unauthorized'), { status: 403 }));+ const res = await post({ brandId: BRAND, resultIds: [R1] });+ expect(res.status).toBe(403);+ expect(sendMentionsToActionCenter).not.toHaveBeenCalled();+ });+});diff --git a/server/src/routes/mentions.js b/server/src/routes/mentions.jsnew file mode 100644index 000000000..75d05af77--- /dev/null+++ b/server/src/routes/mentions.js@@ -0,0 +1,49 @@+import { Router } from 'express';+import { z } from 'zod';+import { assertBrandAccess } from '../lib/access.js';+import { MAX_MENTIONS, sendMentionsToActionCenter } from '../lib/action-center/from-mentions.js';++const router = Router();++const mentionActionSchema = z.object({+ // guid, not uuid: seeded ids aren't RFC 4122 versions.+ brandId: z.guid(),+ resultIds: z.array(z.guid()).min(1).max(MAX_MENTIONS),+ // The passage around each answer's mention, as the Mentions table shows it.+ excerpts: z.record(z.guid(), z.string().max(2000)).optional(),+});++/**+ * POST /api/mentions/action+ * Body: { brandId, resultIds, excerpts? }+ *+ * "Send to Action Center" on the Mentions tab (MS-08): the chosen answers+ * naming the brand as one action. Sending the same answers again returns the+ * action already open.+ */+router.post('/action', async (req, res) => {+ try {+ const parsed = mentionActionSchema.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });+ }+ const { brandId, resultIds, excerpts } = parsed.data;+ await assertBrandAccess(brandId, req.user.id);++ const result = await sendMentionsToActionCenter(brandId, {+ resultIds,+ excerpts,+ 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 }, 'mention 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 3219b1e36..3163ce121 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1290,6 +1290,7 @@"gap": "{gap} pts behind"},"noSignalsTopicOpportunity": "This action was sent from Insights' Opportunities, so it has no detection signals. Its evidence is the topic and suggested prompts on the Overview tab.",+ "noSignalsMentionReview": "This action was sent from Mentions, so it has no detection signals. Its evidence is the answers quoted on the Overview tab.","topicOpportunity": {"source": "Source","sourceValue": "Insights › Opportunities",@@ -1301,6 +1302,20 @@"demand": "Suggested prompts when sent","demandValue": "{count, plural, one {# prompt} other {# prompts}} · ~{volume}/mo","volume": "~{volume}/mo"+ },+ "mentionReview": {+ "source": "Source",+ "sourceValue": "Mentions & Sentiment › Mentions",+ "openMentions": "Open Mentions",+ "answers": "Answers when sent",+ "answersValue": "{count, plural, one {# answer naming your brand} other {# answers naming your brand}}",+ "answersNegative": "{count, plural, one {# answer naming your brand} other {# answers naming your brand}} · {negative} negative",+ "quotes": "What they said",+ "sentiment": {+ "positive": "Positive",+ "neutral": "Neutral",+ "negative": "Negative"+ }}}},@@ -1714,6 +1729,15 @@"titleGeneric": "Capture the AI demand in a topic","description": "Sent from Insights: prompts suggested for one of your topics, with the monthly AI demand behind them.","goal": "Get the brand into AI answers for the topic's suggested prompts."+ },+ "mention_review": {+ "title": "Improve how AI describes you for \"{prompt}\"",+ "titleMany": "Improve how AI describes you across {count, plural, one {# prompt} other {# prompts}}",+ "titleGeneric": "Improve how AI describes you",+ "description": "Sent from Mentions: answers naming your brand, to change how AI describes it.",+ "descriptionCounts": "Sent from Mentions: {count, plural, one {# answer} other {# answers}} naming your brand.",+ "descriptionNegative": "Sent from Mentions: {count, plural, one {# answer} other {# answers}} naming your brand, {negative} of them negative.",+ "goal": "Get AI to describe the brand accurately and favourably in these answers."}},"actionTasks": {@@ -3156,6 +3180,31 @@"close": "Close","legendBrand": "Your brand","legendCompetitor": "Competitors"+ },+ "actions": {+ "sendToActionCenter": "Send to Action Center",+ "sending": "Sending to the Action Center…",+ "sent": "Sent to the Action Center",+ "sentDescription": "AC-{number} · {count, plural, one {# answer} other {# answers}}",+ "alreadySent": "Already in the Action Center",+ "alreadySentDescription": "AC-{number} is open with these answers.",+ "open": "Open",+ "sendFailed": "Couldn't send to the Action Center",+ "suggestContent": "Suggest content",+ "suggesting": "Writing a content suggestion…",+ "suggested": "Content suggestion created",+ "suggestionExists": "This prompt already has a content suggestion",+ "openExisting": "Open existing",+ "suggestLimited": "Monthly content limit reached.",+ "suggestNothing": "Couldn't write a suggestion for this prompt yet",+ "suggestNothingDescription": "It needs tracked answers and a prompt group first; both come with its next tracking run.",+ "suggestFailed": "Couldn't write a content suggestion",+ "suggestTimeout": "Still writing the content suggestion",+ "suggestTimeoutDescription": "It will appear in Content when it is done.",+ "selected": "{count, plural, one {# answer selected} other {# answers selected}}",+ "clearSelection": "Clear",+ "selectAll": "Select every answer on this page",+ "selectRow": "Select the answer to “{prompt}” on {platform}"}},"competitors": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsxindex 817200781..752ec68a8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx@@ -10,17 +10,33 @@ import { MentionsListTab } from './_mentions-tab';const listMentions = vi.fn();const getMentionResponse = vi.fn();+const sendMentionsToActionCenter = vi.fn();vi.mock('@/lib/actions/mentions', () => ({listMentions: (...args: unknown[]) => listMentions(...args),getMentionResponse: (...args: unknown[]) => getMentionResponse(...args),+ sendMentionsToActionCenter: (...args: unknown[]) => sendMentionsToActionCenter(...args),}));+const suggestContentForPrompt = vi.fn();+vi.mock('@/lib/actions/content', () => ({+ suggestContentForPrompt: (...args: unknown[]) => suggestContentForPrompt(...args),+ getGenerationJobStatus: vi.fn(),+}));+const push = vi.fn();vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (<a href={href} {...props}>{children}</a>),+ useRouter: () => ({ push }),+}));+const toast = vi.hoisted(() => ({+ loading: vi.fn(() => 'toast-1'),+ success: vi.fn(),+ info: vi.fn(),+ error: vi.fn(),}));+vi.mock('sonner', () => ({ toast }));(globalThis as typeof globalThis & {@@ -104,6 +120,10 @@ afterEach(() => {container.remove();listMentions.mockReset();getMentionResponse.mockReset();+ sendMentionsToActionCenter.mockReset();+ suggestContentForPrompt.mockReset();+ push.mockReset();+ Object.values(toast).forEach((fn) => fn.mockClear());vi.useRealTimers();});@@ -202,6 +222,85 @@ describe('MentionsListTab', () => {expect(cited[2]).toContain('Forum');});+ it('sends the ticked answers to the Action Center as one action', async () => {+ listMentions.mockResolvedValue(list());+ sendMentionsToActionCenter.mockResolvedValue({ actionId: 'a1', actionNo: 62, created: true });+ render(tab());+ await settle();++ const boxes = () => [...container.querySelectorAll('button[role="checkbox"]')] as HTMLElement[];+ // The header's box, then one per row.+ expect(boxes()).toHaveLength(3);+ act(() => boxes()[1].click());+ expect(container.textContent).toContain('1 answer selected');+ // Ticking doesn't open the answer.+ expect(getMentionResponse).not.toHaveBeenCalled();+ act(() => boxes()[0].click());+ expect(container.textContent).toContain('2 answers selected');++ const send = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Send to Action Center',+ ) as HTMLElement;+ await act(async () => {+ send.click();+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(sendMentionsToActionCenter).toHaveBeenCalledWith('b1', [+ { id: 'r1', excerpt: 'Crema Club is first; Acme Coffee is pricier.' },+ { id: 'r2', excerpt: 'Crema Club is first; Acme Coffee is pricier.' },+ ]);+ expect(toast.success).toHaveBeenCalledWith(+ 'Sent to the Action Center',+ expect.objectContaining({ description: 'AC-62 · 2 answers' }),+ );+ const [, options] = toast.success.mock.calls[0] as unknown as [+ string,+ { action: { onClick: () => void } },+ ];+ options.action.onClick();+ expect(push).toHaveBeenCalledWith('/dashboard/action-center/actions?action=a1');+ // Sent: the selection is cleared.+ expect(container.textContent).not.toContain('selected');+ });++ it('sends one answer, and suggests content for its prompt, from the drawer', async () => {+ listMentions.mockResolvedValue(list());+ getMentionResponse.mockResolvedValue({ response: 'Acme Coffee.', citations: [] });+ sendMentionsToActionCenter.mockResolvedValue({ actionId: 'a9', actionNo: 9, created: false });+ suggestContentForPrompt.mockResolvedValue({ ok: true, existingId: 'opp-1' });+ render(tab());+ await settle();+ await act(async () => {+ (container.querySelector('tbody tr[tabindex]') as HTMLElement).click();+ await vi.advanceTimersByTimeAsync(0);+ });+ const drawer = document.body.querySelector('[role="dialog"]') as HTMLElement;+ const button = (label: string) =>+ [...drawer.querySelectorAll('button')].find((b) => b.textContent === label) as HTMLElement;++ await act(async () => {+ button('Send to Action Center').click();+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(sendMentionsToActionCenter).toHaveBeenCalledWith('b1', [+ { id: 'r1', excerpt: 'Crema Club is first; Acme Coffee is pricier.' },+ ]);+ expect(toast.info).toHaveBeenCalledWith(+ 'Already in the Action Center',+ expect.objectContaining({ description: 'AC-9 is open with these answers.' }),+ );++ await act(async () => {+ button('Suggest content').click();+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(suggestContentForPrompt).toHaveBeenCalledWith('p1', expect.any(String));+ expect(toast.info).toHaveBeenCalledWith(+ 'This prompt already has a content suggestion',+ expect.objectContaining({ description: 'Best espresso beans?' }),+ );+ });+it('keeps its page when a read fails, and says so', async () => {listMentions.mockResolvedValueOnce(list({ total: 250 }));render(tab());diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsxindex a1cdde938..df6f18237 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx@@ -3,6 +3,8 @@import { useEffect, useMemo, useRef, useState } from 'react';import { useTranslations } from 'next-intl';import { TablePager, usePagination } from '@/components/table-pager';+import { Send } from 'lucide-react';+import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';import { Skeleton } from '@/components/ui/skeleton';import { listMentions } from '@/lib/actions/mentions';@@ -24,6 +26,7 @@ import { FilterSelect } from './_filter-bar';import type { MentionNames } from './_mention-parts';import { MentionsTable } from './_mentions-table';import { ResponseDrawer } from './_response-drawer';+import { useMentionActions } from './_use-mention-actions';/** Typing in the search box reads once it pauses, not on every key. */const READ_DELAY_MS = 250;@@ -47,7 +50,8 @@ function Message({ children }: { children: React.ReactNode }) {* The Mentions tab (MS-07): the answers naming the brand, a page of 100 at* a time, under the page's filters and the table's own (sentiment, a* competitor named in the same answer, grouping, sort), which live in the- * URL too. A row opens the response drawer.+ * URL too. A row opens the response drawer; ticked rows go to the Action+ * Center together.*/export function MentionsListTab({brandId,@@ -63,6 +67,7 @@ export function MentionsListTab({showCountry: boolean;}) {const t = useTranslations('mentions.table');+ const tActions = useTranslations('mentions.actions');const tSentiment = useTranslations('mentions.overview.sentiment');const query = useMemo(() => mentionsQuery(filters), [filters]);@@ -107,6 +112,34 @@ export function MentionsListTab({}, [brandId, key, query, table, pager.page]);const [open, setOpen] = useState<MentionRow | null>(null);+ const actions = useMentionActions(brandId);++ // Answers ticked for a bulk action, on the page shown; a new page or+ // filter starts with none.+ const shownRows = useMemo(+ () => (loaded?.status === 'ok' ? (loaded.list?.rows ?? []) : []),+ [loaded],+ );+ const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set());+ const [selectionKey, setSelectionKey] = useState<string | null>(null);+ const shownKey = loaded?.status === 'ok' ? loaded.key : null;+ if (selectionKey !== shownKey) {+ setSelectionKey(shownKey);+ setSelected(new Set());+ }+ const select = (ids: string[], on: boolean) =>+ setSelected((prev) => {+ const next = new Set(prev);+ for (const id of ids) {+ if (on) next.add(id);+ else next.delete(id);+ }+ return next;+ });+ const selectedRows = shownRows.filter((r) => selected.has(r.id));+ const sendSelected = async () => {+ if (await actions.send(selectedRows)) setSelected(new Set());+ };// A new page starts at its first row: the table scrolls inside its own box.const tableBox = useRef<HTMLDivElement>(null);@@ -206,6 +239,8 @@ export function MentionsListTab({names={names}group={table.group}showCountry={showCountry}+ selected={selected}+ onSelect={select}onOpen={setOpen}/><TablePager@@ -223,6 +258,24 @@ export function MentionsListTab({return (<section aria-label={t('sectionLabel')} className="flex flex-col gap-3">{controls}+ {selectedRows.length > 0 && (+ <div+ role="region"+ aria-label={tActions('selected', { count: selectedRows.length })}+ className="flex flex-wrap items-center gap-3 rounded-lg border bg-muted/50 px-4 py-2 text-sm"+ >+ <span className="font-medium">+ {tActions('selected', { count: selectedRows.length })}+ </span>+ <Button size="sm" onClick={sendSelected} disabled={actions.sending}>+ <Send className="h-3.5 w-3.5" />+ {tActions('sendToActionCenter')}+ </Button>+ <Button variant="ghost" size="sm" onClick={() => setSelected(new Set())}>+ {tActions('clearSelection')}+ </Button>+ </div>+ )}{body}<ResponseDrawerbrandId={brandId}@@ -232,6 +285,7 @@ export function MentionsListTab({brand: brandDomains,competitors: competitors.map((c) => c.domain).filter(Boolean),}}+ actions={actions}onClose={() => setOpen(null)}/></section>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-table.tsxindex 344c684b7..9d1b1ed0b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-table.tsx@@ -3,6 +3,7 @@import { Fragment } from 'react';import { useLocale, useTranslations } from 'next-intl';import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';+import { Checkbox } from '@/components/ui/checkbox';import {Table,TableBody,@@ -22,22 +23,30 @@ import { Highlighted, SentimentPill, type MentionNames } from './_mention-parts'* header), platform, country, the passage around the mention with the names* marked, sentiment, position, the competitors named beside you, topic and* date. With grouping on, each group opens with its name and size. A row- * opens the answer.+ * opens the answer; its box ticks it for a bulk action.*/export function MentionsTable({rows,names,group,showCountry,+ selected,+ onSelect,onOpen,}: {rows: MentionRow[];names: MentionNames;group: MentionGroup | '';showCountry: boolean;+ /** The answers ticked for a bulk action, by id. */+ selected: ReadonlySet<string>;+ /** Ticks or unticks answers; the header box takes every row on the page. */+ onSelect: (ids: string[], on: boolean) => void;onOpen: (row: MentionRow) => void;}) {const t = useTranslations('mentions.table');+ const tActions = useTranslations('mentions.actions');+ const ticked = rows.filter((r) => selected.has(r.id)).length;const locale = useLocale();const columns = showCountry ? 9 : 8;const day = (iso: string) =>@@ -47,7 +56,21 @@ export function MentionsTable({<Table stickyHeader stickyFirstColumn aria-label={t('tableLabel')}><TableHeader><TableRow>- <TableHead className="min-w-[220px] pl-4">{t('columns.prompt')}</TableHead>+ <TableHead className="min-w-[240px] pl-4">+ <span className="flex items-center gap-3">+ <Checkbox+ aria-label={tActions('selectAll')}+ checked={ticked === 0 ? false : ticked === rows.length ? true : 'indeterminate'}+ onCheckedChange={(on) =>+ onSelect(+ rows.map((r) => r.id),+ on === true,+ )+ }+ />+ {t('columns.prompt')}+ </span>+ </TableHead><TableHead>{t('columns.platform')}</TableHead>{showCountry && <TableHead>{t('columns.country')}</TableHead>}<TableHead className="min-w-[320px]">{t('columns.context')}</TableHead>@@ -83,15 +106,26 @@ export function MentionsTable({className="cursor-pointer align-top hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:outline-none"onClick={() => onOpen(row)}onKeyDown={(e) => {+ // Space on the row's box ticks it; only the row itself opens.+ if (e.target !== e.currentTarget) return;if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();onOpen(row);}}}>- <TableCell className="max-w-[260px] pl-4 whitespace-normal">- <span className="line-clamp-2 text-sm font-medium" title={row.promptText}>- {row.promptText}+ <TableCell className="max-w-[280px] pl-4 whitespace-normal">+ <span className="flex items-start gap-3">+ <Checkbox+ aria-label={tActions('selectRow', { prompt: row.promptText, platform })}+ checked={selected.has(row.id)}+ onClick={(e) => e.stopPropagation()}+ onCheckedChange={(on) => onSelect([row.id], on === true)}+ className="mt-0.5"+ />+ <span className="line-clamp-2 text-sm font-medium" title={row.promptText}>+ {row.promptText}+ </span></span></TableCell><TableCell>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsxindex e36f6991d..974cdcade 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx@@ -2,7 +2,7 @@import { useEffect, useMemo, useState, type ComponentProps, type ReactNode } from 'react';import { useLocale, useTranslations } from 'next-intl';-import { ArrowUpRight, ChevronDown, Copy, ExternalLink } from 'lucide-react';+import { ArrowUpRight, ChevronDown, Copy, ExternalLink, Send, Sparkles } from 'lucide-react';import { toast } from 'sonner';import type { Components } from 'react-markdown';import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';@@ -34,6 +34,7 @@ import {SentimentPill,type MentionNames,} from './_mention-parts';+import type { useMentionActions } from './_use-mention-actions';type Loaded =| { id: string; status: 'ok'; response: string; citations: Citation[] }@@ -65,14 +66,15 @@ function Section({* position; the passage around the mention; the competitors named beside* you; the full stored answer with your brand marked in violet and* competitors in grey; and the sources it cites, typed as on the Citations- * page. Sending to the Action Center, suggesting content and correcting the- * sentiment come next.+ * page. Its footer sends the answer to the Action Center, suggests content+ * for its prompt, and copies it; correcting the sentiment comes next.*/export function ResponseDrawer({brandId,row,names,domains,+ actions,onClose,}: {brandId: string;@@ -80,9 +82,15 @@ export function ResponseDrawer({names: MentionNames;/** For typing the cited sources: your domains and the competitors'. */domains: { brand: string[]; competitors: string[] };+ /** Send the answer to the Action Center, or suggest content for its prompt. */+ actions: Pick<+ ReturnType<typeof useMentionActions>,+ 'send' | 'sending' | 'suggest' | 'suggesting'+ >;onClose: () => void;}) {const t = useTranslations('mentions.drawer');+ const tActions = useTranslations('mentions.actions');const locale = useLocale();const [loaded, setLoaded] = useState<Loaded | null>(null);const [showResponse, setShowResponse] = useState(true);@@ -325,11 +333,31 @@ export function ResponseDrawer({)}</div>- <div className="flex items-center justify-between gap-2 border-t px-5 py-3">- <Button variant="outline" size="sm" onClick={copy} disabled={answer?.status !== 'ok'}>- <Copy className="h-3.5 w-3.5" />- {t('copy')}- </Button>+ <div className="flex flex-wrap items-center justify-between gap-2 border-t px-5 py-3">+ <div className="flex flex-wrap items-center gap-2">+ <Button size="sm" onClick={() => actions.send([row])} disabled={actions.sending}>+ <Send className="h-3.5 w-3.5" />+ {tActions('sendToActionCenter')}+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => actions.suggest(row)}+ disabled={actions.suggesting === row.promptId}+ >+ <Sparkles className="h-3.5 w-3.5" />+ {tActions('suggestContent')}+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={copy}+ disabled={answer?.status !== 'ok'}+ >+ <Copy className="h-3.5 w-3.5" />+ {t('copy')}+ </Button>+ </div><SheetClose render={<Button variant="ghost" size="sm" />}>{t('close')}</SheetClose></div></>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mention-actions.ts b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mention-actions.tsnew file mode 100644index 000000000..3fca58408--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mention-actions.ts@@ -0,0 +1,123 @@+'use client';++import { useCallback, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { useRouter } from '@/i18n/navigation';+import { getGenerationJobStatus, suggestContentForPrompt } from '@/lib/actions/content';+import { sendMentionsToActionCenter } from '@/lib/actions/mentions';+import { suggestForPrompt } from '@/lib/content-job';+import type { MentionRow } from '@/lib/mentions-list';++/** The server calls behind "Suggest content", as on the Prompts page (PROMPT-006). */+const SUGGEST_CALLS = { start: suggestContentForPrompt, getStatus: getGenerationJobStatus };++/**+ * The Mentions tab's actions (MS-08), shared by the response drawer and the+ * table's selection bar: send answers to the Action Center as one action,+ * and suggest content for an answer's prompt. Each reports how it went in a+ * toast that opens what it made.+ */+export function useMentionActions(brandId: string) {+ const t = useTranslations('mentions.actions');+ const router = useRouter();+ const [sending, setSending] = useState(false);+ const [suggesting, setSuggesting] = useState<string | null>(null);++ const send = useCallback(+ async (rows: MentionRow[]): Promise<boolean> => {+ if (rows.length === 0) return false;+ setSending(true);+ const toastId = toast.loading(t('sending'));+ try {+ const result = await sendMentionsToActionCenter(+ brandId,+ rows.map((r) => ({ id: r.id, excerpt: r.excerpt })),+ );+ if ('error' in result) {+ toast.error(t('sendFailed'), { id: toastId, description: result.error });+ return false;+ }+ const open = {+ label: t('open'),+ onClick: () => router.push(`/dashboard/action-center/actions?action=${result.actionId}`),+ };+ if (result.created) {+ toast.success(t('sent'), {+ id: toastId,+ description: t('sentDescription', { number: result.actionNo, count: rows.length }),+ duration: 10_000,+ action: open,+ });+ } else {+ toast.info(t('alreadySent'), {+ id: toastId,+ description: t('alreadySentDescription', { number: result.actionNo }),+ duration: 10_000,+ action: open,+ });+ }+ return true;+ } catch {+ toast.error(t('sendFailed'), { id: toastId });+ return false;+ } finally {+ setSending(false);+ }+ },+ [brandId, router, t],+ );++ const suggest = useCallback(+ async (row: MentionRow) => {+ setSuggesting(row.promptId);+ const toastId = toast.loading(t('suggesting'), { description: row.promptText });+ const outcome = await suggestForPrompt(row.promptId, SUGGEST_CALLS);+ setSuggesting(null);+ const openOpportunity = (id: string) => () =>+ router.push(`/dashboard/content?opportunity=${id}`);+ switch (outcome.kind) {+ case 'created':+ toast.success(t('suggested'), {+ id: toastId,+ description: row.promptText,+ duration: 10_000,+ action: { label: t('open'), onClick: openOpportunity(outcome.opportunityId) },+ });+ break;+ case 'existing':+ toast.info(t('suggestionExists'), {+ id: toastId,+ description: row.promptText,+ duration: 10_000,+ action: { label: t('openExisting'), onClick: openOpportunity(outcome.opportunityId) },+ });+ break;+ case 'limited':+ toast.error(t('suggestLimited'), { id: toastId, description: row.promptText });+ break;+ case 'nothing':+ toast.info(t('suggestNothing'), {+ id: toastId,+ description: t('suggestNothingDescription'),+ });+ break;+ case 'failed':+ toast.error(t('suggestFailed'), {+ id: toastId,+ description: outcome.message ?? undefined,+ });+ break;+ case 'timeout':+ toast.info(t('suggestTimeout'), {+ id: toastId,+ description: t('suggestTimeoutDescription'),+ });+ break;+ }+ },+ [router, t],+ );++ return { send, sending, suggest, suggesting };+}diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex 2362122b0..0116525d4 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -68,6 +68,7 @@ import { useActionStory } from './use-action-story';import { ImproveContext } from './improve-context';import { TopicGapContext } from './topic-gap-context';import { TopicOpportunityContext } from './topic-opportunity-context';+import { MentionReviewContext } from './mention-review-context';import { TaskDetailForm, TaskDetailView, TaskTypeBadge, type TaskSendOptions } from './task-detail';import { hasActiveWebhook, sendActionTask } from '@/lib/actions/action-task-send';import { RegenerateTasks, taskWriterEnabled } from './regenerate-tasks';@@ -477,6 +478,11 @@ export function ActionDrawer({<Separator /><TopicOpportunityContext payload={action.payload ?? {}} /></>+ ) : action.kind === 'mention_review' ? (+ <>+ <Separator />+ <MentionReviewContext payload={action.payload ?? {}} />+ </>) : opportunityId ? (<><Separator />@@ -562,9 +568,11 @@ export function ActionDrawer({? t('drawer.noSignalsTopicGap'): action.kind === 'topic_opportunity'? t('drawer.noSignalsTopicOpportunity')- : opportunityId- ? t('drawer.noSignalsOpportunity')- : t('drawer.noSignals')}+ : action.kind === 'mention_review'+ ? t('drawer.noSignalsMentionReview')+ : opportunityId+ ? t('drawer.noSignalsOpportunity')+ : t('drawer.noSignals')}</p>)}{detail.signals.map((signal) => {diff --git a/web/src/components/action-center/mention-review-context.tsx b/web/src/components/action-center/mention-review-context.tsxnew file mode 100644index 000000000..841cd5d7a--- /dev/null+++ b/web/src/components/action-center/mention-review-context.tsx@@ -0,0 +1,112 @@+'use client';++import { useLocale, useTranslations } from 'next-intl';+import { ExternalLink } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { mentionPlatformLabel } from '@/lib/mentions-headline';+import { cn } from '@/lib/utils';++interface Evidence {+ resultId: string;+ promptText: string;+ platform: string;+ sentiment: string | null;+ createdAt: string;+ excerpt: string;+}++const TONE: Record<string, string> = {+ positive: 'text-emerald-700 dark:text-emerald-300',+ negative: 'text-rose-700 dark:text-rose-300',+};++/**+ * What answers sent from the Mentions tab are about (MS-08): their source,+ * how many and how many were negative, and the answers quoted as they read+ * when sent, with their platform, date and tone. Copied onto the action at+ * send time, so it still reads after newer answers come in.+ */+export function MentionReviewContext({ payload }: { payload: Record<string, unknown> }) {+ const t = useTranslations('actionCenter.actionsPage.drawer.mentionReview');+ const locale = useLocale();+ const count = typeof payload.mentionCount === 'number' ? payload.mentionCount : 0;+ const negative = typeof payload.negativeCount === 'number' ? payload.negativeCount : 0;+ const evidence: Evidence[] = Array.isArray(payload.evidence)+ ? (payload.evidence as Record<string, unknown>[]).flatMap((e) =>+ typeof e?.resultId === 'string'+ ? [+ {+ resultId: e.resultId,+ promptText: typeof e.promptText === 'string' ? e.promptText : '',+ platform: typeof e.platform === 'string' ? e.platform : '',+ sentiment: typeof e.sentiment === 'string' ? e.sentiment : null,+ createdAt: typeof e.createdAt === 'string' ? e.createdAt : '',+ excerpt: typeof e.excerpt === 'string' ? e.excerpt : '',+ },+ ]+ : [],+ )+ : [];+ const day = (iso: string) =>+ iso ? new Date(iso).toLocaleDateString(locale, { month: 'short', day: 'numeric' }) : '';++ return (+ <section className="space-y-3">+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('source')}</p>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <span>{t('sourceValue')}</span>+ <Link+ href="/dashboard/mentions?tab=mentions"+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"+ >+ {t('openMentions')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ </div>+ </div>+ {count > 0 && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('answers')}</p>+ <p className="mt-1 tabular-nums">+ {negative > 0+ ? t('answersNegative', { count, negative })+ : t('answersValue', { count })}+ </p>+ </div>+ )}+ {evidence.length > 0 && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('quotes')}</p>+ <ul className="mt-1.5 space-y-2">+ {evidence.map((e) => (+ <li key={e.resultId} className="rounded-md border px-3 py-2 text-xs">+ <p className="flex flex-wrap items-center gap-x-1.5 text-muted-foreground">+ <span className="font-medium text-foreground">+ {mentionPlatformLabel(e.platform)}+ </span>+ <span aria-hidden>·</span>+ <span>{day(e.createdAt)}</span>+ {e.sentiment && (+ <>+ <span aria-hidden>·</span>+ <span className={cn('font-medium', TONE[e.sentiment])}>+ {t(+ `sentiment.${e.sentiment === 'positive' || e.sentiment === 'negative' ? e.sentiment : 'neutral'}`,+ )}+ </span>+ </>+ )}+ </p>+ <p className="mt-1 font-medium">{e.promptText}</p>+ {e.excerpt && (+ <p className="mt-1 leading-relaxed text-muted-foreground">{e.excerpt}</p>+ )}+ </li>+ ))}+ </ul>+ </div>+ )}+ </section>+ );+}diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex 651e5ecf4..a65c7e17f 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -51,8 +51,26 @@ describe('actionTexts', () => {expect(() => actionGoal(kind, t)).not.toThrow();});- it('holds copy for all sixty-two definitions and the four person-sent kinds', () => {- expect(ACTION_KINDS).toHaveLength(66);+ it('holds copy for all sixty-two definitions and the five person-sent kinds', () => {+ expect(ACTION_KINDS).toHaveLength(67);+ });++ it('names answers sent from Mentions after their prompt, or how many (MS-08)', () => {+ const one = { mentionCount: 3, negativeCount: 2, promptCount: 1, promptText: 'Best beans?' };+ const texts = actionTexts(action({ kind: 'mention_review', payload: one }), t);+ expect(texts.title).toBe('Improve how AI describes you for "Best beans?"');+ expect(texts.description).toBe(+ 'Sent from Mentions: 3 answers naming your brand, 2 of them negative.',+ );+ const many = { mentionCount: 2, negativeCount: 0, promptCount: 4 };+ const manyTexts = actionTexts(action({ kind: 'mention_review', payload: many }), t);+ expect(manyTexts.title).toBe('Improve how AI describes you across 4 prompts');+ expect(manyTexts.description).toBe('Sent from Mentions: 2 answers naming your brand.');+ const tags = actionContextTags(+ action({ kind: 'mention_review', payload: many, signalCount: 0 }),+ (key: string) => key,+ );+ expect(tags).not.toContain('tags.signals');});it('names a topic opportunity after its topic and demand (VIS-011)', () => {diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 384483116..5f14bff57 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -111,6 +111,24 @@ export function actionTexts(description: t(`${action.kind}.description`),};}+ // Answers sent from Mentions (MS-08) name their prompt, or how many prompts.+ if (+ action.kind === 'mention_review' &&+ typeof p.mentionCount === 'number' &&+ typeof p.promptCount === 'number'+ ) {+ const negative = typeof p.negativeCount === 'number' ? p.negativeCount : 0;+ return {+ title:+ p.promptCount === 1 && typeof p.promptText === 'string' && p.promptText+ ? t(`${action.kind}.title`, { prompt: p.promptText })+ : t(`${action.kind}.titleMany`, { count: p.promptCount }),+ description:+ negative > 0+ ? t(`${action.kind}.descriptionNegative`, { count: p.mentionCount, negative })+ : t(`${action.kind}.descriptionCounts`, { count: p.mentionCount }),+ };+ }const targets = targetLabel(p, t);return {title: targets ? t(`${action.kind}.title`, { targets }) : t(`${action.kind}.titleGeneric`),@@ -185,6 +203,7 @@ const PERSON_SENT_KINDS: string[] = ['prompt_improve','topic_competitor_gap','topic_opportunity',+ 'mention_review',];/** Compact evidence chips under the title: signal count plus the kind's owndiff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex e16ff5b26..0218bc225 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -37,7 +37,7 @@ export type ActionOutcome =| 'not_measurable';/** A kind this build has copy for — the V1 library's sixty-two definitions, plus- * actions sent from a content opportunity. */+ * the kinds a person sends from another page. */export type ActionKind =| 'capture_ai_traffic'| 'convert_mentions'@@ -108,7 +108,9 @@ export type ActionKind =// Sent by a person from Insights' Topics vs competitors (VIS-010).| 'topic_competitor_gap'// Sent by a person from an Insights Opportunities topic (VIS-011).- | 'topic_opportunity';+ | 'topic_opportunity'+ // Sent by a person from answers on the Mentions tab (MS-08).+ | 'mention_review';export type TaskStatus =| 'todo'@@ -227,6 +229,7 @@ export const ACTION_KINDS: readonly ActionKind[] = ['prompt_improve','topic_competitor_gap','topic_opportunity',+ 'mention_review',];/**diff --git a/web/src/lib/actions/mentions.test.ts b/web/src/lib/actions/mentions.test.tsindex e5ae48445..8924f6d56 100644--- a/web/src/lib/actions/mentions.test.ts+++ b/web/src/lib/actions/mentions.test.ts@@ -11,11 +11,22 @@ const query = {maybeSingle: async () => tableResult,};const from = vi.fn((table: string) => (tableCalls.push(['from', table]), query));+let session: { access_token: string } | null = { access_token: 'tok' };vi.mock('@/lib/supabase/server', () => ({- createClient: vi.fn(async () => ({ rpc, from })),+ createClient: vi.fn(async () => ({+ rpc,+ from,+ auth: { getSession: async () => ({ data: { session } }) },+ })),}));+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));-import { getMentionResponse, getMentionsOverview, listMentions } from './mentions';+import {+ getMentionResponse,+ getMentionsOverview,+ listMentions,+ sendMentionsToActionCenter,+} from './mentions';import { DEFAULT_MENTIONS_TABLE } from '@/lib/mentions-list';beforeEach(() => {@@ -187,3 +198,49 @@ describe('getMentionResponse', () => {await expect(getMentionResponse('b1', 'r1')).resolves.toBeNull();});});++describe('sendMentionsToActionCenter', () => {+ const fetchMock = vi.fn();+ beforeEach(() => {+ session = { access_token: 'tok' };+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ });++ it('posts the answers and their excerpts as the signed-in user', async () => {+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ actionId: 'a1', actionNo: 62, created: true }), {+ status: 201,+ }),+ );+ await expect(+ sendMentionsToActionCenter('b1', [+ { id: 'r1', excerpt: '…Acme…' },+ { id: 'r2', excerpt: '' },+ ]),+ ).resolves.toEqual({ actionId: 'a1', actionNo: 62, created: true });+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('http://api.test/api/mentions/action');+ expect(init.headers.Authorization).toBe('Bearer tok');+ expect(JSON.parse(init.body)).toEqual({+ brandId: 'b1',+ resultIds: ['r1', 'r2'],+ excerpts: { r1: '…Acme…', r2: '' },+ });+ });++ it("returns the server's error instead of throwing", async () => {+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ error: 'Failed', details: 'No answers naming the brand' }), {+ status: 404,+ }),+ );+ await expect(sendMentionsToActionCenter('b1', [{ id: 'r1', excerpt: '' }])).resolves.toEqual({+ error: 'No answers naming the brand',+ });+ session = null;+ await expect(sendMentionsToActionCenter('b1', [{ id: 'r1', excerpt: '' }])).resolves.toEqual({+ error: 'Not authenticated',+ });+ });+});diff --git a/web/src/lib/actions/mentions.ts b/web/src/lib/actions/mentions.tsindex da52f46cf..1bbfe20fa 100644--- a/web/src/lib/actions/mentions.ts+++ b/web/src/lib/actions/mentions.ts@@ -1,5 +1,6 @@'use server';+import { API_BASE_URL } from '@/config/api';import { createClient } from '@/lib/supabase/server';import { mentionExcerpt } from '@/lib/mention-match';import type { MentionsQuery } from '@/lib/mentions-filters';@@ -109,3 +110,40 @@ export async function getMentionResponse(citations: Array.isArray(data.citations) ? (data.citations as unknown as Citation[]) : [],};}++/**+ * "Send to Action Center" on the Mentions tab (MS-08): the chosen answers+ * as one action to change how AI describes the brand. The server reads the+ * answers again; the excerpts are the table's, so the action quotes what the+ * person saw. The same answers sent again return the open action.+ */+export async function sendMentionsToActionCenter(+ brandId: string,+ mentions: { id: string; excerpt: string }[],+): Promise<{ actionId: string; actionNo: number; created: boolean } | { error: string }> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'Not authenticated' };++ const res = await fetch(`${API_BASE_URL}/api/mentions/action`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({+ brandId,+ resultIds: mentions.map((m) => m.id),+ excerpts: Object.fromEntries(mentions.map((m) => [m.id, m.excerpt])),+ }),+ });++ // Returned, not thrown: a thrown error's message is masked in production.+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ return { error: body.details || body.error || `Server error: ${res.status}` };+ }+ return res.json();+}