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(content): send an opportunity or one of its assets to the Action Center (#943)
Gökhan Geyik9611c7b9bc97
diff --git a/server/src/lib/action-center/from-opportunity.js b/server/src/lib/action-center/from-opportunity.jsnew file mode 100644index 000000000..0ad21716f--- /dev/null+++ b/server/src/lib/action-center/from-opportunity.js@@ -0,0 +1,195 @@+/**+ * Turning a content opportunity, or one of its assets, into an Action Center+ * action (#857, Phase 2).+ *+ * Signal-driven actions come from the nightly engine (generate.js). These are+ * created by a person instead, so they skip the definitions and the candidate+ * queue, and plan their tasks from the asset itself: what kind of work it is+ * (owned or earned) and what the opportunity decided to do with the brand's+ * page. The tasks are the library's own, so they render, run and get+ * measured like any other action's.+ */++import supabaseAdmin from '../../config/supabase.js';+import { resolveBrandSources } from './sources.js';+import { planTasks } from './tasks/plan.js';++export const OPPORTUNITY_ACTION_KIND = 'content_opportunity';++/** What a completed opportunity action is measured on (validate.js). */+const KPI_KEYS = ['ai_visibility', 'citations', 'mentions'];++/** The key an opportunity sent as a whole is recorded under. */+export const WHOLE = 'all';++const OWNED_WORK = {+ create: ['create_content_brief', 'create_content_draft', 'add_internal_links'],+ refresh: ['refresh_content'],+ // optimize, expand, consolidate and defend all work on an existing page.+ default: ['optimize_content', 'add_internal_links'],+};++const EARNED_WORK = {+ third_party_article: ['identify_target_sources', 'prepare_contribution', 'execute_outreach'],+ backlink: ['identify_target_sources', 'prepare_outreach', 'execute_outreach'],+};++/** The library tasks one asset needs, in order. */+export function assetTasks(asset) {+ if (asset.channel === 'earned') {+ const work = EARNED_WORK[asset.type] || EARNED_WORK.third_party_article;+ return [+ ...work,+ 'track_third_party_status',+ asset.type === 'backlink' ? 'validate_third_party_citation' : 'validate_third_party_presence',+ ];+ }+ return [+ ...(OWNED_WORK[asset.decision] || OWNED_WORK.default),+ 'publish_content',+ 'validate_ai_visibility',+ ];+}++/**+ * The tasks for several assets as one plan: each task once, the work first,+ * then every check, then the outcome measurement last.+ */+export function combinedTasks(assets) {+ const all = [...new Set(assets.flatMap(assetTasks))];+ const isCheck = (id) => id.startsWith('validate_');+ return [...all.filter((id) => !isCheck(id)), ...all.filter(isCheck), 'measure_action_outcome'];+}++/**+ * An opportunity's assets. Opportunities written before assets existed get+ * one, from their own type and decision.+ */+export function opportunityAssets(opportunity) {+ const assets = opportunity.source_data?.assets;+ if (Array.isArray(assets) && assets.length) return assets;+ return [+ {+ key: 'a1',+ type: null,+ channel: opportunity.type === 'earned' ? 'earned' : 'owned',+ decision: opportunity.decision || 'create',+ title: opportunity.title,+ pages: opportunity.source_data?.targetPages || [],+ },+ ];+}++const ACTIVE = ['new', 'in_progress', 'on_hold'];++/**+ * Creates the action, or returns the open one if this opportunity or asset+ * was already sent. Records the action on the opportunity and marks it sent.+ *+ * @param {object} opportunity - the content_opportunities row+ * @param {{ assetKey?: string|null, userId: string }} opts+ * @returns {Promise<{ actionId: string, created: boolean }>}+ */+export async function sendToActionCenter(opportunity, { assetKey = null, userId }) {+ const assets = opportunityAssets(opportunity);+ const chosen = assetKey ? assets.filter((a) => a.key === assetKey) : assets;+ if (!chosen.length) {+ const err = new Error('Asset not found');+ err.status = 404;+ throw err;+ }++ const key = assetKey || WHOLE;+ const dedupKey = `opportunity:${opportunity.id}:${key}`;+ const { data: open } = await supabaseAdmin+ .from('actions')+ .select('id')+ .eq('brand_id', opportunity.brand_id)+ .eq('dedup_key', dedupKey)+ .in('status', ACTIVE)+ .maybeSingle();+ if (open) return { actionId: open.id, created: false };++ const sd = opportunity.source_data || {};+ const prompts = sd.prompts || [];+ const payload = {+ source: OPPORTUNITY_ACTION_KIND,+ opportunityId: opportunity.id,+ assetKey,+ title: assetKey ? chosen[0].title : opportunity.title,+ decision: chosen[0].decision,+ assets: chosen.map(({ key: k, type, channel, decision, title }) => ({+ key: k,+ type,+ channel,+ decision,+ title,+ })),+ pages: [...new Set(chosen.flatMap((a) => (a.pages || []).map((p) => p.url)))],+ targetEntity: 'prompts',+ targetCount: prompts.length,+ targets: prompts.slice(0, 50),+ contentExists: chosen.some((a) => a.decision !== 'create'),+ };++ const { data: action, error } = await supabaseAdmin+ .from('actions')+ .insert({+ brand_id: opportunity.brand_id,+ category: 'growth',+ kind: OPPORTUNITY_ACTION_KIND,+ definition_version: 1,+ impact: opportunity.impact,+ payload,+ kpi_keys: KPI_KEYS,+ baseline: {},+ dedup_key: dedupKey,+ })+ .select('id')+ .single();+ if (error) throw new Error(error.message);++ const sources = await resolveBrandSources(opportunity.brand_id);+ const plan = planTasks(+ { id: OPPORTUNITY_ACTION_KIND, tasks: combinedTasks(chosen) },+ { 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,+ })),+ );+ if (tasksErr) throw new Error(tasksErr.message);++ await supabaseAdmin.from('action_events').insert({+ action_id: action.id,+ event: 'created',+ actor_id: userId,+ data: {+ source: OPPORTUNITY_ACTION_KIND,+ opportunityId: opportunity.id,+ assetKey,+ impact: opportunity.impact,+ taskCount: plan.length,+ },+ });++ const { error: oppErr } = await supabaseAdmin+ .from('content_opportunities')+ .update({+ source_data: { ...sd, actions: { ...(sd.actions || {}), [key]: action.id } },+ ...(opportunity.status === 'new' ? { status: 'sent' } : {}),+ updated_at: new Date().toISOString(),+ })+ .eq('id', opportunity.id);+ if (oppErr) throw new Error(oppErr.message);++ return { actionId: action.id, created: true };+}diff --git a/server/src/lib/action-center/from-opportunity.test.js b/server/src/lib/action-center/from-opportunity.test.jsnew file mode 100644index 000000000..f05f70cc6--- /dev/null+++ b/server/src/lib/action-center/from-opportunity.test.js@@ -0,0 +1,93 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('../../config/supabase.js', () => ({ default: {} }));++const { assetTasks, combinedTasks, opportunityAssets } = await import('./from-opportunity.js');+const { getTask } = await import('./tasks/registry.js');++const owned = (decision) => ({ type: 'blog_post', channel: 'owned', decision });++describe('assetTasks', () => {+ it('writes a new page from a brief when there is none', () => {+ expect(assetTasks(owned('create'))).toEqual([+ 'create_content_brief',+ 'create_content_draft',+ 'add_internal_links',+ 'publish_content',+ 'validate_ai_visibility',+ ]);+ });++ it('works on the existing page otherwise', () => {+ expect(assetTasks(owned('expand'))[0]).toBe('optimize_content');+ expect(assetTasks(owned('refresh'))[0]).toBe('refresh_content');+ });++ it('takes earned work through outreach', () => {+ expect(assetTasks({ type: 'backlink', channel: 'earned', decision: 'create' })).toEqual([+ 'identify_target_sources',+ 'prepare_outreach',+ 'execute_outreach',+ 'track_third_party_status',+ 'validate_third_party_citation',+ ]);+ });++ it('uses only tasks the library has', () => {+ const all = combinedTasks([+ owned('create'),+ owned('refresh'),+ owned('optimize'),+ { type: 'third_party_article', channel: 'earned', decision: 'create' },+ { type: 'backlink', channel: 'earned', decision: 'create' },+ ]);+ for (const id of all) expect(getTask(id), id).toBeTruthy();+ });+});++describe('combinedTasks', () => {+ it('lists each task once, work before checks, measurement last', () => {+ const tasks = combinedTasks([+ owned('optimize'),+ { type: 'third_party_article', channel: 'earned', decision: 'create' },+ ]);+ expect(tasks).toEqual([+ 'optimize_content',+ 'add_internal_links',+ 'publish_content',+ 'identify_target_sources',+ 'prepare_contribution',+ 'execute_outreach',+ 'track_third_party_status',+ 'validate_ai_visibility',+ 'validate_third_party_presence',+ 'measure_action_outcome',+ ]);+ });+});++describe('opportunityAssets', () => {+ it('gives an opportunity from before assets one, from its own fields', () => {+ expect(+ opportunityAssets({+ title: 'T',+ type: 'owned',+ decision: 'optimize',+ source_data: { targetPages: [{ url: 'u' }] },+ }),+ ).toEqual([+ {+ key: 'a1',+ type: null,+ channel: 'owned',+ decision: 'optimize',+ title: 'T',+ pages: [{ url: 'u' }],+ },+ ]);+ expect(opportunityAssets({ title: 'T', type: 'earned', source_data: {} })[0]).toMatchObject({+ channel: 'earned',+ decision: 'create',+ });+ });+});diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex 04d2a30b8..d5e435693 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -20,6 +20,7 @@ import {assertOpportunityAccess,} from '../lib/access.js';import { loadClusters } from '../lib/prompt-clusters.js';+import { sendToActionCenter } from '../lib/action-center/from-opportunity.js';const router = Router();@@ -1098,6 +1099,26 @@ router.post('/:id/brief', async (req, res) => {* GET /api/content/:id* Get a single opportunity by ID.*/+/**+ * POST /api/content/:id/action+ * Send the opportunity, or one of its assets ({ assetKey }), to the Action+ * Center. Sending the same thing again returns the action already open.+ */+router.post('/:id/action', async (req, res) => {+ try {+ const opp = await assertOpportunityAccess(req.params.id, req.user.id);+ const assetKey = typeof req.body?.assetKey === 'string' ? req.body.assetKey : null;+ const result = await sendToActionCenter(opp, { assetKey, userId: req.user.id });+ return res.status(result.created ? 201 : 200).json(result);+ } catch (error) {+ req.log.error({ err: error }, 'send opportunity to action center error');+ return res.status(error.status || 500).json({+ error: 'Failed to send to the Action Center',+ details: error.message,+ });+ }+});+router.get('/:id/basket', async (req, res) => {try {const opp = await assertOpportunityAccess(req.params.id, req.user.id);diff --git a/web/messages/en.json b/web/messages/en.jsonindex 520d1ec81..69b3e3c35 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1102,6 +1102,12 @@"platforms": "{count, plural, one {# platform} other {# platforms}}","regions": "{count, plural, one {# region} other {# regions}}","competitors": "{count, plural, one {# competitor} other {# competitors}}"+ },+ "content_opportunity": {+ "title": "Act on a content opportunity for {targets}",+ "titleGeneric": "Act on a content opportunity",+ "description": "Sent from Content Optimization: a piece of content, or work on an existing page, that answers a group of related prompts.",+ "goal": "Get the brand into AI answers for these prompts with the content this opportunity calls for."}},"actionTasks": {@@ -1788,7 +1794,13 @@"category_page": "Category page","third_party_article": "Third-party article","backlink": "Backlink"- }+ },+ "sendToActionCenter": "Send to Action Center",+ "sendAsset": "Send",+ "openInActionCenter": "Open in Action Center",+ "sentToActionCenter": "Sent to the Action Center",+ "alreadyInActionCenter": "Already in the Action Center",+ "sendToActionCenterError": "Failed to send to the Action Center"},"traffic": {"title": "AI Traffic Analytics",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsxindex 3bc696f4c..07092beb8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx@@ -32,6 +32,7 @@ import {sendToWebhook,generateBrief,getBriefQuota,+ sendOpportunityToActionCenter,type BriefQuota,} from '@/lib/actions/content';import type { ContentBrief, ContentOpportunity } from '@/types';@@ -173,6 +174,25 @@ export default function ContentDetailPage() {}};+ // Action Center (#857): the whole opportunity, or one asset by its key.+ const [sendingAction, setSendingAction] = useState<string | null>(null);+ const handleSendToActionCenter = async (assetKey?: string) => {+ setSendingAction(assetKey ?? 'all');+ try {+ const result = await sendOpportunityToActionCenter(id, assetKey);+ if ('error' in result) {+ toast.error(result.error);+ return;+ }+ toast.success(result.created ? t('sentToActionCenter') : t('alreadyInActionCenter'));+ setOpportunity(await getOpportunity(id));+ } catch {+ toast.error(t('sendToActionCenterError'));+ } finally {+ setSendingAction(null);+ }+ };+const handleRestore = async () => {try {await updateOpportunityStatus(id, 'new');@@ -219,6 +239,7 @@ export default function ContentDetailPage() {}const sd = opportunity.sourceData;+ const canSendToActionCenter = !['dismissed', 'archived', 'done'].includes(opportunity.status);const quotaLimited = quota !== null && quota.limit !== -1;const quotaExhausted = quotaLimited && quota.remaining <= 0;@@ -237,6 +258,33 @@ export default function ContentDetailPage() {)}</div><div className="flex items-center gap-2">+ {opportunity.clusterId &&+ (sd.actions?.all ? (+ <Link href={`/dashboard/action-center/actions?action=${sd.actions.all}`}>+ <Button variant="outline" size="sm" className="gap-2">+ <Target className="h-4 w-4" />+ {t('openInActionCenter')}+ </Button>+ </Link>+ ) : (+ canSendToActionCenter &&+ !Object.keys(sd.actions ?? {}).length && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => handleSendToActionCenter()}+ disabled={sendingAction !== null}+ className="gap-2"+ >+ {sendingAction === 'all' ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Target className="h-4 w-4" />+ )}+ {t('sendToActionCenter')}+ </Button>+ )+ ))}{opportunity.status === 'archived' && (<Button variant="outline" size="sm" onClick={handleRestore} className="gap-2"><RotateCcw className="h-4 w-4" />@@ -296,7 +344,11 @@ export default function ContentDetailPage() {{opportunity.decision && (<TargetPagesCard decision={opportunity.decision} sourceData={sd} />)}- <AssetsCard sourceData={sd} />+ <AssetsCard+ sourceData={sd}+ onSend={canSendToActionCenter ? handleSendToActionCenter : undefined}+ sendingKey={sendingAction}+ /><OpportunityBasketCard opportunityId={opportunity.id} /></div><ScoreBreakdown sourceData={sd} />diff --git a/web/src/components/content/opportunity-basket.tsx b/web/src/components/content/opportunity-basket.tsxindex 82d8a653a..cee8b74a0 100644--- a/web/src/components/content/opportunity-basket.tsx+++ b/web/src/components/content/opportunity-basket.tsx@@ -2,7 +2,8 @@import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';-import { Boxes, ExternalLink, FileText, Layers, Search } from 'lucide-react';+import { Boxes, ExternalLink, FileText, Layers, Loader2, Search } from 'lucide-react';+import { Link } from '@/i18n/navigation';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -232,9 +233,19 @@ export function TargetPagesCard({}/** Everything the opportunity asks for: the primary content first, then supporting work. */-export function AssetsCard({ sourceData }: { sourceData: ContentOpportunitySourceData }) {+export function AssetsCard({+ sourceData,+ onSend,+ sendingKey,+}: {+ sourceData: ContentOpportunitySourceData;+ /** Sends one asset to the Action Center; omitted when sending is not offered. */+ onSend?: (assetKey: string) => void;+ sendingKey?: string | null;+}) {const t = useTranslations('content');const assets = sourceData.assets ?? [];+ const actions = sourceData.actions ?? {};if (assets.length < 2) return null;return (@@ -264,7 +275,34 @@ export function AssetsCard({ sourceData }: { sourceData: ContentOpportunitySourc{t(`decision.${a.decision}`)}</Badge></div>- <p className="text-sm">{a.title}</p>+ <div className="flex items-start justify-between gap-2">+ <p className="text-sm">{a.title}</p>+ {actions[a.key] ? (+ <Link+ href={`/dashboard/action-center/actions?action=${actions[a.key]}`}+ className="shrink-0 text-xs text-primary hover:underline"+ >+ {t('openInActionCenter')}+ </Link>+ ) : (+ onSend &&+ !actions.all && (+ <Button+ size="sm"+ variant="outline"+ className="h-7 shrink-0 px-2 text-xs"+ disabled={sendingKey !== null && sendingKey !== undefined}+ onClick={() => onSend(a.key)}+ >+ {sendingKey === a.key ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ t('sendAsset')+ )}+ </Button>+ )+ )}+ </div>{a.pages.map((p) => (<akey={p.url}diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex 0c5a8a8b9..b3f8ca282 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -40,8 +40,16 @@ describe('actionTexts', () => {expect(() => actionGoal(kind, t)).not.toThrow();});- it('holds copy for all sixty-two definitions', () => {- expect(ACTION_KINDS).toHaveLength(62);+ it('holds copy for all sixty-two definitions and opportunity actions', () => {+ expect(ACTION_KINDS).toHaveLength(63);+ });++ it('names an opportunity action after the work it was sent for', () => {+ const texts = actionTexts(+ action({ kind: 'content_opportunity', payload: { title: 'Expand the tool list' } }),+ t,+ );+ expect(texts.title).toBe('Expand the tool list');});/**diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex ab9ea6177..9ba4136ab 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -66,6 +66,10 @@ export function actionTexts(if (!isActionKind(action.kind)) {return { title: humanizeKind(action.kind), description: t('unknown.description') };}+ // An action sent from a content opportunity is named after the work itself.+ if (action.kind === 'content_opportunity' && typeof p.title === 'string' && p.title) {+ return { title: p.title, description: t(`${action.kind}.description`) };+ }const targets = targetLabel(p, t);return {title: targets ? t(`${action.kind}.title`, { targets }) : t(`${action.kind}.titleGeneric`),diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex a7649eae3..f326dd5ab 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -36,7 +36,8 @@ export type ActionOutcome =| 'declined'| 'not_measurable';-/** A kind this build has copy for — the V1 library's sixty-two definitions. */+/** A kind this build has copy for — the V1 library's sixty-two definitions, plus+ * actions sent from a content opportunity. */export type ActionKind =| 'capture_ai_traffic'| 'convert_mentions'@@ -99,7 +100,9 @@ export type ActionKind =| 'capture_competitor_fanouts'| 'respond_to_competitor_momentum'| 'earn_competitor_source_presence'- | 'create_content_for_competitor_gaps';+ | 'create_content_for_competitor_gaps'+ // Sent by a person from a content opportunity, not raised by a definition.+ | 'content_opportunity';export type TaskStatus =| 'todo'@@ -213,6 +216,7 @@ export const ACTION_KINDS: readonly ActionKind[] = ['respond_to_competitor_momentum','earn_competitor_source_presence','create_content_for_competitor_gaps',+ 'content_opportunity',];/**diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.tsindex dafeb488a..82004ca45 100644--- a/web/src/lib/actions/content.ts+++ b/web/src/lib/actions/content.ts@@ -153,6 +153,29 @@ export async function getOpportunityPrompts(brandId: string): Promise<Opportunitreturn body.prompts;}+export async function sendOpportunityToActionCenter(+ id: string,+ assetKey?: string,+): Promise<{ actionId: string; created: boolean } | { error: string }> {+ const session = await getSession();++ const res = await fetch(`${AEO_SERVER_URL}/api/content/${id}/action`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ assetKey: assetKey ?? null }),+ });++ // 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();+}+export interface OpportunityTopic {topicId: string;name: string;diff --git a/web/src/types/index.ts b/web/src/types/index.tsindex 7c9c3f99a..497a236f3 100644--- a/web/src/types/index.ts+++ b/web/src/types/index.ts@@ -222,6 +222,8 @@ export interface ContentOpportunitySourceData {windowDays?: number;targetPages?: OpportunityPage[];assets?: OpportunityAsset[];+ /** Action Center actions sent from this opportunity, by asset key ('all' for the whole). */+ actions?: Record<string, string>;}export interface OpportunityPage {