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(prompts): suggest content for a prompt from its row menu (#1028)
Cihan4f822ec7d24d
diff --git a/server/src/lib/access.js b/server/src/lib/access.jsindex 4568ba7df..af7a3188b 100644--- a/server/src/lib/access.js+++ b/server/src/lib/access.js@@ -104,7 +104,8 @@ export async function assertOpportunityAccess(id, userId) {/*** Assert that every prompt in `promptIds` belongs to the caller's org,* resolved through prompts -> prompt_sets -> brands.- * @returns {Promise<object[]>} the matched prompt rows+ * @returns {Promise<object[]>} the matched prompt rows, each with+ * prompt_sets.brand_id and prompt_sets.brands.organization_id*/export async function assertPromptAccess(promptIds, userId) {const ids = Array.isArray(promptIds) ? promptIds : [promptIds];@@ -112,7 +113,7 @@ export async function assertPromptAccess(promptIds, userId) {const { data: rows } = await supabaseAdmin.from('prompts')- .select('id, prompt_sets!inner(brands!inner(organization_id))')+ .select('id, prompt_sets!inner(brand_id, brands!inner(organization_id))').in('id', ids);if (!rows || rows.length < new Set(ids).size) {diff --git a/server/src/lib/opportunity-candidates.test.js b/server/src/lib/opportunity-candidates.test.jsnew file mode 100644index 000000000..201cd0685--- /dev/null+++ b/server/src/lib/opportunity-candidates.test.js@@ -0,0 +1,51 @@+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 { openCandidates } = await import('./opportunity-generator.js');+const { openlyCoveredClusterIds } = await import('./opportunity-limits.js');++// Which clusters a run may write an opportunity for.++const cluster = (id, tested = 3) => ({ id, metrics: { tested } });+const candidates = [cluster('c1'), cluster('c2'), cluster('c3', 0)];+const covered = new Set(['c1']);+const everywhere = () => true;+const ids = (list) => list.map((c) => c.id);++describe('openCandidates', () => {+ it('skips covered clusters and clusters without answers', () => {+ expect(ids(openCandidates(candidates, { covered, inFocus: everywhere }))).toEqual(['c2']);+ });++ it("lets a prompt's own request revisit a cluster whose opportunity was dismissed (PROMPT-006)", () => {+ const inFocus = (c) => c.id === 'c1';+ const dismissed = [{ cluster_id: 'c1', related_cluster_ids: [], status: 'dismissed' }];+ const open = [{ cluster_id: 'c1', related_cluster_ids: [], status: 'new' }];+ expect(+ ids(openCandidates(candidates, { covered: openlyCoveredClusterIds(dismissed), inFocus })),+ ).toEqual(['c1']);+ expect(+ ids(openCandidates(candidates, { covered: openlyCoveredClusterIds(open), inFocus })),+ ).toEqual([]);+ });++ it("still needs answers for a prompt's own request", () => {+ const inFocus = (c) => c.id === 'c3';+ expect(ids(openCandidates(candidates, { covered: new Set(), inFocus }))).toEqual([]);+ });++ it('keeps another angle to its own cluster (CONTENT-006)', () => {+ expect(+ ids(+ openCandidates(candidates, {+ covered,+ inFocus: everywhere,+ alternativeOf: { clusterId: 'c1' },+ }),+ ),+ ).toEqual(['c1']);+ });+});diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.jsindex 54bc49830..1696b5ba1 100644--- a/server/src/lib/opportunity-generator.js+++ b/server/src/lib/opportunity-generator.js@@ -20,6 +20,8 @@ import {OPPORTUNITY_WINDOW_DAYS,clusterMetrics,coveredClusterIds,+ openOpportunityOn,+ openlyCoveredClusterIds,opportunityScore,pickClusters,scoreComponents,@@ -220,6 +222,16 @@ async function loadPromptTexts(promptIds) {return data || [];}+/**+ * The clusters a run may write for: those with answers to go on that aren't+ * covered yet, within the request's focus. "Another angle" (CONTENT-006) is+ * for its own cluster only.+ */+export function openCandidates(candidates, { covered, inFocus, alternativeOf = null }) {+ if (alternativeOf) return candidates.filter((c) => c.id === alternativeOf.clusterId);+ return candidates.filter((c) => c.metrics.tested > 0 && !covered.has(c.id) && inFocus(c));+}+/*** 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@@ -250,13 +262,18 @@ export const IDEA_MAX_LENGTH = 500;* idea?: string | null,* source?: 'system' | 'manual' | 'prompt',* alternativeOf?: { id: string, title: string, description?: string|null, decision?: string|null, clusterId: string } | null,+ * explicit?: boolean,* }} [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 }>}+ * `explicit` is a request for the focused prompt's cluster itself (PROMPT-006+ * "Suggest content"): it is written even if the cluster was covered by a+ * dismissed or finished opportunity, never when an open one covers it, and+ * never merged away.+ * @returns {Promise<{ generated: number, merged: number, reopened?: number, duplicates?: number, limited?: boolean, opportunityIds?: string[], existingId?: string }>}*/export async function generateContentOpportunities(brandId,@@ -269,8 +286,12 @@ export async function generateContentOpportunities(idea = null,source = 'system',alternativeOf = null,+ explicit = false,} = {},) {+ // The user asked for this cluster by name: the duplicate check, merging+ // into another opportunity and reopening finished ones don't apply.+ const targeted = !!alternativeOf || explicit;onProgress?.({ phase: 'collecting_data', message: 'Fetching clusters and metrics...' });const { data: brand } = await supabaseAdmin@@ -346,16 +367,22 @@ export async function generateContentOpportunities(};// Finished opportunities whose signals moved go back to New before any new- // ones are written; they keep their clusters, so nothing is duplicated.+ // ones are written; they keep their clusters, so nothing is duplicated. A+ // run asked for one cluster leaves that to the next regular run: reopening+ // that cluster's own would put two open opportunities on it.let reopened = 0;- try {- reopened = await reopenStrengthened(brandId, existing, measure);- } catch (err) {- logger.error({ err, brandId }, '[opportunities] re-opening finished opportunities failed');+ if (!targeted) {+ try {+ reopened = await reopenStrengthened(brandId, existing, measure);+ } catch (err) {+ logger.error({ err, brandId }, '[opportunities] re-opening finished opportunities failed');+ }}const candidates = clusters.map((c) => ({ id: c.id, topicId: c.topic_id, ...measure([c.id]) }));- const covered = coveredClusterIds(existing);+ // A prompt's own request may revisit a cluster whose opportunity was+ // dismissed or finished, never one with an open opportunity.+ const covered = explicit ? openlyCoveredClusterIds(existing) : coveredClusterIds(existing);// The fan-out baskets of every cluster still open for an opportunity: the// duplicate check compares them, and the prompt shows the picked ones'.@@ -363,9 +390,7 @@ export async function generateContentOpportunities(const inFocus = (c) =>(!topicId || c.topicId === topicId) &&(!promptId || clusterById.get(c.id).prompt_ids.includes(promptId));- const open = alternativeOf- ? candidates.filter((c) => c.id === alternativeOf.clusterId)- : candidates.filter((c) => c.metrics.tested > 0 && !covered.has(c.id) && inFocus(c));+ const open = openCandidates(candidates, { covered, inFocus, alternativeOf });const { data: basketRows, error: basketErr } = await selectInChunks(open.map((c) => c.id),(chunk) =>@@ -381,7 +406,7 @@ 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 = alternativeOf+ const duplicates = targeted? 0: await skipDuplicates(brandId, open, {clusterById,@@ -389,8 +414,8 @@ export async function generateContentOpportunities(covered,});- const wanted = alternativeOf- ? open.slice(0, 1)+ const wanted = targeted+ ? open.slice(0, count ?? 1): pickClusters(open, covered, count ?? OPPORTUNITIES_PER_RUN, {fill: count !== undefined,});@@ -399,7 +424,14 @@ export async function generateContentOpportunities({ brandId, clusters: clusters.length, opportunities: existing.length, reopened, duplicates },'[opportunities] every cluster with answers already has an opportunity',);- return { generated: 0, merged: 0, reopened, duplicates };+ // A request for one prompt that an open opportunity already answers+ // points at it (PROMPT-006): regrouping or another run may have covered+ // the prompt since the request was checked.+ const promptCluster = promptId+ ? clusters.find((c) => c.prompt_ids.includes(promptId))?.id+ : null;+ const existingId = openOpportunityOn(existing, promptCluster);+ return { generated: 0, merged: 0, reopened, duplicates, ...(existingId ? { existingId } : {}) };}// Each new opportunity takes one of the organization's monthly slots@@ -416,8 +448,8 @@ export async function generateContentOpportunities(logger.error({ err, brandId }, '[opportunities] handing back slots failed'),);- // An alternative is its own take, never folded into another opportunity.- const shown = (alternativeOf ? [] : existing)+ // An asked-for opportunity is its own, never folded into another one.+ const shown = (targeted ? [] : existing).filter((o) =>o.status !== 'dismissed' &&@@ -612,5 +644,12 @@ ${alternativeOf ? `${alternativeInstruction(alternativeOf)}\n\n` : ''}${{ brandId, generated: inserts.length, merged, reopened, duplicates, clusters: clusters.length },'[opportunities] generated',);- return { generated: inserts.length, merged, reopened, duplicates };+ // The new rows' ids, so a caller that asked for one can open it.+ return {+ generated: inserts.length,+ merged,+ reopened,+ duplicates,+ opportunityIds: created.map((row) => row.id),+ };}diff --git a/server/src/lib/opportunity-limits.js b/server/src/lib/opportunity-limits.jsindex ad55059a0..2ffcc8f02 100644--- a/server/src/lib/opportunity-limits.js+++ b/server/src/lib/opportunity-limits.js@@ -131,6 +131,31 @@ export function coveredClusterIds(rows) {return ids;}+/** Statuses that still stand for a need's content work. */+export const OPEN_OPPORTUNITY_STATUSES = ['new', 'reviewed', 'sent', 'in_progress'];++/**+ * Clusters with an open opportunity, which is all that holds back a prompt's+ * own "Suggest content" (PROMPT-006): unlike coveredClusterIds, a dismissed+ * or finished one doesn't count, since the user is asking again on purpose.+ */+export function openlyCoveredClusterIds(rows) {+ return coveredClusterIds(+ (rows || []).filter((r) => OPEN_OPPORTUNITY_STATUSES.includes(r.status)),+ );+}++/** An open opportunity covering the cluster, as its own or a merged one; null when none. */+export function openOpportunityOn(rows, clusterId) {+ if (!clusterId) return null;+ const match = (rows || []).find(+ (r) =>+ OPEN_OPPORTUNITY_STATUSES.includes(r.status) &&+ (r.cluster_id === clusterId || (r.related_cluster_ids || []).includes(clusterId)),+ );+ return match?.id ?? null;+}+/*** The highest-scoring clusters with answers and no opportunity yet, at most* one per topic, so a run's few suggestions spread across the brand's topicsdiff --git a/server/src/lib/opportunity-limits.test.js b/server/src/lib/opportunity-limits.test.jsindex 784196381..1e399a9e1 100644--- a/server/src/lib/opportunity-limits.test.js+++ b/server/src/lib/opportunity-limits.test.js@@ -2,10 +2,13 @@ import { describe, expect, it } from 'vitest';import { readFileSync } from 'node:fs';import { fileURLToPath } from 'node:url';import {+ OPEN_OPPORTUNITY_STATUSES,OPPORTUNITIES_PER_RUN,SCORE_WEIGHTS,clusterMetrics,coveredClusterIds,+ openOpportunityOn,+ openlyCoveredClusterIds,opportunityScore,pickClusters,scoreComponents,@@ -96,6 +99,27 @@ describe('cluster selection', () => {expect([...covered].sort()).toEqual(['c1', 'c2', 'c3']);});+ it("holds a prompt's own request back only with an open opportunity (PROMPT-006)", () => {+ const rows = [+ { cluster_id: 'c1', related_cluster_ids: ['c2'], status: 'in_progress' },+ { cluster_id: 'c3', related_cluster_ids: [], status: 'dismissed' },+ { cluster_id: 'c4', related_cluster_ids: [], status: 'done' },+ { cluster_id: 'c5', related_cluster_ids: [], status: 'archived' },+ ];+ expect([...openlyCoveredClusterIds(rows)].sort()).toEqual(['c1', 'c2']);+ expect(OPEN_OPPORTUNITY_STATUSES).toEqual(['new', 'reviewed', 'sent', 'in_progress']);+ });++ it('names the open opportunity that covers a cluster, merged ones included', () => {+ const rows = [+ { id: 'o1', cluster_id: 'c1', related_cluster_ids: [], status: 'dismissed' },+ { id: 'o2', cluster_id: 'c9', related_cluster_ids: ['c1'], status: 'sent' },+ ];+ expect(openOpportunityOn(rows, 'c1')).toBe('o2');+ expect(openOpportunityOn(rows, 'c2')).toBeNull();+ expect(openOpportunityOn(rows, null)).toBeNull();+ });+it('takes the best uncovered clusters that have answers', () => {const cand = (id, score, tested = 1) => ({ id, score, topicId: id, metrics: { tested } });const picked = pickClusters(diff --git a/server/src/lib/prompt-content-suggestion.js b/server/src/lib/prompt-content-suggestion.jsnew file mode 100644index 000000000..b4def370e--- /dev/null+++ b/server/src/lib/prompt-content-suggestion.js@@ -0,0 +1,78 @@+/**+ * "Suggest content" from a prompt's row (PROMPT-006): one content opportunity+ * for that prompt, unless it already has an open one.+ *+ * A prompt is answered by its cluster's opportunity, or, for older ones, by an+ * opportunity written for the prompt itself, so both count as its own. Only+ * an open one stops a new suggestion: a dismissed or finished one doesn't,+ * since the user is asking again on purpose.+ */++import supabaseAdmin from '../config/supabase.js';+import { OPEN_OPPORTUNITY_STATUSES } from './opportunity-limits.js';++/** How long a queued or running job holds back a suggestion for its prompt. */+const RUNNING_WINDOW_MS = 10 * 60 * 1000;++/** The cluster the prompt is in today, or null before it's grouped. */+export async function promptClusterId(promptId) {+ const { data, error } = await supabaseAdmin+ .from('prompt_cluster_members')+ .select('cluster_id')+ .eq('prompt_id', promptId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ return data?.cluster_id ?? null;+}++/**+ * The newest open opportunity that answers this prompt: its cluster's own+ * or merged one, or one written for the prompt itself. Null when none is open.+ */+export async function openOpportunityForPrompt(brandId, promptId) {+ const clusterId = await promptClusterId(promptId);+ let query = supabaseAdmin+ .from('content_opportunities')+ .select('id')+ .eq('brand_id', brandId)+ .in('status', OPEN_OPPORTUNITY_STATUSES);+ query = clusterId+ ? query.or(+ `prompt_id.eq.${promptId},cluster_id.eq.${clusterId},related_cluster_ids.cs.{${clusterId}}`,+ )+ : query.eq('prompt_id', promptId);+ const { data, error } = await query.order('created_at', { ascending: false }).limit(1);+ if (error) throw new Error(error.message);+ return data?.[0]?.id ?? null;+}++/**+ * A content job for this prompt that is still queued or running: an earlier+ * suggestion, or "+ New" focused on the prompt. Asking again (after the page+ * stopped waiting, or from another tab) follows it instead of writing the+ * same opportunity twice; a job focused on one prompt writes at most one, for+ * the prompt's cluster. Null when there is none.+ */+export async function runningSuggestionJob(brandId, promptId) {+ const since = new Date(Date.now() - RUNNING_WINDOW_MS).toISOString();+ const { data, error } = await supabaseAdmin+ .from('jobs')+ .select('id')+ .eq('type', 'content')+ .eq('brand_id', brandId)+ .in('status', ['waiting', 'active'])+ .eq('data->request->>promptId', promptId)+ .gte('created_at', since)+ .order('created_at', { ascending: false })+ .limit(1);+ if (error) throw new Error(error.message);+ return data?.[0]?.id ?? null;+}++/**+ * The content job request for one suggestion: exactly one, for the prompt's+ * cluster even if an earlier opportunity there was dismissed, tagged prompt.+ */+export function promptSuggestionRequest(promptId, idempotencyKey) {+ return { count: 1, promptId, explicit: true, source: 'prompt', idempotencyKey };+}diff --git a/server/src/lib/prompt-content-suggestion.test.js b/server/src/lib/prompt-content-suggestion.test.jsnew file mode 100644index 000000000..afcccc8a6--- /dev/null+++ b/server/src/lib/prompt-content-suggestion.test.js@@ -0,0 +1,89 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++// PROMPT-006 "Suggest content": a prompt gets a new content opportunity only+// when nothing open answers it already.++const calls = [];+const results = {};+vi.mock('../config/supabase.js', () => ({+ default: {+ from: (table) => {+ const call = { table, ops: [] };+ calls.push(call);+ const b = new Proxy(+ {},+ {+ get: (_t, op) => {+ if (op === 'then') return (resolve) => resolve(results[table]);+ if (op === 'maybeSingle') return () => Promise.resolve(results[table]);+ return (...args) => {+ call.ops.push([op, ...args]);+ return b;+ };+ },+ },+ );+ return b;+ },+ },+}));++const { openOpportunityForPrompt, promptSuggestionRequest, runningSuggestionJob } =+ await import('./prompt-content-suggestion.js');+const { OPEN_OPPORTUNITY_STATUSES } = await import('./opportunity-limits.js');++beforeEach(() => {+ calls.length = 0;+ for (const k of Object.keys(results)) delete results[k];+});++describe('openOpportunityForPrompt', () => {+ it("finds an open opportunity on the prompt's cluster or for the prompt itself", async () => {+ results.prompt_cluster_members = { data: { cluster_id: 'c1' }, error: null };+ results.content_opportunities = { data: [{ id: 'o1' }], error: null };+ expect(await openOpportunityForPrompt('b1', 'p1')).toBe('o1');+ const opps = calls.find((c) => c.table === 'content_opportunities');+ expect(opps.ops).toContainEqual(['in', 'status', OPEN_OPPORTUNITY_STATUSES]);+ expect(opps.ops).toContainEqual([+ 'or',+ 'prompt_id.eq.p1,cluster_id.eq.c1,related_cluster_ids.cs.{c1}',+ ]);+ });++ it('looks only at the prompt itself before it is grouped', async () => {+ results.prompt_cluster_members = { data: null, error: null };+ results.content_opportunities = { data: [], error: null };+ expect(await openOpportunityForPrompt('b1', 'p1')).toBeNull();+ const opps = calls.find((c) => c.table === 'content_opportunities');+ expect(opps.ops).toContainEqual(['eq', 'prompt_id', 'p1']);+ });+});++describe('runningSuggestionJob', () => {+ it('finds a job for the prompt that is still queued or running', async () => {+ results.jobs = { data: [{ id: 'j1' }], error: null };+ expect(await runningSuggestionJob('b1', 'p1')).toBe('j1');+ const jobs = calls.find((c) => c.table === 'jobs');+ expect(jobs.ops).toContainEqual(['in', 'status', ['waiting', 'active']]);+ expect(jobs.ops).toContainEqual(['eq', 'data->request->>promptId', 'p1']);+ // "+ New" focused on the prompt counts too, not only earlier suggestions.+ expect(jobs.ops.some(([, column]) => column === 'data->request->>source')).toBe(false);+ });++ it('is null when nothing is being written for the prompt', async () => {+ results.jobs = { data: [], error: null };+ expect(await runningSuggestionJob('b1', 'p1')).toBeNull();+ });+});++describe('promptSuggestionRequest', () => {+ it('asks for exactly one opportunity on the prompt, tagged prompt', () => {+ expect(promptSuggestionRequest('p1', 'key-123456')).toEqual({+ count: 1,+ promptId: 'p1',+ explicit: true,+ source: 'prompt',+ idempotencyKey: 'key-123456',+ });+ });+});diff --git a/server/src/routes/content-suggest.test.js b/server/src/routes/content-suggest.test.jsnew file mode 100644index 000000000..36a4f44e6--- /dev/null+++ b/server/src/routes/content-suggest.test.js@@ -0,0 +1,204 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for "Suggest content" from the prompts table (PROMPT-006).+ *+ * The helpers are tested on their own; what only shows up here is the order+ * the route checks things in, which decides whether a click spends the+ * month's quota and whether the same opportunity can be written twice: a+ * repeated request, a job still running for the prompt and an open+ * opportunity all come before the quota, and only then is a job started.+ */++class PlanLimitError extends Error {+ constructor(message, statusCode = 403) {+ super(message);+ this.name = 'PlanLimitError';+ this.statusCode = statusCode;+ }+}++const assertPromptAccess = vi.fn();+const getOpportunityRequestAllowance = vi.fn();+const createJob = vi.fn();+const runContentJob = vi.fn();+const openOpportunityForPrompt = vi.fn();+const runningSuggestionJob = vi.fn();+let previousJob = null;++let server;+let baseUrl;++async function startApp() {+ vi.resetModules();+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError,+ requireFeature: () => (req, res, next) => next(),+ enforceBriefQuota: vi.fn(),+ getBriefQuotaStatus: vi.fn(),+ getContentUsage: vi.fn(),+ getOpportunityRequestAllowance,+ getOrgIdForUser: vi.fn(),+ }));+ vi.doMock('../lib/access.js', () => ({+ assertBrandAccess: vi.fn(),+ assertOpportunitiesAccess: vi.fn(),+ assertOpportunityAccess: vi.fn(),+ assertPromptAccess,+ }));+ vi.doMock('../lib/job-manager.js', () => ({ createJob, getJob: vi.fn() }));+ vi.doMock('../lib/job-runner.js', () => ({ runContentJob }));+ vi.doMock('../lib/prompt-content-suggestion.js', async () => {+ const actual = await vi.importActual('../lib/prompt-content-suggestion.js');+ return { ...actual, openOpportunityForPrompt, runningSuggestionJob };+ });+ // The idempotency lookup (startedJob) is the only table the route reads.+ vi.doMock('../config/supabase.js', () => {+ const chain = new Proxy(+ {},+ {+ get: (_t, op) =>+ op === 'maybeSingle' ? async () => ({ data: previousJob, error: null }) : () => chain,+ },+ );+ return { default: { from: () => chain } };+ });+ vi.doMock('../lib/prompt-clusters.js', () => ({ loadClusters: vi.fn() }));+ vi.doMock('../lib/action-center/from-opportunity.js', () => ({ sendToActionCenter: vi.fn() }));+ vi.doMock('../lib/ai-provider.js', () => ({ resolveModel: 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: router } = await import('./content.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() };+ next();+ });+ app.set('io', null);+ app.use('/api/content', router);++ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/content`;+}++const suggest = () =>+ fetch(`${baseUrl}/prompts/p1/suggest`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ idempotencyKey: 'key-123456' }),+ });++const allowance = (max) => ({ perRequest: 3, remaining: max, max, periodEnd: null, planId: 'x' });++beforeEach(async () => {+ vi.clearAllMocks();+ previousJob = null;+ assertPromptAccess.mockResolvedValue([+ { id: 'p1', prompt_sets: { brand_id: 'b1', brands: { organization_id: 'org1' } } },+ ]);+ runningSuggestionJob.mockResolvedValue(null);+ openOpportunityForPrompt.mockResolvedValue(null);+ getOpportunityRequestAllowance.mockResolvedValue(allowance(3));+ createJob.mockResolvedValue({ id: 'job-new' });+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /prompts/:promptId/suggest', () => {+ it('starts one prompt-tagged opportunity against the quota', async () => {+ const res = await suggest();++ expect(res.status).toBe(202);+ expect(await res.json()).toEqual({ jobId: 'job-new' });+ expect(getOpportunityRequestAllowance).toHaveBeenCalledWith('org1');+ expect(createJob).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'content',+ brandId: 'b1',+ data: expect.objectContaining({+ request: expect.objectContaining({+ count: 1,+ promptId: 'p1',+ explicit: true,+ source: 'prompt',+ }),+ }),+ }),+ );+ expect(runContentJob).toHaveBeenCalledWith('job-new', null);+ });++ it('offers the open opportunity even when the quota is used up', async () => {+ openOpportunityForPrompt.mockResolvedValue('opp-1');+ getOpportunityRequestAllowance.mockResolvedValue(allowance(0));++ const res = await suggest();++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ existingId: 'opp-1' });+ expect(getOpportunityRequestAllowance).not.toHaveBeenCalled();+ expect(createJob).not.toHaveBeenCalled();+ });++ it('follows a job still running for the prompt instead of starting another', async () => {+ runningSuggestionJob.mockResolvedValue('job-running');++ const res = await suggest();++ expect(res.status).toBe(202);+ expect(await res.json()).toEqual({ jobId: 'job-running' });+ expect(openOpportunityForPrompt).not.toHaveBeenCalled();+ expect(createJob).not.toHaveBeenCalled();+ });++ it('returns the job a repeated request already started', async () => {+ previousJob = { id: 'job-before', data: {} };++ const res = await suggest();++ expect(await res.json()).toEqual({ jobId: 'job-before' });+ expect(runningSuggestionJob).not.toHaveBeenCalled();+ expect(createJob).not.toHaveBeenCalled();+ });++ it('refuses with quota_exhausted when nothing is left and nothing is open', async () => {+ getOpportunityRequestAllowance.mockResolvedValue(allowance(0));++ const res = await suggest();++ expect(res.status).toBe(429);+ expect(await res.json()).toMatchObject({ error: 'quota_exhausted' });+ expect(createJob).not.toHaveBeenCalled();+ });++ it("stops at the access check for someone else's prompt", async () => {+ assertPromptAccess.mockRejectedValue(Object.assign(new Error('Unauthorized'), { status: 403 }));++ const res = await suggest();++ expect(res.status).toBe(403);+ expect(createJob).not.toHaveBeenCalled();+ });+});++describe('GET /prompts/:promptId/suggestion', () => {+ it("names the prompt's open opportunity", async () => {+ openOpportunityForPrompt.mockResolvedValue('opp-1');++ const res = await fetch(`${baseUrl}/prompts/p1/suggestion`);++ expect(await res.json()).toEqual({ existingId: 'opp-1' });+ expect(openOpportunityForPrompt).toHaveBeenCalledWith('b1', 'p1');+ });+});diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex 54bb79534..176209ed6 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -20,12 +20,19 @@ import {assertBrandAccess,assertOpportunitiesAccess,assertOpportunityAccess,+ assertPromptAccess,} from '../lib/access.js';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';+import {+ openOpportunityForPrompt,+ promptClusterId,+ promptSuggestionRequest,+ runningSuggestionJob,+} from '../lib/prompt-content-suggestion.js';const router = Router();@@ -235,13 +242,7 @@ const alternativeSchema = z.object({*/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;+ return opp.prompt_id ? promptClusterId(opp.prompt_id) : null;}/**@@ -314,6 +315,96 @@ router.post('/:id/alternative', requireFeature('content_optimization'), async (r}});+/**+ * GET /api/content/prompts/:promptId/suggestion+ * The prompt's open content opportunity, if any: { existingId } (or null).+ * The row menu asks once the month's quota is used up, so a prompt that+ * already has a suggestion can still open it (PROMPT-006).+ */+router.get(+ '/prompts/:promptId/suggestion',+ requireFeature('content_optimization'),+ async (req, res) => {+ const { promptId } = req.params;+ try {+ const [prompt] = await assertPromptAccess(promptId, req.user.id);+ const existingId = await openOpportunityForPrompt(prompt.prompt_sets.brand_id, promptId);+ return res.json({ existingId });+ } catch (error) {+ if (error.status) return res.status(error.status).json({ error: error.message });+ req.log.error({ err: error }, 'prompt content suggestion lookup error');+ return res.status(500).json({ error: 'Failed to look up the suggestion' });+ }+ },+);++const promptSuggestionSchema = z.object({+ idempotencyKey: z.string().min(8).max(100),+});++/**+ * POST /api/content/prompts/:promptId/suggest+ * "Suggest content" from a prompt's row in the prompts table (PROMPT-006).+ * Returns { existingId } (200) when an open opportunity already answers the+ * prompt, so the page offers that one instead of a duplicate. Otherwise it+ * queues exactly one opportunity for the prompt's cluster, tagged `prompt`,+ * against the monthly quota (its slot handed back on failure): { jobId }+ * (202), or 429 'quota_exhausted'. A repeated idempotency key, or a+ * suggestion for the prompt that is still being written, returns that job.+ * The job's result carries the new opportunity's id.+ */+router.post(+ '/prompts/:promptId/suggest',+ requireFeature('content_optimization'),+ async (req, res) => {+ const parsed = promptSuggestionSchema.safeParse(req.body);+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.issues });+ }+ const { promptId } = req.params;+ const { idempotencyKey } = parsed.data;++ try {+ const [prompt] = await assertPromptAccess(promptId, req.user.id);+ const { brand_id: brandId, brands } = prompt.prompt_sets;++ const previous = await startedJob(brandId, idempotencyKey);+ if (previous) return res.status(202).json({ jobId: previous.id });++ // A suggestion still being written is followed, not started twice.+ const running = await runningSuggestionJob(brandId, promptId);+ if (running) return res.status(202).json({ jobId: running });++ const existingId = await openOpportunityForPrompt(brandId, promptId);+ if (existingId) return res.json({ existingId });++ const allowance = await requestAllowance(brands.organization_id);+ if (allowance.max <= 0) return quotaExhausted(res, allowance);++ const job = await createJob({+ type: 'content',+ brandId,+ data: { brandId, model: null, request: promptSuggestionRequest(promptId, idempotencyKey) },+ 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 }, 'prompt content suggestion error');+ return res.status(500).json({ error: 'Failed to start generation' });+ }+ },+);+/*** GET /api/content/job/:jobId* Returns job state and progress for content generation.diff --git a/server/src/workers/content-worker.js b/server/src/workers/content-worker.jsindex f79bca27f..5faf9fff7 100644--- a/server/src/workers/content-worker.js+++ b/server/src/workers/content-worker.js@@ -40,7 +40,10 @@ export async function processContentJob({ brandId, model, job, request = null })promptId: request.promptId ?? null,idea: request.idea ?? null,alternativeOf: request.alternativeOf ?? null,- source: 'manual',+ explicit: !!request.explicit,+ // "+ New" and "Another angle" are manual; "Suggest content" from+ // the prompts table is tagged prompt.+ source: request.source === 'prompt' ? 'prompt' : 'manual',}: {}),});diff --git a/server/src/workers/content-worker.test.js b/server/src/workers/content-worker.test.jsnew file mode 100644index 000000000..4a44c6c2c--- /dev/null+++ b/server/src/workers/content-worker.test.js@@ -0,0 +1,69 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * What a content job hands the generator: the nightly run passes nothing,+ * "+ New" and "Another angle" are manual, and "Suggest content" from the+ * prompts table (PROMPT-006) asks for its prompt's cluster and is tagged+ * prompt.+ */++const generateContentOpportunities = vi.fn();+const refreshPromptClusters = vi.fn();++vi.mock('../lib/opportunity-generator.js', () => ({ generateContentOpportunities }));+vi.mock('../lib/prompt-clusters.js', () => ({ refreshPromptClusters }));+vi.mock('../lib/logger.js', () => ({ default: { info: vi.fn(), error: vi.fn() } }));++const { processContentJob } = await import('./content-worker.js');++const job = { progress: vi.fn() };+const optsOf = () => generateContentOpportunities.mock.calls[0][1];++beforeEach(() => {+ vi.clearAllMocks();+ generateContentOpportunities.mockResolvedValue({ generated: 1, merged: 0 });+ refreshPromptClusters.mockResolvedValue(undefined);+});++describe('processContentJob', () => {+ it("asks for a prompt's own suggestion, tagged prompt", async () => {+ await processContentJob({+ brandId: 'b1',+ job,+ request: { count: 1, promptId: 'p1', explicit: true, source: 'prompt' },+ });+ expect(optsOf()).toMatchObject({+ count: 1,+ promptId: 'p1',+ explicit: true,+ source: 'prompt',+ });+ // A new prompt is only grouped by the refresh, so it runs first.+ expect(refreshPromptClusters).toHaveBeenCalledWith('b1');+ });++ it('marks "+ New" as manual, with no special request', async () => {+ await processContentJob({ brandId: 'b1', job, request: { count: 3, promptId: null } });+ expect(optsOf()).toMatchObject({ count: 3, explicit: false, source: 'manual' });+ });++ it('never lets a request pick its own tag', async () => {+ await processContentJob({ brandId: 'b1', job, request: { count: 1, source: 'system' } });+ expect(optsOf().source).toBe('manual');+ });++ it("doesn't regroup before another angle, which is asked for a known cluster", async () => {+ await processContentJob({+ brandId: 'b1',+ job,+ request: { count: 1, alternativeOf: { id: 'o1', title: 'T', clusterId: 'c1' } },+ });+ expect(refreshPromptClusters).not.toHaveBeenCalled();+ });++ it('leaves the nightly run to the generator defaults', async () => {+ await processContentJob({ brandId: 'b1', job });+ expect(optsOf()).not.toHaveProperty('source');+ expect(optsOf()).not.toHaveProperty('explicit');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex fdbe1efa4..d3e906bba 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -4,7 +4,7 @@ import { useState, useRef, useEffect, useCallback, useMemo } from 'react';import { createPortal } from 'react-dom';import { useTranslations } from 'next-intl';import { useSearchParams } from 'next/navigation';-import { Link, usePathname } from '@/i18n/navigation';+import { Link, usePathname, useRouter } from '@/i18n/navigation';import { PROMPTS_BASE, sectionFor, sectionFromPath } from '@/lib/prompts-routes';import dynamic from 'next/dynamic';import { Skeleton } from '@/components/ui/skeleton';@@ -77,6 +77,7 @@ import {MoreHorizontal,Pause,Play,+ Lightbulb,} from 'lucide-react';import { cn } from '@/lib/utils';import { useBrandStore } from '@/stores/use-brand-store';@@ -120,6 +121,14 @@ import { analyzeNewPrompt, type PromptVisibilitySummary } from '@/lib/actions/trimport { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';import type { PromptVolume, Prompt, Topic } from '@/types';import { toast } from 'sonner';+import {+ getContentUsage,+ getGenerationJobStatus,+ getOpenSuggestionForPrompt,+ suggestContentForPrompt,+} from '@/lib/actions/content';+import { hasContentQuota, type ContentUsage } from '@/lib/content-usage';+import { waitForContentJob } from '@/lib/content-job';import { toCsv } from '@/lib/csv';import { formatRelative } from '@/lib/format-relative';import { compareNullsLast, type SortDir } from './prompt-sort';@@ -2182,31 +2191,54 @@ const DELETE_UNDO_MS = 10_000;/*** The row's ⋯ menu (PROMPT-006): Edit, pause or resume tracking, open the- * Positions panel on Improve, and Delete behind a confirmation. Base UI's menu- * opens from mouse and keyboard and closes on Esc and outside clicks.+ * Positions panel on Improve, suggest content, and Delete behind a+ * confirmation. Base UI's menu opens from mouse and keyboard and closes on+ * Esc and outside clicks.*/function RowActionsMenu({prompt,onEdit,onToggleActive,onImprove,+ onSuggestContent,+ onOpenSuggestion,+ suggesting,+ suggestDisabledReason,onDelete,}: {prompt: Prompt;onEdit: () => void;onToggleActive: () => void;onImprove: () => void;+ /** One content opportunity for this prompt (PROMPT-006). */+ onSuggestContent: () => void;+ /** Opens one of the prompt's content opportunities. */+ onOpenSuggestion: (opportunityId: string) => void;+ /** A suggestion for this prompt is being written. */+ suggesting: boolean;+ /** Why Suggest content can't run now (the month's quota is used up). */+ suggestDisabledReason: string | null;onDelete: () => void;}) {+ // With the month's quota used up, a prompt that already has a suggestion+ // can still open it, which costs nothing; the menu asks as it opens.+ const [openSuggestionId, setOpenSuggestionId] = useState<string | null>(null);+ const lookUpSuggestion = (open: boolean) => {+ if (!open || suggestDisabledReason === null) return;+ getOpenSuggestionForPrompt(prompt.id).then(setOpenSuggestionId, () =>+ setOpenSuggestionId(null),+ );+ };+return (- <DropdownMenu>+ <DropdownMenu onOpenChange={lookUpSuggestion}><DropdownMenuTriggerclassName="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"aria-label={`Actions for ${prompt.text}`}><MoreHorizontal className="h-4 w-4" /></DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuContent align="end" className="w-56"><DropdownMenuItem className="gap-2" onClick={onEdit}><Pencil className="h-3.5 w-3.5" />Edit@@ -2219,6 +2251,30 @@ function RowActionsMenu({<TrendingUp className="h-3.5 w-3.5" />Improve position…</DropdownMenuItem>+ {suggestDisabledReason !== null && openSuggestionId ? (+ <DropdownMenuItem className="gap-2" onClick={() => onOpenSuggestion(openSuggestionId)}>+ <Lightbulb className="h-3.5 w-3.5" />+ Open content suggestion+ </DropdownMenuItem>+ ) : (+ <DropdownMenuItem+ className="gap-2"+ onClick={onSuggestContent}+ disabled={suggesting || suggestDisabledReason !== null}+ >+ {suggesting ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Lightbulb className="h-3.5 w-3.5" />+ )}+ <span className="flex flex-col">+ <span>{suggesting ? 'Writing a suggestion…' : 'Suggest content'}</span>+ {suggestDisabledReason && (+ <span className="text-[11px] text-muted-foreground">{suggestDisabledReason}</span>+ )}+ </span>+ </DropdownMenuItem>+ )}<DropdownMenuSeparator /><DropdownMenuItemclassName="gap-2 text-red-600 focus:text-red-600 dark:text-red-400"@@ -2353,6 +2409,130 @@ function AllPromptsTab({},[onChanged],);++ // "Suggest content" (PROMPT-006): one content opportunity for a prompt,+ // against the month's content quota. The quota is read up front so the+ // menu can say when nothing is left; the server enforces it either way.+ const router = useRouter();+ const [contentUsage, setContentUsage] = useState<ContentUsage | null>(null);+ const [usageVersion, setUsageVersion] = useState(0);+ const [suggestingIds, setSuggestingIds] = useState<Set<string>>(new Set());+ useEffect(() => {+ let cancelled = false;+ getContentUsage().then(+ (usage) => !cancelled && setContentUsage(usage),+ () => !cancelled && setContentUsage(null),+ );+ return () => {+ cancelled = true;+ };+ }, [activeBrandId, usageVersion]);+ const hasOpportunityLimit =+ hasContentQuota(contentUsage) && contentUsage.opportunities.limit !== -1;+ const suggestDisabledReason =+ hasOpportunityLimit && contentUsage.opportunities.remaining <= 0+ ? contentUsage.periodEnd+ ? `Limit reached · resets ${new Date(contentUsage.periodEnd).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ timeZone: 'UTC',+ })}`+ : 'Monthly limit reached'+ : null;++ const openOpportunity = useCallback(+ (id: string) => router.push(`/dashboard/content?opportunity=${id}`),+ [router],+ );+ const suggestContent = useCallback(+ async (prompt: Prompt) => {+ // Only a plan with a monthly limit has a quota to say was left alone.+ const quotaUntouched = hasOpportunityLimit+ ? 'Nothing was used from your monthly content quota.'+ : undefined;+ setSuggestingIds((set) => new Set(set).add(prompt.id));+ const toastId = toast.loading('Writing a content suggestion…', {+ description: prompt.text,+ });+ // CONTENT-004: an open suggestion already answers this prompt.+ const showExisting = (id: string) =>+ toast.info('This prompt already has a content suggestion', {+ id: toastId,+ description: prompt.text,+ duration: 10_000,+ action: { label: 'Open existing', onClick: () => openOpportunity(id) },+ });+ try {+ const started = await suggestContentForPrompt(prompt.id, crypto.randomUUID());+ if (!started.ok) {+ toast.error(started.quotaExhausted ? 'Monthly content limit reached.' : started.error, {+ id: toastId,+ description: prompt.text,+ });+ return;+ }+ if ('existingId' in started) {+ showExisting(started.existingId);+ return;+ }++ const outcome = await waitForContentJob(started.jobId, {+ getStatus: getGenerationJobStatus,+ });+ if (outcome.kind === 'completed') {+ const createdId = outcome.result.opportunityIds?.[0];+ if (createdId) {+ toast.success('Content suggestion created', {+ id: toastId,+ description: prompt.text,+ duration: 10_000,+ action: { label: 'Open', onClick: () => openOpportunity(createdId) },+ });+ } else if (outcome.result.existingId) {+ // Covered while the job ran, e.g. once the prompt was regrouped.+ showExisting(outcome.result.existingId);+ } else if (outcome.result.limited) {+ toast.error('Monthly content limit reached.', { id: toastId });+ } else {+ toast.info("Couldn't write a suggestion for this prompt yet", {+ id: toastId,+ // Not grouped with other prompts yet, or no answers to go on.+ description: [+ 'It needs tracked answers and a prompt group first; both come with its next tracking run.',+ quotaUntouched,+ ]+ .filter(Boolean)+ .join(' '),+ });+ }+ } else if (outcome.kind === 'failed') {+ toast.error("Couldn't write a content suggestion", {+ id: toastId,+ description: quotaUntouched,+ });+ } else {+ toast.info('Still writing the content suggestion', {+ id: toastId,+ description: 'It will appear in Content when it is done.',+ });+ }+ } catch (err) {+ // Nothing may be left spinning, whatever went wrong on the way.+ toast.error("Couldn't write a content suggestion", {+ id: toastId,+ description: err instanceof Error ? err.message : quotaUntouched,+ });+ } finally {+ setSuggestingIds((set) => {+ const next = new Set(set);+ next.delete(prompt.id);+ return next;+ });+ setUsageVersion((v) => v + 1);+ }+ },+ [openOpportunity, hasOpportunityLimit],+ );const [search, setSearch] = useState('');const [workFilter, setWorkFilter] = useState<'all' | 'none' | PromptWorkStatus>('all');// Optimistic per-row status overrides — the prompts prop belongs to the@@ -2826,6 +3006,10 @@ function AllPromptsTab({onEdit={() => onEditPrompt(p)}onToggleActive={() => void toggleActive(p)}onImprove={() => openPositionsPanel(p.id, 'improve')}+ onSuggestContent={() => void suggestContent(p)}+ onOpenSuggestion={openOpportunity}+ suggesting={suggestingIds.has(p.id)}+ suggestDisabledReason={suggestDisabledReason}onDelete={() => setConfirmDelete(p)}/></TableCell>diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.tsindex 675506bf1..4f11c28ca 100644--- a/web/src/lib/actions/content.ts+++ b/web/src/lib/actions/content.ts@@ -67,6 +67,10 @@ export interface GenerationJobStatus {duplicates?: number;/** The month's quota ran out before anything could be generated. */limited?: boolean;+ /** The opportunities this run created, newest work first. */+ opportunityIds?: string[];+ /** A run for one prompt wrote nothing: the open opportunity that answers it. */+ existingId?: string;} | null;failedReason: string | null;}@@ -636,3 +640,57 @@ export async function suggestAlternative(}return { ok: true, jobId: body.jobId };}++export type PromptSuggestionResult =+ | { ok: true; jobId: string }+ | { ok: true; existingId: string }+ | { ok: false; error: string; quotaExhausted?: boolean };++/**+ * "Suggest content" from the prompts table (PROMPT-006): one content+ * opportunity for the prompt, or the open one it already has. Errors come+ * back as values.+ */+export async function suggestContentForPrompt(+ promptId: string,+ idempotencyKey: string,+): Promise<PromptSuggestionResult> {+ const session = await getSession();++ const res = await fetch(`${AEO_SERVER_URL}/api/content/prompts/${promptId}/suggest`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ 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',+ };+ }+ return body.existingId+ ? { ok: true, existingId: body.existingId }+ : { ok: true, jobId: body.jobId };+}++/**+ * The prompt's open content opportunity, if any (PROMPT-006): with the+ * month's quota used up, the row menu can still open it. Null when there is+ * none or it can't be read.+ */+export async function getOpenSuggestionForPrompt(promptId: string): Promise<string | null> {+ const session = await getSession();++ const res = await fetch(`${AEO_SERVER_URL}/api/content/prompts/${promptId}/suggestion`, {+ headers: { Authorization: `Bearer ${session.access_token}` },+ });+ if (!res.ok) return null;+ const body = await res.json().catch(() => ({}));+ return body.existingId ?? null;+}diff --git a/web/src/lib/content-job.test.ts b/web/src/lib/content-job.test.tsnew file mode 100644index 000000000..86a5b85ae--- /dev/null+++ b/web/src/lib/content-job.test.ts@@ -0,0 +1,75 @@+/**+ * content-job.test.ts (PROMPT-006)+ *+ * Following a content job until it completes, fails or we stop waiting.+ */++import { describe, expect, test } from 'vitest';+import type { GenerationJobStatus } from '@/lib/actions/content';+import { waitForContentJob } from './content-job';++const status = (s: Partial<GenerationJobStatus>): GenerationJobStatus => ({+ status: 'active',+ progress: null,+ result: null,+ failedReason: null,+ ...s,+});++/** A clock that moves only when the wait sleeps. */+function fakeClock() {+ let t = 0;+ return { now: () => t, sleep: async (ms: number) => void (t += ms) };+}++describe('waitForContentJob', () => {+ test('returns the result once the job completes, through blips', async () => {+ const seen = [+ status({ status: 'not_found' }),+ status({ status: 'active' }),+ status({ status: 'completed', result: { generated: 1, opportunityIds: ['o1'] } }),+ ];+ const outcome = await waitForContentJob('j1', {+ getStatus: async () => seen.shift()!,+ ...fakeClock(),+ });+ expect(outcome).toEqual({+ kind: 'completed',+ result: { generated: 1, opportunityIds: ['o1'] },+ });+ });++ test('keeps waiting when a status read throws', async () => {+ let calls = 0;+ const outcome = await waitForContentJob('j1', {+ getStatus: async () => {+ calls += 1;+ if (calls === 1) throw new Error('Session expired');+ return status({ status: 'completed', result: { generated: 1, opportunityIds: ['o1'] } });+ },+ ...fakeClock(),+ });+ expect(outcome).toEqual({+ kind: 'completed',+ result: { generated: 1, opportunityIds: ['o1'] },+ });+ });++ test('reports a failure with its reason', async () => {+ const outcome = await waitForContentJob('j1', {+ getStatus: async () => status({ status: 'failed', failedReason: 'No AI key' }),+ ...fakeClock(),+ });+ expect(outcome).toEqual({ kind: 'failed', reason: 'No AI key' });+ });++ test('stops waiting after the timeout, without claiming the job failed', async () => {+ const outcome = await waitForContentJob('j1', {+ getStatus: async () => status({ status: 'active' }),+ timeoutMs: 9000,+ intervalMs: 3000,+ ...fakeClock(),+ });+ expect(outcome).toEqual({ kind: 'timeout' });+ });+});diff --git a/web/src/lib/content-job.ts b/web/src/lib/content-job.tsnew file mode 100644index 000000000..1889a09de--- /dev/null+++ b/web/src/lib/content-job.ts@@ -0,0 +1,45 @@+/**+ * Following a content generation job to its end, for callers that started+ * one and want its outcome ("Suggest content" in the prompts table). The+ * status reader is passed in, so the waiting rules are tested without a+ * server.+ */++import type { GenerationJobStatus } from '@/lib/actions/content';++export type ContentJobOutcome =+ | { kind: 'completed'; result: NonNullable<GenerationJobStatus['result']> }+ | { kind: 'failed'; reason: string | null }+ /** Still running when we stopped waiting: it may yet finish. */+ | { kind: 'timeout' };++export async function waitForContentJob(+ jobId: string,+ {+ getStatus,+ intervalMs = 3000,+ timeoutMs = 3 * 60 * 1000,+ sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms)),+ now = () => Date.now(),+ }: {+ getStatus: (jobId: string) => Promise<GenerationJobStatus>;+ intervalMs?: number;+ timeoutMs?: number;+ sleep?: (ms: number) => Promise<void>;+ now?: () => number;+ },+): Promise<ContentJobOutcome> {+ const startedAt = now();+ while (now() - startedAt < timeoutMs) {+ await sleep(intervalMs);+ // A status the reader can't get ('not_found', or a call that throws) is+ // a blip: keep waiting.+ const status = await getStatus(jobId).catch(() => null);+ if (!status) continue;+ if (status.status === 'completed') {+ return { kind: 'completed', result: status.result ?? { generated: 0 } };+ }+ if (status.status === 'failed') return { kind: 'failed', reason: status.failedReason };+ }+ return { kind: 'timeout' };+}