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.

feat(prompts): open the Content Editor from a tracked prompt (#1333)

Cihan8ddc59d356de
diff --git a/web/messages/en.json b/web/messages/en.json
index c418819cf..3473b224c 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3395,7 +3395,8 @@
"options": {
"optimizeGiven": {
"title": "Optimize {page}",
- "reason": "The page your Content plan picked"
+ "reason": "The page your Content plan picked",
+ "reasonCited": "The page AI engines cite for this prompt"
},
"optimizeInstead": {
"title": "Optimize {page} instead",
@@ -5232,6 +5233,18 @@
"showAll": "Show all performance",
"order": "Furthest behind first: late or missing on the most AI platforms, then the worse average position."
},
+ "content": {
+ "create": "Create content",
+ "optimize": "Optimize content",
+ "openDraft": "Open draft",
+ "createTitle": "No answer mentions or cites you here",
+ "createBody": "None of this period's {answers, plural, one {# answer} other {# answers}} names your brand or cites your site. A page written for this prompt gives AI engines something of yours to use.",
+ "rareTitle": "Mentioned in {pct}% of answers",
+ "lateTitle": "Mentioned at #{position} on average",
+ "optimizePage": "Optimize {page}, the page AI engines cite here, so they name you more often and earlier.",
+ "optimizePick": "Start lists your pages that answer this prompt: pick the one to optimize.",
+ "draftNote": "A draft for this prompt is already being written."
+ },
"improve": {
"quota": {
"left": "{count, plural, one {About # generation left this month} other {About # generations left this month}}",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 30755fc3f..1a6c0cd45 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -100,8 +100,14 @@ import {
Pause,
Play,
Lightbulb,
+ FilePlus,
+ FileText,
RotateCw,
} from 'lucide-react';
+import { NewContentDialog, type DialogPreset } from '@/components/content/new-content-dialog';
+import { getDraftForPrompt } from '@/lib/actions/content-drafts';
+import { contentEditorPath } from '@/lib/content/drafts';
+import { siteTypeOf } from '@/lib/content/page-types';
import { cn } from '@/lib/utils';
import {
compareLateness,
@@ -2553,6 +2559,7 @@ const SUGGEST_CALLS = { start: suggestContentForPrompt, getStatus: getGeneration
*/
function RowActionsMenu({
prompt,
+ brandId,
onEdit,
onToggleActive,
onImprove,
@@ -2560,9 +2567,11 @@ function RowActionsMenu({
onOpenSuggestion,
suggesting,
suggestDisabledReason,
+ onCreateContent,
onDelete,
}: {
prompt: Prompt;
+ brandId: string;
onEdit: () => void;
onToggleActive: () => void;
onImprove: () => void;
@@ -2574,20 +2583,30 @@ function RowActionsMenu({
suggesting: boolean;
/** Why Suggest content can't run now (the month's quota is used up, or a bulk run is going). */
suggestDisabledReason: string | null;
+ /** Opens New content › Start for a new page for this prompt. */
+ onCreateContent: () => void;
onDelete: () => void;
}) {
+ const t = useTranslations('prompts.content');
+ const router = useRouter();
// 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;
+ // A draft already being written for the prompt opens instead of a second
+ // one; undefined while the menu asks.
+ const [draftId, setDraftId] = useState<string | null | undefined>(undefined);
+ const lookUp = (open: boolean) => {
+ if (!open) return;
+ setDraftId(undefined);
+ getDraftForPrompt(brandId, prompt.id).then(setDraftId, () => setDraftId(null));
+ if (suggestDisabledReason === null) return;
getOpenSuggestionForPrompt(prompt.id).then(setOpenSuggestionId, () =>
setOpenSuggestionId(null),
);
};
return (
- <DropdownMenu onOpenChange={lookUpSuggestion}>
+ <DropdownMenu onOpenChange={lookUp}>
<DropdownMenuTrigger
className="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}`}
@@ -2631,6 +2650,28 @@ function RowActionsMenu({
</span>
</DropdownMenuItem>
)}
+ {draftId ? (
+ <DropdownMenuItem
+ className="gap-2"
+ onClick={() => router.push(contentEditorPath(draftId))}
+ >
+ <FileText className="h-3.5 w-3.5" />
+ {t('openDraft')}
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuItem
+ className="gap-2"
+ onClick={onCreateContent}
+ disabled={draftId === undefined}
+ >
+ {draftId === undefined ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <FilePlus className="h-3.5 w-3.5" />
+ )}
+ {t('create')}
+ </DropdownMenuItem>
+ )}
<DropdownMenuSeparator />
<DropdownMenuItem
className="gap-2 text-red-600 focus:text-red-600 dark:text-red-400"
@@ -2739,6 +2780,12 @@ function AllPromptsTab({
);
const [confirmDelete, setConfirmDelete] = useState<Prompt[] | null>(null);
const [positionsTab, setPositionsTab] = useState<'platforms' | 'improve'>('platforms');
+ // New content › Start for a prompt, from its row menu or its Improve tab.
+ const [contentPreset, setContentPreset] = useState<DialogPreset | null>(null);
+ // Bumped when Start sends a draft to the Agent or the Team and the panel
+ // stays open, so its content step looks for that draft again.
+ const [contentSent, setContentSent] = useState(0);
+ const activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId));
const prompts = useMemo(
() => allRows.filter((p) => !pendingDeletes.has(p.id)),
[allRows, pendingDeletes],
@@ -3819,6 +3866,7 @@ function AllPromptsTab({
<TableCell className="text-right pr-6">
<RowActionsMenu
prompt={p}
+ brandId={activeBrandId}
onEdit={() => onEditPrompt(p)}
onToggleActive={() => void toggleActive(p)}
onImprove={() => openPositionsPanel(p.id, 'improve')}
@@ -3829,6 +3877,14 @@ function AllPromptsTab({
suggestDisabledReason ??
(bulkSuggesting ? 'Wait for the selected prompts' : null)
}
+ onCreateContent={() =>
+ setContentPreset({
+ kind: 'prompt',
+ id: p.id,
+ text: p.text,
+ method: 'create',
+ })
+ }
onDelete={() => setConfirmDelete([p])}
/>
</TableCell>
@@ -3886,7 +3942,20 @@ function AllPromptsTab({
onRangeChange={setPositionsRange}
region={regionFilter}
initialTab={positionsTab}
- onClose={() => setPositionsId(null)}
+ // Escape and a click outside belong to Start while it is open over the
+ // panel: they close Start, and the panel stays.
+ onClose={() => contentPreset === null && setPositionsId(null)}
+ brandId={activeBrandId}
+ onStartContent={setContentPreset}
+ contentSent={contentSent}
+ />
+ <NewContentDialog
+ open={contentPreset !== null}
+ onOpenChange={(open) => !open && setContentPreset(null)}
+ brandId={activeBrandId}
+ siteType={siteTypeOf(activeBrand ?? {})}
+ preset={contentPreset}
+ onSent={() => setContentSent((n) => n + 1)}
/>
<Dialog open={confirmDelete !== null} onOpenChange={(v) => !v && setConfirmDelete(null)}>
<DialogContent className="sm:max-w-md">
diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsx
index 511d80d41..2861f79fd 100644
--- a/web/src/components/content/new-content-dialog.test.tsx
+++ b/web/src/components/content/new-content-dialog.test.tsx
@@ -407,6 +407,72 @@ describe('New content', () => {
expect(button('Pick a content opportunity')).toBeDefined();
});
+ describe('opened from Tracked Prompts', () => {
+ const prompt = { kind: 'prompt' as const, id: 'p1', text: 'best crm for realtors' };
+
+ it('goes straight to Start for a new page for the prompt', async () => {
+ await render('b2b', { ...prompt, method: 'create' });
+ expect(document.body.textContent).toContain('Create: best crm for realtors');
+ await click(button('Open editor'));
+ expect(createContentDraft.mock.calls[0][1]).toMatchObject({
+ method: 'create',
+ title: 'best crm for realtors',
+ source: { kind: 'prompt', id: 'p1' },
+ });
+ });
+
+ it('optimizes the page AI cites for the prompt', async () => {
+ await render('b2b', {
+ ...prompt,
+ method: 'optimize',
+ page: { url: 'https://northwind.example/blog/crm-guide', title: 'CRM guide' },
+ });
+ await act(async () => {});
+ expect(document.body.textContent).toContain('Optimize: CRM guide');
+ expect(document.body.textContent).toContain('The page AI engines cite for this prompt');
+ await click(button('Open editor'));
+ expect(createContentDraft.mock.calls[0][1]).toMatchObject({
+ method: 'optimize',
+ title: 'CRM guide',
+ source: { kind: 'prompt', id: 'p1' },
+ sourceUrl: 'https://northwind.example/blog/crm-guide',
+ });
+ });
+
+ // A page covering part of the prompts: a new linked page is recommended.
+ const partial = {
+ totalPrompts: 4,
+ pages: [
+ {
+ url: 'https://northwind.example/blog/crm-guide',
+ title: 'CRM guide',
+ promptsInCommon: 1,
+ citations: 6,
+ gscPosition: null,
+ },
+ ],
+ };
+
+ // The person picked Optimize: with no cited page, the Overview's first
+ // page to optimize is picked once its read lands (#1320 keeps that pick).
+ it('picks the first page to optimize from the Overview when none is cited', async () => {
+ getContentOverlap.mockResolvedValue(partial);
+ await render('b2b', { ...prompt, method: 'optimize' });
+ await act(async () => {});
+ expect(document.body.textContent).toContain('Optimize: CRM guide');
+ // A pick of the person's own stays.
+ await click(radio('Create a new page'));
+ expect(document.body.textContent).toContain('Create: best crm for realtors');
+ });
+
+ it('stays on a new page when writing one', async () => {
+ getContentOverlap.mockResolvedValue(partial);
+ await render('b2b', { ...prompt, method: 'create' });
+ await act(async () => {});
+ expect(document.body.textContent).toContain('Create: best crm for realtors');
+ });
+ });
+
describe('opened from the Content plan (CE-014)', () => {
it('goes straight to Start for the opportunity', async () => {
await render('b2b', { kind: 'opportunity', id: 'o2' });
diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsx
index 3527ba8e7..7140ffbaa 100644
--- a/web/src/components/content/new-content-dialog.tsx
+++ b/web/src/components/content/new-content-dialog.tsx
@@ -132,11 +132,22 @@ interface StartChoice {
/**
* What the dialog opens on, from the Content plan (CE-014): an opportunity
- * (for an existing page, Start optimizes that page), or a page to read.
+ * (for an existing page, Start optimizes that page), or a page to read. From
+ * Tracked Prompts: a prompt, to write a page for or, with `method`
+ * 'optimize', to optimize its cited `page`; with no page, the Overview's
+ * first page to optimize is picked once its read lands (the person picked
+ * Optimize), and they can pick another.
*/
export type DialogPreset = (
| { kind: 'opportunity'; id: string; page?: { url: string; title: string | null } | null }
| { kind: 'page'; url: string }
+ | {
+ kind: 'prompt';
+ id: string;
+ text: string;
+ method: 'create' | 'optimize';
+ page?: { url: string; title: string | null } | null;
+ }
) & {
/** Opened to assign the work (the Plan's "Assign to…"): Start chooses Team. */
who?: 'team';
@@ -241,6 +252,10 @@ export function NewContentDialog({
// From the Content plan: Start for its opportunity once the options are in
// (one no longer open is left to pick), or its page read to optimize.
const presetApplied = useRef(false);
+ // Opened to optimize a prompt with no cited page: the Overview's first page
+ // to optimize is picked once, when its read lands. A pick of the person's
+ // own, or a retry, leaves the choice to them.
+ const optimizeOnce = useRef(false);
useEffect(() => {
if (!open || !preset || presetApplied.current) return;
if (preset.who === 'team') setWho('team');
@@ -252,6 +267,15 @@ export function NewContentDialog({
void readPage(preset.url);
return;
}
+ if (preset.kind === 'prompt') {
+ presetApplied.current = true;
+ optimizeOnce.current = preset.method === 'optimize' && !preset.page;
+ const item = { value: preset.id, label: preset.text };
+ setKind('prompt');
+ setPicked(item);
+ startFrom(item, 'prompt', preset.page ? givenPage(preset.page) : undefined);
+ return;
+ }
if (!options) return;
presetApplied.current = true;
const opportunity = options.opportunities.find((o) => o.id === preset.id);
@@ -259,19 +283,7 @@ export function NewContentDialog({
const item = opportunityItem(opportunity, siteType);
setKind('opportunity');
setPicked(item);
- startFrom(
- item,
- 'opportunity',
- preset.page
- ? {
- url: preset.page.url,
- title: preset.page.title,
- promptsInCommon: 0,
- citations: 0,
- gscPosition: null,
- }
- : undefined,
- );
+ startFrom(item, 'opportunity', preset.page ? givenPage(preset.page) : undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps -- once per opening
}, [open, preset, options]);
@@ -289,6 +301,11 @@ export function NewContentDialog({
.then((overlap) => {
if (cancelled) return;
setOverlapRead({ key, overlap, failed: false });
+ if (optimizeOnce.current && overlap) {
+ optimizeOnce.current = false;
+ const optimize = overlapOptions(overlap, null).find((o) => o.choice.kind === 'optimize');
+ if (optimize) setStart((s) => (s ? withChoice(s, optimize.choice, siteType) : s));
+ }
})
.catch((err) => {
console.error('Failed to read the pages cited for these prompts:', err);
@@ -297,10 +314,11 @@ export function NewContentDialog({
return () => {
cancelled = true;
};
- }, [brandId, startSource, overlapAttempt]);
+ }, [brandId, startSource, siteType, overlapAttempt]);
const reset = () => {
presetApplied.current = false;
+ optimizeOnce.current = false;
setMethod('create');
setKind('opportunity');
setPicked(null);
@@ -646,8 +664,13 @@ export function NewContentDialog({
read={overlapRead?.key === overlapKey ? overlapRead : null}
choice={start.choice}
given={start.givenPage ?? null}
- onChoose={(choice) => setStart(withChoice(start, choice, siteType))}
+ givenCited={start.source.kind === 'prompt'}
+ onChoose={(choice) => {
+ optimizeOnce.current = false;
+ setStart(withChoice(start, choice, siteType));
+ }}
onRetry={() => {
+ optimizeOnce.current = false;
setOverlapRead(null);
setOverlapAttempt((n) => n + 1);
}}
@@ -990,6 +1013,11 @@ export function NewContentDialog({
);
}
+/** A page a preset names, as Start's overlap options carry one. */
+function givenPage(page: { url: string; title: string | null }): OverlapPage {
+ return { url: page.url, title: page.title, promptsInCommon: 0, citations: 0, gscPosition: null };
+}
+
/** An opportunity to pick, with the page type it names when the site writes it. */
function opportunityItem(
opportunity: DraftStartOptions['opportunities'][number],
@@ -1036,12 +1064,15 @@ function OverlapCheck({
read,
choice,
given,
+ givenCited,
onChoose,
onRetry,
}: {
read: OverlapRead | null;
choice: OverlapChoice;
given: OverlapPage | null;
+ /** The given page is the one AI cites for the prompt (Tracked Prompts), not the plan's pick. */
+ givenCited: boolean;
onChoose: (choice: OverlapChoice) => void;
onRetry: () => void;
}) {
@@ -1062,7 +1093,9 @@ function OverlapCheck({
case 'optimizeGiven':
return {
title: t('options.optimizeGiven.title', { page: given ? pagePath(given.url) : '' }),
- reason: t('options.optimizeGiven.reason'),
+ reason: t(
+ givenCited ? 'options.optimizeGiven.reasonCited' : 'options.optimizeGiven.reason',
+ ),
};
case 'optimizeInstead':
return {
diff --git a/web/src/components/prompts/prompt-content-step.test.tsx b/web/src/components/prompts/prompt-content-step.test.tsx
new file mode 100644
index 000000000..09f8e4897
--- /dev/null
+++ b/web/src/components/prompts/prompt-content-step.test.tsx
@@ -0,0 +1,134 @@
+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 type { CitedPage, PositionsSummary } from '@/lib/prompt-positions';
+import { PromptContentStep } from './prompt-content-step';
+
+const getDraftForPrompt = vi.fn();
+vi.mock('@/lib/actions/content-drafts', () => ({
+ getDraftForPrompt: (...args: unknown[]) => getDraftForPrompt(...args),
+}));
+const push = vi.fn();
+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push }) }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const summary = (over: Partial<PositionsSummary>): PositionsSummary => ({
+ days: [],
+ runs: 10,
+ answers: 10,
+ mentionedAnswers: 1,
+ citedAnswers: 1,
+ mentions: 1,
+ citations: 1,
+ trackedDays: 7,
+ mentionedDays: 1,
+ citedDays: 1,
+ untrackedDays: 0,
+ lastAnswerAt: null,
+ mentionPosition: null,
+ citationPosition: null,
+ ...over,
+});
+const GUIDE: CitedPage = {
+ url: 'https://acme.example/guides/crm',
+ title: 'The CRM guide',
+ answers: 1,
+};
+
+let container: HTMLDivElement;
+let root: Root;
+const onStart = vi.fn();
+
+async function render(s: PositionsSummary, citedPage: CitedPage | null = null, recheck = 0) {
+ await act(async () =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <PromptContentStep
+ brandId="b1"
+ prompt={{ id: 'p1', text: 'best crm for realtors' }}
+ summary={s}
+ citedPage={citedPage}
+ onStart={onStart}
+ recheck={recheck}
+ />
+ </NextIntlClientProvider>,
+ ),
+ );
+ await act(async () => {});
+}
+const button = () => container.querySelector('button')!;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ getDraftForPrompt.mockReset().mockResolvedValue(null);
+ onStart.mockReset();
+ push.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('PromptContentStep', () => {
+ it('optimizes the page AI cites when the brand is named rarely', async () => {
+ await render(summary({}), GUIDE);
+ expect(getDraftForPrompt).toHaveBeenCalledWith('b1', 'p1');
+ expect(container.textContent).toContain('Mentioned in 10% of answers');
+ expect(container.textContent).toContain(
+ 'Optimize The CRM guide, the page AI engines cite here',
+ );
+ await act(async () => button().click());
+ expect(onStart).toHaveBeenCalledWith({
+ kind: 'prompt',
+ id: 'p1',
+ text: 'best crm for realtors',
+ method: 'optimize',
+ page: { url: GUIDE.url, title: GUIDE.title },
+ });
+ });
+
+ it('leaves the page to Start when none is cited, and names a late position', async () => {
+ await render(
+ summary({ mentionedAnswers: 6, mentionPosition: { best: 2, worst: 7, avg: 4.5, count: 6 } }),
+ );
+ expect(container.textContent).toContain('Mentioned at #4.5 on average');
+ expect(container.textContent).toContain('pick the one to optimize');
+ await act(async () => button().click());
+ expect(onStart.mock.calls[0][0]).toMatchObject({ method: 'optimize', page: null });
+ });
+
+ it('opens the draft already being written instead of starting another', async () => {
+ getDraftForPrompt.mockResolvedValue('d7');
+ await render(summary({ mentionedAnswers: 0, citedAnswers: 0 }));
+ expect(container.textContent).toContain('A draft for this prompt is already being written.');
+ expect(button().textContent).toBe('Open draft');
+ await act(async () => button().click());
+ expect(push).toHaveBeenCalledWith('/dashboard/content/editor/d7');
+ expect(onStart).not.toHaveBeenCalled();
+ });
+
+ // Start sent to the Agent or the Team closes over the panel, which stays
+ // open: the step must not offer a second draft.
+ it('looks for the draft again once Start sent one, and opens it then', async () => {
+ const lost = summary({ mentionedAnswers: 0, citedAnswers: 0 });
+ await render(lost);
+ expect(button().textContent).toBe('Create content');
+ getDraftForPrompt.mockResolvedValue('d9');
+ await render(lost, null, 1);
+ expect(getDraftForPrompt).toHaveBeenCalledTimes(2);
+ expect(button().textContent).toBe('Open draft');
+ });
+
+ it('shows nothing, and looks up nothing, when the prompt does well', async () => {
+ await render(summary({ mentionedAnswers: 8 }));
+ expect(container.textContent).toBe('');
+ expect(getDraftForPrompt).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/components/prompts/prompt-content-step.tsx b/web/src/components/prompts/prompt-content-step.tsx
new file mode 100644
index 000000000..00dd92562
--- /dev/null
+++ b/web/src/components/prompts/prompt-content-step.tsx
@@ -0,0 +1,132 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { FilePen, FilePlus, FileText, Loader2 } from 'lucide-react';
+import { useRouter } from '@/i18n/navigation';
+import { Button } from '@/components/ui/button';
+import type { DialogPreset } from '@/components/content/new-content-dialog';
+import { getDraftForPrompt } from '@/lib/actions/content-drafts';
+import { contentEditorPath } from '@/lib/content/drafts';
+import { contentStep } from '@/lib/prompt-content';
+import type { CitedPage, PositionsSummary } from '@/lib/prompt-positions';
+
+/**
+ * The Improve tab's way into the Content Editor: whether this prompt calls
+ * for content in the panel's period (lib/prompt-content.ts), and Start for
+ * it, a new page or the page AI cites for it to optimize. A draft already
+ * being written for the prompt opens instead of a second one.
+ */
+export function PromptContentStep({
+ brandId,
+ prompt,
+ summary,
+ citedPage,
+ onStart,
+ recheck = 0,
+}: {
+ brandId: string;
+ prompt: { id: string; text: string };
+ summary: PositionsSummary;
+ citedPage: CitedPage | null;
+ onStart: (preset: DialogPreset) => void;
+ /**
+ * Changes when Start sent a draft to the Agent or the Team and the panel
+ * stayed open: the lookup runs again, so the step offers Open draft rather
+ * than a second draft.
+ */
+ recheck?: number;
+}) {
+ const t = useTranslations('prompts.content');
+ const router = useRouter();
+ const step = contentStep(summary);
+ const wanted = step !== null;
+ // The draft lookup for this prompt: undefined while it runs.
+ const [draft, setDraft] = useState<{ promptId: string; id: string | null } | null>(null);
+ useEffect(() => {
+ if (!wanted) return;
+ let cancelled = false;
+ getDraftForPrompt(brandId, prompt.id).then(
+ (id) => !cancelled && setDraft({ promptId: prompt.id, id }),
+ () => !cancelled && setDraft({ promptId: prompt.id, id: null }),
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, prompt.id, wanted, recheck]);
+
+ if (!step) return null;
+ const draftId = draft?.promptId === prompt.id ? draft.id : undefined;
+ const page = citedPage ? (citedPage.title ?? pathOf(citedPage.url)) : null;
+ const start = () =>
+ onStart(
+ step.kind === 'create'
+ ? { kind: 'prompt', id: prompt.id, text: prompt.text, method: 'create' }
+ : {
+ kind: 'prompt',
+ id: prompt.id,
+ text: prompt.text,
+ method: 'optimize',
+ page: citedPage ? { url: citedPage.url, title: citedPage.title } : null,
+ },
+ );
+
+ return (
+ <div className="flex flex-col gap-3 rounded-lg border bg-card p-3 sm:flex-row sm:items-center">
+ <div className="min-w-0 flex-1 space-y-0.5">
+ <p className="text-sm font-medium">
+ {step.kind === 'create'
+ ? t('createTitle')
+ : step.reason === 'rare'
+ ? t('rareTitle', { pct: step.mentionPct })
+ : t('lateTitle', { position: step.position })}
+ </p>
+ <p className="text-xs text-muted-foreground [overflow-wrap:anywhere]">
+ {draftId
+ ? t('draftNote')
+ : step.kind === 'create'
+ ? t('createBody', { answers: step.answers })
+ : page
+ ? t('optimizePage', { page })
+ : t('optimizePick')}
+ </p>
+ </div>
+ {draftId ? (
+ <Button
+ size="sm"
+ variant="outline"
+ className="shrink-0 gap-1.5"
+ onClick={() => router.push(contentEditorPath(draftId))}
+ >
+ <FileText className="h-3.5 w-3.5" />
+ {t('openDraft')}
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ className="shrink-0 gap-1.5"
+ disabled={draftId === undefined}
+ onClick={start}
+ >
+ {draftId === undefined ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : step.kind === 'create' ? (
+ <FilePlus className="h-3.5 w-3.5" />
+ ) : (
+ <FilePen className="h-3.5 w-3.5" />
+ )}
+ {step.kind === 'create' ? t('create') : t('optimize')}
+ </Button>
+ )}
+ </div>
+ );
+}
+
+/** "https://acme.example/guides/x?y" → "/guides/x". */
+function pathOf(url: string): string {
+ try {
+ return new URL(url).pathname || url;
+ } catch {
+ return url;
+ }
+}
diff --git a/web/src/components/prompts/prompt-positions-sheet.test.tsx b/web/src/components/prompts/prompt-positions-sheet.test.tsx
index 15b6e56b1..cd8fa88ac 100644
--- a/web/src/components/prompts/prompt-positions-sheet.test.tsx
+++ b/web/src/components/prompts/prompt-positions-sheet.test.tsx
@@ -23,7 +23,9 @@ vi.mock('@/i18n/navigation', () => ({
Link: ({ href, children }: { href: string; children: React.ReactNode }) => (
<a href={href}>{children}</a>
),
+ useRouter: () => ({ push: vi.fn() }),
}));
+vi.mock('@/lib/actions/content-drafts', () => ({ getDraftForPrompt: async () => null }));
const { PromptPositionsSheet } = await import('./prompt-positions-sheet');
@@ -94,13 +96,27 @@ function data({ locked = false, unanswered = false } = {}): PromptPositionsData
summary,
platforms,
improving: null,
+ citedPage: null,
};
}
+/** Two answers that neither name nor cite the brand. */
+function unnamed(): PromptPositionsData {
+ const { summary, platforms } = summarizePositions(
+ [answer({ createdAt: '2026-10-08T02:00:00Z' }), answer({ createdAt: '2026-10-09T02:00:00Z' })],
+ [{ id: 'chatgpt-web', label: 'ChatGPT', access: { state: 'included' } }],
+ WEEK,
+ );
+ return { ...data(), summary, platforms };
+}
+
let container: HTMLDivElement;
let root: Root;
-async function open(preset: '7d' | '24h' = '7d') {
+async function open(
+ preset: '7d' | '24h' = '7d',
+ more: Partial<React.ComponentProps<typeof PromptPositionsSheet>> = {},
+) {
await act(async () =>
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
@@ -111,6 +127,7 @@ async function open(preset: '7d' | '24h' = '7d') {
onRangeChange={() => {}}
region=""
onClose={() => {}}
+ {...more}
/>
</NextIntlClientProvider>,
),
@@ -130,6 +147,30 @@ afterEach(() => {
});
describe('PromptPositionsSheet', () => {
+ it('offers content first in the Improve tab when no answer names the brand', async () => {
+ getPromptPositions.mockResolvedValue(unnamed());
+ const onStartContent = vi.fn();
+ await open('7d', { initialTab: 'improve', brandId: 'b1', onStartContent });
+ await act(async () => {});
+ expect(document.body.textContent).toContain('No answer mentions or cites you here');
+ const create = [...document.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Create content',
+ )!;
+ await act(async () => create.click());
+ expect(onStartContent).toHaveBeenCalledWith({
+ kind: 'prompt',
+ id: 'p1',
+ text: 'Best coffee subscription?',
+ method: 'create',
+ });
+ });
+
+ it('offers no content step where the page gives no way to start', async () => {
+ getPromptPositions.mockResolvedValue(unnamed());
+ await open('7d', { initialTab: 'improve' });
+ expect(document.body.textContent).not.toContain('Create content');
+ });
+
it("puts the table's answer, mention and citation counts beside the days", async () => {
await open();
const text = document.body.textContent ?? '';
diff --git a/web/src/components/prompts/prompt-positions-sheet.tsx b/web/src/components/prompts/prompt-positions-sheet.tsx
index 262c709c7..0ed89b1c4 100644
--- a/web/src/components/prompts/prompt-positions-sheet.tsx
+++ b/web/src/components/prompts/prompt-positions-sheet.tsx
@@ -52,6 +52,8 @@ import { PROMPT_RANGE_PRESETS, type PromptRangePreset } from '@/config/prompt-op
import type { PositionsRange } from '@/lib/positions-range';
import { DateRangeFilter } from '@/components/filters/date-range-filter';
import { ImproveTab, useImprove, type ImproveController } from './prompt-improve-tab';
+import { PromptContentStep } from './prompt-content-step';
+import type { DialogPreset } from '@/components/content/new-content-dialog';
import { getPromptPositions, type PromptPositionsData } from '@/lib/actions/prompt-positions';
import { viewerTimeZone } from '@/lib/time-zone';
import type {
@@ -85,6 +87,12 @@ interface Props {
/** The tab the panel opens on: Improve when opened from the row menu (PROMPT-006). */
initialTab?: 'platforms' | 'improve';
onClose: () => void;
+ /** The prompt's brand, for the Improve tab's way into the Content Editor. */
+ brandId?: string;
+ /** Opens New content › Start for the prompt; without it the Improve tab offers no content step. */
+ onStartContent?: (preset: DialogPreset) => void;
+ /** Bumped when Start sent a draft (Agent or Team): the content step looks for it again. */
+ contentSent?: number;
}
const DAYS_PAGE = 10;
@@ -136,6 +144,9 @@ export function PromptPositionsSheet({
region,
initialTab = 'platforms',
onClose,
+ brandId,
+ onStartContent,
+ contentSent = 0,
}: Props) {
const preset = range.preset;
// A range change asked for while the Improve tab has unsent edits waits here
@@ -182,6 +193,17 @@ export function PromptPositionsSheet({
const current = loaded?.key === key && key !== '' ? loaded : null;
const data = current?.data ?? null;
const latestMode = preset === '24h';
+ const contentStepFor = (loaded: PromptPositionsData) =>
+ brandId && onStartContent ? (
+ <PromptContentStep
+ brandId={brandId}
+ prompt={loaded.prompt}
+ summary={loaded.summary}
+ citedPage={loaded.citedPage}
+ onStart={onStartContent}
+ recheck={contentSent}
+ />
+ ) : null;
const improve = useImprove({
promptId: prompt?.id ?? null,
@@ -302,9 +324,19 @@ export function PromptPositionsSheet({
{current?.error && <LoadError message={current.error} onRetry={retry} />}
{data &&
(latestMode ? (
- <LatestView data={data} improve={improve} initialTab={initialTab} />
+ <LatestView
+ data={data}
+ improve={improve}
+ initialTab={initialTab}
+ content={contentStepFor(data)}
+ />
) : (
- <PeriodView data={data} improve={improve} initialTab={initialTab} />
+ <PeriodView
+ data={data}
+ improve={improve}
+ initialTab={initialTab}
+ content={contentStepFor(data)}
+ />
))}
</div>
@@ -560,9 +592,12 @@ function LatestView({
data,
improve,
initialTab,
+ content,
}: {
data: PromptPositionsData;
improve: ImproveController;
+ /** The Improve tab's content step, first in the tab. */
+ content: React.ReactNode;
initialTab: 'platforms' | 'improve';
}) {
const included = data.platforms.filter((p) => p.access.state === 'included');
@@ -619,7 +654,8 @@ function LatestView({
)}
</div>
</TabsContent>
- <TabsContent value="improve" className="mt-3">
+ <TabsContent value="improve" className="mt-3 space-y-3">
+ {content}
<ImproveTab improve={improve} />
</TabsContent>
</Tabs>
@@ -682,9 +718,12 @@ function PeriodView({
data,
improve,
initialTab,
+ content,
}: {
data: PromptPositionsData;
improve: ImproveController;
+ /** The Improve tab's content step, first in the tab. */
+ content: React.ReactNode;
initialTab: 'platforms' | 'improve';
}) {
const s = data.summary;
@@ -753,7 +792,8 @@ function PeriodView({
<TabsContent value="history" className="mt-3">
<DailyHistory platforms={data.platforms} />
</TabsContent>
- <TabsContent value="improve" className="mt-3">
+ <TabsContent value="improve" className="mt-3 space-y-3">
+ {content}
<ImproveTab improve={improve} />
</TabsContent>
</Tabs>
diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.ts
index d474beec2..395198ea1 100644
--- a/web/src/lib/actions/content-drafts-start.test.ts
+++ b/web/src/lib/actions/content-drafts-start.test.ts
@@ -69,6 +69,7 @@ vi.mock('@/lib/supabase/server', () => ({
eq: (col: string, v: unknown) => (call.filters.push(['eq', col, v]), chain),
in: (col: string, v: unknown) => (call.filters.push(['in', col, v]), chain),
is: (col: string, v: unknown) => (call.filters.push(['is', col, v]), chain),
+ contains: (col: string, v: unknown) => (call.filters.push(['contains', col, v]), chain),
order: () => chain,
limit: () => chain,
insert: (value: unknown) => ((call.op = 'insert'), (call.value = value), chain),
@@ -83,6 +84,7 @@ vi.mock('@/lib/supabase/server', () => ({
}));
const {
+ getDraftForPrompt,
getOpportunityDrafts,
createContentDraft,
getContentOverlap,
@@ -254,6 +256,30 @@ describe('getOpportunityDrafts', () => {
});
});
+describe('getDraftForPrompt', () => {
+ it('finds the latest draft not yet published among those for the prompt', async () => {
+ reads = { content_drafts: { id: 'd7' } };
+ await expect(getDraftForPrompt(BRAND, PROMPT)).resolves.toBe('d7');
+ expect(calls).toEqual([
+ {
+ table: 'content_drafts',
+ op: 'select',
+ filters: [
+ ['eq', 'brand_id', BRAND],
+ ['contains', 'prompt_ids', [PROMPT]],
+ ['in', 'status', ['draft', 'in_review', 'ready']],
+ ],
+ },
+ ]);
+ });
+
+ it("is null when there is none, and doesn't read for an id that isn't one", async () => {
+ await expect(getDraftForPrompt(BRAND, PROMPT)).resolves.toBeNull();
+ await expect(getDraftForPrompt(BRAND, 'not-an-id')).resolves.toBeNull();
+ expect(calls).toHaveLength(1);
+ });
+});
+
describe('createContentDraft', () => {
const start = (over: Partial<DraftStart> = {}): DraftStart => ({
method: 'create',
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 81a62a249..157862974 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -339,6 +339,28 @@ export async function getContentStartOptions(brandId: string): Promise<DraftStar
};
}
+/**
+ * The draft being written for a tracked prompt (Tracked Prompts' Create
+ * content): the latest one not yet published whose prompts include it, from
+ * the prompt itself, its topic or an opportunity. Opened instead of starting
+ * a second page. Null when there is none, or the member can't read it.
+ */
+export async function getDraftForPrompt(brandId: string, promptId: string): Promise<string | null> {
+ if (!draftId.safeParse(brandId).success || !draftId.safeParse(promptId).success) return null;
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_drafts')
+ .select('id')
+ .eq('brand_id', brandId)
+ .contains('prompt_ids', [promptId])
+ .in('status', ['draft', 'in_review', 'ready'])
+ .order('updated_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ return data?.id ?? null;
+}
+
/** How many opportunities one Open draft lookup covers: a page of the list. */
const MAX_DRAFT_LOOKUPS = 200;
diff --git a/web/src/lib/actions/prompt-positions.ts b/web/src/lib/actions/prompt-positions.ts
index f1c8135d8..5032bff94 100644
--- a/web/src/lib/actions/prompt-positions.ts
+++ b/web/src/lib/actions/prompt-positions.ts
@@ -6,8 +6,10 @@ import type { PlanId } from '@/config/plans';
import {
POSITION_PLATFORMS,
brandCitationPosition,
+ brandCitedPage,
platformAccess,
summarizePositions,
+ type CitedPage,
type PlatformPositions,
type PositionAnswer,
type PositionsSummary,
@@ -24,6 +26,8 @@ export interface PromptPositionsData {
platforms: PlatformPositions[];
/** An Improve action sent for this prompt that is still tracked (PROMPT-008). */
improving: ImprovingAction | null;
+ /** The brand's page AI engines cite most for this prompt in the window: the one to optimize. */
+ citedPage: CitedPage | null;
}
/** 90 days × 8 engines × a few locations, with room to spare. */
@@ -173,5 +177,10 @@ export async function getPromptPositions(
summary,
platforms: rowsByPlatform,
improving: pickImprovingAction(improveRows ?? []),
+ // Newest answer first, so a tie goes to the page cited most recently.
+ citedPage: brandCitedPage(
+ citedIds.map((id) => sourcesById.get(id)),
+ brandDomains,
+ ),
};
}
diff --git a/web/src/lib/prompt-content.test.ts b/web/src/lib/prompt-content.test.ts
new file mode 100644
index 000000000..ce18351cc
--- /dev/null
+++ b/web/src/lib/prompt-content.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+import { contentStep } from './prompt-content';
+
+const summary = (
+ answers: number,
+ mentionedAnswers: number,
+ citedAnswers = 0,
+ position: { avg: number; count: number } | null = null,
+) => ({
+ answers,
+ mentionedAnswers,
+ citedAnswers,
+ mentionPosition: position ? { best: 1, worst: 9, ...position } : null,
+});
+
+describe('contentStep', () => {
+ it('writes a page when no answer mentions or cites the brand', () => {
+ expect(contentStep(summary(4, 0))).toEqual({ kind: 'create', answers: 4 });
+ // Cited without being named: there is a page to work on.
+ expect(contentStep(summary(4, 0, 1))).toBeNull();
+ });
+
+ it('optimizes when the brand is named in under a fifth of five or more answers', () => {
+ expect(contentStep(summary(10, 1))).toEqual({
+ kind: 'optimize',
+ reason: 'rare',
+ mentionPct: 10,
+ answers: 10,
+ });
+ // 19.6% reads as 19%, never as the 20% line.
+ expect(contentStep(summary(46, 9))).toMatchObject({ reason: 'rare', mentionPct: 19 });
+ expect(contentStep(summary(10, 0, 2))).toMatchObject({ reason: 'rare', mentionPct: 0 });
+ expect(contentStep(summary(10, 2))).toBeNull();
+ // Too few answers to call it rare.
+ expect(contentStep(summary(4, 0, 1))).toBeNull();
+ });
+
+ it('optimizes when the brand is placed after third on three or more answers', () => {
+ expect(contentStep(summary(6, 4, 0, { avg: 3.4, count: 3 }))).toEqual({
+ kind: 'optimize',
+ reason: 'late',
+ position: 3.4,
+ });
+ expect(contentStep(summary(6, 4, 0, { avg: 3, count: 4 }))).toBeNull();
+ expect(contentStep(summary(6, 4, 0, { avg: 5, count: 2 }))).toBeNull();
+ });
+
+ it('says nothing without answers', () => {
+ expect(contentStep(summary(0, 0))).toBeNull();
+ });
+});
diff --git a/web/src/lib/prompt-content.ts b/web/src/lib/prompt-content.ts
new file mode 100644
index 000000000..882de245b
--- /dev/null
+++ b/web/src/lib/prompt-content.ts
@@ -0,0 +1,47 @@
+import type { PositionsSummary } from './prompt-positions';
+
+/**
+ * Whether a tracked prompt calls for content, and which, in the Positions
+ * panel's period (the user's thresholds, 2026-10-22). No answer mentions or
+ * cites the brand: write a page for it. The brand is mentioned rarely, or
+ * late: optimize the page AI cites for it, or one picked in Start. Fewer
+ * answers than a threshold needs say nothing either way.
+ */
+
+/** Mentioned in fewer than this share of the answers is rarely… */
+export const RARE_SHARE = 0.2;
+/** …once there are this many answers. */
+export const MIN_ANSWERS = 5;
+/** An average position after this one is late… */
+export const LATE_POSITION = 3;
+/** …over this many answers that place the brand. */
+export const MIN_PLACED = 3;
+
+export type ContentStep =
+ | { kind: 'create'; answers: number }
+ | { kind: 'optimize'; reason: 'rare'; mentionPct: number; answers: number }
+ | { kind: 'optimize'; reason: 'late'; position: number };
+
+export function contentStep(
+ summary: Pick<
+ PositionsSummary,
+ 'answers' | 'mentionedAnswers' | 'citedAnswers' | 'mentionPosition'
+ >,
+): ContentStep | null {
+ const { answers, mentionedAnswers, citedAnswers, mentionPosition } = summary;
+ if (answers === 0) return null;
+ if (mentionedAnswers === 0 && citedAnswers === 0) return { kind: 'create', answers };
+ if (answers >= MIN_ANSWERS && mentionedAnswers / answers < RARE_SHARE) {
+ // Rounded down, so a share under the line never reads as 20%.
+ const mentionPct = Math.floor((mentionedAnswers / answers) * 100);
+ return { kind: 'optimize', reason: 'rare', mentionPct, answers };
+ }
+ if (
+ mentionPosition &&
+ mentionPosition.count >= MIN_PLACED &&
+ mentionPosition.avg > LATE_POSITION
+ ) {
+ return { kind: 'optimize', reason: 'late', position: mentionPosition.avg };
+ }
+ return null;
+}
diff --git a/web/src/lib/prompt-positions.test.ts b/web/src/lib/prompt-positions.test.ts
index a692e9e51..30a18a6db 100644
--- a/web/src/lib/prompt-positions.test.ts
+++ b/web/src/lib/prompt-positions.test.ts
@@ -4,6 +4,7 @@ import { PLANS, type Plan } from '@/config/plans';
import {
POSITION_PLATFORMS,
brandCitationPosition,
+ brandCitedPage,
countRuns,
platformAccess,
summarizePositions,
@@ -90,6 +91,45 @@ describe('positionTone', () => {
});
});
+describe('brandCitedPage', () => {
+ const brand = ['acme.example'];
+ const cite = (url: string, title?: string) => ({ url, title });
+
+ it('is the brand page cited in the most answers, whatever its address carries', () => {
+ expect(
+ brandCitedPage(
+ [
+ [
+ cite('https://rival.example/a'),
+ cite('https://acme.example/guide?utm_source=chatgpt.com'),
+ ],
+ [
+ cite('https://www.acme.example/guide/', 'The guide'),
+ cite('https://acme.example/pricing'),
+ ],
+ // Twice in one answer counts once.
+ [cite('https://blog.acme.example/x'), cite('https://blog.acme.example/x#top')],
+ ],
+ brand,
+ ),
+ ).toEqual({ url: 'https://acme.example/guide', title: 'The guide', answers: 2 });
+ });
+
+ it('breaks a tie for the newest answer, the first list', () => {
+ expect(
+ brandCitedPage(
+ [[cite('https://acme.example/new')], [cite('https://acme.example/old')]],
+ brand,
+ ),
+ ).toMatchObject({ url: 'https://acme.example/new', answers: 1 });
+ });
+
+ it('is null with no source of the brand, or no domains', () => {
+ expect(brandCitedPage([[cite('https://rival.example/a')], null, 'x'], brand)).toBeNull();
+ expect(brandCitedPage([[cite('https://acme.example/a')]], [])).toBeNull();
+ });
+});
+
describe('brandCitationPosition', () => {
const cites = (...urls: (string | null)[]) => urls.map((url) => ({ url, title: '' }));
diff --git a/web/src/lib/prompt-positions.ts b/web/src/lib/prompt-positions.ts
index 1d43d1dc1..70e914325 100644
--- a/web/src/lib/prompt-positions.ts
+++ b/web/src/lib/prompt-positions.ts
@@ -9,6 +9,7 @@
*/
import { PLANS, PLAN_ORDER, type Plan } from '@/config/plans';
import { extractHostname, normalizeDomain } from '@/lib/citations/classify';
+import { pageKey } from '@/lib/content/sources';
import { dayIn, nextDay, startOfDayIn } from '@/lib/time-zone';
import type { Sentiment } from '@/types';
@@ -103,6 +104,49 @@ export function brandCitationPosition(
return rank === null ? null : { rank, total };
}
+/** The brand's page AI engines cite most for a prompt, and in how many answers. */
+export interface CitedPage {
+ url: string;
+ title: string | null;
+ answers: number;
+}
+
+/**
+ * The brand's page cited in the most answers, on brandCitationPosition's
+ * host rule. One page however its address is written: query, fragment,
+ * www and a trailing slash don't count (ChatGPT adds ?utm_source=…). A tie
+ * goes to the page cited in the newest answer, as `sourceLists` comes
+ * newest first. Null when no source is the brand's.
+ */
+export function brandCitedPage(sourceLists: unknown[], brandDomains: string[]): CitedPage | null {
+ const domains = brandDomains.map(normalizeDomain).filter(Boolean);
+ if (domains.length === 0) return null;
+ const pages = new Map<string, CitedPage>();
+ for (const citations of sourceLists) {
+ if (!Array.isArray(citations)) continue;
+ const inAnswer = new Set<string>();
+ for (const cite of citations) {
+ const url = typeof cite?.url === 'string' ? cite.url.trim() : '';
+ const host = url ? extractHostname(url) : null;
+ if (!host || !domains.some((d) => host === d || host.endsWith(`.${d}`))) continue;
+ const key = pageKey(url);
+ if (!key || inAnswer.has(key)) continue;
+ inAnswer.add(key);
+ const title = typeof cite?.title === 'string' && cite.title.trim() ? cite.title.trim() : null;
+ const page = pages.get(key);
+ if (page) {
+ page.answers += 1;
+ page.title ??= title;
+ } else {
+ pages.set(key, { url: url.split(/[?#]/)[0], title, answers: 1 });
+ }
+ }
+ }
+ let top: CitedPage | null = null;
+ for (const page of pages.values()) if (!top || page.answers > top.answers) top = page;
+ return top;
+}
+
/** One stored answer, reduced to what the panel needs. */
export interface PositionAnswer {
platform: string;