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(content): link Action Center writing tasks and Content Editor drafts both ways (#1306)

Cihan78c7edea05d5
diff --git a/supabase/migrations/00218_content_draft_action_work.sql b/supabase/migrations/00218_content_draft_action_work.sql
new file mode 100644
index 000000000..9bf720d75
--- /dev/null
+++ b/supabase/migrations/00218_content_draft_action_work.sql
@@ -0,0 +1,24 @@
+-- ============================================================================
+-- 00218: one draft per action's work (Content Editor, CE-022)
+-- ============================================================================
+-- An Action Center action's writing task opens the Content Editor with a
+-- draft linked to the action (content_drafts.action_id, 00208): "Create
+-- content" for a new page, "Optimize page" for one of the pages the action
+-- names. Opening it again opens the same draft. An action can hold both kinds
+-- of work and name several pages, so the draft is one per action, method and
+-- page; this index makes a second start (two clicks, two tabs) find the first
+-- rather than write a second draft.
+--
+-- Start › Team (00208) links one draft to the action it creates, so the
+-- drafts linked so far already meet it.
+--
+-- The page is indexed by its md5: an address may run to 2,048 characters,
+-- and a non-ASCII one near that would pass btree's ~2.7 KB row limit and
+-- fail the insert.
+
+create unique index if not exists content_drafts_action_work_key
+ on public.content_drafts (action_id, method, md5(coalesce(source_url, '')))
+ where action_id is not null;
+
+comment on index public.content_drafts_action_work_key is
+ 'Content Editor (CE-022): one draft per action, method and page.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 27e04939d..d7beb91f4 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -30414,3 +30414,31 @@ revoke all on function public.content_draft_decide_suggestions(uuid[], text) fro
grant execute on function public.content_draft_decide_suggestions(uuid[], text)
to authenticated, service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00218_content_draft_action_work.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00218: one draft per action's work (Content Editor, CE-022)
+-- ============================================================================
+-- An Action Center action's writing task opens the Content Editor with a
+-- draft linked to the action (content_drafts.action_id, 00208): "Create
+-- content" for a new page, "Optimize page" for one of the pages the action
+-- names. Opening it again opens the same draft. An action can hold both kinds
+-- of work and name several pages, so the draft is one per action, method and
+-- page; this index makes a second start (two clicks, two tabs) find the first
+-- rather than write a second draft.
+--
+-- Start › Team (00208) links one draft to the action it creates, so the
+-- drafts linked so far already meet it.
+--
+-- The page is indexed by its md5: an address may run to 2,048 characters,
+-- and a non-ASCII one near that would pass btree's ~2.7 KB row limit and
+-- fail the insert.
+
+create unique index if not exists content_drafts_action_work_key
+ on public.content_drafts (action_id, method, md5(coalesce(source_url, '')))
+ where action_id is not null;
+
+comment on index public.content_drafts_action_work_key is
+ 'Content Editor (CE-022): one draft per action, method and page.';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index a46703aaa..6e3745381 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1288,7 +1288,14 @@
"sendToWebhookAgain": "Send to webhook again",
"sentToContent": "Sent to Content as an opportunity ·",
"openInContent": "Open",
- "sentToWebhook": "Sent to the webhook on {date}"
+ "sentToWebhook": "Sent to the webhook on {date}",
+ "createContent": "Create content",
+ "optimizePage": "Optimize page",
+ "optimize": "Optimize",
+ "openDraft": "Open draft",
+ "pagesToOptimize": "Pages to optimize",
+ "draftFailed": "Couldn't open the Content Editor. Try again.",
+ "pageNotRead": "Couldn't read the live page, so the draft starts with its title. Paste the page into the editor."
},
"noSignalsOpportunity": "This action was sent from Content Optimization. Its evidence is the opportunity on the Overview tab, not detection signals.",
"opportunity": {
@@ -3352,6 +3359,9 @@
"insert": "Add block"
},
"markedReady": "Marked ready. Publish it on your site when you're ready.",
+ "markedReadyAction": "Marked ready, and {count, plural, one {its task} other {its # tasks}} in Action AC-{no} {count, plural, one {is} other {are}} done. Publish it on your site when you're ready.",
+ "actionBar": "This draft is the work of <link>Action AC-{no}</link>. Mark ready completes its task there.",
+ "actionBarDone": "This draft is the work of <link>Action AC-{no}</link>.",
"suggestions": {
"bar": "Agent suggestions",
"agent": "Content Agent",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
index ce37b7f1d..b117fc6e8 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
@@ -9,7 +9,7 @@ import StarterKit from '@tiptap/starter-kit';
import { TableKit } from '@tiptap/extension-table';
import Image from '@tiptap/extension-image';
import { CharacterCount, Placeholder } from '@tiptap/extensions';
-import { ArrowLeft, Check, Copy, Loader2, PanelRight } from 'lucide-react';
+import { ArrowLeft, Check, Copy, Loader2, PanelRight, Target } from 'lucide-react';
import { Link } from '@/i18n/navigation';
import { Button } from '@/components/ui/button';
import { buttonVariants } from '@/components/ui/button-variants';
@@ -640,8 +640,12 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
return;
}
const next = await markContentDraftReady(draft.id);
- setStatus(next);
- toast.success(t('markedReady'));
+ setStatus(next.status);
+ toast.success(
+ next.tasksDone > 0 && draft.action
+ ? t('markedReadyAction', { no: draft.action.number, count: next.tasksDone })
+ : t('markedReady'),
+ );
} catch (err) {
console.error('Failed to mark the draft ready:', err);
toast.error(t('markReadyFailed'));
@@ -819,6 +823,26 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
<div className="flex min-h-0 flex-1">
<div className="flex min-w-0 flex-1 flex-col">
+ {/* The action this draft is the work of (CE-022): under the header,
+ which has no room left at 1024px, and Mark ready completes its task. */}
+ {draft.action && (
+ <p className="flex items-center gap-2 border-b bg-muted/40 px-4 py-1.5 text-[13px] text-muted-foreground">
+ <Target aria-hidden className="h-3.5 w-3.5 shrink-0" />
+ <span className="min-w-0">
+ {t.rich(canMarkReady ? 'actionBar' : 'actionBarDone', {
+ no: draft.action.number,
+ link: (chunks) => (
+ <Link
+ href={`/dashboard/action-center/actions?action=${draft.action!.id}`}
+ className="font-medium text-foreground underline underline-offset-2 hover:no-underline"
+ >
+ {chunks}
+ </Link>
+ ),
+ })}
+ </span>
+ </p>
+ )}
{suggestions.length > 0 && !(barClosed && openSuggestions === 0) && (
<AgentBar
suggestions={suggestions}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
index d1b4e398e..07ec99a59 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
@@ -139,6 +139,7 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({
bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams trust it.</p>',
author: 'agent',
rules: { set: null, source: null, overrides: {}, textRules: [] },
+ action: null,
updatedAt: '2026-10-20T10:00:00Z',
...over,
});
@@ -364,16 +365,40 @@ describe('the content editor', () => {
it('marks the draft ready once', async () => {
getContentDraft.mockResolvedValue(draft());
- markContentDraftReady.mockResolvedValue('ready');
+ markContentDraftReady.mockResolvedValue({ status: 'ready', tasksDone: 0 });
await renderPage();
await act(async () => button('Mark ready')!.click());
expect(markContentDraftReady).toHaveBeenCalledWith('d1');
- expect(toast.success).toHaveBeenCalled();
+ expect(toast.success).toHaveBeenCalledWith(
+ "Marked ready. Publish it on your site when you're ready.",
+ );
expect(container.querySelector('header')!.textContent).toContain('Ready');
expect(button('Mark ready')!.disabled).toBe(true);
});
+ it('links the action the draft is the work of, and says Ready completed its task', async () => {
+ getContentDraft.mockResolvedValue(draft({ action: { id: 'act-1', number: 214 } }));
+ markContentDraftReady.mockResolvedValue({ status: 'ready', tasksDone: 1 });
+ await renderPage();
+
+ const note = [...container.querySelectorAll('p')].find((p) =>
+ p.textContent?.startsWith('This draft is the work of'),
+ )!;
+ expect(note.textContent).toBe(
+ 'This draft is the work of Action AC-214. Mark ready completes its task there.',
+ );
+ expect(note.querySelector('a')!.getAttribute('href')).toBe(
+ '/dashboard/action-center/actions?action=act-1',
+ );
+
+ await act(async () => button('Mark ready')!.click());
+ expect(toast.success).toHaveBeenCalledWith(
+ "Marked ready, and its task in Action AC-214 is done. Publish it on your site when you're ready.",
+ );
+ expect(note.textContent).toBe('This draft is the work of Action AC-214.');
+ });
+
describe('history', () => {
const versions = [
{
diff --git a/web/src/components/action-center/action-drawer.test.tsx b/web/src/components/action-center/action-drawer.test.tsx
index 82b00c903..611c4e2ce 100644
--- a/web/src/components/action-center/action-drawer.test.tsx
+++ b/web/src/components/action-center/action-drawer.test.tsx
@@ -21,9 +21,19 @@ const server = vi.hoisted(() => ({
updateTaskStatus: vi.fn(),
updateTaskTitle: vi.fn(),
}));
-const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
-vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));
+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn() }));
+const push = vi.hoisted(() => vi.fn());
+const drafts = vi.hoisted(() => ({ getActionDrafts: vi.fn(), startDraftFromAction: vi.fn() }));
+vi.mock('@/i18n/navigation', () => ({
+ useRouter: () => ({ push }),
+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ ),
+}));
vi.mock('@/lib/actions/action-center', () => server);
+vi.mock('@/lib/actions/content-drafts', () => drafts);
vi.mock('sonner', () => ({ toast }));
const { ActionDrawer } = await import('./action-drawer');
@@ -62,6 +72,7 @@ const emptyDetail = { tasks: [], signals: [], events: [], kpis: [], positionOutc
beforeEach(() => {
vi.clearAllMocks();
server.getActionDetail.mockResolvedValue(emptyDetail);
+ drafts.getActionDrafts.mockResolvedValue([]);
for (const fn of [server.addTask, server.setActionDueDate]) fn.mockResolvedValue(undefined);
container = document.createElement('div');
document.body.appendChild(container);
@@ -73,13 +84,13 @@ afterEach(() => {
container.remove();
});
-async function renderDrawer() {
+async function renderDrawer(shown: ActionItem = action) {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
<ActionDrawer
brandId="b1"
- action={action}
+ action={shown}
members={[]}
onOpenChange={() => {}}
onChanged={onChanged}
@@ -214,4 +225,104 @@ describe('ActionDrawer', () => {
expect(onChanged).not.toHaveBeenCalled();
});
});
+
+ describe('writing tasks (CE-022)', () => {
+ const PRICING = 'https://acme.example/pricing';
+ const FEATURES = 'https://acme.example/features';
+ const task = (id: string, taskKey: string, title: string) => ({
+ id,
+ position: 1,
+ status: 'todo',
+ taskKey,
+ title,
+ titleParams: {},
+ dependsOn: [],
+ details: null,
+ });
+ const button = (name: string) =>
+ [...document.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === name || b.textContent?.startsWith(`${name} (`),
+ );
+ const openTask = async (title: string) => {
+ await act(async () => button('Tasks')!.click());
+ await act(async () => button(`1. ${title}`)!.click());
+ };
+
+ it('opens the Content Editor on a draft for the page the action names', async () => {
+ server.getActionDetail.mockResolvedValue({
+ ...emptyDetail,
+ tasks: [task('t1', 'optimize_content', 'Optimize the page')],
+ });
+ drafts.startDraftFromAction.mockResolvedValue({
+ draftId: 'd-new',
+ created: true,
+ importFailed: false,
+ });
+ await renderDrawer({ ...action, payload: { pages: [PRICING] } });
+ await openTask('Optimize the page');
+
+ await act(async () => button('Optimize page')!.click());
+ expect(drafts.startDraftFromAction).toHaveBeenCalledWith('b1', 'a1', 't1', {
+ page: PRICING,
+ title: expect.any(String),
+ });
+ expect(push).toHaveBeenCalledWith('/dashboard/content/editor/d-new');
+ });
+
+ it('opens the draft already written, and lists each page when the action names several', async () => {
+ server.getActionDetail.mockResolvedValue({
+ ...emptyDetail,
+ tasks: [task('t1', 'refresh_content', 'Refresh the pages')],
+ });
+ drafts.getActionDrafts.mockResolvedValue([
+ { id: 'd-pricing', method: 'optimize', sourceUrl: PRICING, status: 'draft' },
+ ]);
+ await renderDrawer({ ...action, payload: { pages: [PRICING, FEATURES] } });
+ await openTask('Refresh the pages');
+
+ expect(drafts.getActionDrafts).toHaveBeenCalledWith('b1', 'a1');
+ const rows = [...document.querySelectorAll('li')].filter((li) =>
+ li.textContent?.startsWith('/'),
+ );
+ expect(rows.map((li) => li.textContent)).toEqual(['/pricingOpen draft', '/featuresOptimize']);
+ expect(rows[0].querySelector('a')!.getAttribute('href')).toBe(
+ '/dashboard/content/editor/d-pricing',
+ );
+ await act(async () => rows[1].querySelector('button')!.click());
+ expect(drafts.startDraftFromAction).toHaveBeenCalledWith(
+ 'b1',
+ 'a1',
+ 't1',
+ expect.objectContaining({ page: FEATURES }),
+ );
+ });
+
+ it('starts a new page without one, and says so when it can’t', async () => {
+ server.getActionDetail.mockResolvedValue({
+ ...emptyDetail,
+ tasks: [
+ task('t1', 'create_content_draft', 'Write the draft'),
+ task('t2', 'create_content_brief', 'Write the brief'),
+ ],
+ });
+ drafts.startDraftFromAction.mockResolvedValue({ error: 'failed' });
+ await renderDrawer({ ...action, payload: { pages: [PRICING] } });
+ await openTask('Write the draft');
+
+ await act(async () => button('Create content')!.click());
+ expect(drafts.startDraftFromAction).toHaveBeenCalledWith(
+ 'b1',
+ 'a1',
+ 't1',
+ expect.objectContaining({ page: null }),
+ );
+ expect(toast.error).toHaveBeenCalledWith("Couldn't open the Content Editor. Try again.");
+ expect(push).not.toHaveBeenCalled();
+ // Only the writing task has one.
+ await act(async () => button('1. Write the brief')!.click());
+ expect(
+ [...document.querySelectorAll('button')].filter((b) => b.textContent === 'Create content'),
+ ).toHaveLength(1);
+ });
+ });
});
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index d0f3a9956..d133589a8 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -73,8 +73,17 @@ import { TopicOpportunityContext } from './topic-opportunity-context';
import { MentionReviewContext } from './mention-review-context';
import { TrafficPagesContext } from './traffic-pages-context';
import { ContentDraftContext } from './content-draft-context';
-import { TaskDetailForm, TaskDetailView, TaskTypeBadge, type TaskSendOptions } from './task-detail';
+import {
+ TaskDetailForm,
+ TaskDetailView,
+ TaskTypeBadge,
+ type TaskDraftWork,
+ type TaskSendOptions,
+} from './task-detail';
import { hasActiveWebhook, sendActionTask } from '@/lib/actions/action-task-send';
+import { getActionDrafts, startDraftFromAction } from '@/lib/actions/content-drafts';
+import { actionPages, draftMethodForTask, type ActionDraft } from '@/lib/content/action-drafts';
+import { contentEditorPath } from '@/lib/content/drafts';
import { RegenerateTasks, taskWriterEnabled } from './regenerate-tasks';
import { hasTaskSpec, type TaskDetailsEdit } from '@/lib/action-center/task-details';
import { ImproveOutcomeCard } from './improve-outcome-card';
@@ -133,6 +142,8 @@ export function ActionDrawer({
const [detail, setDetail] = useState<ActionDetail | null>(null);
const [isBusy, setIsBusy] = useState(false);
const tSend = useTranslations('actionCenter.actionsPage.drawer.send');
+ // The drafts written for the action's writing tasks (CE-022), once read.
+ const [drafts, setDrafts] = useState<ActionDraft[]>([]);
// Whether a task can go to the brand's webhook (AC-004). Best effort: no
// answer is no button.
@@ -185,10 +196,27 @@ export function ActionDrawer({
setTab('overview');
setDetail(null);
setDueDraft(null);
+ setDrafts([]);
if (action) void load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [action?.id]);
+ // Read once the action shows a writing task: its buttons open the draft
+ // already written rather than starting another. Best effort: without an
+ // answer they start one, and the server finds it (startDraftFromAction).
+ const hasWritingTask = !!detail?.tasks.some((task) => draftMethodForTask(task.taskKey));
+ useEffect(() => {
+ if (!action || !hasWritingTask) return;
+ const id = action.id;
+ getActionDrafts(brandId, id).then(
+ (next) => {
+ if (openId.current === id) setDrafts(next);
+ },
+ () => undefined,
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [brandId, action?.id, hasWritingTask]);
+
// The signals the action rests on, what they affect, their prompts' demand
// and the Why and Goal they tell (AC-003), as the History drawer reads them.
const { affected, volumes, story, ready } = useActionStory(
@@ -250,6 +278,28 @@ export function ActionDrawer({
}
};
+ /**
+ * Create content / Optimize page (CE-022): the draft for the task's work,
+ * linked to the action, opened in the Content Editor.
+ */
+ const startDraft = async (taskId: string, page: string | null) => {
+ setIsBusy(true);
+ try {
+ const result = await startDraftFromAction(brandId, action.id, taskId, {
+ page,
+ title: texts.title,
+ });
+ if ('error' in result) {
+ toast.error(t('drawer.task.draftFailed'));
+ return;
+ }
+ if (result.importFailed) toast.warning(t('drawer.task.pageNotRead'));
+ router.push(contentEditorPath(result.draftId));
+ } finally {
+ setIsBusy(false);
+ }
+ };
+
/**
* A task change: saved, then the detail read again to show it, and the
* list's task count patched from it rather than the list read again.
@@ -606,31 +656,43 @@ export function ActionDrawer({
{t('drawer.tasksProgress', taskProgress(detail.tasks.map((task) => task.status)))}
</p>
<div className="mt-3 space-y-2">
- {detail.tasks.map((task) => (
- <TaskRow
- key={task.id}
- task={task}
- disabled={isBusy}
- text={taskText(task, tTasks)}
- statusLabel={tTaskStatus}
- t={t}
- onStatusChange={(status, skipReason) =>
- void mutate(() =>
- updateTaskStatus(brandId, action.id, task.id, status, skipReason),
- )
- }
- onEdit={(edit) =>
- mutate(() => updateTaskDetails(brandId, action.id, task.id, edit))
- }
- onDelete={() => void mutate(() => deleteTask(brandId, action.id, task.id))}
- send={{
- // A content task, unless the action itself came from Content.
- content: task.details?.type === 'content' && !opportunityId,
- webhook: webhookReady,
- onSend: (to) => void sendTask(task.id, taskText(task, tTasks), to),
- }}
- />
- ))}
+ {detail.tasks.map((task) => {
+ const method = draftMethodForTask(task.taskKey);
+ const draftWork: TaskDraftWork | undefined = method
+ ? {
+ method,
+ pages: method === 'optimize' ? actionPages(action.payload) : [],
+ drafts,
+ onStart: (page) => void startDraft(task.id, page),
+ }
+ : undefined;
+ return (
+ <TaskRow
+ key={task.id}
+ task={task}
+ disabled={isBusy}
+ text={taskText(task, tTasks)}
+ statusLabel={tTaskStatus}
+ t={t}
+ onStatusChange={(status, skipReason) =>
+ void mutate(() =>
+ updateTaskStatus(brandId, action.id, task.id, status, skipReason),
+ )
+ }
+ onEdit={(edit) =>
+ mutate(() => updateTaskDetails(brandId, action.id, task.id, edit))
+ }
+ onDelete={() => void mutate(() => deleteTask(brandId, action.id, task.id))}
+ send={{
+ // A content task, unless the action itself came from Content.
+ content: task.details?.type === 'content' && !opportunityId,
+ webhook: webhookReady,
+ onSend: (to) => void sendTask(task.id, taskText(task, tTasks), to),
+ }}
+ draftWork={draftWork}
+ />
+ );
+ })}
</div>
<AddTaskForm
disabled={isBusy}
@@ -747,6 +809,7 @@ function TaskRow({
onEdit,
onDelete,
send,
+ draftWork,
}: {
task: ActionTask;
text: string;
@@ -758,6 +821,7 @@ function TaskRow({
onEdit: (edit: TaskDetailsEdit & { title: string | null }) => Promise<boolean>;
onDelete: () => void;
send: TaskSendOptions;
+ draftWork?: TaskDraftWork;
}) {
// A task sent from the Improve tab opens on its suggestion, as it always
// showed it; the rest open on a click.
@@ -856,6 +920,7 @@ function TaskRow({
disabled={disabled || skipDraft !== null}
onEdit={() => setEditing(true)}
send={send}
+ draftWork={draftWork}
/>
))}
diff --git a/web/src/components/action-center/task-detail.test.tsx b/web/src/components/action-center/task-detail.test.tsx
index 4f8a06156..f121880a6 100644
--- a/web/src/components/action-center/task-detail.test.tsx
+++ b/web/src/components/action-center/task-detail.test.tsx
@@ -224,6 +224,23 @@ describe('sending a task (AC-004)', () => {
]);
});
+ it('writes a writing task in the Content Editor, not through Send to Content', () => {
+ render(
+ <TaskDetailView
+ details={details}
+ disabled={false}
+ onEdit={() => {}}
+ send={send()}
+ draftWork={{ method: 'create', pages: [], drafts: [], onStart: vi.fn() }}
+ />,
+ );
+ expect([...container.querySelectorAll('button')].map((b) => b.textContent)).toEqual([
+ 'Create content',
+ 'Edit',
+ 'Send to webhook',
+ ]);
+ });
+
it('offers nothing it cannot do', () => {
render(
<TaskDetailView
diff --git a/web/src/components/action-center/task-detail.tsx b/web/src/components/action-center/task-detail.tsx
index 292c1a4f3..5e681507b 100644
--- a/web/src/components/action-center/task-detail.tsx
+++ b/web/src/components/action-center/task-detail.tsx
@@ -6,6 +6,7 @@ import { ArrowUpRight } from 'lucide-react';
import { Link } from '@/i18n/navigation';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
+import { buttonVariants } from '@/components/ui/button-variants';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
@@ -24,6 +25,10 @@ import {
type ActionTaskDetails,
type TaskDetailsEdit,
} from '@/lib/action-center/task-details';
+import { findActionDraft, type ActionDraft } from '@/lib/content/action-drafts';
+import { contentEditorPath, type DraftMethod } from '@/lib/content/drafts';
+import { pagePath } from '@/lib/content/overlap';
+import { cn } from '@/lib/utils';
/** The type of work, beside the task's text (AC-004). */
export function TaskTypeBadge({ type }: { type: ActionTaskDetails['type'] }) {
@@ -45,6 +50,67 @@ export interface TaskSendOptions {
onSend: (to: 'content' | 'webhook') => void;
}
+/** A writing task's work in the Content Editor (CE-022), and starting it. */
+export interface TaskDraftWork {
+ method: DraftMethod;
+ /** The pages the action names, for an existing page's work. */
+ pages: string[];
+ /** The drafts already linked to the action. */
+ drafts: ActionDraft[];
+ onStart: (page: string | null) => void;
+}
+
+/**
+ * "Create content" or "Optimize page" (CE-022): opens the Content Editor on
+ * the draft for this work, started when there is none yet, and "Open draft"
+ * once there is. An action naming several pages lists them, one draft each.
+ */
+function DraftWorkButtons({ work, disabled }: { work: TaskDraftWork; disabled: boolean }) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.task');
+ const button = (page: string | null, label: string) => {
+ const draft = findActionDraft(work.drafts, work.method, page);
+ return draft ? (
+ <Link
+ href={contentEditorPath(draft.id)}
+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 shrink-0 text-xs')}
+ >
+ {t('openDraft')}
+ </Link>
+ ) : (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={() => work.onStart(page)}
+ className="h-7 shrink-0 text-xs"
+ >
+ {label}
+ </Button>
+ );
+ };
+
+ if (work.method === 'create' || work.pages.length === 0) {
+ return button(null, t(work.method === 'create' ? 'createContent' : 'optimizePage'));
+ }
+ if (work.pages.length === 1) return button(work.pages[0], t('optimizePage'));
+ return (
+ <div className="w-full space-y-1">
+ <p className="text-xs text-muted-foreground">{t('pagesToOptimize')}</p>
+ <ul className="space-y-1">
+ {work.pages.map((page) => (
+ <li key={page} className="flex items-center justify-between gap-2 text-xs">
+ <span className="min-w-0 truncate" title={page}>
+ {pagePath(page)}
+ </span>
+ {button(page, t('optimize'))}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
/**
* An opened task (AC-004): where to do it, why, how, when it counts as done
* and what it takes, where it was sent, and for a task sent from the Improve
@@ -55,11 +121,14 @@ export function TaskDetailView({
disabled,
onEdit,
send,
+ draftWork,
}: {
details: ActionTaskDetails | null;
disabled: boolean;
onEdit: () => void;
send?: TaskSendOptions;
+ /** A writing task's draft (CE-022). */
+ draftWork?: TaskDraftWork;
}) {
const t = useTranslations('actionCenter.actionsPage.drawer.task');
const format = useFormatter();
@@ -141,6 +210,7 @@ export function TaskDetailView({
</div>
)}
<div className="flex flex-wrap gap-2">
+ {draftWork && <DraftWorkButtons work={draftWork} disabled={disabled} />}
<Button
type="button"
variant="outline"
@@ -151,7 +221,8 @@ export function TaskDetailView({
>
{t('edit')}
</Button>
- {send?.content && !sentContent && (
+ {/* A writing task is written in the Content Editor: Create content / Optimize page. */}
+ {send?.content && !sentContent && !draftWork && (
<Button
type="button"
variant="outline"
diff --git a/web/src/lib/actions/content-drafts-brief.test.ts b/web/src/lib/actions/content-drafts-brief.test.ts
index 490958d31..aefcb0072 100644
--- a/web/src/lib/actions/content-drafts-brief.test.ts
+++ b/web/src/lib/actions/content-drafts-brief.test.ts
@@ -18,6 +18,7 @@ let reads: Record<string, unknown>;
let session: { access_token: string } | null;
vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
auth: { getSession: async () => ({ data: { session } }) },
diff --git a/web/src/lib/actions/content-drafts-impact.test.ts b/web/src/lib/actions/content-drafts-impact.test.ts
index 2b1575cc3..b07a17631 100644
--- a/web/src/lib/actions/content-drafts-impact.test.ts
+++ b/web/src/lib/actions/content-drafts-impact.test.ts
@@ -9,6 +9,7 @@ let rpcCalls: { fn: string; args: unknown }[];
let rpcResult: { data: unknown; error: { message: string } | null };
vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
rpc: async (fn: string, args: unknown) => {
diff --git a/web/src/lib/actions/content-drafts-my-rules.test.ts b/web/src/lib/actions/content-drafts-my-rules.test.ts
index cebb39c19..ea43c9df8 100644
--- a/web/src/lib/actions/content-drafts-my-rules.test.ts
+++ b/web/src/lib/actions/content-drafts-my-rules.test.ts
@@ -10,6 +10,7 @@ let filters: [string, string, unknown][];
let user: { id: string } | null;
vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
auth: { getUser: async () => ({ data: { user } }) },
diff --git a/web/src/lib/actions/content-drafts-rules.test.ts b/web/src/lib/actions/content-drafts-rules.test.ts
index 2f499c57b..cc5e8c299 100644
--- a/web/src/lib/actions/content-drafts-rules.test.ts
+++ b/web/src/lib/actions/content-drafts-rules.test.ts
@@ -9,6 +9,7 @@ let row: Record<string, unknown> | null;
let updated: { id: string } | null;
vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
from: () => {
diff --git a/web/src/lib/actions/content-drafts-sources.test.ts b/web/src/lib/actions/content-drafts-sources.test.ts
index a6c0bd805..88da21424 100644
--- a/web/src/lib/actions/content-drafts-sources.test.ts
+++ b/web/src/lib/actions/content-drafts-sources.test.ts
@@ -19,6 +19,7 @@ let rpcResult: { data: unknown; error: { message: string } | null };
let reads: Record<string, unknown>;
vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
rpc: async (fn: string, args: unknown) => {
diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.ts
index a1415ce67..5ac7be575 100644
--- a/web/src/lib/actions/content-drafts-start.test.ts
+++ b/web/src/lib/actions/content-drafts-start.test.ts
@@ -24,6 +24,26 @@ let rpcCalls: { fn: string; args: unknown }[];
let rpcRows: unknown[];
vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+// The server's writes: a draft linked to an action (CE-022).
+const admin = vi.hoisted(() => ({
+ inserts: [] as { table: string; value: Record<string, unknown> }[],
+ result: { data: { id: 'action-draft' }, error: null } as {
+ data: { id: string } | null;
+ error: { code: string; message: string } | null;
+ },
+ onInsert: null as (() => void) | null,
+}));
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: (table: string) => ({
+ insert: (value: Record<string, unknown>) => {
+ admin.inserts.push({ table, value });
+ admin.onInsert?.();
+ return { select: () => ({ single: async () => admin.result }) };
+ },
+ }),
+ },
+}));
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
auth: {
@@ -40,14 +60,18 @@ vi.mock('@/lib/supabase/server', () => ({
const result = () =>
call.op === 'insert'
? { data: { id: 'new-draft' }, error: null }
- : { data: reads[table] ?? null, error: null };
+ : call.op === 'update'
+ ? { data: null, error: null }
+ : { data: reads[table] ?? null, error: null };
const chain: Record<string, unknown> = {
select: () => chain,
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),
order: () => chain,
limit: () => chain,
insert: (value: unknown) => ((call.op = 'insert'), (call.value = value), chain),
+ update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),
maybeSingle: async () => result(),
single: async () => result(),
then: (resolve: (r: unknown) => void) => resolve(result()),
@@ -63,6 +87,7 @@ const {
getContentStartOptions,
importContentPage,
sendContentDraftToActionCenter,
+ startDraftFromAction,
} = await import('./content-drafts');
const inserted = () => calls.find((call) => call.op === 'insert')?.value as Record<string, unknown>;
@@ -72,6 +97,9 @@ beforeEach(() => {
reads = {};
rpcCalls = [];
rpcRows = [];
+ admin.inserts = [];
+ admin.result = { data: { id: 'action-draft' }, error: null };
+ admin.onInsert = null;
});
describe('getContentStartOptions', () => {
@@ -452,3 +480,203 @@ describe('sendContentDraftToActionCenter', () => {
vi.unstubAllGlobals();
});
});
+
+describe('startDraftFromAction', () => {
+ const ACTION = '77777777-7777-7777-7777-777777777777';
+ const TASK = '88888888-8888-8888-8888-888888888888';
+ const PAGE = 'https://northwind.example/forecasting';
+ const DELETED_PROMPT = '99999999-9999-9999-9999-999999999999';
+ const action = (payload: Record<string, unknown> = {}) => ({
+ id: ACTION,
+ payload: {
+ title: 'Pipeline forecasting',
+ pages: [PAGE, 'https://northwind.example/pricing'],
+ promptIds: [PROMPT, DELETED_PROMPT, 'not-an-id'],
+ opportunityId: OPPORTUNITY,
+ ...payload,
+ },
+ });
+ const start = (page: string | null = PAGE) =>
+ startDraftFromAction(BRAND, ACTION, TASK, { page, title: 'Recover visibility' });
+
+ it('writes the draft for the page, linked to the action, and starts the task', async () => {
+ reads = {
+ actions: action({ title: undefined }),
+ action_tasks: { id: TASK, task_key: 'optimize_content', status: 'todo' },
+ content_drafts: [],
+ brands: { site_type: 'b2b', industry: 'Software', shopping_mode_enabled: false },
+ prompts: [{ id: PROMPT }],
+ content_opportunities: { id: OPPORTUNITY },
+ };
+ const fetchMock = vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ url: PAGE,
+ title: 'Forecasting',
+ html: '<h1>Forecasting</h1><p onclick="x()">Forecast every deal.</p>',
+ }),
+ { status: 200 },
+ ),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(start()).resolves.toEqual({
+ draftId: 'action-draft',
+ created: true,
+ importFailed: false,
+ });
+ expect(
+ JSON.parse((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body as string),
+ ).toEqual({ brandId: BRAND, url: PAGE });
+ // A deleted action starts no work.
+ expect(calls.find((call) => call.table === 'actions')!.filters).toContainEqual([
+ 'is',
+ 'deleted_at',
+ null,
+ ]);
+ expect(admin.inserts).toEqual([
+ {
+ table: 'content_drafts',
+ value: expect.objectContaining({
+ brand_id: BRAND,
+ created_by: 'u1',
+ author: 'user',
+ method: 'optimize',
+ title: 'Forecasting',
+ page_type_source: 'detected',
+ body_html: '<h1>Forecasting</h1><p>Forecast every deal.</p>',
+ source_url: PAGE,
+ opportunity_id: OPPORTUNITY,
+ prompt_ids: [PROMPT],
+ action_id: ACTION,
+ }),
+ },
+ ]);
+ // Only the brand's prompts, read through the member's session.
+ expect(calls.find((call) => call.table === 'prompts')!.filters).toEqual([
+ ['eq', 'prompt_sets.brand_id', BRAND],
+ ['in', 'id', [PROMPT, DELETED_PROMPT]],
+ ]);
+ expect(rpcCalls).toEqual([
+ { fn: 'content_draft_snapshot', args: { p_draft_id: 'action-draft', p_origin: 'import' } },
+ ]);
+ const taskUpdate = calls.find((call) => call.table === 'action_tasks' && call.op === 'update');
+ expect(taskUpdate).toMatchObject({
+ value: { status: 'in_progress' },
+ filters: [
+ ['eq', 'action_id', ACTION],
+ ['eq', 'id', TASK],
+ ],
+ });
+ vi.unstubAllGlobals();
+ });
+
+ it('opens the draft already written for that work, writing nothing', async () => {
+ reads = {
+ actions: action(),
+ action_tasks: { id: TASK, task_key: 'refresh_content', status: 'in_progress' },
+ content_drafts: [
+ {
+ id: 'd-pricing',
+ method: 'optimize',
+ source_url: 'https://northwind.example/pricing',
+ status: 'draft',
+ },
+ { id: 'd-page', method: 'optimize', source_url: PAGE, status: 'ready' },
+ ],
+ };
+ await expect(start()).resolves.toEqual({
+ draftId: 'd-page',
+ created: false,
+ importFailed: false,
+ });
+ expect(admin.inserts).toEqual([]);
+ });
+
+ it('starts a new page with its title when the live page can’t be read, and a create task has no page', async () => {
+ reads = {
+ actions: action(),
+ action_tasks: { id: TASK, task_key: 'create_content_draft', status: 'completed' },
+ content_drafts: [{ id: 'd-page', method: 'optimize', source_url: PAGE, status: 'draft' }],
+ brands: { site_type: 'b2b', industry: null, shopping_mode_enabled: false },
+ prompts: [],
+ content_opportunities: null,
+ };
+ await expect(start(null)).resolves.toMatchObject({ created: true, importFailed: false });
+ expect(admin.inserts[0].value).toMatchObject({
+ method: 'create',
+ title: 'Pipeline forecasting',
+ body_html: '<h1>Pipeline forecasting</h1>',
+ source_url: null,
+ opportunity_id: null,
+ });
+ // A task already past To do keeps its status.
+ expect(calls.some((call) => call.table === 'action_tasks' && call.op === 'update')).toBe(false);
+
+ admin.inserts = [];
+ reads.action_tasks = { id: TASK, task_key: 'optimize_content', status: 'todo' };
+ reads.content_drafts = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('{}', { status: 502 })),
+ );
+ await expect(start()).resolves.toMatchObject({ created: true, importFailed: true });
+ expect(admin.inserts[0].value).toMatchObject({
+ title: 'Pipeline forecasting',
+ body_html: '<h1>Pipeline forecasting</h1>',
+ source_url: PAGE,
+ });
+
+ // The page's address tells its type, even when the page can't be read.
+ admin.inserts = [];
+ await expect(start('https://northwind.example/pricing')).resolves.toMatchObject({
+ created: true,
+ });
+ expect(admin.inserts[0].value).toMatchObject({
+ page_type: 'pricing',
+ source_url: 'https://northwind.example/pricing',
+ });
+ vi.unstubAllGlobals();
+ });
+
+ it('refuses a page the action doesn’t name, a task that isn’t writing, or an unreadable action', async () => {
+ reads = {
+ actions: action(),
+ action_tasks: { id: TASK, task_key: 'optimize_content', status: 'todo' },
+ };
+ await expect(start('https://elsewhere.example/')).resolves.toEqual({ error: 'invalid' });
+ reads.action_tasks = { id: TASK, task_key: 'create_content_draft', status: 'todo' };
+ await expect(start(PAGE)).resolves.toEqual({ error: 'invalid' });
+ reads.action_tasks = { id: TASK, task_key: 'publish_content', status: 'todo' };
+ await expect(start(null)).resolves.toEqual({ error: 'invalid' });
+ reads.actions = null;
+ await expect(start(null)).resolves.toEqual({ error: 'not_found' });
+ await expect(
+ startDraftFromAction(BRAND, 'nope', TASK, { page: null, title: '' }),
+ ).resolves.toEqual({ error: 'invalid' });
+ expect(admin.inserts).toEqual([]);
+ });
+
+ it('opens the draft another start wrote at the same time', async () => {
+ reads = {
+ actions: action({ pages: [] }),
+ action_tasks: { id: TASK, task_key: 'create_content_draft', status: 'todo' },
+ content_drafts: [],
+ brands: null,
+ prompts: [],
+ content_opportunities: null,
+ };
+ admin.result = { data: null, error: { code: '23505', message: 'duplicate key' } };
+ admin.onInsert = () => {
+ reads.content_drafts = [
+ { id: 'd-first', method: 'create', source_url: null, status: 'draft' },
+ ];
+ };
+ await expect(start(null)).resolves.toEqual({
+ draftId: 'd-first',
+ created: false,
+ importFailed: false,
+ });
+ });
+});
diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.ts
index 860a00614..2933a2179 100644
--- a/web/src/lib/actions/content-drafts.test.ts
+++ b/web/src/lib/actions/content-drafts.test.ts
@@ -25,6 +25,12 @@ let rpcCalls: [string, unknown][];
let rpcResult: { data: unknown; error: { message: string } | null };
vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+const completeDraftTasks = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/content/action-drafts', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/content/action-drafts')>()),
+ completeDraftTasks,
+}));
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
auth: {
@@ -82,6 +88,7 @@ beforeEach(() => {
list = [];
rpcCalls = [];
rpcResult = { data: 'v-new', error: null };
+ completeDraftTasks.mockReset().mockResolvedValue(0);
});
describe('saveContentDraft', () => {
@@ -262,7 +269,8 @@ describe('setContentDraftPageType', () => {
describe('markContentDraftReady', () => {
it('moves a draft or an agent draft in review to ready', async () => {
updated = { status: 'ready' };
- await expect(markContentDraftReady(DRAFT)).resolves.toBe('ready');
+ await expect(markContentDraftReady(DRAFT)).resolves.toEqual({ status: 'ready', tasksDone: 0 });
+ expect(completeDraftTasks).not.toHaveBeenCalled();
expect(calls[0]).toMatchObject({
op: 'update',
value: { status: 'ready' },
@@ -285,7 +293,27 @@ describe('markContentDraftReady', () => {
author: 'user',
updated_at: '2026-10-20T15:00:00Z',
};
- await expect(markContentDraftReady(DRAFT)).resolves.toBe('published');
+ await expect(markContentDraftReady(DRAFT)).resolves.toEqual({
+ status: 'published',
+ tasksDone: 0,
+ });
+ expect(completeDraftTasks).not.toHaveBeenCalled();
+ });
+
+ it('completes the task of the action the draft is the work of (CE-022)', async () => {
+ updated = { status: 'ready', brand_id: 'b1', method: 'optimize', action_id: 'act-1' };
+ completeDraftTasks.mockResolvedValue(1);
+ await expect(markContentDraftReady(DRAFT)).resolves.toEqual({ status: 'ready', tasksDone: 1 });
+ expect(completeDraftTasks).toHaveBeenCalledWith(
+ expect.anything(),
+ { id: DRAFT, brandId: 'b1', actionId: 'act-1', method: 'optimize' },
+ 'u1',
+ );
+
+ // The draft is ready even when the task couldn't be completed.
+ completeDraftTasks.mockRejectedValue(new Error('rls'));
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ await expect(markContentDraftReady(DRAFT)).resolves.toEqual({ status: 'ready', tasksDone: 0 });
});
it('says so when the draft isn’t the member’s', async () => {
@@ -310,7 +338,7 @@ describe('markContentDraftReady', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
updated = { status: 'ready' };
rpcResult = { data: null, error: { message: 'timeout' } };
- await expect(markContentDraftReady(DRAFT)).resolves.toBe('ready');
+ await expect(markContentDraftReady(DRAFT)).resolves.toEqual({ status: 'ready', tasksDone: 0 });
expect(error).toHaveBeenCalled();
error.mockRestore();
});
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 4da1f4c96..a59c94ca3 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -64,6 +64,15 @@ import {
type RestoredDraft,
type VersionOrigin,
} from '@/lib/content/history';
+import {
+ actionPages,
+ completeDraftTasks,
+ draftMethodForTask,
+ findActionDraft,
+ setDraftTasksStatus,
+ type ActionDraft,
+} from '@/lib/content/action-drafts';
+import { supabaseAdmin } from '@/lib/supabase/admin';
import {
DRAFT_SOURCE_KINDS,
SOURCES_DAYS,
@@ -152,7 +161,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>
const { data, error } = await supabase
.from('content_drafts')
.select(
- `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, source_url, rules, updated_at, ${BRAND_SITE}`,
+ `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, source_url, rules, action_id, updated_at, ${BRAND_SITE}, actions(action_no)`,
)
.eq('id', id)
.maybeSingle();
@@ -171,6 +180,10 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>
bodyHtml: data.body_html,
author: data.author === 'agent' ? 'agent' : 'user',
rules: draftRulesSchema.safeParse(data.rules).data ?? NO_DRAFT_RULES,
+ action:
+ data.action_id && data.actions
+ ? { id: data.action_id, number: data.actions.action_no }
+ : null,
updatedAt: data.updated_at,
};
}
@@ -405,6 +418,215 @@ export async function sendContentDraftToActionCenter(
}
}
+/** The drafts linked to an action (CE-022), for its writing tasks: open one, or start it. */
+async function readActionDrafts(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ brandId: string,
+ actionId: string,
+): Promise<ActionDraft[]> {
+ const { data, error } = await supabase
+ .from('content_drafts')
+ .select('id, method, source_url, status')
+ .eq('brand_id', brandId)
+ .eq('action_id', actionId)
+ .order('created_at', { ascending: true });
+ if (error) throw new Error(error.message);
+ return (data ?? []).map((row) => ({
+ id: row.id,
+ method: row.method === 'create' ? 'create' : 'optimize',
+ sourceUrl: row.source_url,
+ status: draftStatus(row.status),
+ }));
+}
+
+/** The drafts written for an action's tasks, for the Action Center drawer. */
+export async function getActionDrafts(brandId: string, actionId: string): Promise<ActionDraft[]> {
+ if (!draftId.safeParse(brandId).success || !draftId.safeParse(actionId).success) return [];
+ return readActionDrafts(await createClient(), brandId, actionId);
+}
+
+const actionStartInput = z.object({
+ brandId: z.guid(),
+ actionId: z.guid(),
+ taskId: z.guid(),
+ page: z.string().max(2048).nullable(),
+ // The action's own title, for one whose payload names none.
+ title: z.string().max(5_000),
+});
+
+/**
+ * "Create content" or "Optimize page" on an action's writing task (CE-022,
+ * spec §15): the draft for that work, linked to the action, or the one
+ * already written for it. A new draft takes what the action knows: its
+ * title, the page it names (brought in from the live site, as Start does),
+ * its prompts and its opportunity; the page type is detected and follows the
+ * page. The task moves to In progress.
+ *
+ * The action and task are read through the member's session, so only their
+ * organization's can start one; the draft is then written by the server, as
+ * its action_id is server-set (00208), with the member as its author. Two
+ * starts at once find the same draft (00218). Returned, not thrown:
+ * production hides a server action's errors.
+ */
+export async function startDraftFromAction(
+ brandId: string,
+ actionId: string,
+ taskId: string,
+ options: { page: string | null; title: string },
+): Promise<
+ | { draftId: string; created: boolean; importFailed: boolean }
+ | { error: 'invalid' | 'not_found' | 'failed' }
+> {
+ const parsed = actionStartInput.safeParse({ brandId, actionId, taskId, ...options });
+ if (!parsed.success) return { error: 'invalid' };
+ const { page } = parsed.data;
+ try {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) return { error: 'failed' };
+
+ const [actionRes, taskRes] = await Promise.all([
+ supabase
+ .from('actions')
+ .select('id, payload')
+ .eq('brand_id', brandId)
+ .eq('id', actionId)
+ // A deleted action (00168) starts no work.
+ .is('deleted_at', null)
+ .maybeSingle(),
+ supabase
+ .from('action_tasks')
+ .select('id, task_key, status')
+ .eq('action_id', actionId)
+ .eq('id', taskId)
+ .maybeSingle(),
+ ]);
+ if (actionRes.error) throw new Error(actionRes.error.message);
+ if (taskRes.error) throw new Error(taskRes.error.message);
+ if (!actionRes.data || !taskRes.data) return { error: 'not_found' };
+ const payload = (actionRes.data.payload ?? {}) as Record<string, unknown>;
+ const method = draftMethodForTask(taskRes.data.task_key);
+ // A page is one the action names, and only an existing page's work has one.
+ if (
+ !method ||
+ (page !== null && (method === 'create' || !actionPages(payload).includes(page)))
+ ) {
+ return { error: 'invalid' };
+ }
+
+ const linked = await readActionDrafts(supabase, brandId, actionId);
+ const existing = findActionDraft(linked, method, page);
+ if (existing) return { draftId: existing.id, created: false, importFailed: false };
+
+ let title = typeof payload.title === 'string' ? payload.title.trim() : '';
+ let bodyHtml: string | undefined;
+ let importFailed = false;
+ if (page) {
+ const imported = await importContentPage(brandId, page);
+ if ('page' in imported) {
+ bodyHtml = imported.page.html;
+ title ||= imported.page.title.trim();
+ } else {
+ importFailed = true;
+ }
+ }
+ title = (title || parsed.data.title.trim()).slice(0, MAX_TITLE_LENGTH).trim();
+ const body =
+ bodyHtml !== undefined
+ ? sanitizeDraftHtml(bodyHtml)
+ : title
+ ? `<h1>${escapeHtml(title)}</h1>`
+ : '';
+
+ const wantedPrompts = Array.isArray(payload.promptIds)
+ ? payload.promptIds
+ .filter((id): id is string => typeof id === 'string' && draftId.safeParse(id).success)
+ .slice(0, MAX_DRAFT_PROMPTS)
+ : [];
+ const opportunity =
+ typeof payload.opportunityId === 'string' && draftId.safeParse(payload.opportunityId).success
+ ? payload.opportunityId
+ : null;
+ // Only what the member's brand still has: a deleted prompt or opportunity drops out.
+ const [brandRes, promptsRes, opportunityRes] = await Promise.all([
+ supabase
+ .from('brands')
+ .select('site_type, industry, shopping_mode_enabled')
+ .eq('id', brandId)
+ .maybeSingle(),
+ wantedPrompts.length
+ ? supabase
+ .from('prompts')
+ .select('id, prompt_sets!inner(brand_id)')
+ .eq('prompt_sets.brand_id', brandId)
+ .in('id', wantedPrompts)
+ : Promise.resolve({ data: [] as { id: string }[], error: null }),
+ opportunity
+ ? supabase
+ .from('content_opportunities')
+ .select('id')
+ .eq('brand_id', brandId)
+ .eq('id', opportunity)
+ .maybeSingle()
+ : Promise.resolve({ data: null, error: null }),
+ ]);
+ if (brandRes.error) throw new Error(brandRes.error.message);
+ if (promptsRes.error) throw new Error(promptsRes.error.message);
+ if (opportunityRes.error) throw new Error(opportunityRes.error.message);
+
+ const { data: inserted, error } = await supabaseAdmin
+ .from('content_drafts')
+ .insert({
+ brand_id: brandId,
+ created_by: user.id,
+ author: 'user',
+ method,
+ title,
+ // The page's address is the strongest sign of its type, as in Start.
+ page_type: detectPageType({ title, html: body, url: page }, brandSiteType(brandRes.data)),
+ page_type_source: 'detected',
+ body_html: body,
+ opportunity_id: opportunityRes.data?.id ?? null,
+ source_url: page,
+ prompt_ids: [...new Set((promptsRes.data ?? []).map((p) => p.id))],
+ action_id: actionId,
+ })
+ .select('id')
+ .single();
+ if (error) {
+ // Started twice at once: the other start wrote it.
+ if (error.code === '23505') {
+ const winner = findActionDraft(
+ await readActionDrafts(supabase, brandId, actionId),
+ method,
+ page,
+ );
+ if (winner) return { draftId: winner.id, created: false, importFailed: false };
+ }
+ throw new Error(error.message);
+ }
+
+ // A page brought in from its address starts History as the live page.
+ if (bodyHtml !== undefined) await keepVersion(supabase, inserted.id, 'import');
+ if (taskRes.data.status === 'todo') {
+ // The draft is started either way; the task's status can be set in the drawer.
+ await setDraftTasksStatus(
+ supabase,
+ { id: inserted.id, brandId, actionId },
+ [taskId],
+ 'in_progress',
+ user.id,
+ ).catch((err) => console.error("Failed to start the action's task:", err));
+ }
+ return { draftId: inserted.id, created: true, importFailed };
+ } catch (err) {
+ console.error('Failed to start a draft from an action:', err);
+ return { error: 'failed' };
+ }
+}
+
/**
* The Impact tab (CE-016): what the page a draft optimizes earns over the
* last `days` against the `days` before (content_page_impact, 00209). Null
@@ -653,9 +875,12 @@ export async function setContentDraftPageType(id: string, pageType: PageType): P
* Mark ready: a draft, or an agent's draft in review, is ready to publish.
* Ansvisor never publishes it; the person does (CE-013 records the URL).
* Returns the status the draft has after, so a draft already ready or
- * published keeps its own.
+ * published keeps its own, and how many of its action's tasks it completed
+ * (CE-022; completeDraftTasks).
*/
-export async function markContentDraftReady(id: string): Promise<DraftStatus> {
+export async function markContentDraftReady(
+ id: string,
+): Promise<{ status: DraftStatus; tasksDone: number }> {
if (!draftId.safeParse(id).success) throw new Error('invalid');
const supabase = await createClient();
const { data, error } = await supabase
@@ -663,16 +888,37 @@ export async function markContentDraftReady(id: string): Promise<DraftStatus> {
.update({ status: 'ready' })
.eq('id', id)
.in('status', ['draft', 'in_review'])
- .select('status')
+ .select('status, brand_id, method, action_id')
.maybeSingle();
if (error) throw new Error(error.message);
if (data) {
await keepVersion(supabase, id, 'ready');
- return draftStatus(data.status);
+ let tasksDone = 0;
+ if (data.action_id) {
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ // The draft is ready either way; a task left open can be ticked in the drawer.
+ try {
+ tasksDone = await completeDraftTasks(
+ supabase,
+ {
+ id,
+ brandId: data.brand_id,
+ actionId: data.action_id,
+ method: data.method === 'create' ? 'create' : 'optimize',
+ },
+ user?.id ?? null,
+ );
+ } catch (err) {
+ console.error("Failed to complete the action's task:", err);
+ }
+ }
+ return { status: draftStatus(data.status), tasksDone };
}
const current = await getContentDraft(id);
if (!current) throw new Error('not_found');
- return current.status;
+ return { status: current.status, tasksDone: 0 };
}
/**
diff --git a/web/src/lib/content/action-drafts.test.ts b/web/src/lib/content/action-drafts.test.ts
new file mode 100644
index 000000000..52651868b
--- /dev/null
+++ b/web/src/lib/content/action-drafts.test.ts
@@ -0,0 +1,178 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import type { SupabaseClient } from '@supabase/supabase-js';
+import {
+ actionPages,
+ completeDraftTasks,
+ draftMethodForTask,
+ findActionDraft,
+ type ActionDraft,
+} from './action-drafts';
+
+/**
+ * An action's writing tasks and their drafts (CE-022): which draft a task is
+ * written in, and Ready completing the task once the work's drafts are done.
+ */
+
+interface Op {
+ table: string;
+ op: 'select' | 'update' | 'insert';
+ value?: unknown;
+ filters: [string, string, unknown][];
+}
+let ops: Op[];
+let rows: Record<string, unknown[]>;
+
+const db = {
+ from: (table: string) => {
+ const op: Op = { table, op: 'select', filters: [] };
+ ops.push(op);
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ eq: (col: string, v: unknown) => (op.filters.push(['eq', col, v]), chain),
+ in: (col: string, v: unknown) => (op.filters.push(['in', col, v]), chain),
+ is: (col: string, v: unknown) => (op.filters.push(['is', col, v]), chain),
+ limit: () => chain,
+ update: (value: unknown) => ((op.op = 'update'), (op.value = value), chain),
+ insert: (value: unknown) => ((op.op = 'insert'), (op.value = value), chain),
+ maybeSingle: async () => ({ data: rows[table]?.[0] ?? null, error: null }),
+ then: (resolve: (r: unknown) => void) =>
+ resolve({ data: op.op === 'select' ? (rows[table] ?? []) : null, error: null }),
+ };
+ return chain;
+ },
+} as unknown as SupabaseClient;
+
+const draft = { id: 'd1', brandId: 'b1', actionId: 'act-1', method: 'optimize' as const };
+
+beforeEach(() => {
+ ops = [];
+ rows = {};
+});
+
+describe('draftMethodForTask', () => {
+ it('writes a new page for the draft task and an existing one for optimize or refresh', () => {
+ expect(draftMethodForTask('create_content_draft')).toBe('create');
+ expect(draftMethodForTask('optimize_content')).toBe('optimize');
+ expect(draftMethodForTask('refresh_content')).toBe('optimize');
+ expect(draftMethodForTask('create_content_brief')).toBeNull();
+ expect(draftMethodForTask(null)).toBeNull();
+ });
+});
+
+describe('actionPages and findActionDraft', () => {
+ const drafts: ActionDraft[] = [
+ { id: 'new', method: 'create', sourceUrl: null, status: 'draft' },
+ { id: 'pricing', method: 'optimize', sourceUrl: 'https://a.example/pricing', status: 'ready' },
+ ];
+
+ it('reads the pages an action names, once each', () => {
+ expect(
+ actionPages({
+ pages: ['https://a.example/pricing', 'https://a.example/pricing', '/relative', 3],
+ }),
+ ).toEqual(['https://a.example/pricing']);
+ expect(actionPages(null)).toEqual([]);
+ });
+
+ it('finds the draft for a page, or the work’s draft without one', () => {
+ expect(findActionDraft(drafts, 'optimize', 'https://a.example/pricing')?.id).toBe('pricing');
+ expect(findActionDraft(drafts, 'optimize', 'https://a.example/other')).toBeNull();
+ expect(findActionDraft(drafts, 'optimize', null)?.id).toBe('pricing');
+ expect(findActionDraft(drafts, 'create', null)?.id).toBe('new');
+ });
+});
+
+describe('completeDraftTasks', () => {
+ it('completes the work’s open tasks, each in the action’s History', async () => {
+ rows.action_tasks = [
+ { id: 't-optimize', status: 'in_progress' },
+ { id: 't-refresh', status: 'skipped' },
+ ];
+ rows.actions = [{ payload: { pages: ['https://a.example/pricing'] } }];
+ await expect(completeDraftTasks(db, draft, 'u1')).resolves.toBe(1);
+
+ expect(ops[0]).toMatchObject({
+ table: 'actions',
+ filters: [
+ ['eq', 'id', 'act-1'],
+ ['is', 'deleted_at', null],
+ ],
+ });
+ expect(ops[1].filters).toContainEqual([
+ 'in',
+ 'task_key',
+ ['optimize_content', 'refresh_content'],
+ ]);
+ expect(ops.slice(2)).toEqual([
+ {
+ table: 'action_tasks',
+ op: 'update',
+ value: expect.objectContaining({ status: 'completed', skip_reason: null }),
+ filters: [
+ ['eq', 'action_id', 'act-1'],
+ ['eq', 'id', 't-optimize'],
+ ],
+ },
+ {
+ table: 'action_events',
+ op: 'insert',
+ value: {
+ action_id: 'act-1',
+ event: 'task_status',
+ data: { taskId: 't-optimize', to: 'completed', draftId: 'd1' },
+ actor_id: 'u1',
+ },
+ filters: [],
+ },
+ {
+ table: 'actions',
+ op: 'update',
+ value: { updated_at: expect.any(String) },
+ filters: [
+ ['eq', 'brand_id', 'b1'],
+ ['eq', 'id', 'act-1'],
+ ],
+ },
+ ]);
+ });
+
+ it('waits until each page the action names has a ready draft', async () => {
+ rows.actions = [{ payload: { pages: ['https://a.example/pricing', 'https://a.example/faq'] } }];
+ rows.content_drafts = [{ source_url: 'https://a.example/pricing' }];
+ rows.action_tasks = [{ id: 't-optimize', status: 'todo' }];
+ await expect(completeDraftTasks(db, draft, 'u1')).resolves.toBe(0);
+ expect(ops[1]).toMatchObject({
+ table: 'content_drafts',
+ filters: [
+ ['eq', 'action_id', 'act-1'],
+ ['eq', 'method', 'optimize'],
+ ['in', 'status', ['ready', 'published']],
+ ],
+ });
+ expect(ops.some((op) => op.op === 'update')).toBe(false);
+
+ ops = [];
+ rows.content_drafts.push({ source_url: 'https://a.example/faq' });
+ await expect(completeDraftTasks(db, draft, 'u1')).resolves.toBe(1);
+ });
+
+ it('completes a new page’s task without reading pages', async () => {
+ rows.actions = [{ payload: { pages: ['https://a.example/pricing'] } }];
+ rows.action_tasks = [{ id: 't-draft', status: 'todo' }];
+ await expect(completeDraftTasks(db, { ...draft, method: 'create' }, null)).resolves.toBe(1);
+ expect(ops.some((op) => op.table === 'content_drafts')).toBe(false);
+ expect(ops[1]).toMatchObject({
+ table: 'action_tasks',
+ filters: [
+ ['eq', 'action_id', 'act-1'],
+ ['in', 'task_key', ['create_content_draft']],
+ ],
+ });
+ });
+
+ it('leaves a deleted action’s tasks as they were', async () => {
+ rows.action_tasks = [{ id: 't-draft', status: 'todo' }];
+ await expect(completeDraftTasks(db, { ...draft, method: 'create' }, 'u1')).resolves.toBe(0);
+ expect(ops.map((op) => op.table)).toEqual(['actions']);
+ });
+});
diff --git a/web/src/lib/content/action-drafts.ts b/web/src/lib/content/action-drafts.ts
new file mode 100644
index 000000000..aa18555c4
--- /dev/null
+++ b/web/src/lib/content/action-drafts.ts
@@ -0,0 +1,152 @@
+/**
+ * The Content Editor and the Action Center, both ways (CE-022, spec §15): an
+ * action's writing task opens a draft linked to the action, and marking that
+ * draft Ready completes the task.
+ *
+ * A draft is linked through content_drafts.action_id (00208). An action can
+ * hold a new page's task and an existing page's, and name several pages: it
+ * gets one draft per kind of work and page (00218).
+ */
+
+import type { SupabaseClient } from '@supabase/supabase-js';
+import type { DraftMethod, DraftStatus } from './drafts';
+
+/** The library tasks a draft is the work of, by the draft's method. */
+export const DRAFT_TASK_KEYS: Record<DraftMethod, readonly string[]> = {
+ create: ['create_content_draft'],
+ optimize: ['optimize_content', 'refresh_content'],
+};
+
+/** The draft a task is written in: a new page, or an existing page's new version. */
+export function draftMethodForTask(taskKey: string | null | undefined): DraftMethod | null {
+ if (!taskKey) return null;
+ if (DRAFT_TASK_KEYS.create.includes(taskKey)) return 'create';
+ if (DRAFT_TASK_KEYS.optimize.includes(taskKey)) return 'optimize';
+ return null;
+}
+
+/** A draft linked to an action, as the action's tasks read it. */
+export interface ActionDraft {
+ id: string;
+ method: DraftMethod;
+ sourceUrl: string | null;
+ status: DraftStatus;
+}
+
+/** The brand pages an action works on (payload.pages), as basket-metrics.js reads them. */
+export function actionPages(payload: Record<string, unknown> | null | undefined): string[] {
+ const pages = payload?.pages;
+ if (!Array.isArray(pages)) return [];
+ return [
+ ...new Set(pages.filter((p): p is string => typeof p === 'string' && /^https?:\/\//i.test(p))),
+ ];
+}
+
+/**
+ * The draft already written for this work: for a page, the one optimizing
+ * it; without one, the action's draft of that method.
+ */
+export function findActionDraft(
+ drafts: readonly ActionDraft[],
+ method: DraftMethod,
+ page: string | null,
+): ActionDraft | null {
+ return (
+ drafts.find(
+ (draft) => draft.method === method && (page === null || draft.sourceUrl === page),
+ ) ?? null
+ );
+}
+
+/** Statuses after which a task is no longer outstanding work. */
+const TASK_DONE = ['completed', 'skipped', 'failed'];
+/** A draft whose writing is done. */
+const DRAFT_DONE: DraftStatus[] = ['ready', 'published'];
+
+/**
+ * Moves an action's tasks to a status for a draft's work, as a change in the
+ * drawer does (updateTaskStatus): each recorded in the action's History, and
+ * the action's Updated stamp bumped. Runs with the caller's client: the
+ * member's for the editor, the service role for the agent API.
+ */
+export async function setDraftTasksStatus(
+ db: SupabaseClient,
+ draft: { id: string; brandId: string; actionId: string },
+ taskIds: readonly string[],
+ status: 'in_progress' | 'completed',
+ actorId: string | null,
+): Promise<void> {
+ if (!taskIds.length) return;
+ const now = new Date().toISOString();
+ for (const taskId of taskIds) {
+ const { error } = await db
+ .from('action_tasks')
+ .update({ status, skip_reason: null, updated_at: now })
+ .eq('action_id', draft.actionId)
+ .eq('id', taskId);
+ if (error) throw new Error(error.message);
+ // Best effort, as in the drawer: a missing trail entry doesn't undo the change.
+ await db.from('action_events').insert({
+ action_id: draft.actionId,
+ event: 'task_status',
+ data: { taskId, to: status, draftId: draft.id },
+ actor_id: actorId,
+ });
+ }
+ await db
+ .from('actions')
+ .update({ updated_at: now })
+ .eq('brand_id', draft.brandId)
+ .eq('id', draft.actionId);
+}
+
+/**
+ * Marking a linked draft Ready completes the action's task for that work.
+ * An action naming several pages has one draft per page: its task is done
+ * once each page has a draft that is ready (or published). A deleted action
+ * (00168) keeps its tasks as they were. Returns how many tasks it completed.
+ */
+export async function completeDraftTasks(
+ db: SupabaseClient,
+ draft: { id: string; brandId: string; actionId: string; method: DraftMethod },
+ actorId: string | null,
+): Promise<number> {
+ const { data: action, error: actionError } = await db
+ .from('actions')
+ .select('payload')
+ .eq('id', draft.actionId)
+ .is('deleted_at', null)
+ .maybeSingle();
+ if (actionError) throw new Error(actionError.message);
+ if (!action) return 0;
+ if (draft.method === 'optimize') {
+ const pages = actionPages(action.payload);
+ if (pages.length > 1) {
+ const { data: done, error: doneError } = await db
+ .from('content_drafts')
+ .select('source_url')
+ .eq('action_id', draft.actionId)
+ .eq('method', 'optimize')
+ .in('status', DRAFT_DONE);
+ if (doneError) throw new Error(doneError.message);
+ const ready = new Set((done ?? []).map((row) => row.source_url));
+ if (pages.some((page) => !ready.has(page))) return 0;
+ }
+ }
+
+ const { data: tasks, error: tasksError } = await db
+ .from('action_tasks')
+ .select('id, status')
+ .eq('action_id', draft.actionId)
+ .in('task_key', [...DRAFT_TASK_KEYS[draft.method]]);
+ if (tasksError) throw new Error(tasksError.message);
+ const todo = (tasks ?? []).filter((task) => !TASK_DONE.includes(task.status));
+ await setDraftTasksStatus(
+ db,
+ draft,
+ todo.map((task) => task.id),
+ 'completed',
+ actorId,
+ );
+ return todo.length;
+}
diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.ts
index d24b513a7..d946f3973 100644
--- a/web/src/lib/content/drafts.ts
+++ b/web/src/lib/content/drafts.ts
@@ -102,6 +102,8 @@ export interface ContentDraft {
author: 'user' | 'agent';
/** What the person changed on the page's rules for this draft (CE-009). */
rules: DraftRules;
+ /** The Action Center action the draft is the work of (CE-022), shown as "from Action AC-214". */
+ action: { id: string; number: number } | null;
updatedAt: string;
}
diff --git a/web/src/lib/mcp/content.test.ts b/web/src/lib/mcp/content.test.ts
index 5b06f9e6f..1bd17e950 100644
--- a/web/src/lib/mcp/content.test.ts
+++ b/web/src/lib/mcp/content.test.ts
@@ -28,6 +28,7 @@ vi.mock('@/lib/supabase/admin', () => ({
select: () => chain,
eq: (col: string, v: unknown) => (db.filters.push([table, col, v]), chain),
in: () => chain,
+ is: (col: string, v: unknown) => (db.filters.push([table, col, v]), chain),
order: () => chain,
limit: () => chain,
insert: (value: unknown) => (db.writes.push({ table, op: 'insert', value }), chain),
@@ -258,8 +259,10 @@ describe('suggestContentChangesFor', () => {
});
describe('setContentDraftReadyFor', () => {
- it('marks a draft ready and keeps the version, once', async () => {
+ it('marks a draft ready, keeps the version and completes its action’s task, once', async () => {
db.rows.content_drafts = draftRow({ status: 'draft' });
+ db.rows.actions = { payload: {} };
+ db.rows.action_tasks = [{ id: 't-optimize', status: 'in_progress' }];
// The update reads back the same row; its status is what the update set.
const result = await setContentDraftReadyFor(auth, 'd1');
expect(db.writes).toContainEqual({
@@ -268,7 +271,17 @@ describe('setContentDraftReadyFor', () => {
value: { status: 'ready' },
});
expect(db.filters).toContainEqual(['content_drafts', 'status', 'draft']);
- expect(result).toEqual({ status: 'draft' });
+ expect(result).toEqual({ status: 'draft', action_tasks_done: 1 });
+ expect(db.writes).toContainEqual({
+ table: 'action_events',
+ op: 'insert',
+ value: {
+ action_id: 'act-1',
+ event: 'task_status',
+ data: { taskId: 't-optimize', to: 'completed', draftId: 'd1' },
+ actor_id: 'user-1',
+ },
+ });
expect(db.rpcCalls).toContainEqual([
'content_draft_snapshot',
{ p_draft_id: 'd1', p_origin: 'ready' },
@@ -276,7 +289,10 @@ describe('setContentDraftReadyFor', () => {
db.writes = [];
db.rows.content_drafts = draftRow({ status: 'published' });
- await expect(setContentDraftReadyFor(auth, 'd1')).resolves.toEqual({ status: 'published' });
+ await expect(setContentDraftReadyFor(auth, 'd1')).resolves.toEqual({
+ status: 'published',
+ action_tasks_done: 0,
+ });
expect(db.writes).toEqual([]);
});
diff --git a/web/src/lib/mcp/content.ts b/web/src/lib/mcp/content.ts
index dc1877b54..9c4c02c67 100644
--- a/web/src/lib/mcp/content.ts
+++ b/web/src/lib/mcp/content.ts
@@ -8,6 +8,7 @@ import {
type DroppedReason,
} from '@/lib/content/agent-suggestions';
import { classifyDomain, extractHostname, normalizeDomain } from '@/lib/citations/classify';
+import { completeDraftTasks } from '@/lib/content/action-drafts';
import { CITED_DAYS, passageKey, quotedPassages } from '@/lib/content/cited-passages';
import { contentEditorPath, isPageType, type PageType } from '@/lib/content/drafts';
import { IMPACT_PERIODS } from '@/lib/content/impact';
@@ -442,18 +443,20 @@ export async function suggestContentChangesFor(
/**
* Ready (spec §6): a draft is ready to publish, and History keeps it as a
- * version. An agent's draft in review waits for a person to mark it ready in
- * the editor ('in_review'): the key that wrote it can't approve it. A draft
- * already ready or published keeps its status. Null outside the organization.
+ * version; a draft linked to an action completes its task there, as Mark
+ * ready does (CE-022). An agent's draft in review waits for a person to mark
+ * it ready in the editor ('in_review'): the key that wrote it can't approve
+ * it. A draft already ready or published keeps its status. Null outside the
+ * organization.
*/
export async function setContentDraftReadyFor(
auth: McpAuthContext,
draftId: string,
-): Promise<{ status: string } | 'in_review' | null> {
+): Promise<{ status: string; action_tasks_done: number } | 'in_review' | null> {
const draft = await draftFor(auth, draftId);
if (!draft) return null;
if (draft.status === 'in_review') return 'in_review';
- if (draft.status !== 'draft') return { status: draft.status };
+ if (draft.status !== 'draft') return { status: draft.status, action_tasks_done: 0 };
const { data, error } = await supabaseAdmin
.from('content_drafts')
.update({ status: 'ready' })
@@ -469,5 +472,24 @@ export async function setContentDraftReadyFor(
});
if (versionError) console.error('Failed to keep the ready version:', versionError.message);
}
- return { status: data?.status ?? draft.status };
+ let done = 0;
+ if (data && draft.action_id) {
+ // The draft is ready either way; a task left open can be ticked in the drawer.
+ try {
+ done = await completeDraftTasks(
+ supabaseAdmin,
+ {
+ id: draft.id,
+ brandId: draft.brand_id,
+ actionId: draft.action_id,
+ method: draft.method === 'create' ? 'create' : 'optimize',
+ },
+ // The API key's user, as update_task_status records it.
+ auth.userId,
+ );
+ } catch (err) {
+ console.error("Failed to complete the action's task:", err);
+ }
+ }
+ return { status: data?.status ?? draft.status, action_tasks_done: done };
}
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 703a94bdb..d01d76a3c 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -1516,7 +1516,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'set_content_draft_ready',
{
description:
- "Mark a draft ready to publish, as the editor's Mark ready does: from draft only — an agent's draft in review waits for a person to mark it ready in the editor. History keeps the page as a version. Ansvisor never publishes — a person does. Only on explicit user intent.",
+ "Mark a draft ready to publish, as the editor's Mark ready does: from draft only — an agent's draft in review waits for a person to mark it ready in the editor. History keeps the page as a version, and a draft linked to an Action Center action completes the action's writing task (action_tasks_done). Ansvisor never publishes — a person does. Only on explicit user intent.",
inputSchema: {
draft_id: relaxedUuid.describe('Draft UUID.'),
},
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 2ca10a504..9d5abd632 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -941,6 +941,13 @@ export type Database = {
referencedRelation: "profiles"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "content_drafts_action_id_fkey"
+ columns: ["action_id"]
+ isOneToOne: false
+ referencedRelation: "actions"
+ referencedColumns: ["id"]
+ },
]
}
content_draft_sources: {