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(content): let single-prompt opportunities go to the Action Center too (#1025)
Cihan51462721982a
diff --git a/server/src/lib/action-center/basket-metrics.js b/server/src/lib/action-center/basket-metrics.jsindex 1d691cb05..d12e01917 100644--- a/server/src/lib/action-center/basket-metrics.js+++ b/server/src/lib/action-center/basket-metrics.js@@ -75,7 +75,8 @@ export function basketValues(raw, { pageCount }) {/*** The prompts and pages an action covers. Actions sent before the payload- * carried prompt ids take them from the opportunity's clusters as they are now.+ * carried prompt ids take them from the opportunity's clusters as they are+ * now, or, without clusters, from the one prompt it was written for.*/export async function basketScope(action) {const payload = action.payload || {};@@ -83,7 +84,7 @@ export async function basketScope(action) {if (!promptIds.length && payload.opportunityId) {const { data: opp } = await supabaseAdmin.from('content_opportunities')- .select('cluster_id, related_cluster_ids')+ .select('cluster_id, related_cluster_ids, prompt_id').eq('id', payload.opportunityId).maybeSingle();const clusterIds = [opp?.cluster_id, ...(opp?.related_cluster_ids || [])].filter(Boolean);@@ -95,6 +96,7 @@ export async function basketScope(action) {if (error) throw new Error(error.message);promptIds = (members || []).map((m) => m.prompt_id);}+ if (!promptIds.length && opp?.prompt_id) promptIds = [opp.prompt_id];}return { promptIds, pages: Array.isArray(payload.pages) ? payload.pages : [] };}diff --git a/server/src/lib/action-center/basket-metrics.test.js b/server/src/lib/action-center/basket-metrics.test.jsindex fad5c880b..7cb9b195e 100644--- a/server/src/lib/action-center/basket-metrics.test.js+++ b/server/src/lib/action-center/basket-metrics.test.js@@ -1,8 +1,22 @@import { describe, expect, it, vi } from 'vitest';-vi.mock('../../config/supabase.js', () => ({ default: {} }));+const tables = {};+vi.mock('../../config/supabase.js', () => ({+ default: { from: (table) => tables[table]() },+}));-const { BASKET_KPIS, basketValues, pageScope } = await import('./basket-metrics.js');+const { BASKET_KPIS, basketScope, basketValues, pageScope } = await import('./basket-metrics.js');++/** A query builder that resolves to `result` however it is chained. */+function chain(result) {+ const b = {+ select: () => b,+ eq: () => b,+ in: () => Promise.resolve(result),+ maybeSingle: () => Promise.resolve(result),+ };+ return b;+}describe('pageScope', () => {it('turns page URLs into citation keys, hosts and GA paths', () => {@@ -63,3 +77,27 @@ describe('basketValues', () => {);});});++describe('basketScope', () => {+ it('uses the prompt ids the action was sent with', async () => {+ expect(await basketScope({ payload: { promptIds: ['p1'], pages: ['u'] } })).toEqual({+ promptIds: ['p1'],+ pages: ['u'],+ });+ });++ it("falls back to the opportunity's clusters, then to its own prompt", async () => {+ tables.content_opportunities = () =>+ chain({ data: { cluster_id: 'c1', related_cluster_ids: [], prompt_id: 'p9' } });+ tables.prompt_cluster_members = () =>+ chain({ data: [{ prompt_id: 'p1' }, { prompt_id: 'p2' }], error: null });+ expect((await basketScope({ payload: { opportunityId: 'o1' } })).promptIds).toEqual([+ 'p1',+ 'p2',+ ]);++ tables.content_opportunities = () =>+ chain({ data: { cluster_id: null, related_cluster_ids: [], prompt_id: 'p9' } });+ expect((await basketScope({ payload: { opportunityId: 'o1' } })).promptIds).toEqual(['p9']);+ });+});diff --git a/server/src/lib/action-center/from-opportunity.js b/server/src/lib/action-center/from-opportunity.jsindex 56ac29b26..2780dc28b 100644--- a/server/src/lib/action-center/from-opportunity.js+++ b/server/src/lib/action-center/from-opportunity.js@@ -82,6 +82,20 @@ export function opportunityAssets(opportunity) {const ACTIVE = ['new', 'in_progress', 'on_hold'];+/**+ * What the action is measured on and shows as its targets: the prompts of+ * the opportunity's clusters, or, without any (the older per-prompt+ * generator, or clusters a re-clustering removed), the one prompt it was+ * written for. The targets always name what is measured.+ */+export function actionPromptScope(opportunity, memberPromptIds) {+ const sd = opportunity.source_data || {};+ if (memberPromptIds.length || !opportunity.prompt_id) {+ return { promptIds: memberPromptIds, prompts: sd.prompts || [] };+ }+ return { promptIds: [opportunity.prompt_id], prompts: sd.promptText ? [sd.promptText] : [] };+}+/*** A task's status when the action opens. The brief task starts completed when* the opportunity already has a brief: the work is done, and the brief is@@ -121,7 +135,6 @@ export async function sendToActionCenter(opportunity, { assetKey = null, userIdif (open) return { actionId: open.id, created: false };const sd = opportunity.source_data || {};- const prompts = sd.prompts || [];// The prompts the action is measured on (basket-metrics.js), fixed at send// time so a later re-clustering does not change what it is judged by.const clusterIds = [opportunity.cluster_id, ...(opportunity.related_cluster_ids || [])].filter(@@ -134,6 +147,10 @@ export async function sendToActionCenter(opportunity, { assetKey = null, userId.in('cluster_id', clusterIds): { data: [], error: null };if (membersErr) throw new Error(membersErr.message);+ const { promptIds, prompts } = actionPromptScope(+ opportunity,+ (members || []).map((m) => m.prompt_id),+ );const payload = {source: OPPORTUNITY_ACTION_KIND,opportunityId: opportunity.id,@@ -148,7 +165,7 @@ export async function sendToActionCenter(opportunity, { assetKey = null, userIdtitle,})),pages: [...new Set(chosen.flatMap((a) => (a.pages || []).map((p) => p.url)))],- promptIds: (members || []).map((m) => m.prompt_id),+ promptIds,targetEntity: 'prompts',targetCount: prompts.length,targets: prompts.slice(0, 50),diff --git a/server/src/lib/action-center/from-opportunity.test.js b/server/src/lib/action-center/from-opportunity.test.jsindex c8efff4cc..e4d2b331f 100644--- a/server/src/lib/action-center/from-opportunity.test.js+++ b/server/src/lib/action-center/from-opportunity.test.js@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';vi.mock('../../config/supabase.js', () => ({ default: {} }));-const { assetTasks, combinedTasks, initialTaskStatus, opportunityAssets } =+const { actionPromptScope, assetTasks, combinedTasks, initialTaskStatus, opportunityAssets } =await import('./from-opportunity.js');const { getTask } = await import('./tasks/registry.js');@@ -100,3 +100,33 @@ describe('opportunityAssets', () => {});});});++describe('actionPromptScope', () => {+ it("measures a cluster opportunity on its clusters' prompts", () => {+ expect(+ actionPromptScope({ prompt_id: 'p1', source_data: { prompts: ['A', 'B'] } }, ['p1', 'p2']),+ ).toEqual({ promptIds: ['p1', 'p2'], prompts: ['A', 'B'] });+ });++ it('measures a single-prompt opportunity on its own prompt', () => {+ expect(+ actionPromptScope({ prompt_id: 'p9', source_data: { promptText: 'Best espresso?' } }, []),+ ).toEqual({ promptIds: ['p9'], prompts: ['Best espresso?'] });+ });++ it('names only the prompt it measures when the clusters are gone', () => {+ expect(+ actionPromptScope(+ { prompt_id: 'p1', source_data: { promptText: 'A', prompts: ['A', 'B', 'C'] } },+ [],+ ),+ ).toEqual({ promptIds: ['p1'], prompts: ['A'] });+ });++ it('has nothing to measure when neither is known', () => {+ expect(actionPromptScope({ prompt_id: null, source_data: {} }, [])).toEqual({+ promptIds: [],+ prompts: [],+ });+ });+});diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex 4478459af..a9828ceb6 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -1273,7 +1273,31 @@ router.get('/:id/basket', async (req, res) => {try {const opp = await assertOpportunityAccess(req.params.id, req.user.id);const clusterIds = [opp.cluster_id, ...(opp.related_cluster_ids || [])].filter(Boolean);- if (!clusterIds.length) return res.json({ clusters: [], queries: [] });+ if (!clusterIds.length) {+ // An opportunity from the per-prompt generator rests on its one prompt:+ // the Action Center lists it like a one-prompt group.+ if (!opp.prompt_id) return res.json({ clusters: [], queries: [] });+ const { data: prompt, error: promptErr } = await supabaseAdmin+ .from('prompts')+ .select('id, text')+ .eq('id', opp.prompt_id)+ .maybeSingle();+ if (promptErr) throw new Error(promptErr.message);+ return res.json({+ clusters: prompt+ ? [+ {+ id: `prompt:${prompt.id}`,+ label: prompt.text,+ need: '',+ topicName: null,+ prompts: [prompt],+ },+ ]+ : [],+ queries: [],+ });+ }const [clustersRes, membersRes, queriesRes] = await Promise.all([supabaseAdmindiff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsxindex 1af657b93..fcffeb74e 100644--- a/web/src/components/content/opportunity-detail.tsx+++ b/web/src/components/content/opportunity-detail.tsx@@ -365,32 +365,32 @@ export function OpportunityDetail({{generatingBrief ? t('generatingBrief') : t('generateBrief')}</Button>)}- {opportunity.clusterId &&- (actionId ? (- <Link href={`/dashboard/action-center/actions?action=${actionId}`}>- <Button variant="outline" size="sm" className="gap-2">- <ExternalLink className="h-4 w-4" />- {t('openInActions')}- </Button>- </Link>- ) : (- canSendToActionCenter && (- <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('sendToActions')}- </Button>- )- ))}+ {/* Every opportunity can go to the Action Center, cluster or single prompt. */}+ {actionId ? (+ <Link href={`/dashboard/action-center/actions?action=${actionId}`}>+ <Button variant="outline" size="sm" className="gap-2">+ <ExternalLink className="h-4 w-4" />+ {t('openInActions')}+ </Button>+ </Link>+ ) : (+ canSendToActionCenter && (+ <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('sendToActions')}+ </Button>+ )+ )}{canSendToWorkflow && (<Buttonvariant="outline"