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): put the opportunity's actions in one row that follows its progress (#967)
Gökhan Geyik56b3e39f08f8
diff --git a/web/messages/en.json b/web/messages/en.jsonindex f7994f33a..adc1c8a7e 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1638,6 +1638,17 @@"generating": "Analyzing...","send": "Send","sendToWorkflow": "Send to Workflow",+ "generateBrief": "Generate Brief",+ "generatingBrief": "Generating...",+ "briefGenerated": "Brief Generated",+ "briefLimitReached": "You've used this month's content briefs",+ "sendToActions": "Send to Actions",+ "openInActions": "Open in Actions",+ "sendAgain": "Send Again",+ "copyAllData": "Copy All Data",+ "copiedToast": "Copied to clipboard",+ "copyError": "Could not copy to the clipboard",+ "moreActions": "More actions","sending": "Sending...","noResults": "No opportunities match your filters.","clearFilters": "Clear filters",diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsxindex d7271f994..9bcf4edf2 100644--- a/web/src/components/content/opportunity-detail.tsx+++ b/web/src/components/content/opportunity-detail.tsx@@ -23,6 +23,10 @@ import {Crown,RotateCcw,CheckCheck,+ Check,+ Copy,+ ExternalLink,+ MoreHorizontal,} from 'lucide-react';import { cn } from '@/lib/utils';import { Link } from '@/i18n/navigation';@@ -44,6 +48,13 @@ import {ScoreBreakdown,TargetPagesCard,} from '@/components/content/opportunity-basket';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { opportunityToMarkdown } from '@/lib/content/opportunity-markdown';import { toast } from 'sonner';const IMPACT_COLORS: Record<string, string> = {@@ -273,85 +284,181 @@ export function OpportunityDetail({const canSendToActionCenter = !['dismissed', 'archived', 'done'].includes(opportunity.status);const quotaLimited = quota !== null && quota.limit !== -1;const quotaExhausted = quotaLimited && quota.remaining <= 0;+ const actionId = sd.actions?.all ?? Object.values(sd.actions ?? {})[0];+ const canSendToWorkflow = !['dismissed', 'archived'].includes(opportunity.status);+ const hasMenu = opportunity.status === 'new' || opportunity.status === 'archived';++ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(opportunityToMarkdown(opportunity, brief, fanoutQueries));+ toast.success(t('copiedToast'));+ } catch {+ toast.error(t('copyError'));+ }+ };return (// A container, so the layout follows the space it is given — the page's// full width or the drawer's — rather than the viewport.<div className="@container space-y-6">- <div className="flex flex-wrap items-center gap-4">- {!inDrawer && (- <Link href="/dashboard/content">- <Button variant="ghost" size="icon" aria-label="Go back to content list">- <ArrowLeft className="h-4 w-4" />- </Button>- </Link>- )}- <div className="min-w-0 flex-1">- <h1 className="text-xl font-bold tracking-tight">{opportunity.title}</h1>- {opportunity.description && (- <p className="text-sm text-muted-foreground mt-1">{opportunity.description}</p>+ <div className="space-y-3">+ <div className="flex items-start gap-3">+ {!inDrawer && (+ <Link href="/dashboard/content">+ <Button variant="ghost" size="icon" aria-label="Go back to content list">+ <ArrowLeft className="h-4 w-4" />+ </Button>+ </Link>)}+ <div className="min-w-0 flex-1">+ <h1 className="text-xl font-bold tracking-tight">{opportunity.title}</h1>+ {opportunity.description && (+ <p className="text-sm text-muted-foreground mt-1">{opportunity.description}</p>+ )}+ </div>+ </div>++ <div className="flex flex-wrap items-center gap-2">+ <Badge+ variant="outline"+ className="text-xs"+ title={t(`typeHint.${opportunity.type}` as 'typeHint.owned' | 'typeHint.earned')}+ >+ {t(`type.${opportunity.type}` as 'type.owned' | 'type.earned')}+ </Badge>+ <Badge variant="outline" className={cn('text-xs', IMPACT_COLORS[opportunity.impact])}>+ {t(`impact.${opportunity.impact}` as 'impact.high' | 'impact.medium' | 'impact.low')}+ </Badge>+ <Badge variant="outline" className={cn('text-xs', STATUS_COLORS[opportunity.status])}>+ {t(`status.${opportunity.status}` as `status.${typeof opportunity.status}`)}+ </Badge>+ <Badge variant="outline" className="text-xs tabular-nums">+ Score: {Math.round(opportunity.opportunityScore)}+ </Badge>+ <span className="text-xs text-muted-foreground ml-auto flex items-center gap-1.5">+ <Clock className="h-3.5 w-3.5" />+ {new Date(opportunity.createdAt).toLocaleDateString(undefined, {+ day: 'numeric',+ month: 'short',+ year: 'numeric',+ })}+ </span></div><div className="flex flex-wrap items-center gap-2">+ {brief ? (+ <Button+ variant="outline"+ size="sm"+ disabled+ className="min-w-40 flex-1 gap-2 disabled:opacity-100"+ >+ <Check className="h-4 w-4" />+ {t('briefGenerated')}+ </Button>+ ) : (+ <Button+ size="sm"+ onClick={handleGenerateBrief}+ disabled={generatingBrief || quotaExhausted}+ title={quotaExhausted ? t('briefLimitReached') : undefined}+ className="min-w-40 flex-1 gap-2"+ >+ {generatingBrief ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Sparkles className="h-4 w-4" />+ )}+ {generatingBrief ? t('generatingBrief') : t('generateBrief')}+ </Button>+ )}{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')}+ (actionId ? (+ <Link+ href={`/dashboard/action-center/actions?action=${actionId}`}+ className="min-w-40 flex-1"+ >+ <Button variant="outline" size="sm" className="w-full gap-2">+ <ExternalLink className="h-4 w-4" />+ {t('openInActions')}</Button></Link>) : (- canSendToActionCenter &&- !Object.keys(sd.actions ?? {}).length && (+ canSendToActionCenter && (<Buttonvariant="outline"size="sm"onClick={() => handleSendToActionCenter()}disabled={sendingAction !== null}- className="gap-2"+ className="min-w-40 flex-1 gap-2">{sendingAction === 'all' ? (<Loader2 className="h-4 w-4 animate-spin" />) : (<Target className="h-4 w-4" />)}- {t('sendToActionCenter')}+ {t('sendToActions')}</Button>)))}- {opportunity.status === 'archived' && (- <Button variant="outline" size="sm" onClick={handleRestore} className="gap-2">- <RotateCcw className="h-4 w-4" />- {t('restore')}- </Button>- )}- {opportunity.status === 'new' && (- <Button variant="outline" size="sm" onClick={handleReviewed} className="gap-2">- <CheckCheck className="h-4 w-4" />- {t('markReviewed')}+ {canSendToWorkflow && (+ <Button+ variant="outline"+ size="sm"+ onClick={handleSend}+ disabled={sending}+ className="min-w-40 flex-1 gap-2"+ >+ {sending ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Send className="h-4 w-4" />+ )}+ {sending+ ? t('sending')+ : opportunity.webhookSentAt+ ? t('sendAgain')+ : t('sendToWorkflow')}</Button>)}- {opportunity.status === 'new' && (- <>- <Button- variant="outline"- size="sm"- onClick={handleDismiss}- className="gap-2 text-muted-foreground"- >- <X className="h-4 w-4" />- {t('dismiss')}- </Button>- <Button size="sm" onClick={handleSend} disabled={sending} className="gap-2">- {sending ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Send className="h-4 w-4" />+ <Button+ variant="outline"+ size="sm"+ onClick={handleCopy}+ className="min-w-40 flex-1 gap-2"+ >+ <Copy className="h-4 w-4" />+ {t('copyAllData')}+ </Button>+ {hasMenu && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button variant="outline" size="icon-sm" aria-label={t('moreActions')}>+ <MoreHorizontal className="h-4 w-4" />+ </Button>+ }+ />+ <DropdownMenuContent align="end">+ {opportunity.status === 'new' && (+ <DropdownMenuItem onClick={handleReviewed}>+ <CheckCheck className="h-4 w-4" />+ {t('markReviewed')}+ </DropdownMenuItem>)}- {sending ? t('sending') : t('sendToWorkflow')}- </Button>- </>+ {opportunity.status === 'archived' && (+ <DropdownMenuItem onClick={handleRestore}>+ <RotateCcw className="h-4 w-4" />+ {t('restore')}+ </DropdownMenuItem>+ )}+ {opportunity.status === 'new' && (+ <DropdownMenuItem variant="destructive" onClick={handleDismiss}>+ <X className="h-4 w-4" />+ {t('dismiss')}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>)}</div></div>@@ -373,33 +480,6 @@ export function OpportunityDetail({</div>)}- <div className="flex flex-wrap items-center gap-2">- <Badge- variant="outline"- className="text-xs"- title={t(`typeHint.${opportunity.type}` as 'typeHint.owned' | 'typeHint.earned')}- >- {t(`type.${opportunity.type}` as 'type.owned' | 'type.earned')}- </Badge>- <Badge variant="outline" className={cn('text-xs', IMPACT_COLORS[opportunity.impact])}>- {t(`impact.${opportunity.impact}` as 'impact.high' | 'impact.medium' | 'impact.low')}- </Badge>- <Badge variant="outline" className={cn('text-xs', STATUS_COLORS[opportunity.status])}>- {t(`status.${opportunity.status}` as `status.${typeof opportunity.status}`)}- </Badge>- <Badge variant="outline" className="text-xs tabular-nums">- Score: {Math.round(opportunity.opportunityScore)}- </Badge>- <span className="text-xs text-muted-foreground ml-auto flex items-center gap-1.5">- <Clock className="h-3.5 w-3.5" />- {new Date(opportunity.createdAt).toLocaleDateString(undefined, {- day: 'numeric',- month: 'short',- year: 'numeric',- })}- </span>- </div>-{opportunity.clusterId && (<div className="grid grid-cols-1 gap-4 @5xl:grid-cols-3"><div className="space-y-4 @5xl:col-span-2">diff --git a/web/src/lib/content/opportunity-markdown.test.ts b/web/src/lib/content/opportunity-markdown.test.tsnew file mode 100644index 000000000..489a14792--- /dev/null+++ b/web/src/lib/content/opportunity-markdown.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from 'vitest';+import type { ContentBrief, ContentOpportunity } from '@/types';+import { opportunityToMarkdown } from './opportunity-markdown';++const base: ContentOpportunity = {+ id: 'opp-1',+ brandId: 'brand-1',+ clusterId: 'cluster-1',+ decision: 'expand',+ title: 'Compare the top running shoes for flat feet',+ description: 'Shoppers ask engines which shoes suit flat feet.',+ type: 'owned',+ impact: 'high',+ opportunityScore: 86.6,+ status: 'new',+ sourceData: {+ clusterLabel: 'Shoes for flat feet',+ topicName: 'Running shoes',+ estAiVolume: 18660,+ visibilityScore: 0,+ competitorsCited: ['Rival One', 'Rival Two'],+ prompts: ['Best shoes for flat feet?', 'Running shoes for overpronation'],+ queries: { included: 2, excluded: 5, top: [{ query: 'flat feet shoes', timesSearched: 9 }] },+ scoreComponents: { demand: 30, visibilityGap: 25, competitorGap: 20, intent: 11.6 },+ targetPages: [+ {+ url: 'https://example.com/guides/flat-feet',+ title: 'Flat feet guide',+ aiCitations: 0,+ gaSessions: 0,+ lastmod: null,+ },+ ],+ assets: [+ {+ key: 'a1',+ type: 'comparison_page',+ channel: 'owned',+ decision: 'expand',+ title: 'Flat feet shoe comparison',+ pages: [],+ },+ ],+ },+ createdAt: '2026-10-05T08:00:00.000Z',+ updatedAt: '2026-10-05T08:00:00.000Z',+};++const brief: ContentBrief = {+ suggestedTitle: 'The 10 best running shoes for flat feet',+ contentType: 'Comparison',+ targetWordCount: 2200,+ outline: [+ { heading: 'What flat feet need', keyPoints: ['Arch support', 'Stability'] },+ { heading: 'The shoes', keyPoints: [] },+ ],+ targetKeywords: ['flat feet', 'stability shoes'],+ competitorInsights: 'Rivals list shoes without fit advice.',+ callToAction: 'Find your fit',+};++describe('opportunityToMarkdown', () => {+ it('writes the opportunity in page order', () => {+ const md = opportunityToMarkdown(base, brief);++ const order = [+ '# Compare the top running shoes for flat feet',+ '- Score: 87',+ '## Target pages',+ '## Recommended assets',+ '## Score breakdown',+ '## Source data',+ '## Prompts',+ '## Fan-out queries',+ '## Content brief',+ '## Brief outline',+ '## Competitor insights',+ ];+ const positions = order.map((s) => md.indexOf(s));+ expect(positions.every((p) => p >= 0)).toBe(true);+ expect([...positions].sort((a, b) => a - b)).toEqual(positions);++ expect(md).toContain('- Flat feet shoe comparison (Comparison page, Owned, Expand)');+ expect(md).toContain('- Est. AI volume: 18,660');+ expect(md).toContain('- Visibility: 0%');+ expect(md).toContain('1. What flat feet need\n - Arch support\n - Stability\n2. The shoes');+ });++ it('copies the opportunity and its source data before a brief exists', () => {+ const md = opportunityToMarkdown(+ { ...base, clusterId: null, decision: null, sourceData: { promptText: 'Best shoes?' } },+ null,+ [{ query: 'best shoes 2026' }],+ );++ expect(md).toContain('- Related prompt: Best shoes?');+ expect(md).toContain('## Fan-out queries\n\n- best shoes 2026');+ expect(md).not.toContain('## Content brief');+ expect(md).not.toContain('## Target pages');+ expect(md).not.toContain('Decision:');+ });+});diff --git a/web/src/lib/content/opportunity-markdown.ts b/web/src/lib/content/opportunity-markdown.tsnew file mode 100644index 000000000..4f5602291--- /dev/null+++ b/web/src/lib/content/opportunity-markdown.ts@@ -0,0 +1,123 @@+import type { ContentBrief, ContentOpportunity } from '@/types';++/** `blog_post` → `Blog post`. */+function humanize(slug: string): string {+ const words = slug.replace(/_/g, ' ');+ return words.charAt(0).toUpperCase() + words.slice(1);+}++function section(title: string, lines: (string | null | undefined | false)[]): string | null {+ const body = lines.filter((l): l is string => typeof l === 'string' && l.length > 0);+ return body.length ? `## ${title}\n\n${body.join('\n')}` : null;+}++const fmt = (n: number) => Math.round(n).toLocaleString('en-US');++/**+ * Everything the opportunity detail shows, as Markdown in page order, for the+ * Copy All Data button. Empty sections are left out.+ */+export function opportunityToMarkdown(+ opportunity: ContentOpportunity,+ brief: ContentBrief | null,+ fanoutQueries: { query: string }[] = [],+): string {+ const sd = opportunity.sourceData;+ const parts: (string | null)[] = [];++ parts.push([`# ${opportunity.title}`, opportunity.description].filter(Boolean).join('\n\n'));++ parts.push(+ [+ `- Type: ${humanize(opportunity.type)}`,+ `- Impact: ${humanize(opportunity.impact)}`,+ `- Status: ${humanize(opportunity.status)}`,+ `- Score: ${Math.round(opportunity.opportunityScore)}`,+ `- Created: ${opportunity.createdAt.slice(0, 10)}`,+ opportunity.decision && `- Decision: ${humanize(opportunity.decision)}`,+ ]+ .filter(Boolean)+ .join('\n'),+ );++ parts.push(+ section(+ 'Target pages',+ (sd.targetPages ?? []).map((p) => `- ${p.title ? `${p.title}: ` : ''}${p.url}`),+ ),+ );++ parts.push(+ section(+ 'Recommended assets',+ (sd.assets ?? []).map(+ (a) =>+ `- ${a.title} (${humanize(a.type)}, ${humanize(a.channel)}, ${humanize(a.decision)})`,+ ),+ ),+ );++ const sc = sd.scoreComponents;+ parts.push(+ section('Score breakdown', [+ sc && `- Demand: ${Math.round(sc.demand)}`,+ sc && `- Visibility gap: ${Math.round(sc.visibilityGap)}`,+ sc && `- Competitor gap: ${Math.round(sc.competitorGap)}`,+ sc && `- Intent: ${Math.round(sc.intent)}`,+ ]),+ );++ const queries = sd.queries?.top.map((q) => q.query) ?? fanoutQueries.map((q) => q.query);+ parts.push(+ section('Source data', [+ sd.promptText && `- Related prompt: ${sd.promptText}`,+ sd.clusterLabel && `- Cluster: ${sd.clusterLabel}`,+ sd.topicName && `- Topic: ${sd.topicName}`,+ sd.estAiVolume != null && `- Est. AI volume: ${fmt(sd.estAiVolume)}`,+ sd.visibilityScore != null && `- Visibility: ${Math.round(sd.visibilityScore)}%`,+ sd.competitorGap != null && `- Competitor gap: ${Math.round(sd.competitorGap)}%`,+ sd.intent && `- Intent: ${sd.intent}`,+ !!sd.keywords?.length && `- Keywords: ${sd.keywords.join(', ')}`,+ !!sd.competitorsCited?.length && `- Competitors cited: ${sd.competitorsCited.join(', ')}`,+ ]),+ );++ parts.push(+ section(+ 'Prompts',+ (sd.prompts ?? []).map((p) => `- ${p}`),+ ),+ );+ parts.push(+ section(+ 'Fan-out queries',+ queries.map((q) => `- ${q}`),+ ),+ );++ if (brief) {+ parts.push(+ section('Content brief', [+ `- Suggested title: ${brief.suggestedTitle}`,+ `- Content type: ${brief.contentType}`,+ `- Target word count: ${fmt(brief.targetWordCount)}`,+ brief.targetKeywords.length > 0 && `- Keywords: ${brief.targetKeywords.join(', ')}`,+ brief.callToAction && `- CTA: ${brief.callToAction}`,+ ]),+ );+ parts.push(+ brief.outline.length+ ? `## Brief outline\n\n${brief.outline+ .map(+ (s, i) => `${i + 1}. ${s.heading}${s.keyPoints.map((k) => `\n - ${k}`).join('')}`,+ )+ .join('\n')}`+ : null,+ );+ parts.push(+ brief.competitorInsights ? `## Competitor insights\n\n${brief.competitorInsights}` : null,+ );+ }++ return parts.filter((p): p is string => !!p).join('\n\n') + '\n';+}