Skip to content

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.

fix(content): ask for one opportunity for a prompt, and offer the one it already has (#1797)

Cihane4cbcec03e44
diff --git a/web/messages/en.json b/web/messages/en.json
index 44e2e2cfb..628b7bc43 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7094,6 +7094,8 @@
"new": "New",
"newDone": "{generated, plural, =0 {No new opportunities} one {1 opportunity created} other {# opportunities created}}{duplicates, plural, =0 {} one { · 1 duplicate skipped (not counted)} other { · # duplicates skipped (not counted)}}",
"newNothing": "No new opportunities: every matching need already has one.",
+ "newExisting": "This prompt already has an opportunity",
+ "openExisting": "Open existing",
"newLimitReached": "Monthly opportunity limit reached.",
"newLimitTooltip": "Monthly limit reached. Resets on {date}.",
"newRefunded": "Nothing was used from your monthly quota.",
@@ -7148,6 +7150,7 @@
"fewer": "Fewer",
"more": "More",
"max": "max {max}",
+ "promptOne": "One per prompt. For a different take, use Another angle on its opportunity.",
"uses": "Uses {count} of your {remaining} remaining this month → {after} left after this. Duplicates of existing opportunities are skipped and don't count.",
"usesUnlimited": "Generates up to {count}. Duplicates of existing opportunities are skipped.",
"noneLeft": "You've used this month's opportunities. They reset when your subscription renews.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx
index e84c475e1..1d7d356bb 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx
@@ -73,9 +73,18 @@ vi.mock('@/components/content/new-content-dialog', () => ({
return null;
},
}));
-vi.mock('@/components/content/opportunity-detail', () => ({ OpportunityDetail: () => null }));
+const detail = vi.hoisted(() => ({ id: null as string | null }));
+vi.mock('@/components/content/opportunity-detail', () => ({
+ OpportunityDetail: ({ id }: { id: string }) => {
+ detail.id = id;
+ return null;
+ },
+}));
+const toast = vi.hoisted(() =>
+ Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn() }),
+);
vi.mock('sonner', () => ({
- toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn() }),
+ toast,
}));
const { default: ContentPage } = await import('./page');
@@ -141,6 +150,7 @@ beforeEach(() => {
viewer.canManage = true;
opened.newOpportunities = false;
opened.newContent = false;
+ detail.id = null;
window.history.replaceState(null, '', '/dashboard/content');
content.getOpportunities.mockResolvedValue({
opportunities: [OPPORTUNITY],
@@ -330,3 +340,48 @@ describe('Content Opportunities for an analyst or an agency partner', () => {
expect(labels()).not.toContain('Dismiss');
});
});
+
+describe('A "+ New" request for one prompt', () => {
+ // An in-memory localStorage holding the running job: the test environment has none.
+ const store = new Map<string, string>();
+ beforeEach(() => {
+ store.clear();
+ Object.defineProperty(window, 'localStorage', {
+ configurable: true,
+ value: {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ removeItem: (key: string) => void store.delete(key),
+ },
+ });
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ Reflect.deleteProperty(window, 'localStorage');
+ });
+
+ it('offers the open opportunity that already answers the prompt', async () => {
+ localStorage.setItem(
+ 'aeo:content-generation',
+ JSON.stringify({ brandId: 'b1', jobId: 'j1', startedAt: Date.now(), count: 1 }),
+ );
+ content.getGenerationJobStatus.mockResolvedValue({
+ status: 'completed',
+ progress: null,
+ result: { generated: 0, duplicates: 0, existingId: 'o9' },
+ failedReason: null,
+ });
+ vi.useFakeTimers();
+ await render(false);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3000);
+ });
+
+ expect(toast).toHaveBeenCalledWith('This prompt already has an opportunity', {
+ action: { label: 'Open existing', onClick: expect.any(Function) },
+ });
+ await act(async () => toast.mock.calls[0][1].action.onClick());
+ expect(detail.id).toBe('o9');
+ expect(new URL(window.location.href).searchParams.get('opportunity')).toBe('o9');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index f63fc3254..1d2abe9a2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -733,7 +733,16 @@ export default function ContentPage() {
setPendingCount(0);
const generated = status.result?.generated ?? 0;
const duplicates = status.result?.duplicates ?? 0;
+ const existingId = status.result?.existingId;
if (status.result?.limited) toast.error(t('newLimitReached'));
+ // A request for one prompt that an open opportunity answers.
+ else if (generated === 0 && existingId)
+ toast(t('newExisting'), {
+ action: {
+ label: t('openExisting'),
+ onClick: () => selectOpportunity(existingId),
+ },
+ });
else if (generated === 0 && duplicates === 0) toast(t('newNothing'));
else toast.success(t('newDone', { generated, duplicates }));
loadData();
@@ -770,7 +779,7 @@ export default function ContentPage() {
poll();
},
- [loadData, loadPromptOptions, t],
+ [loadData, loadPromptOptions, selectOpportunity, t],
);
// Restore generation state from localStorage on mount
useEffect(() => {
diff --git a/web/src/components/content/new-opportunities-dialog.test.tsx b/web/src/components/content/new-opportunities-dialog.test.tsx
new file mode 100644
index 000000000..96766e945
--- /dev/null
+++ b/web/src/components/content/new-opportunities-dialog.test.tsx
@@ -0,0 +1,124 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+import { NewOpportunitiesDialog } from './new-opportunities-dialog';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+vi.mock('@/lib/actions/topic', () => ({ getTopics: vi.fn(async () => []) }));
+vi.mock('@/lib/actions/tracking', () => ({
+ getBrandPrompts: vi.fn(async () => [{ id: 'p1', text: 'best crm for agencies' }]),
+}));
+// The prompt picker as a native select: Base UI's popup doesn't open in jsdom.
+vi.mock('@/components/ui/combobox', () => ({
+ Combobox: ({
+ items,
+ onValueChange,
+ }: {
+ items: { value: string; label: string }[];
+ onValueChange: (item: { value: string; label: string } | null) => void;
+ }) => (
+ <select
+ data-combobox
+ onChange={(e) => onValueChange(items.find((i) => i.value === e.target.value) ?? null)}
+ >
+ <option value="" />
+ {items.map((i) => (
+ <option key={i.value} value={i.value}>
+ {i.label}
+ </option>
+ ))}
+ </select>
+ ),
+ ComboboxCollection: () => null,
+ ComboboxContent: () => null,
+ ComboboxEmpty: () => null,
+ ComboboxInput: () => null,
+ ComboboxItem: () => null,
+ ComboboxList: () => null,
+ ComboboxTrigger: () => null,
+ ComboboxValue: () => null,
+}));
+
+const onSubmit = vi.fn();
+let container: HTMLDivElement;
+let root: Root;
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <NewOpportunitiesDialog
+ open
+ onOpenChange={() => {}}
+ brandId="b1"
+ max={3}
+ remaining={8}
+ onSubmit={onSubmit}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+}
+
+const button = (name: string) =>
+ [...document.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === name || b.getAttribute('aria-label') === name,
+ );
+const click = async (el: Element | undefined) => {
+ await act(async () => {
+ (el as HTMLElement).click();
+ });
+};
+const text = () => document.body.textContent ?? '';
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ onSubmit.mockReset().mockResolvedValue(true);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ document.body.replaceChildren();
+});
+
+describe('New content opportunities', () => {
+ it('asks for one opportunity for a prompt, since its group gets one', async () => {
+ await render();
+ expect(button('Generate 3')).toBeDefined();
+
+ await click(button('Prompt'));
+ expect(button('Generate 1')).toBeDefined();
+ expect(button('More')!.disabled).toBe(true);
+ expect(text()).toContain('One per prompt.');
+ expect(text()).toContain('Uses 1 of your 8 remaining this month → 7 left after this.');
+
+ const select = document.querySelector<HTMLSelectElement>('[data-combobox]')!;
+ await act(async () => {
+ select.value = 'p1';
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+ await click(button('Generate 1'));
+ expect(onSubmit).toHaveBeenCalledWith({
+ count: 1,
+ topicId: null,
+ promptId: 'p1',
+ idea: null,
+ });
+ });
+
+ it('brings the chosen count back when the focus leaves the prompt', async () => {
+ await render();
+ await click(button('Prompt'));
+ await click(button('Let Ansvisor choose'));
+ expect(button('Generate 3')).toBeDefined();
+ expect(text()).not.toContain('One per prompt.');
+ });
+});
diff --git a/web/src/components/content/new-opportunities-dialog.tsx b/web/src/components/content/new-opportunities-dialog.tsx
index bc8e76e88..da06cdf11 100644
--- a/web/src/components/content/new-opportunities-dialog.tsx
+++ b/web/src/components/content/new-opportunities-dialog.tsx
@@ -59,7 +59,9 @@ interface Option {
* "+ New" (CONTENT-003): generate opportunities now, optionally around a
* topic, a prompt or a free-text idea. The count is capped by `max` — the
* plan's per-request limit, never more than what is left of the month — and
- * the dialog says what the request will use before it is sent.
+ * the dialog says what the request will use before it is sent. A prompt
+ * belongs to one prompt group, which gets one opportunity, so a request for
+ * a prompt asks for one.
*/
export function NewOpportunitiesDialog({
open,
@@ -104,7 +106,7 @@ function NewOpportunitiesForm({
const [topicId, setTopicId] = useState('');
const [prompt, setPrompt] = useState<Option | null>(null);
const [idea, setIdea] = useState('');
- const [count, setCount] = useState(() => Math.max(1, Math.min(DEFAULT_COUNT, max)));
+ const [chosenCount, setCount] = useState(() => Math.max(1, Math.min(DEFAULT_COUNT, max)));
const [submitting, setSubmitting] = useState(false);
const [topics, setTopics] = useState<Option[]>([]);
const [prompts, setPrompts] = useState<Option[]>([]);
@@ -128,9 +130,13 @@ function NewOpportunitiesForm({
};
}, [brandId]);
+ const cap = focus === 'prompt' ? Math.min(1, max) : max;
+ // Kept as chosen, so leaving the prompt focus brings the count back.
+ const count = Math.min(chosenCount, Math.max(1, cap));
+
const focusReady =
focus === 'auto' || (focus === 'topic' && !!topicId) || (focus === 'prompt' && !!prompt);
- const canSubmit = max > 0 && count >= 1 && count <= max && focusReady && !submitting;
+ const canSubmit = max > 0 && count >= 1 && count <= cap && focusReady && !submitting;
const submit = async () => {
if (!canSubmit) return;
@@ -239,7 +245,7 @@ function NewOpportunitiesForm({
size="icon-sm"
aria-label={t('fewer')}
disabled={count <= 1}
- onClick={() => setCount((n) => Math.max(1, n - 1))}
+ onClick={() => setCount(Math.max(1, count - 1))}
>
<Minus className="h-3.5 w-3.5" />
</Button>
@@ -249,13 +255,15 @@ function NewOpportunitiesForm({
variant="ghost"
size="icon-sm"
aria-label={t('more')}
- disabled={count >= max}
- onClick={() => setCount((n) => Math.min(max, n + 1))}
+ disabled={count >= cap}
+ onClick={() => setCount(Math.min(cap, count + 1))}
>
<Plus className="h-3.5 w-3.5" />
</Button>
</div>
- <span className="text-xs text-muted-foreground">{t('max', { max })}</span>
+ <span className="text-xs text-muted-foreground">
+ {focus === 'prompt' ? t('promptOne') : t('max', { max })}
+ </span>
</div>
</div>