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): suggest another angle on an opportunity (#1027)
Cihan95505cf9bc3e
diff --git a/server/src/lib/opportunity-alternative.test.js b/server/src/lib/opportunity-alternative.test.jsnew file mode 100644index 000000000..0a20e2606--- /dev/null+++ b/server/src/lib/opportunity-alternative.test.js@@ -0,0 +1,31 @@+import { describe, expect, it, vi } from 'vitest';++// The generator imports the supabase admin client, whose config exits when+// SUPABASE_* env is absent (as in CI) — stub it before the import chain.+vi.mock('../config/supabase.js', () => ({ default: {} }));++const { alternativeInstruction } = await import('./opportunity-generator.js');++// CONTENT-006: "Another angle" asks the model for a second take on a need+// that already has an opportunity.++describe('alternativeInstruction', () => {+ it('names the original and asks for a different kind of content', () => {+ const text = alternativeInstruction({+ title: 'Comparison guide: top 5 coffee subscriptions',+ description: 'A structured comparison page with FAQ schema.',+ decision: 'create',+ });+ expect(text).toContain('"Comparison guide: top 5 coffee subscriptions"');+ expect(text).toContain('(A structured comparison page with FAQ schema.)');+ expect(text).toContain('decided as "create"');+ expect(text).toMatch(/differs clearly in content type, format, audience or decision/);+ expect(text).toMatch(/Don't repeat its title or approach/);+ });++ it('leaves out what the original lacks', () => {+ expect(alternativeInstruction({ title: 'Office coffee FAQ' })).toBe(+ 'This cluster already has the opportunity "Office coffee FAQ". The user wants a different angle on the same need: write one opportunity that differs clearly in content type, format, audience or decision. Don\'t repeat its title or approach.',+ );+ });+});diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.jsindex dafa7c77e..54bc49830 100644--- a/server/src/lib/opportunity-generator.js+++ b/server/src/lib/opportunity-generator.js@@ -220,6 +220,22 @@ async function loadPromptTexts(promptIds) {return data || [];}+/**+ * What the model is told when the user asks for another angle on an existing+ * opportunity (CONTENT-006): the original, and that this one must differ in+ * kind, not just in wording.+ */+export function alternativeInstruction({ title, description, decision }) {+ const about = [+ `"${title}"`,+ description ? `(${description})` : null,+ decision ? `decided as "${decision}"` : null,+ ]+ .filter(Boolean)+ .join(' ');+ return `This cluster already has the opportunity ${about}. The user wants a different angle on the same need: write one opportunity that differs clearly in content type, format, audience or decision. Don't repeat its title or approach.`;+}+/** Longest idea a "+ New" request may carry into the model prompt. */export const IDEA_MAX_LENGTH = 500;@@ -233,8 +249,13 @@ export const IDEA_MAX_LENGTH = 500;* promptId?: string | null,* idea?: string | null,* source?: 'system' | 'manual' | 'prompt',+ * alternativeOf?: { id: string, title: string, description?: string|null, decision?: string|null, clusterId: string } | null,* }} [opts] - `count`, the focus (`topicId` / `promptId`) and `idea` come from* an on-demand request (CONTENT-003); the nightly run passes none of them.+ * `alternativeOf` asks for one more opportunity on that opportunity's+ * cluster with a different angle (CONTENT-006): the user wants a second+ * take on a need that's already covered, so neither coverage nor the+ * duplicate check stands in its way, and it isn't merged into anything.* @returns {Promise<{ generated: number, merged: number, reopened?: number, duplicates?: number, limited?: boolean }>}*/export async function generateContentOpportunities(@@ -247,6 +268,7 @@ export async function generateContentOpportunities(promptId = null,idea = null,source = 'system',+ alternativeOf = null,} = {},) {onProgress?.({ phase: 'collecting_data', message: 'Fetching clusters and metrics...' });@@ -341,7 +363,9 @@ export async function generateContentOpportunities(const inFocus = (c) =>(!topicId || c.topicId === topicId) &&(!promptId || clusterById.get(c.id).prompt_ids.includes(promptId));- const open = candidates.filter((c) => c.metrics.tested > 0 && !covered.has(c.id) && inFocus(c));+ const open = alternativeOf+ ? candidates.filter((c) => c.id === alternativeOf.clusterId)+ : candidates.filter((c) => c.metrics.tested > 0 && !covered.has(c.id) && inFocus(c));const { data: basketRows, error: basketErr } = await selectInChunks(open.map((c) => c.id),(chunk) =>@@ -357,15 +381,19 @@ export async function generateContentOpportunities(// that opportunity again. It is never written, so it costs neither a model// call nor a slot of the quota; an open match takes it in as a related// cluster, so it is covered from now on.- const duplicates = await skipDuplicates(brandId, open, {- clusterById,- basketRows: basketRows || [],- covered,- });+ const duplicates = alternativeOf+ ? 0+ : await skipDuplicates(brandId, open, {+ clusterById,+ basketRows: basketRows || [],+ covered,+ });- const wanted = pickClusters(open, covered, count ?? OPPORTUNITIES_PER_RUN, {- fill: count !== undefined,- });+ const wanted = alternativeOf+ ? open.slice(0, 1)+ : pickClusters(open, covered, count ?? OPPORTUNITIES_PER_RUN, {+ fill: count !== undefined,+ });if (!wanted.length) {logger.info({ brandId, clusters: clusters.length, opportunities: existing.length, reopened, duplicates },@@ -388,7 +416,8 @@ export async function generateContentOpportunities(logger.error({ err, brandId }, '[opportunities] handing back slots failed'),);- const shown = existing+ // An alternative is its own take, never folded into another opportunity.+ const shown = (alternativeOf ? [] : existing).filter((o) =>o.status !== 'dismissed' &&@@ -438,11 +467,11 @@ ${picked.map(clusterLine).join('\n\n')}Existing opportunities in other topics:${shown.map((o, i) => `[E${i}] ${o.title} (topic: ${topicName(clusterById.get(o.cluster_id)) || 'none'})`).join('\n') || 'none'}-${- idea- ? `The user asked for ideas around: "${idea.slice(0, IDEA_MAX_LENGTH)}". Shape the opportunities toward it wherever the clusters' prompts allow; never invent a need the data doesn't show.\n\n`- : ''-}Write every title and description in ${getLanguageName(brand.language)}.`;+${alternativeOf ? `${alternativeInstruction(alternativeOf)}\n\n` : ''}${+ idea+ ? `The user asked for ideas around: "${idea.slice(0, IDEA_MAX_LENGTH)}". Shape the opportunities toward it wherever the clusters' prompts allow; never invent a need the data doesn't show.\n\n`+ : ''+ }Write every title and description in ${getLanguageName(brand.language)}.`;onProgress?.({ phase: 'analyzing', message: 'Generating opportunities with AI...' });const { object } = await generateObject({@@ -553,6 +582,9 @@ ${}),targetPages: primary.pages,assets,+ ...(alternativeOf+ ? { alternativeOf: { id: alternativeOf.id, title: alternativeOf.title } }+ : {}),},});}diff --git a/server/src/lib/opportunity-status.js b/server/src/lib/opportunity-status.jsnew file mode 100644index 000000000..31c2b5335--- /dev/null+++ b/server/src/lib/opportunity-status.js@@ -0,0 +1,26 @@+/**+ * What a status change does to an opportunity's source data (CONTENT-006).+ *+ * Dismissing can say why: the topic doesn't matter to the brand, or the topic+ * is right and the angle wrong. The reason lives in source_data while the+ * opportunity stays dismissed and goes once it's restored, so it never+ * describes an opportunity the user kept.+ */++export const DISMISS_REASONS = ['not_relevant', 'wrong_angle'];++/**+ * The source data to write with a status change, or null when it stays as+ * it is. An unknown reason is ignored.+ */+export function sourceDataForStatus(sourceData, status, reason) {+ const sd = sourceData || {};+ if (status === 'dismissed' && DISMISS_REASONS.includes(reason)) {+ return sd.dismissReason === reason ? null : { ...sd, dismissReason: reason };+ }+ if (status !== 'dismissed' && sd.dismissReason) {+ const { dismissReason: _dropped, ...rest } = sd;+ return rest;+ }+ return null;+}diff --git a/server/src/lib/opportunity-status.test.js b/server/src/lib/opportunity-status.test.jsnew file mode 100644index 000000000..adf2bd956--- /dev/null+++ b/server/src/lib/opportunity-status.test.js@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';+import { sourceDataForStatus } from './opportunity-status.js';++// CONTENT-006: why an opportunity was dismissed, kept only while it is.++describe('sourceDataForStatus', () => {+ const sd = { promptText: 'best coffee' };++ it('records an accepted reason with a dismissal', () => {+ expect(sourceDataForStatus(sd, 'dismissed', 'wrong_angle')).toEqual({+ promptText: 'best coffee',+ dismissReason: 'wrong_angle',+ });+ });++ it('ignores an unknown reason, or a reason on another status', () => {+ expect(sourceDataForStatus(sd, 'dismissed', 'because')).toBeNull();+ expect(sourceDataForStatus(sd, 'reviewed', 'wrong_angle')).toBeNull();+ expect(sourceDataForStatus(sd, 'dismissed', undefined)).toBeNull();+ });++ it('drops the reason once the opportunity is restored', () => {+ expect(sourceDataForStatus({ ...sd, dismissReason: 'wrong_angle' }, 'new', undefined)).toEqual(+ sd,+ );+ });++ it('writes nothing when nothing changes', () => {+ expect(+ sourceDataForStatus({ ...sd, dismissReason: 'not_relevant' }, 'dismissed', 'not_relevant'),+ ).toBeNull();+ expect(sourceDataForStatus(null, 'new')).toBeNull();+ });+});diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex a94f9a50e..54bb79534 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -25,9 +25,42 @@ import { loadClusters } from '../lib/prompt-clusters.js';import { sendToActionCenter } from '../lib/action-center/from-opportunity.js';import { IDEA_MAX_LENGTH } from '../lib/opportunity-generator.js';import { cleanStoredOpportunity } from '../lib/opportunity-text.js';+import { sourceDataForStatus } from '../lib/opportunity-status.js';const router = Router();+/** The job a repeated "+ New" or alternative request already started. */+async function startedJob(brandId, idempotencyKey) {+ const since = new Date(Date.now() - IDEMPOTENCY_WINDOW_MS).toISOString();+ const { data } = await supabaseAdmin+ .from('jobs')+ .select('id, data')+ .eq('type', 'content')+ .eq('brand_id', brandId)+ .eq('data->request->>idempotencyKey', idempotencyKey)+ .gte('created_at', since)+ .limit(1)+ .maybeSingle();+ return data;+}++/** What one request may ask for; self-hosted setups without an org have no quota. */+function requestAllowance(orgId) {+ return orgId+ ? getOpportunityRequestAllowance(orgId)+ : { perRequest: 5, remaining: -1, max: 5, periodEnd: null, planId: 'self_hosted' };+}++function quotaExhausted(res, allowance) {+ return res.status(429).json({+ success: false,+ error: 'quota_exhausted',+ message: 'Monthly opportunity limit reached.',+ periodEnd: allowance.periodEnd,+ plan: allowance.planId,+ });+}+/*** The brand's competitor names, which opportunity text is checked against* when it's read (CONTENT-005).@@ -153,32 +186,13 @@ router.post('/opportunities/generate', requireFeature('content_optimization'), atry {const { orgId } = await assertBrandAccess(brandId, req.user.id);- const since = new Date(Date.now() - IDEMPOTENCY_WINDOW_MS).toISOString();- const { data: previous } = await supabaseAdmin- .from('jobs')- .select('id, data')- .eq('type', 'content')- .eq('brand_id', brandId)- .eq('data->request->>idempotencyKey', idempotencyKey)- .gte('created_at', since)- .limit(1)- .maybeSingle();+ const previous = await startedJob(brandId, idempotencyKey);if (previous) {return res.status(202).json({ jobId: previous.id, count: previous.data.request.count });}- const allowance = orgId- ? await getOpportunityRequestAllowance(orgId)- : { perRequest: 5, remaining: -1, max: 5, periodEnd: null, planId: 'self_hosted' };- if (allowance.max <= 0) {- return res.status(429).json({- success: false,- error: 'quota_exhausted',- message: 'Monthly opportunity limit reached.',- periodEnd: allowance.periodEnd,- plan: allowance.planId,- });- }+ const allowance = await requestAllowance(orgId);+ if (allowance.max <= 0) return quotaExhausted(res, allowance);const request = {count: Math.min(count, allowance.max),@@ -210,6 +224,96 @@ router.post('/opportunities/generate', requireFeature('content_optimization'), a}});+const alternativeSchema = z.object({+ direction: z.string().trim().max(IDEA_MAX_LENGTH).nullish(),+ idempotencyKey: z.string().min(8).max(100),+});++/**+ * The cluster an alternative is written for: the opportunity's own, or, for+ * one from the per-prompt generator, the cluster its prompt is in today.+ */+async function alternativeCluster(opp) {+ if (opp.cluster_id) return opp.cluster_id;+ if (!opp.prompt_id) return null;+ const { data } = await supabaseAdmin+ .from('prompt_cluster_members')+ .select('cluster_id')+ .eq('prompt_id', opp.prompt_id)+ .maybeSingle();+ return data?.cluster_id ?? null;+}++/**+ * POST /api/content/:id/alternative+ * "Another angle" (CONTENT-006): one more opportunity for the same need with+ * a different angle, optionally steered by `direction`. It stands beside the+ * original (source_data.alternativeOf), uses one quota slot (handed back on+ * failure) and skips the duplicate check, since the user asked for it.+ * Body: { direction?, idempotencyKey }. Returns { jobId } (202); 409+ * 'no_cluster' when the prompt isn't in any cluster; 429 'quota_exhausted'.+ */+router.post('/:id/alternative', requireFeature('content_optimization'), async (req, res) => {+ const parsed = alternativeSchema.safeParse(req.body);+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.issues });+ }+ const { direction, idempotencyKey } = parsed.data;++ try {+ const opp = await assertOpportunityAccess(req.params.id, req.user.id);+ const previous = await startedJob(opp.brand_id, idempotencyKey);+ if (previous) return res.status(202).json({ jobId: previous.id });++ const clusterId = await alternativeCluster(opp);+ if (!clusterId) {+ return res.status(409).json({+ error: 'no_cluster',+ message:+ "This opportunity's prompt isn't grouped yet, so there's no need to write another angle for.",+ });+ }++ const allowance = await requestAllowance(await getOrgIdForUser(req.user.id));+ if (allowance.max <= 0) return quotaExhausted(res, allowance);++ // The model sees the original as users read it.+ const readable = cleanStoredOpportunity(opp, await competitorNames(opp.brand_id));+ const request = {+ count: 1,+ idea: direction || null,+ alternativeOf: {+ id: opp.id,+ title: readable.title,+ description: readable.description ?? null,+ decision: opp.decision ?? null,+ clusterId,+ },+ idempotencyKey,+ };+ const job = await createJob({+ type: 'content',+ brandId: opp.brand_id,+ data: { brandId: opp.brand_id, model: null, request },+ maxAttempts: 2,+ });+ runContentJob(job.id, req.app.get('io'));++ return res.status(202).json({ jobId: job.id });+ } catch (error) {+ if (error instanceof PlanLimitError) {+ return res.status(error.statusCode).json({+ success: false,+ error: 'plan_limit',+ message: error.message,+ });+ }+ if (error.status) return res.status(error.status).json({ error: error.message });+ req.log.error({ err: error }, 'alternative opportunity error');+ return res.status(500).json({ error: 'Failed to start generation' });+ }+});+/*** GET /api/content/job/:jobId* Returns job state and progress for content generation.@@ -755,7 +859,7 @@ router.post('/bulk/send-webhook', async (req, res) => {router.patch('/:id/status', async (req, res) => {try {const { id } = req.params;- const { status } = req.body;+ const { status, reason } = req.body;const validStatuses = ['new', 'reviewed', 'sent', 'in_progress', 'done', 'dismissed'];if (!validStatuses.includes(status)) {@@ -764,14 +868,37 @@ router.patch('/:id/status', async (req, res) => {.json({ error: `Invalid status. Must be one of: ${validStatuses.join(', ')}` });}- await assertOpportunityAccess(id, req.user.id);-- const { data, error } = await supabaseAdmin- .from('content_opportunities')- .update({ status, updated_at: new Date().toISOString() })- .eq('id', id)- .select()- .single();+ let current = await assertOpportunityAccess(id, req.user.id);++ // Why it was dismissed (CONTENT-006) rides in source_data, which other+ // writers touch too (an Action Center send, a duplicate merge). The row+ // is written only if it hasn't changed since it was read; otherwise it is+ // read again and the change applied once more on the fresh copy.+ let data = null;+ let error = null;+ for (let attempt = 0; attempt < 2 && !data && !error; attempt++) {+ if (attempt > 0) {+ const fresh = await supabaseAdmin+ .from('content_opportunities')+ .select('*')+ .eq('id', id)+ .maybeSingle();+ if (fresh.error) throw new Error(fresh.error.message);+ if (!fresh.data) break;+ current = fresh.data;+ }+ const sourceData = sourceDataForStatus(current.source_data, status, reason);+ let update = supabaseAdmin+ .from('content_opportunities')+ .update({+ status,+ updated_at: new Date().toISOString(),+ ...(sourceData ? { source_data: sourceData } : {}),+ })+ .eq('id', id);+ if (sourceData) update = update.eq('updated_at', current.updated_at);+ ({ data, error } = await update.select().maybeSingle());+ }if (error) throw new Error(error.message);if (!data) return res.status(404).json({ error: 'Opportunity not found' });diff --git a/server/src/workers/content-worker.js b/server/src/workers/content-worker.jsindex 70ce0b923..f79bca27f 100644--- a/server/src/workers/content-worker.js+++ b/server/src/workers/content-worker.js@@ -17,11 +17,15 @@ import { refreshPromptClusters } from '../lib/prompt-clusters.js';* @param {{ brandId: string, model?: string, job: { progress: function }, request?: object | null }} opts*/export async function processContentJob({ brandId, model, job, request = null }) {- job.progress({ phase: 'collecting_data', message: 'Grouping prompts into clusters...' });- try {- await refreshPromptClusters(brandId);- } catch (err) {- logger.error({ err, brandId }, 'prompt cluster refresh failed before generation');+ // An alternative (CONTENT-006) is asked for one known cluster; regrouping+ // first could replace that cluster before it's read.+ if (!request?.alternativeOf) {+ job.progress({ phase: 'collecting_data', message: 'Grouping prompts into clusters...' });+ try {+ await refreshPromptClusters(brandId);+ } catch (err) {+ logger.error({ err, brandId }, 'prompt cluster refresh failed before generation');+ }}// A "+ New" request (CONTENT-003) carries its count, focus and idea, and@@ -35,6 +39,7 @@ export async function processContentJob({ brandId, model, job, request = null })topicId: request.topicId ?? null,promptId: request.promptId ?? null,idea: request.idea ?? null,+ alternativeOf: request.alternativeOf ?? null,source: 'manual',}: {}),diff --git a/web/messages/en.json b/web/messages/en.jsonindex 0bf5947ac..14a3ba23f 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1818,6 +1818,38 @@"newRefunded": "Nothing was used from your monthly quota.","retry": "Retry","generatingRow": "Generating…",+ "alternative": {+ "button": "Another angle",+ "running": "Writing another angle…",+ "hint": "Suggest one more opportunity for the same need, with a different angle",+ "badge": "Alternative",+ "of": "Another angle on",+ "title": "Another angle",+ "description": "Ansvisor writes one more opportunity for the same need, with a different content type, format, audience or approach. Both stay in the list so you can keep the one you prefer.",+ "direction": "Direction (optional)",+ "directionPlaceholder": "e.g. more technical, a video instead of a blog post, aimed at agencies",+ "uses": "Uses 1 of your {remaining} remaining this month → {after} left after this.",+ "usesUnlimited": "Uses one generation.",+ "noneLeft": "You've used this month's opportunities. They reset when your subscription renews.",+ "generate": "Write another angle",+ "started": "Writing another angle — it will appear in the list.",+ "done": "Another angle is in the list.",+ "none": "No new angle could be written for this need.",+ "failed": "Couldn't write another angle — please try again.",+ "stillRunning": "Still writing another angle — it will appear in the list when it's done."+ },+ "dismissReason": {+ "title": "Why dismiss it?",+ "description": "This helps Ansvisor suggest better opportunities.",+ "not_relevant": {+ "label": "The topic doesn't matter to us",+ "hint": "It won't be suggested again in this form for 90 days."+ },+ "wrong_angle": {+ "label": "Right topic, wrong angle",+ "hint": "Dismiss it and ask for another angle on the same need."+ }+ },"newDialog": {"title": "New content opportunities","description": "Generate fresh suggestions now instead of waiting for the next scheduled run.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex 49b08147b..4e71db111 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -1461,6 +1461,17 @@ export default function ContentPage() {</Badge>)}{/* Before the title, which is clamped to one line. */}+ {opp.sourceData?.alternativeOf && (+ <Badge+ variant="outline"+ className="mr-1.5 align-middle text-[10px] font-normal text-muted-foreground"+ title={+ t('alternative.of') + ' ' + opp.sourceData.alternativeOf.title+ }+ >+ {t('alternative.badge')}+ </Badge>+ )}{opp.source && opp.source !== 'system' && (<Badgevariant="outline"diff --git a/web/src/components/content/opportunity-angle-dialogs.tsx b/web/src/components/content/opportunity-angle-dialogs.tsxnew file mode 100644index 000000000..fee7e8c1a--- /dev/null+++ b/web/src/components/content/opportunity-angle-dialogs.tsx@@ -0,0 +1,185 @@+'use client';++import { useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Loader2, RefreshCw } from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Textarea } from '@/components/ui/textarea';+import { cn } from '@/lib/utils';+import { getContentUsage } from '@/lib/actions/content';++/** Longest direction the server accepts (IDEA_MAX_LENGTH in opportunity-generator.js). */+const DIRECTION_MAX_LENGTH = 500;++/**+ * "Another angle" (CONTENT-006): ask for one more opportunity for the same+ * need with a different angle, optionally steered by a short direction. It+ * uses one of the month's opportunities, which the dialog says up front.+ */+export function AlternativeDialog({+ open,+ onOpenChange,+ onSubmit,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Starts generation; resolves to whether it started. */+ onSubmit: (direction: string | null) => Promise<boolean>;+}) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ {/* Mounted per opening, so every opening starts from a fresh form. */}+ {open && <AlternativeForm onSubmit={onSubmit} onClose={() => onOpenChange(false)} />}+ </DialogContent>+ </Dialog>+ );+}++function AlternativeForm({+ onSubmit,+ onClose,+}: {+ onSubmit: (direction: string | null) => Promise<boolean>;+ onClose: () => void;+}) {+ const t = useTranslations('content.alternative');+ const tCommon = useTranslations('common');+ const [direction, setDirection] = useState('');+ const [submitting, setSubmitting] = useState(false);+ // null while loading; -1 when the month is unlimited.+ const [remaining, setRemaining] = useState<number | null>(null);++ useEffect(() => {+ let cancelled = false;+ getContentUsage().then(+ (usage) => {+ if (!cancelled) {+ setRemaining(usage.opportunities.limit === -1 ? -1 : usage.opportunities.remaining);+ }+ },+ () => !cancelled && setRemaining(-1),+ );+ return () => {+ cancelled = true;+ };+ }, []);++ const noneLeft = remaining === 0;++ const submit = async () => {+ if (submitting || noneLeft) return;+ setSubmitting(true);+ const ok = await onSubmit(direction.trim() || null);+ setSubmitting(false);+ if (ok) onClose();+ };++ return (+ <>+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ <DialogDescription>{t('description')}</DialogDescription>+ </DialogHeader>+ <div className="space-y-3">+ <div className="space-y-1.5">+ <label+ htmlFor="alternative-direction"+ className="text-xs font-medium text-muted-foreground"+ >+ {t('direction')}+ </label>+ <Textarea+ id="alternative-direction"+ value={direction}+ onChange={(e) => setDirection(e.target.value.slice(0, DIRECTION_MAX_LENGTH))}+ placeholder={t('directionPlaceholder')}+ rows={2}+ className="text-sm"+ />+ </div>+ {remaining !== null && (+ <p+ className={cn(+ 'rounded-md border bg-muted/40 px-3 py-2 text-xs',+ noneLeft && 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',+ )}+ >+ {noneLeft+ ? t('noneLeft')+ : remaining === -1+ ? t('usesUnlimited')+ : t('uses', { remaining, after: remaining - 1 })}+ </p>+ )}+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={onClose} disabled={submitting}>+ {tCommon('cancel')}+ </Button>+ <Button onClick={submit} disabled={submitting || noneLeft} className="gap-2">+ {submitting ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <RefreshCw className="h-4 w-4" />+ )}+ {t('generate')}+ </Button>+ </DialogFooter>+ </>+ );+}++export type DismissReason = 'not_relevant' | 'wrong_angle';++/**+ * Why an opportunity is being dismissed (CONTENT-006): the topic doesn't+ * matter to the brand, or the topic is right and the angle wrong — which+ * goes on to ask for another angle.+ */+export function DismissReasonDialog({+ open,+ onOpenChange,+ onChoose,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onChoose: (reason: DismissReason) => void;+}) {+ const t = useTranslations('content.dismissReason');+ const choose = (reason: DismissReason) => {+ onOpenChange(false);+ onChoose(reason);+ };+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ <DialogDescription>{t('description')}</DialogDescription>+ </DialogHeader>+ <div className="grid gap-2">+ {(['not_relevant', 'wrong_angle'] as const).map((reason) => (+ <button+ key={reason}+ type="button"+ onClick={() => choose(reason)}+ className="rounded-md border px-3 py-2.5 text-left transition-colors hover:bg-muted/50"+ >+ <p className="text-sm font-medium">{t(`${reason}.label`)}</p>+ <p className="text-xs text-muted-foreground">{t(`${reason}.hint`)}</p>+ </button>+ ))}+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsxindex fcffeb74e..2d20797a9 100644--- a/web/src/components/content/opportunity-detail.tsx+++ b/web/src/components/content/opportunity-detail.tsx@@ -27,6 +27,7 @@ import {Copy,ExternalLink,Info,+ RefreshCw,} from 'lucide-react';import { cn } from '@/lib/utils';import { Link } from '@/i18n/navigation';@@ -37,8 +38,15 @@ import {generateBrief,getBriefQuota,sendOpportunityToActionCenter,+ suggestAlternative,+ getGenerationJobStatus,type BriefQuota,} from '@/lib/actions/content';+import {+ AlternativeDialog,+ DismissReasonDialog,+ type DismissReason,+} from '@/components/content/opportunity-angle-dialogs';import type { ContentBrief, ContentOpportunity } from '@/types';import { getPromptFanout, type FanoutSubQuery } from '@/lib/actions/fanout';import {@@ -106,6 +114,9 @@ function StatCard({* actions. Rendered as its own page (/dashboard/content/[id]) and inside the* list's drawer, so reviewing one never loses the list's filters.*/+/** How long the panel follows an "Another angle" job before giving up. */+const ALTERNATIVE_TIMEOUT_MS = 3 * 60 * 1000;+export function OpportunityDetail({id,inDrawer = false,@@ -183,12 +194,67 @@ export function OpportunityDetail({}};- const handleDismiss = async () => {+ // "Another angle" (CONTENT-006): generation runs as a content job; the+ // panel follows it and says when the alternative is in the list.+ const [alternativeOpen, setAlternativeOpen] = useState(false);+ const [dismissOpen, setDismissOpen] = useState(false);+ const [alternativeRunning, setAlternativeRunning] = useState(false);++ const followAlternative = async (jobId: string) => {+ setAlternativeRunning(true);+ const startedAt = Date.now();try {- await updateOpportunityStatus(id, 'dismissed');+ while (Date.now() - startedAt < ALTERNATIVE_TIMEOUT_MS) {+ await new Promise((r) => setTimeout(r, 3000));+ const job = await getGenerationJobStatus(jobId);+ if (job.status === 'completed') {+ if (job.result?.limited) toast.error(t('newLimitReached'));+ else if ((job.result?.generated ?? 0) > 0) toast.success(t('alternative.done'));+ else toast(t('alternative.none'));+ onChanged?.();+ return;+ }+ if (job.status === 'failed') {+ toast.error(job.failedReason || t('alternative.failed'), {+ description: t('newRefunded'),+ });+ return;+ }+ }+ // The job may still finish (and use its slot), so don't promise a refund.+ toast(t('alternative.stillRunning'));+ } finally {+ setAlternativeRunning(false);+ }+ };++ const handleAlternative = async (direction: string | null): Promise<boolean> => {+ const result = await suggestAlternative(id, {+ direction,+ idempotencyKey: crypto.randomUUID(),+ }).catch((err: unknown) => ({+ ok: false as const,+ error: err instanceof Error ? err.message : t('alternative.failed'),+ quotaExhausted: false,+ noCluster: false,+ }));+ if (!result.ok) {+ toast.error(result.quotaExhausted ? t('newLimitReached') : result.error);+ return false;+ }+ toast(t('alternative.started'));+ void followAlternative(result.jobId);+ return true;+ };++ const handleDismiss = async (reason?: DismissReason) => {+ try {+ await updateOpportunityStatus(id, 'dismissed', reason);const updated = await getOpportunity(id);setOpportunity(updated);onChanged?.();+ // The topic is right, the angle wrong: offer the other angle straight away.+ if (reason === 'wrong_angle') setAlternativeOpen(true);toast.success(t('dismissedToast'), {action: {label: t('undo'),@@ -307,6 +373,20 @@ export function OpportunityDetail({)}<div className="min-w-0 flex-1"><h1 className="text-xl font-bold tracking-tight">{opportunity.title}</h1>+ {sd.alternativeOf && (+ <p className="mt-1 text-xs text-muted-foreground">+ <Badge variant="outline" className="mr-1.5 text-[10px] font-normal">+ {t('alternative.badge')}+ </Badge>+ {t('alternative.of')}{' '}+ <Link+ href={`/dashboard/content?opportunity=${sd.alternativeOf.id}`}+ className="text-primary hover:underline"+ >+ {sd.alternativeOf.title}+ </Link>+ </p>+ )}{opportunity.description && (<p className="text-sm text-muted-foreground mt-1">{opportunity.description}</p>)}@@ -330,9 +410,25 @@ export function OpportunityDetail({<Badge variant="outline" className="text-xs tabular-nums">Score: {Math.round(opportunity.opportunityScore)}</Badge>+ <Button+ type="button"+ variant="ghost"+ size="xs"+ className="ml-auto gap-1 text-xs text-muted-foreground"+ onClick={() => setAlternativeOpen(true)}+ disabled={alternativeRunning}+ title={t('alternative.hint')}+ >+ {alternativeRunning ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <RefreshCw className="h-3 w-3" />+ )}+ {alternativeRunning ? t('alternative.running') : t('alternative.button')}+ </Button>{/* The UI's language, not the browser's: an English page showed "25 Eyl". */}<span- className="text-xs text-muted-foreground ml-auto flex items-center gap-1.5"+ className="text-xs text-muted-foreground flex items-center gap-1.5"title={suggestedDate(opportunity.createdAt, locale).full}><Clock className="h-3.5 w-3.5" />@@ -432,7 +528,7 @@ export function OpportunityDetail({<Buttonvariant="ghost"size="sm"- onClick={handleDismiss}+ onClick={() => setDismissOpen(true)}className="gap-2 text-muted-foreground hover:text-destructive"><X className="h-4 w-4" />@@ -732,6 +828,16 @@ export function OpportunityDetail({</CardContent></Card>)}+ <AlternativeDialog+ open={alternativeOpen}+ onOpenChange={setAlternativeOpen}+ onSubmit={handleAlternative}+ />+ <DismissReasonDialog+ open={dismissOpen}+ onOpenChange={setDismissOpen}+ onChoose={(reason) => void handleDismiss(reason)}+ /></div>);}diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.tsindex 71457566b..675506bf1 100644--- a/web/src/lib/actions/content.ts+++ b/web/src/lib/actions/content.ts@@ -374,6 +374,8 @@ export async function generateBrief(export async function updateOpportunityStatus(id: string,status: string,+ /** Why it was dismissed (CONTENT-006); only read with status 'dismissed'. */+ reason?: 'not_relevant' | 'wrong_angle',): Promise<ContentOpportunity> {const session = await getSession();@@ -383,7 +385,7 @@ export async function updateOpportunityStatus('Content-Type': 'application/json',Authorization: `Bearer ${session.access_token}`,},- body: JSON.stringify({ status }),+ body: JSON.stringify({ status, ...(reason ? { reason } : {}) }),});if (!res.ok) {@@ -599,3 +601,38 @@ export async function saveWebhookConfig(updatedAt: data.updated_at ?? new Date().toISOString(),};}++export type AlternativeResult =+ | { ok: true; jobId: string }+ | { ok: false; error: string; quotaExhausted?: boolean; noCluster?: boolean };++/**+ * "Another angle" (CONTENT-006): starts generating one more opportunity for+ * the same need with a different angle. Errors come back as values.+ */+export async function suggestAlternative(+ id: string,+ { direction, idempotencyKey }: { direction?: string | null; idempotencyKey: string },+): Promise<AlternativeResult> {+ const session = await getSession();++ const res = await fetch(`${AEO_SERVER_URL}/api/content/${id}/alternative`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ direction: direction || null, idempotencyKey }),+ });++ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ return {+ ok: false,+ error: body.message || body.error || `Server error: ${res.status}`,+ quotaExhausted: body.error === 'quota_exhausted',+ noCluster: body.error === 'no_cluster',+ };+ }+ return { ok: true, jobId: body.jobId };+}diff --git a/web/src/types/index.ts b/web/src/types/index.tsindex 85738f600..866cec0c2 100644--- a/web/src/types/index.ts+++ b/web/src/types/index.ts@@ -232,6 +232,10 @@ export interface ContentOpportunitySourceData {* (CONTENT-004): clusters whose prompt and fan-out baskets matched its own.*/duplicatesMerged?: number;+ /** The opportunity this one is another angle on (CONTENT-006). */+ alternativeOf?: { id: string; title: string };+ /** Why it was dismissed, when the user said (CONTENT-006). */+ dismissReason?: 'not_relevant' | 'wrong_angle';/** Why a finished opportunity went back to New (#857, Phase 4). */reopened?: {at: string;