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
fix(server): keep costly generation to admins and managers (#1769)
Cihan5956f4d32889
diff --git a/server/src/routes/content-suggest.test.js b/server/src/routes/content-suggest.test.jsindex 1ab1377ad..11ff97cfb 100644--- a/server/src/routes/content-suggest.test.js+++ b/server/src/routes/content-suggest.test.js@@ -43,10 +43,13 @@ async function startApp() {getOrgIdForUser: vi.fn(),}));vi.doMock('../lib/access.js', () => ({+ MANAGER_ROLES: ['admin', 'manager'],assertBrandAccess,assertOpportunitiesAccess: vi.fn(),assertOpportunityAccess: vi.fn(),assertPromptAccess,+ // Generating is a manager's (2026-10-29): the caller is one here.+ assertRole: vi.fn(async () => 'manager'),}));vi.doMock('../lib/job-manager.js', () => ({ createJob, getJob: vi.fn() }));vi.doMock('../lib/job-runner.js', () => ({ runContentJob }));diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex 8b9601eaa..8995d57aa 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -114,6 +114,10 @@ function mapOpportunityRow(stored, competitors = []) {};}+/** Generating opportunities and briefs costs AI: admins and managers start it (2026-10-29). */+const GENERATE_OPPORTUNITIES_REFUSAL = 'Only admins and managers can generate opportunities.';+const GENERATE_BRIEF_REFUSAL = 'Only admins and managers can generate briefs.';+/*** POST /api/content/generate* Enqueues a content opportunity generation job. Returns { jobId } immediately.@@ -145,6 +149,7 @@ router.post('/generate', requireFeature('content_optimization'), async (req, resif (!profile || profile.organization_id !== brand.organization_id) {return res.status(403).json({ error: NOT_IN_WORKSPACE, code: 'not_in_workspace' });}+ await assertRole(req.user.id, MANAGER_ROLES, GENERATE_OPPORTUNITIES_REFUSAL);const job = await createJob({type: 'content',@@ -162,6 +167,9 @@ router.post('/generate', requireFeature('content_optimization'), async (req, resmessage: 'Content generation job enqueued',});} catch (error) {+ if (error.status) {+ return res.status(error.status).json({ error: error.message, code: error.code });+ }req.log.error({ err: error }, 'content enqueue error');return res.status(500).json({ error: error.message });}@@ -205,6 +213,7 @@ router.post('/opportunities/generate', requireFeature('content_optimization'), atry {const { orgId } = await assertBrandAccess(brandId, req.user.id);+ await assertRole(req.user.id, MANAGER_ROLES, GENERATE_OPPORTUNITIES_REFUSAL);const previous = await startedJob(brandId, idempotencyKey);if (previous) {@@ -280,6 +289,7 @@ router.post('/:id/alternative', requireFeature('content_optimization'), async (rtry {const opp = await assertOpportunityAccess(req.params.id, req.user.id);+ await assertRole(req.user.id, MANAGER_ROLES, GENERATE_OPPORTUNITIES_REFUSAL);const previous = await startedJob(opp.brand_id, idempotencyKey);if (previous) return res.status(202).json({ jobId: previous.id });@@ -388,6 +398,7 @@ router.post(try {const [prompt] = await assertPromptAccess(promptId, req.user.id);+ await assertRole(req.user.id, MANAGER_ROLES, GENERATE_OPPORTUNITIES_REFUSAL);const { brand_id: brandId, brands } = prompt.prompt_sets;const previous = await startedJob(brandId, idempotencyKey);@@ -1633,6 +1644,7 @@ router.post('/:id/brief', async (req, res) => {if (!brand || !userOrgId || userOrgId !== brand.organization_id) {return res.status(403).json({ error: NOT_IN_WORKSPACE, code: 'not_in_workspace' });}+ await assertRole(req.user.id, MANAGER_ROLES, GENERATE_BRIEF_REFUSAL);const result = await generateBriefForOpportunity(id, { model });const quota = await getBriefQuotaStatus(userOrgId);@@ -1648,6 +1660,9 @@ router.post('/:id/brief', async (req, res) => {if (error.status === 404) {return res.status(404).json({ error: error.message });}+ if (error.status === 403) {+ return res.status(403).json({ error: error.message, code: error.code });+ }req.log.error({ err: error }, 'content brief generation error');return res.status(500).json({error: 'Failed to generate brief',diff --git a/server/src/routes/costly-roles.test.js b/server/src/routes/costly-roles.test.jsnew file mode 100644index 000000000..3654ea9c6--- /dev/null+++ b/server/src/routes/costly-roles.test.js@@ -0,0 +1,211 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Who may start costly AI work (2026-10-29): generating prompt and topic+ * suggestions, opportunities, briefs and Improve sets, and sending Improve to+ * the Action Center, is for admins and managers. An analyst or an agency+ * partner is refused before anything is generated or queued. Writing in the+ * Content Editor and running a Site Audit stay open (their own routes).+ */++let role;+let server;+let baseUrl;+const generateObject = vi.fn();+const createJob = vi.fn();+const assertBrandAccess = vi.fn();+const assertOpportunityAccess = vi.fn();+const assertPromptAccess = vi.fn();++/** Every brand and profile is the caller's organization; the caller is `role`. */+function query(table) {+ const answer = () => {+ if (table === 'profiles') return { data: { organization_id: 'o1', role }, error: null };+ if (table === 'brands') {+ return { data: { id: 'b1', name: 'Acme', organization_id: 'o1' }, error: null };+ }+ if (table === 'content_opportunities') return { data: { brand_id: 'b1' }, error: null };+ if (table === 'prompts') {+ return { data: { id: 'p1', text: 'best crm', prompt_sets: { brand_id: 'b1' } }, error: null };+ }+ return { data: null, error: null };+ };+ const chain = new Proxy(+ {},+ {+ get: (_t, op) => {+ if (op === 'then')+ return (resolve, reject) => Promise.resolve(answer()).then(resolve, reject);+ if (op === 'maybeSingle' || op === 'single') return async () => answer();+ return () => chain;+ },+ },+ );+ return chain;+}++async function startApp() {+ vi.resetModules();+ vi.doMock('../config/supabase.js', () => ({ default: { from: (table) => query(table) } }));+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError: class extends Error {},+ requireFeature: () => (req, res, next) => next(),+ enforceFeature: vi.fn(),+ enforceBriefQuota: vi.fn(),+ getBriefQuotaStatus: vi.fn(),+ getContentUsage: vi.fn(),+ getOpportunityRequestAllowance: vi.fn(async () => ({ max: 0 })),+ getOrgIdForUser: async () => 'o1',+ reserveAiBudget: vi.fn(),+ getImproveQuotaStatus: vi.fn(),+ reserveRelevanceAllowance: vi.fn(),+ settleRelevanceUsage: vi.fn(),+ }));+ // The real role check, on the profile above; the organization checks pass.+ vi.doMock('../lib/access.js', async (importOriginal) => ({+ ...(await importOriginal()),+ assertBrandAccess,+ assertOpportunityAccess,+ assertPromptAccess,+ }));+ vi.doMock('ai', () => ({ generateObject, NoObjectGeneratedError: class extends Error {} }));+ vi.doMock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));+ vi.doMock('../lib/job-manager.js', () => ({ createJob, getJob: vi.fn() }));+ vi.doMock('../lib/job-runner.js', () => ({ runContentJob: vi.fn() }));+ vi.doMock('../lib/gsc-suggestions.js', () => ({ getGscSuggestionCandidates: vi.fn() }));+ vi.doMock('../lib/ga-suggestions.js', () => ({ getGaSuggestionCandidates: vi.fn() }));+ vi.doMock('../lib/catalog-suggestions.js', () => ({ getCatalogSuggestionCandidates: vi.fn() }));+ vi.doMock('../lib/page-prompt-suggestions.js', () => ({ suggestPromptsForPage: vi.fn() }));+ vi.doMock('../lib/web-research.js', () => ({ webResearch: vi.fn() }));+ vi.doMock('../lib/prompt-clusters.js', () => ({ loadClusters: vi.fn() }));+ vi.doMock('../lib/action-center/from-opportunity.js', () => ({+ OPPORTUNITY_ACTION_KIND: 'content_opportunity',+ sendToActionCenter: vi.fn(),+ }));+ vi.doMock('../lib/action-center/from-topic-opportunity.js', () => ({+ sendTopicOpportunityToActionCenter: vi.fn(),+ }));+ vi.doMock('../lib/action-center/from-topic-gap.js', () => ({+ sendTopicGapToActionCenter: 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 };+ });++ const { default: content } = await import('./content.js');+ const { default: prompts } = await import('./prompts.js');+ const { default: topics } = 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(), warn: vi.fn() };+ next();+ });+ app.use('/api/content', content);+ app.use('/api/prompts', prompts);+ app.use('/api/topics', topics);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api`;+}++const BRAND = '11111111-1111-4111-8111-111111111111';+const setup = { brandName: 'Acme', industry: 'Coffee', description: 'Office coffee.' };+const range = { preset: '7d', from: '2026-10-21T00:00:00.000Z', to: '2026-10-28T00:00:00.000Z' };++/** Each costly route, what it is sent, and what a refused caller reads. */+const ROUTES = [+ ['/content/generate', { brandId: 'b1' }, 'Only admins and managers can generate opportunities.'],+ [+ '/content/opportunities/generate',+ { brandId: BRAND, count: 3, idempotencyKey: 'key-000001' },+ 'Only admins and managers can generate opportunities.',+ ],+ [+ '/content/o1/alternative',+ { direction: 'different_angle', idempotencyKey: 'key-000001' },+ 'Only admins and managers can generate opportunities.',+ ],+ [+ '/content/prompts/p1/suggest',+ { idempotencyKey: 'key-000001' },+ 'Only admins and managers can generate opportunities.',+ ],+ ['/content/o1/brief', {}, 'Only admins and managers can generate briefs.'],+ [+ `/prompts/suggestions/${BRAND}/refresh`,+ {},+ 'Only admins and managers can generate prompt suggestions.',+ ],+ [+ `/prompts/suggestions/${BRAND}/page`,+ { page: '/pricing' },+ 'Only admins and managers can generate prompt suggestions.',+ ],+ ['/prompts/suggest', setup, 'Only admins and managers can generate prompt suggestions.'],+ ['/prompts/p1/improve', range, 'Only admins and managers can use Improve.'],+ [+ '/prompts/p1/improve/action',+ {+ ...range,+ idempotencyKey: 'key-000001',+ suggestions: [{ id: 's1', platform: 'perplexity-web', title: 'Publish a comparison page' }],+ },+ 'Only admins and managers can use Improve.',+ ],+ ['/topics/suggest', setup, 'Only admins and managers can generate topic suggestions.'],+ [+ `/topics/suggestions/${BRAND}/refresh`,+ {},+ 'Only admins and managers can generate topic suggestions.',+ ],+];++const post = (path, body) =>+ fetch(`${baseUrl}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ vi.clearAllMocks();+ assertBrandAccess.mockResolvedValue({ brand: { id: BRAND, organization_id: 'o1' }, orgId: 'o1' });+ assertOpportunityAccess.mockResolvedValue({ id: 'o1', brand_id: 'b1', source_data: {} });+ assertPromptAccess.mockResolvedValue([+ { id: 'p1', prompt_sets: { brand_id: 'b1', brands: { organization_id: 'o1' } } },+ ]);+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('the costly AI routes', () => {+ for (const refused of ['analyst', 'agency_partner']) {+ it(`refuse an ${refused}, before anything is generated or queued`, async () => {+ role = refused;+ for (const [path, body, message] of ROUTES) {+ const res = await post(path, body);+ expect(res.status, path).toBe(403);+ expect((await res.json()).error, path).toBe(message);+ }+ expect(generateObject).not.toHaveBeenCalled();+ expect(createJob).not.toHaveBeenCalled();+ });+ }++ it('let a manager past the role check', async () => {+ role = 'manager';+ for (const [path, body, message] of ROUTES) {+ const res = await post(path, body);+ expect(res.status, path).not.toBe(403);+ expect(JSON.stringify(await res.json().catch(() => null)), path).not.toContain(message);+ }+ });+});diff --git a/server/src/routes/prompts-improve-generate.test.js b/server/src/routes/prompts-improve-generate.test.jsindex e5a29cd42..5daf8ccfc 100644--- a/server/src/routes/prompts-improve-generate.test.js+++ b/server/src/routes/prompts-improve-generate.test.js@@ -45,7 +45,7 @@ function table(name) {if (name === 'brands') {return { data: { id: 'b1', name: 'Acme', organization_id: 'o1' }, error: null };}- if (name === 'profiles') return { data: { organization_id: 'o1' }, error: null };+ if (name === 'profiles') return { data: { organization_id: 'o1', role: 'admin' }, error: null };if (name === 'prompt_results') return { data: answers, error: null };if (name === 'prompt_improve_suggestions') {return {diff --git a/server/src/routes/prompts-improve-page-checks.test.js b/server/src/routes/prompts-improve-page-checks.test.jsindex deadb1a6d..f270d29ca 100644--- a/server/src/routes/prompts-improve-page-checks.test.js+++ b/server/src/routes/prompts-improve-page-checks.test.js@@ -17,7 +17,9 @@ function table(name) {return { data: { id: 'p1', text: 'best crm', prompt_sets: { brand_id: 'b1' } }, error: null };}if (name === 'brands') return { data: { id: 'b1', organization_id: 'o1' }, error: null };- if (name === 'profiles') return { data: { organization_id: 'o1' }, error: null };+ // Improve is an admin's or a manager's (costly-roles.test.js).+ if (name === 'profiles')+ return { data: { organization_id: 'o1', role: 'manager' }, error: null };if (name === 'prompt_improve_suggestions') {return {data: { range_key: '7d', region: '', platform_states: [], suggestions: [] },diff --git a/server/src/routes/prompts-improve-send.test.js b/server/src/routes/prompts-improve-send.test.jsindex 47bd18b6a..6f0a89dd1 100644--- a/server/src/routes/prompts-improve-send.test.js+++ b/server/src/routes/prompts-improve-send.test.js@@ -86,7 +86,7 @@ describe('sendImproveActionForKeyUser', () => {rows = {prompts: { id: 'p1', text: 'best crm', prompt_sets: { brand_id: 'b1' } },brands: { id: 'b1', organization_id: 'org-1' },- profiles: { organization_id: 'org-1', role: 'member' },+ profiles: { organization_id: 'org-1', role: 'admin' },prompt_improve_suggestions: {id: 'set-1',range_key: '7d',@@ -114,7 +114,7 @@ describe('sendImproveActionForKeyUser', () => {});it('rejects a key user from another org with 403', async () => {- rows.profiles = { organization_id: 'org-2', role: 'member' };+ rows.profiles = { organization_id: 'org-2', role: 'admin' };await expect(sendImproveActionForKeyUser({ promptId: 'p1', userId: 'u1', body }),@@ -122,6 +122,15 @@ describe('sendImproveActionForKeyUser', () => {expect(sendImproveToActionCenter).not.toHaveBeenCalled();});+ it("refuses an analyst's key before sending, as the dashboard's Send Actions (2026-10-29)", async () => {+ rows.profiles = { organization_id: 'org-1', role: 'analyst' };++ await expect(+ sendImproveActionForKeyUser({ promptId: 'p1', userId: 'u1', body }),+ ).rejects.toMatchObject({ status: 403, message: 'Only admins and managers can use Improve.' });+ expect(sendImproveToActionCenter).not.toHaveBeenCalled();+ });+it('rejects bad suggestions with 400 and the validation details', async () => {const bad = { ...body, suggestions: [{ ...body.suggestions[0], platform: 'nope' }] };diff --git a/server/src/routes/prompts-page-suggestions.test.js b/server/src/routes/prompts-page-suggestions.test.jsindex ec724c294..eca605fa3 100644--- a/server/src/routes/prompts-page-suggestions.test.js+++ b/server/src/routes/prompts-page-suggestions.test.js@@ -27,7 +27,9 @@ function table(name) {error: null,};}- if (name === 'profiles') return { data: { organization_id: profileOrg }, error: null };+ if (name === 'profiles') {+ return { data: { organization_id: profileOrg, role: 'admin' }, error: null };+ }if (name === 'prompts')return { data: [{ id: 'p1', text: 'Best espresso beans?' }], error: null };if (name === 'topics') return { data: [{ name: 'Espresso' }], error: null };diff --git a/server/src/routes/prompts-suggestions-refresh.test.js b/server/src/routes/prompts-suggestions-refresh.test.jsindex efa67f43e..2fa08279d 100644--- a/server/src/routes/prompts-suggestions-refresh.test.js+++ b/server/src/routes/prompts-suggestions-refresh.test.js@@ -27,7 +27,7 @@ function table(name) {const brand = { id: 'b1', name: 'Acme', language: 'en', organization_id: 'o1' };return { data: brand, error: null };}- if (name === 'profiles') return { data: { organization_id: 'o1' }, error: null };+ if (name === 'profiles') return { data: { organization_id: 'o1', role: 'admin' }, error: null };// The topic lookup for each suggestion finds one; the topic list is empty.if (name === 'topics') return { data: single ? { id: 't1' } : [], error: null };return { data: [], error: null };diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.jsindex 59c13f4a8..83ce10f4f 100644--- a/server/src/routes/prompts.js+++ b/server/src/routes/prompts.js@@ -468,12 +468,17 @@ async function findOrCreateTopic(brandId, topicName) {return created?.id ?? null;}+/** Generating suggestions and Improve sets costs AI: admins and managers start it (2026-10-29). */+const SUGGEST_PROMPTS_REFUSAL = 'Only admins and managers can generate prompt suggestions.';+const IMPROVE_REFUSAL = 'Only admins and managers can use Improve.';+router.post('/suggestions/:brandId/refresh',requireFeature('prompt_suggestions'),async (req, res) => {try {const { brand } = await assertBrandAccess(req.params.brandId, req.user.id);+ await assertRole(req.user.id, MANAGER_ROLES, SUGGEST_PROMPTS_REFUSAL);const { suggestions, gscCandidates, gaCandidates, catalogCandidates } =await generateSuggestions(req.params.brandId, {orgId: brand.organization_id,@@ -609,6 +614,7 @@ router.post(return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });}await assertBrandAccess(req.params.brandId, req.user.id);+ await assertRole(req.user.id, MANAGER_ROLES, SUGGEST_PROMPTS_REFUSAL);const context = await loadSuggestionContext(req.params.brandId);const result = await suggestPromptsForPage(req.params.brandId, { ...parsed.data, context });return res.json(result);@@ -819,6 +825,7 @@ router.post('/suggest', requireFeature('prompt_suggestions'), async (req, res) =if (!brandName) {return res.status(400).json({ error: 'brandName is required' });}+ await assertRole(req.user.id, MANAGER_ROLES, SUGGEST_PROMPTS_REFUSAL);const userPrompt = `Brand context (DO NOT use the brand name "${brandName}" in any prompt):Industry: ${industry || 'Not specified'}@@ -845,6 +852,9 @@ Based on this brand's industry and context, generate 10 short, generic search prreturn res.json({ prompts: object.prompts });} catch (error) {+ if (error.status) {+ return res.status(error.status).json({ error: error.message, code: error.code });+ }req.log.error({ err: error }, 'prompt suggestion error');return res.status(500).json({error: 'Failed to generate prompt suggestions',@@ -1189,6 +1199,7 @@ router.post('/:promptId/improve', requireFeature('prompt_improve'), async (req,const range = parseImproveRange(req.body);const promptId = req.params.promptId;const { prompt, brand, brandId } = await loadImprovePrompt(promptId, req.user.id);+ await assertRole(req.user.id, MANAGER_ROLES, IMPROVE_REFUSAL);const [rows,@@ -1424,6 +1435,8 @@ export async function sendImproveAction({ promptId, userId, body }) {throw err;}const { prompt, brandId } = await loadImprovePrompt(promptId, userId);+ // The dashboard's Send Actions and an API key's create_improve_action alike.+ await assertRole(userId, MANAGER_ROLES, IMPROVE_REFUSAL);const { data: set } = await supabaseAdmin.from('prompt_improve_suggestions')diff --git a/server/src/routes/topics-suggest.test.js b/server/src/routes/topics-suggest.test.jsindex 3c075a795..da4b6fdeb 100644--- a/server/src/routes/topics-suggest.test.js+++ b/server/src/routes/topics-suggest.test.js@@ -17,7 +17,12 @@ let baseUrl;async function startApp() {vi.resetModules();vi.doMock('ai', () => ({ generateObject }));- vi.doMock('../lib/access.js', () => ({ assertBrandAccess: vi.fn() }));+ // Generating topic ideas is a manager's (2026-10-29): the caller is one here.+ vi.doMock('../lib/access.js', () => ({+ MANAGER_ROLES: ['admin', 'manager'],+ assertBrandAccess: vi.fn(),+ assertRole: vi.fn(async () => 'manager'),+ }));vi.doMock('../lib/action-center/from-topic-opportunity.js', () => ({sendTopicOpportunityToActionCenter: vi.fn(),}));diff --git a/server/src/routes/topics.js b/server/src/routes/topics.jsindex 926e4b430..26620d509 100644--- a/server/src/routes/topics.js+++ b/server/src/routes/topics.js@@ -210,6 +210,9 @@ IMPORTANT: Generate all topic names in ${langName}.`;.filter((topic) => topic.name);}+/** Generating topic ideas costs AI: admins and managers start it (2026-10-29). */+const SUGGEST_TOPICS_REFUSAL = 'Only admins and managers can generate topic suggestions.';+/*** POST /api/topics/suggest* Body: { brandName, industry, description?, website?, language? }@@ -222,6 +225,7 @@ router.post('/suggest', async (req, res) => {return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });}const { brandName, industry, description, website, language } = parsed.data;+ await assertRole(req.user.id, MANAGER_ROLES, SUGGEST_TOPICS_REFUSAL);const topics = await generateTopicIdeas({brandName,@@ -232,6 +236,9 @@ router.post('/suggest', async (req, res) => {});return res.json({ topics });} catch (error) {+ if (error.status) {+ return res.status(error.status).json({ error: error.message, code: error.code });+ }req.log.error({ err: error }, 'topic suggestion error');return res.status(500).json({error: 'Failed to generate topic suggestions',@@ -276,6 +283,7 @@ router.post(try {const brandId = req.params.brandId;await assertBrandAccess(brandId, req.user.id);+ await assertRole(req.user.id, MANAGER_ROLES, SUGGEST_TOPICS_REFUSAL);const { data: brand } = await supabaseAdmin.from('brands')diff --git a/web/messages/en.json b/web/messages/en.jsonindex 768c42ae9..b03217a98 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -252,6 +252,15 @@"changeContentSettings": "Changing content settings needs a plan"}},+ "managersOnly": {+ "suggestPrompts": "Ask an admin or a manager to generate prompt suggestions.",+ "suggestTopics": "Ask an admin or a manager to generate topic suggestions.",+ "generateOpportunities": "Ask an admin or a manager to generate opportunities.",+ "trackOrSuggestContent": "Ask an admin or a manager to track these prompts or suggest content for them.",+ "generateBrief": "Ask an admin or a manager to generate a brief.",+ "improvePrompt": "Ask an admin or a manager to generate or send Improve suggestions.",+ "addPrompts": "Ask an admin or a manager to add prompts."+ },"common": {"loading": "Loading...","error": "Something went wrong.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsxindex 3f070be71..e84c475e1 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx@@ -312,6 +312,13 @@ describe('Content Opportunities for an analyst or an agency partner', () => {}});+ it('leaves New out, and says who generates opportunities', async () => {+ viewer.canManage = false;+ await render(false);+ expect(labels()).not.toContain('New');+ expect(container.textContent).toContain('Ask an admin or a manager to generate opportunities.');+ });+it("leaves Dismiss out of the row's menu", async () => {viewer.canManage = false;await render(false);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex 4aec7058d..f63fc3254 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -355,6 +355,7 @@ export default function ContentPage() {// actions open the upgrade dialog instead; filters and Export stay open.const { guard, isLocked, openUpgrade } = useUpgradeGate();const tActions = useTranslations('readOnly.actions');+ const tManagers = useTranslations('managersOnly');// The bulk bar's Dismiss and Delete ask first: the upgrade dialog instead.const confirmUnlessLocked =(action: string) => (open: boolean, details: { cancel: () => void }) => {@@ -882,7 +883,9 @@ export default function ContentPage() {timeZone: 'UTC',}): '';- const newButton = (+ // Generating opportunities costs AI: admins and managers start it, and+ // anyone else reads who can.+ const newButton = canManage ? (<ButtononClick={guard(() => setNewOpen(true), { action: tActions('generateOpportunities') })}disabled={generating || loading || limitReached}@@ -893,6 +896,8 @@ export default function ContentPage() {{generating ? <LoadingDots /> : <Plus className="h-4 w-4" />}{generating ? t('generating') : t('new')}</Button>+ ) : (+ <span className="text-xs text-muted-foreground">{tManagers('generateOpportunities')}</span>);const handleSendWebhook = async (id: string) => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsxindex 28f4b6be9..b65bad64c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.test.tsx@@ -21,11 +21,17 @@ vi.mock('@/lib/actions/content', () => ({generateOpportunitiesOnDemand: vi.fn(),getGenerationJobStatus: vi.fn(),}));+// The viewer: a manager unless a test says otherwise.+const viewer = vi.hoisted(() => ({ canManage: true }));+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ canManage: viewer.canManage }),+}));let container: HTMLDivElement;let root: Root;beforeEach(() => {+ viewer.canManage = true;container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -78,6 +84,54 @@ describe('Opportunities — estimated volume (PROMPT-013)', () => {});});+describe("Opportunities' Track and Suggest content by role", () => {+ const render = (suggestions: ReturnType<typeof suggestion>[]) =>+ act(() =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <Opportunities+ brandId="b1"+ suggestions={suggestions}+ trackedTopicIds={[]}+ topics={null}+ entities={null}+ slotsLeft={null}+ contentUsage={null}+ onTracked={() => {}}+ />+ </NextIntlClientProvider>,+ ),+ );+ const labels = () => [...container.querySelectorAll('button')].map((b) => b.textContent);+ const prompt = [suggestion('s3', null, 350)];+ const topic = [suggestion('s1', 'Espresso', 800), suggestion('s2', 'Espresso', 400)];++ it('offers an admin or a manager Track and Suggest content', () => {+ render(prompt);+ expect(labels()).toContain('Track');+ expect(labels()).toContain('Suggest content');+ expect(container.textContent).not.toContain('Ask an admin or a manager');+ });++ it('leaves both out for an analyst or an agency partner, who read who can', () => {+ viewer.canManage = false;+ render(prompt);+ expect(labels()).not.toContain('Track');+ expect(labels()).not.toContain('Suggest content');+ expect(container.textContent).toContain(+ 'Ask an admin or a manager to track these prompts or suggest content for them.',+ );+ });++ it("keeps a topic's Send action for an analyst, without Track", () => {+ viewer.canManage = false;+ render(topic);+ expect(labels()).toContain('Send action');+ expect(labels()).not.toContain('Track 2');+ expect(container.textContent).toContain('Ask an admin or a manager to add prompts.');+ });+});+describe('Opportunities on a read-only workspace (plan not active)', () => {const openUpgrade = vi.fn();const render = (isLocked: boolean) =>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsxindex 27933ba81..032779ca5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx@@ -27,6 +27,7 @@ import type { TopicCompetitors } from '@/lib/insights-topics';import { guessedVolumeEstimate } from '@/lib/volume-estimate';import { EstimateRange } from '@/components/prompts/volume-estimate';import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import { useUserRole } from '@/hooks/use-user-role';/** Items shown, as in the mockup; "See all" opens the rest. */const VISIBLE_ITEMS = 4;@@ -73,6 +74,10 @@ export function Opportunities({// content open the upgrade dialog instead.const { guard } = useUpgradeGate();const tActions = useTranslations('readOnly.actions');+ // Tracking adds prompts and suggesting content costs AI: admins and+ // managers do both; anyone else reads the list and sends a topic's action.+ const { canManage } = useUserRole();+ const tManagers = useTranslations('managersOnly');const failureToast = useFailureToast();const format = useFormatter();const f = numberFormat(useLocale());@@ -311,90 +316,106 @@ export function Opportunities({</CardHeader><CardContent>{result.status === 'ready' ? (- <ul className="divide-y" aria-label={t('listLabel')}>- {result.items.slice(0, VISIBLE_ITEMS).map((item) => {- const isTopic = item.kind === 'topic';- const Icon = isTopic ? Tag : MessageCircle;- const count = item.suggestionIds.length;- const blocked = secondaryBlocked(item);- return (- <li- key={item.key}- className="flex items-center gap-2.5 py-2.5 first:pt-0 last:pb-0"- >- <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">- <Icon className="h-3.5 w-3.5" aria-hidden />- <span className="sr-only">{isTopic ? t('topicKind') : t('promptKind')}</span>- </span>- <span className="min-w-0 flex-1">- <span className="block truncate text-[13px] font-medium" title={item.title}>- {item.title}+ <>+ <ul className="divide-y" aria-label={t('listLabel')}>+ {result.items.slice(0, VISIBLE_ITEMS).map((item) => {+ const isTopic = item.kind === 'topic';+ const Icon = isTopic ? Tag : MessageCircle;+ const count = item.suggestionIds.length;+ const blocked = secondaryBlocked(item);+ return (+ <li+ key={item.key}+ className="flex items-center gap-2.5 py-2.5 first:pt-0 last:pb-0"+ >+ <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">+ <Icon className="h-3.5 w-3.5" aria-hidden />+ <span className="sr-only">{isTopic ? t('topicKind') : t('promptKind')}</span></span>- {/* Text truncates, the range doesn't: its focus ring and button stay whole. */}- <span className="flex min-w-0 items-baseline text-xs text-muted-foreground">- {meta(item).map((part, i) =>- typeof part === 'string' ? (- <span key={i} className="truncate">- {part}- </span>- ) : (- <span key={i} className="shrink-0">- {part}- </span>- ),- )}- </span>- </span>- <span className="flex shrink-0 items-center gap-1.5">- {/* The hints sit on wrappers: a disabled button shows no tooltip. */}- <span- title={- planFull- ? t('planFull')- : isTopic- ? t('trackCountHint', { count, topic: item.title })- : t('trackHint')- }- >- <Button- size="sm"- className="h-7 gap-1.5 px-2.5 text-xs"- disabled={planFull || busy !== null}- onClick={guard(() => track(item), { action: tActions('trackPrompts') })}- >- {/* Track N adds one prompt at a time, so a big topic takes a moment. */}- {busy === item.key && (- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[13px] font-medium" title={item.title}>+ {item.title}+ </span>+ {/* Text truncates, the range doesn't: its focus ring and button stay whole. */}+ <span className="flex min-w-0 items-baseline text-xs text-muted-foreground">+ {meta(item).map((part, i) =>+ typeof part === 'string' ? (+ <span key={i} className="truncate">+ {part}+ </span>+ ) : (+ <span key={i} className="shrink-0">+ {part}+ </span>+ ),)}- {isTopic ? t('trackCount', { count }) : t('track')}- </Button>+ </span></span>- <span- title={- blocked ??- (isTopic ? t('sendActionHint', { topic: item.title }) : suggestHint)- }- >- <Button- variant="outline"- size="sm"- className="h-7 gap-1.5 px-2.5 text-xs"- disabled={blocked !== null || working.has(item.key)}- onClick={guard(() => (isTopic ? sendAction(item) : suggestContent(item)), {- action: tActions(isTopic ? 'sendAction' : 'suggestContent'),- })}- >- {working.has(item.key) && (- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />- )}- {isTopic ? t('sendAction') : t('suggestContent')}- </Button>+ <span className="flex shrink-0 items-center gap-1.5">+ {/* The hints sit on wrappers: a disabled button shows no tooltip. */}+ {canManage && (+ <span+ title={+ planFull+ ? t('planFull')+ : isTopic+ ? t('trackCountHint', { count, topic: item.title })+ : t('trackHint')+ }+ >+ <Button+ size="sm"+ className="h-7 gap-1.5 px-2.5 text-xs"+ disabled={planFull || busy !== null}+ onClick={guard(() => track(item), { action: tActions('trackPrompts') })}+ >+ {/* Track N adds one prompt at a time, so a big topic takes a moment. */}+ {busy === item.key && (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ )}+ {isTopic ? t('trackCount', { count }) : t('track')}+ </Button>+ </span>+ )}+ {(isTopic || canManage) && (+ <span+ title={+ blocked ??+ (isTopic ? t('sendActionHint', { topic: item.title }) : suggestHint)+ }+ >+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5 px-2.5 text-xs"+ disabled={blocked !== null || working.has(item.key)}+ onClick={guard(+ () => (isTopic ? sendAction(item) : suggestContent(item)),+ {+ action: tActions(isTopic ? 'sendAction' : 'suggestContent'),+ },+ )}+ >+ {working.has(item.key) && (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ )}+ {isTopic ? t('sendAction') : t('suggestContent')}+ </Button>+ </span>+ )}</span>- </span>- </li>- );- })}- </ul>+ </li>+ );+ })}+ </ul>+ {!canManage && (+ <p className="pt-2.5 text-xs text-muted-foreground">+ {result.items.slice(0, VISIBLE_ITEMS).some((item) => item.kind !== 'topic')+ ? tManagers('trackOrSuggestContent')+ : tManagers('addPrompts')}+ </p>+ )}+ </>) : (<div className="flex flex-col items-center justify-center gap-2 py-6 text-center"><p className="max-w-xs text-xs text-muted-foreground">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 b0b51cc17..1e55f7b17 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@@ -503,6 +503,10 @@ describe('MentionsListTab', () => {});const drawer = document.body.querySelector('[role="dialog"]') as HTMLElement;expect(drawer.textContent).not.toContain('Sentiment is wrong?');+ // Suggesting content costs AI: an admin's or a manager's (2026-10-29).+ const labels = [...drawer.querySelectorAll('button')].map((b) => b.textContent);+ expect(labels).toContain('Send to Action Center');+ expect(labels).not.toContain('Suggest content');});it('keeps its page when a read fails, and says so', async () => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsxindex 57ca3e1eb..627a909e2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx@@ -19,6 +19,7 @@ import {} from '@/components/ui/sheet';import { Skeleton } from '@/components/ui/skeleton';import { Link } from '@/i18n/navigation';+import { useUserRole } from '@/hooks/use-user-role';import { getMentionResponse } from '@/lib/actions/mentions';import { classifyDomain, extractHostname, SOURCE_CATEGORY_LABELS } from '@/lib/citations/classify';import { stripEntityMarkup } from '@/lib/entity-markup';@@ -103,6 +104,8 @@ export function ResponseDrawer({}) {const t = useTranslations('mentions.drawer');const tActions = useTranslations('mentions.actions');+ // Suggesting content costs AI: admins and managers start it.+ const { canManage } = useUserRole();const locale = useLocale();const [loaded, setLoaded] = useState<Loaded | null>(null);const [showResponse, setShowResponse] = useState(true);@@ -373,15 +376,17 @@ export function ResponseDrawer({<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>+ {canManage && (+ <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>+ )}<Buttonvariant="outline"size="sm"diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsxindex fdac16984..4c5042633 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx@@ -312,6 +312,7 @@ describe('SuggestionsCard by role', () => {it('shows an analyst Dismiss and Clear All, but no way to add a prompt', async () => {viewer.role = 'analyst';await render(2);+ expect(labels()).not.toContain('New');expect(labels()).not.toContain('Add All');expect(labels()).not.toContain('Add to tracked prompts');expect(labels()).toContain('Clear All');@@ -327,10 +328,31 @@ describe('SuggestionsCard by role', () => {}});+ it('tells an analyst who generates suggestions, instead of Generate Suggestions', async () => {+ viewer.role = 'analyst';+ await render(0);+ expect(labels()).not.toContain('Generate Suggestions');+ expect(container.textContent).toContain(+ 'Ask an admin or a manager to generate prompt suggestions.',+ );+ });++ it('offers a manager Generate Suggestions on an empty list', async () => {+ viewer.role = 'manager';+ await render(0);+ expect(labels()).toContain('Generate Suggestions');+ });+it('shows a manager every action', async () => {viewer.role = 'manager';await render(1);- for (const label of ['Add All', 'Clear All', 'Add to tracked prompts', 'Dismiss suggestion']) {+ for (const label of [+ 'New',+ 'Add All',+ 'Clear All',+ 'Add to tracked prompts',+ 'Dismiss suggestion',+ ]) {expect(labels(), label).toContain(label);}});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsxindex 64362f18f..56531b131 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx@@ -322,6 +322,8 @@ export function SuggestionsCard({// open to analysts too, as the server and the table's update rule allow.const { role, canManage } = useUserRole();const canDismiss = canManage || role === 'analyst';+ // Generating suggestions costs AI: admins and managers start it.+ const tManagers = useTranslations('managersOnly');// One method note for the list's volume ranges (PROMPT-013).const volumeNote = useMemo(() => createEstimateNoteHandle(), []);const [suggestions, setSuggestions] = useState<PromptSuggestion[]>([]);@@ -576,20 +578,22 @@ export function SuggestionsCard({/></div>- <Button- onClick={guard(handleRefresh, { action: tActions('suggestPrompts') })}- disabled={refreshing}- size="sm"- variant="outline"- className="gap-2"- >- {refreshing ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <RefreshCw className="h-3.5 w-3.5" />- )}- {refreshing ? 'Generating…' : 'New'}- </Button>+ {canManage && (+ <Button+ onClick={guard(handleRefresh, { action: tActions('suggestPrompts') })}+ disabled={refreshing}+ size="sm"+ variant="outline"+ className="gap-2"+ >+ {refreshing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <RefreshCw className="h-3.5 w-3.5" />+ )}+ {refreshing ? 'Generating…' : 'New'}+ </Button>+ )}{canManage && (<Button@@ -691,7 +695,7 @@ export function SuggestionsCard({: `${joinNames(notice.names)} is connected and its first sync is in progress. Suggestions from it will be available once it finishes, usually within a few minutes.`}</p></div>- {notice.kind === 'ready' && (+ {notice.kind === 'ready' && canManage && (<ButtononClick={guard(handleRefresh, { action: tActions('suggestPrompts') })}disabled={refreshing}@@ -726,23 +730,31 @@ export function SuggestionsCard({<div className="flex flex-col items-center justify-center py-10 text-center"><Sparkles className="h-8 w-8 text-muted-foreground/40 mb-2" /><p className="text-sm font-medium mb-1">No suggestions right now</p>- <p className="text-xs text-muted-foreground mb-3 max-w-sm">- Click refresh to generate new prompt ideas tailored to your brand and competitor- activity.- </p>- <Button- onClick={guard(handleRefresh, { action: tActions('suggestPrompts') })}- disabled={refreshing}- size="sm"- className="gap-2"- >- {refreshing ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Sparkles className="h-3.5 w-3.5" />- )}- Generate Suggestions- </Button>+ {canManage ? (+ <>+ <p className="text-xs text-muted-foreground mb-3 max-w-sm">+ Click refresh to generate new prompt ideas tailored to your brand and competitor+ activity.+ </p>+ <Button+ onClick={guard(handleRefresh, { action: tActions('suggestPrompts') })}+ disabled={refreshing}+ size="sm"+ className="gap-2"+ >+ {refreshing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Sparkles className="h-3.5 w-3.5" />+ )}+ Generate Suggestions+ </Button>+ </>+ ) : (+ <p className="text-xs text-muted-foreground max-w-sm">+ {tManagers('suggestPrompts')}+ </p>+ )}</div>) : (<div className="space-y-2">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.test.tsxnew file mode 100644index 000000000..3fb06789b--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.test.tsx@@ -0,0 +1,88 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import { TopicSuggestionsCard } from './_topic-suggestions-card';++/**+ * Topic Suggestions by role: generating ideas costs AI, so Generate and+ * Refresh are an admin's or a manager's (2026-10-29); anyone else reads the+ * ideas and who can generate them.+ */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const actions = vi.hoisted(() => ({+ getTopicSuggestions: vi.fn(),+ refreshTopicSuggestions: vi.fn(),+ acceptTopicSuggestion: vi.fn(),+ dismissTopicSuggestion: vi.fn(),+}));+vi.mock('@/lib/actions/topic-suggestions', () => actions);+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ vi.clearAllMocks();+ // The card remembers being open; each test starts it collapsed.+ try {+ localStorage.clear();+ } catch {+ // No storage: the card starts collapsed anyway.+ }+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++async function render(canManage: boolean, ideas: { id: string; name: string }[] = []) {+ actions.getTopicSuggestions.mockResolvedValue(+ ideas.map((idea) => ({ ...idea, brand_id: 'b1', status: 'new', reason: null })),+ );+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <TopicSuggestionsCard brandId="b1" canManage={canManage} />+ </NextIntlClientProvider>,+ );+ });+ // Collapsed at first: opening it reads the ideas.+ await act(async () => container.querySelector<HTMLElement>('[aria-expanded]')!.click());+ await act(async () => {});+}++const labels = () => [...container.querySelectorAll('button')].map((b) => b.textContent);++describe('TopicSuggestionsCard by role', () => {+ it('offers an admin or a manager Generate Suggestions and Refresh', async () => {+ await render(true);+ expect(labels()).toContain('Generate Suggestions');+ expect(labels()).toContain('Refresh');+ expect(container.textContent).not.toContain('Ask an admin or a manager');+ });++ it('tells an analyst or an agency partner who generates them, with no way to start it', async () => {+ await render(false);+ expect(labels()).not.toContain('Generate Suggestions');+ expect(labels()).not.toContain('Refresh');+ expect(container.textContent).toContain(+ 'Ask an admin or a manager to generate topic suggestions.',+ );+ expect(actions.refreshTopicSuggestions).not.toHaveBeenCalled();+ });++ it('shows an analyst the ideas, without accepting or dismissing them', async () => {+ await render(false, [{ id: 't1', name: 'Office coffee' }]);+ expect(container.textContent).toContain('Office coffee');+ expect(container.querySelectorAll('li button')).toHaveLength(0);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsxindex f346dccd9..b0811cbe6 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx@@ -53,6 +53,7 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)// dismissing open the upgrade dialog instead.const { guard } = useUpgradeGate();const tActions = useTranslations('readOnly.actions');+ const tManagers = useTranslations('managersOnly');useEffect(() => {try {@@ -248,7 +249,7 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)? 'Generate AI topic ideas tailored to your brand and industry. Topics you already track are excluded automatically.': 'No topic suggestions have been generated for this brand yet.'}</p>- {canManage && (+ {canManage ? (<ButtononClick={guard(handleRefresh, { action: tActions('suggestTopics') })}disabled={refreshing}@@ -262,6 +263,8 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props))}Generate Suggestions</Button>+ ) : (+ <p className="text-xs text-muted-foreground">{tManagers('suggestTopics')}</p>)}</div>) : (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsxindex 75b1faca2..558f666a9 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsx@@ -35,6 +35,11 @@ vi.mock('./_page-prompts-dialog', () => ({// The untracked queries card has its own tests.vi.mock('./_untracked-queries', () => ({ UntrackedQueriesCard: () => null }));+// The viewer: a manager unless a test says otherwise.+const viewer = vi.hoisted(() => ({ canManage: true }));+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ canManage: viewer.canManage }),+}));const { GoogleSection } = await import('./_google-section');@@ -88,6 +93,7 @@ let container: HTMLDivElement;let root: Root;beforeEach(() => {+ viewer.canManage = true;dialogPages.length = 0;getTrafficGooglePages.mockReset().mockResolvedValue(pages());container = document.createElement('div');@@ -159,6 +165,15 @@ describe('GoogleSection', () => {expect(dialogPages.at(-1)).toBe('/faq');});+ it('says who adds prompts for a page, instead of Add prompts, to an analyst', async () => {+ viewer.canManage = false;+ await render();+ expect([...container.querySelectorAll('button')].map((b) => b.textContent)).not.toContain(+ 'Add prompts',+ );+ expect(text()).toContain('Ask an admin or a manager to add prompts.');+ });+it('says how many more pages the export has', async () => {getTrafficGooglePages.mockResolvedValue(pages({ count: 14 }));await render();diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsxindex 64355081b..d2bcbba12 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsx@@ -30,6 +30,7 @@ import { UntrackedQueriesCard } from './_untracked-queries';import { getTrafficGooglePages } from '@/lib/traffic-reads';import { useRangeReady } from './_range-ready';import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import { useUserRole } from '@/hooks/use-user-role';/** CTR as the table shows it: "3.1%". */function ctr(clicks: number, impressions: number): string {@@ -101,6 +102,9 @@ export function GoogleSection({// AI as it opens) opens the upgrade dialog instead.const { guard } = useUpgradeGate();const tActions = useTranslations('readOnly.actions');+ // Suggesting prompts for a page costs AI and tracking adds prompts: admins and managers.+ const { canManage } = useUserRole();+ const tManagers = useTranslations('managersOnly');const gscReady = source === null || googleSourceStatus(source) === 'connected';@@ -190,6 +194,8 @@ export function GoogleSection({>{t('taking.positions')}</Link>+ ) : !canManage ? (+ <span className="text-xs text-muted-foreground">{tManagers('addPrompts')}</span>) : (<Buttonsize="sm"diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsxindex 4ee20e7e1..35e4f55c6 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.test.tsx@@ -48,6 +48,11 @@ vi.mock('@/i18n/navigation', () => ({useRouter: () => ({ push }),}));vi.mock('sonner', () => ({ toast }));+// The viewer: a manager unless a test says otherwise.+const viewer = vi.hoisted(() => ({ canManage: true }));+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ canManage: viewer.canManage }),+}));const suggestForPage = vi.fn();vi.mock('@/lib/actions/content', () => ({generateOpportunitiesOnDemand: vi.fn(),@@ -118,6 +123,7 @@ let container: HTMLDivElement;let root: Root;beforeEach(() => {+ viewer.canManage = true;getTrafficPages.mockReset();sendTrafficPagesToActionCenter.mockReset();runAudit.mockReset();@@ -219,6 +225,25 @@ describe('PagesCard', () => {expect(push).toHaveBeenCalledWith('/dashboard/audit/audit-1');});+ it('leaves an analyst Audit and Send, not Add prompts or Suggest content', async () => {+ viewer.canManage = false;+ getTrafficPages.mockResolvedValue(+ pages([page({ citations: 6 }), page({ page: '/about', valueRank: 2 })]),+ );+ await render();+ const labels = () =>+ [...document.body.querySelectorAll('button, [role="menuitem"]')].map((el) =>+ el.textContent?.trim(),+ );+ expect(labels()).not.toContain('Add prompts');+ expect(container.textContent).toContain('Ask an admin or a manager to add prompts.');+ expect(labels()).toContain('Audit page');+ const menu = container.querySelector<HTMLElement>('[aria-label^="More actions for"]')!;+ await act(async () => menu.click());+ expect(labels()).toContain('Send to Action Center');+ expect(labels()).not.toContain('Suggest content');+ });+it('audits, suggests and sends nothing on a read-only workspace: the upgrade dialog instead', async () => {openUpgrade.mockReset();getTrafficPages.mockResolvedValue(diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsxindex 3827c9f2f..fb129a42f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_pages-card.tsx@@ -43,6 +43,7 @@ import { PagePromptsDialog } from './_page-prompts-dialog';import { getTrafficPages } from '@/lib/traffic-reads';import { useRangeReady } from './_range-ready';import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import { useUserRole } from '@/hooks/use-user-role';/*** Pages: which answers send visitors (AT-006, spec §3.5, "the@@ -206,6 +207,10 @@ export function PagesCard({// dialog asks the AI as it opens), open the upgrade dialog instead.const { guard, isLocked } = useUpgradeGate();const tActions = useTranslations('readOnly.actions');+ // Suggesting prompts or content for a page costs AI, and tracking adds+ // prompts: admins and managers do both.+ const { canManage } = useUserRole();+ const tManagers = useTranslations('managersOnly');// The page whose suggested prompts are open (part B2); each opening starts// afresh, and tracking some reads the list again for its prompt counts.const [promptsFor, setPromptsFor] = useState<string | null>(null);@@ -288,11 +293,14 @@ export function PagesCard({{ action: tActions('suggestPrompts') },);- const addPromptsButton = (page: string) => (- <Button size="sm" variant="outline" className="h-7 text-xs" onClick={() => openPrompts(page)}>- {t('addPrompts')}- </Button>- );+ const addPromptsButton = (page: string) =>+ canManage ? (+ <Button size="sm" variant="outline" className="h-7 text-xs" onClick={() => openPrompts(page)}>+ {t('addPrompts')}+ </Button>+ ) : (+ <span className="text-xs text-muted-foreground">{tManagers('addPrompts')}</span>+ );/** A No AI traffic row's next step, by why AI engines skip it. */const reasonAction = (row: TrafficPageRow) =>@@ -330,20 +338,22 @@ export function PagesCard({<Send className="h-3.5 w-3.5" />{t('actions.sendToActionCenter')}</DropdownMenuItem>- {addPrompts && (+ {addPrompts && canManage && (<DropdownMenuItem className="gap-2" onClick={() => openPrompts(row.page)}><ListPlus className="h-3.5 w-3.5" />{t('addPrompts')}</DropdownMenuItem>)}- <DropdownMenuItem- className="gap-2"- disabled={pageActions.suggesting !== null}- onClick={() => void pageActions.suggestContent(row.page, openPrompts)}- >- <Lightbulb className="h-3.5 w-3.5" />- {t('actions.suggestContent')}- </DropdownMenuItem>+ {canManage && (+ <DropdownMenuItem+ className="gap-2"+ disabled={pageActions.suggesting !== null}+ onClick={() => void pageActions.suggestContent(row.page, openPrompts)}+ >+ <Lightbulb className="h-3.5 w-3.5" />+ {t('actions.suggestContent')}+ </DropdownMenuItem>+ )}</DropdownMenuContent></DropdownMenu></div>diff --git a/web/src/components/content/opportunity-actions.tsx b/web/src/components/content/opportunity-actions.tsxindex 16ec10db3..49128939a 100644--- a/web/src/components/content/opportunity-actions.tsx+++ b/web/src/components/content/opportunity-actions.tsx@@ -64,7 +64,8 @@ export function OpportunityActions({generating: boolean;/** Why it can't be generated now (the month's briefs are used up). */blockedReason: string | null;- onGenerate: () => void;+ /** Null for a member who can't generate one (admins and managers do). */+ onGenerate: (() => void) | null;};/*** The Content Editor: the draft written for this opportunity (undefined@@ -127,17 +128,19 @@ export function OpportunityActions({{t('briefGenerated')}</Button>) : (- <Button- variant="outline"- size="sm"- onClick={brief.onGenerate}- disabled={brief.generating || brief.blockedReason !== null}- title={brief.blockedReason ?? undefined}- className="gap-2"- >- {brief.generating ? <LoadingDots /> : <Sparkles className="h-4 w-4" />}- {brief.generating ? t('generatingBrief') : t('generateBrief')}- </Button>+ brief.onGenerate && (+ <Button+ variant="outline"+ size="sm"+ onClick={brief.onGenerate}+ disabled={brief.generating || brief.blockedReason !== null}+ title={brief.blockedReason ?? undefined}+ className="gap-2"+ >+ {brief.generating ? <LoadingDots /> : <Sparkles className="h-4 w-4" />}+ {brief.generating ? t('generatingBrief') : t('generateBrief')}+ </Button>+ ))}{showContent &&(content.lookupFailed ? (diff --git a/web/src/components/content/opportunity-detail.test.tsx b/web/src/components/content/opportunity-detail.test.tsxindex f7ec214bf..26e80a05c 100644--- a/web/src/components/content/opportunity-detail.test.tsx+++ b/web/src/components/content/opportunity-detail.test.tsx@@ -203,6 +203,33 @@ describe('the brief quota without an active plan', () => {});});+describe("the opportunity panel's costly AI work", () => {+ const labels = () =>+ [...document.body.querySelectorAll('button, [role="menuitem"]')].map((el) =>+ el.textContent?.trim(),+ );+ const openMore = () =>+ act(async () => container.querySelector<HTMLElement>('[aria-label="More actions"]')!.click());++ it('offers an admin or a manager Generate Brief and Another angle', async () => {+ await render(false);+ expect(labels()).toContain('Generate Brief');+ expect(labels()).toContain('Generate Content Brief');+ await openMore();+ expect(labels()).toContain('Another angle');+ });++ it('leaves them out for an analyst or an agency partner, saying who generates a brief', async () => {+ viewer.canManage = false;+ await render(false);+ expect(labels()).not.toContain('Generate Brief');+ expect(labels()).not.toContain('Generate Content Brief');+ expect(container.textContent).toContain('Ask an admin or a manager to generate a brief.');+ await openMore();+ expect(labels()).not.toContain('Another angle');+ });+});+describe("the opportunity panel's Dismiss", () => {const menuItems = async () => {await act(async () =>diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsxindex aa948b7d2..d5b0eec23 100644--- a/web/src/components/content/opportunity-detail.tsx+++ b/web/src/components/content/opportunity-detail.tsx@@ -163,6 +163,7 @@ export function OpportunityDetail({const { guard, isLocked } = useUpgradeGate();const tActions = useTranslations('readOnly.actions');const tReadOnly = useTranslations('readOnly');+ const tManagers = useTranslations('managersOnly');const [opportunity, setOpportunity] = useState<ContentOpportunity | null>(null);const [loading, setLoading] = useState(true);@@ -579,9 +580,10 @@ export function OpportunityDetail({generated: !!brief,generating: generatingBrief,blockedReason: quotaExhausted ? t('briefLimitReached') : null,- onGenerate: guard(() => void handleGenerateBrief(), {- action: tActions('generateBrief'),- }),+ // Generating costs AI: admins and managers start it.+ onGenerate: canManage+ ? guard(() => void handleGenerateBrief(), { action: tActions('generateBrief') })+ : null,}}content={{draftId:@@ -608,7 +610,7 @@ export function OpportunityDetail({// Another angle is written from a cluster or a prompt; a task sent// from the Action Center (AC-004) has neither.alternative={- opportunity.source !== 'action'+ canManage && opportunity.source !== 'action'? {running: alternativeRunning,onOpen: guard(() => setAlternativeOpen(true), {@@ -904,14 +906,18 @@ export function OpportunityDetail({Generate an AI-powered content brief with a suggested title, outline, targetkeywords, and competitor insights.</p>- <Button- onClick={guard(handleGenerateBrief, { action: tActions('generateBrief') })}- disabled={generatingBrief}- className="gap-2"- >- {generatingBrief ? <LoadingDots /> : <Sparkles className="h-4 w-4" />}- {generatingBrief ? 'Generating...' : 'Generate Content Brief'}- </Button>+ {canManage ? (+ <Button+ onClick={guard(handleGenerateBrief, { action: tActions('generateBrief') })}+ disabled={generatingBrief}+ className="gap-2"+ >+ {generatingBrief ? <LoadingDots /> : <Sparkles className="h-4 w-4" />}+ {generatingBrief ? 'Generating...' : 'Generate Content Brief'}+ </Button>+ ) : (+ <p className="text-xs text-muted-foreground">{tManagers('generateBrief')}</p>+ )}{quotaLimited && (<p className="text-xs text-muted-foreground mt-3 tabular-nums">{noPlandiff --git a/web/src/components/prompts/prompt-improve-tab.test.tsx b/web/src/components/prompts/prompt-improve-tab.test.tsxindex 7ed7ae167..af9412d0f 100644--- a/web/src/components/prompts/prompt-improve-tab.test.tsx+++ b/web/src/components/prompts/prompt-improve-tab.test.tsx@@ -23,6 +23,12 @@ vi.mock('@/components/providers/upgrade-gate', () => ({useUpgradeGate: () => gate,}));+// The viewer: a manager unless a test says otherwise.+const viewer = vi.hoisted(() => ({ canManage: true }));+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ canManage: viewer.canManage }),+}));+vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (<a href={href} {...props}>@@ -80,6 +86,7 @@ const generateButton = () =>)!;beforeEach(() => {+ viewer.canManage = true;container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -144,6 +151,19 @@ describe('the Improve tab’s budget', () => {});});+describe('the Improve tab for an analyst or an agency partner', () => {+ const quota = { unlimited: false, exhausted: false, generationsLeft: 3, percentLeft: 60 };++ it('says who generates, instead of Generate suggestions', async () => {+ viewer.canManage = false;+ await render(quota, 'growth');+ expect(container.textContent).not.toContain('Generate suggestions');+ expect(container.textContent).toContain(+ 'Ask an admin or a manager to generate or send Improve suggestions.',+ );+ });+});+describe('the Improve tab’s dates', () => {it('reads them in English whatever the browser’s locale is', async () => {// A Turkish browser: a date without a locale would read "17.10.2026".diff --git a/web/src/components/prompts/prompt-improve-tab.tsx b/web/src/components/prompts/prompt-improve-tab.tsxindex ca68551f8..0fb06e718 100644--- a/web/src/components/prompts/prompt-improve-tab.tsx+++ b/web/src/components/prompts/prompt-improve-tab.tsx@@ -38,6 +38,7 @@ import { Textarea } from '@/components/ui/textarea';import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';import { cn } from '@/lib/utils';import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import { useUserRole } from '@/hooks/use-user-role';import { formatDate, formatDateTime } from '@/lib/format';import { PLANS, hasFeature, type PlanId } from '@/config/plans';import {@@ -280,6 +281,9 @@ export function ImproveTab({ improve }: { improve: ImproveController }) {} = improve;const [confirmRegenerate, setConfirmRegenerate] = useState(false);const outOfQuota = !!quota?.exhausted;+ // Generating and sending cost AI: admins and managers do them; anyone reads the set.+ const { canManage } = useUserRole();+ const tManagers = useTranslations('managersOnly');if (status === 'locked') return <LockedImprove />;if (status === 'error') {@@ -310,13 +314,17 @@ export function ImproveTab({ improve }: { improve: ImproveController }) {brand is missing or ranked late.</p>{error && <p className="text-xs text-red-600 dark:text-red-400">{friendlyError(error)}</p>}- <div className="flex flex-wrap items-center gap-3">- <Button size="sm" onClick={generate} disabled={outOfQuota}>- <Sparkles />- Generate suggestions- </Button>- <QuotaNote quota={quota} planId={planId} />- </div>+ {canManage ? (+ <div className="flex flex-wrap items-center gap-3">+ <Button size="sm" onClick={generate} disabled={outOfQuota}>+ <Sparkles />+ Generate suggestions+ </Button>+ <QuotaNote quota={quota} planId={planId} />+ </div>+ ) : (+ <p className="text-xs text-muted-foreground">{tManagers('improvePrompt')}</p>+ )}</div>);}@@ -355,15 +363,17 @@ export function ImproveTab({ improve }: { improve: ImproveController }) {<span className="text-sky-900 dark:text-sky-200">New runs have arrived since these suggestions were generated.</span>- <Button- size="xs"- variant="outline"- disabled={outOfQuota}- onClick={() => (dirty ? setConfirmRegenerate(true) : generate())}- >- <RefreshCw />- Regenerate- </Button>+ {canManage && (+ <Button+ size="xs"+ variant="outline"+ disabled={outOfQuota}+ onClick={() => (dirty ? setConfirmRegenerate(true) : generate())}+ >+ <RefreshCw />+ Regenerate+ </Button>+ )}</div>)}{error && <p className="text-xs text-red-600 dark:text-red-400">{friendlyError(error)}</p>}@@ -405,7 +415,11 @@ export function ImproveTab({ improve }: { improve: ImproveController }) {)}</span><span className="flex flex-wrap items-center gap-2">- {confirmRegenerate ? (+ {!canManage ? (+ !sentLatest && (+ <span className="text-xs text-muted-foreground">{tManagers('improvePrompt')}</span>+ )+ ) : confirmRegenerate ? (<span className="flex items-center gap-2 text-xs">Discard your edits?<Button size="xs" variant="outline" onClick={() => setConfirmRegenerate(false)}>@@ -441,10 +455,12 @@ export function ImproveTab({ improve }: { improve: ImproveController }) {<ArrowUpRight /></Link>) : (- <Button size="sm" onClick={send} disabled={sending || summary.selected === 0}>- {sending ? <Loader2 className="animate-spin" /> : <Send />}- Send Actions- </Button>+ canManage && (+ <Button size="sm" onClick={send} disabled={sending || summary.selected === 0}>+ {sending ? <Loader2 className="animate-spin" /> : <Send />}+ Send Actions+ </Button>+ ))}</span></div>