Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): choose who does the page in Start, and send it to the team (#1289)
Cihan5672e8569e57
diff --git a/server/src/lib/action-center/from-content-draft.js b/server/src/lib/action-center/from-content-draft.jsnew file mode 100644index 000000000..7b9363c95--- /dev/null+++ b/server/src/lib/action-center/from-content-draft.js@@ -0,0 +1,168 @@+/**+ * "Team" in the Content Editor's Start (CE-015, spec §5, §15): a draft sent+ * to the Action Center as an action, for someone on the team to write.+ *+ * The draft is already started (its page type, prompts, the page it+ * optimizes, any text brought in); the action carries the work: the same+ * library tasks a content opportunity's page gets (from-opportunity.js),+ * a new page's or an existing page's. It is measured afterwards on the+ * draft's prompts and page like any person-sent action (basket-metrics.js),+ * and the draft records the action (content_drafts.action_id, 00208).+ */++import supabaseAdmin from '../../config/supabase.js';+import { assetTasks } from './from-opportunity.js';+import { priorityOnCreate } from './priority-data.js';+import { resolveBrandSources } from './sources.js';+import { planTasks } from './tasks/plan.js';++export const CONTENT_DRAFT_ACTION_KIND = 'content_draft';++const ACTIVE = ['new', 'in_progress', 'on_hold'];+const KPI_KEYS = ['ai_visibility', 'citations', 'mentions'];+/** Prompts the action lists by name; it is measured on all of them. */+const MAX_TARGETS = 50;++function httpError(message, status) {+ const err = new Error(message);+ err.status = status;+ return err;+}++/** One action per draft: sending it again finds the one still open. */+export function contentDraftDedupKey(draftId) {+ return `${CONTENT_DRAFT_ACTION_KIND}:${draftId}`;+}++/** The work a draft needs: a new page's, or an existing page's. */+export function contentDraftTasks(method) {+ return assetTasks({ channel: 'owned', decision: method === 'create' ? 'create' : 'optimize' });+}++/**+ * Creates the action, or returns the open one if the draft was already sent.+ *+ * @param {string} brandId - checked against the caller's org by the route+ * @param {{ draftId: string, userId: string }} opts+ * @returns {Promise<{ actionId: string, actionNo: number, created: boolean }>}+ */+export async function sendContentDraftToActionCenter(brandId, { draftId, userId }) {+ const { data: draft, error: draftErr } = await supabaseAdmin+ .from('content_drafts')+ .select('id, brand_id, title, method, page_type, prompt_ids, source_url, opportunity_id')+ .eq('id', draftId)+ .eq('brand_id', brandId)+ .maybeSingle();+ if (draftErr) throw new Error(draftErr.message);+ if (!draft) throw httpError('Draft not found', 404);++ const dedupKey = contentDraftDedupKey(draft.id);+ const openAction = async () => {+ const { data } = await supabaseAdmin+ .from('actions')+ .select('id, action_no')+ .eq('brand_id', brandId)+ .eq('dedup_key', dedupKey)+ .in('status', ACTIVE)+ .maybeSingle();+ return data;+ };+ const open = await openAction();+ if (open) return { actionId: open.id, actionNo: Number(open.action_no), created: false };++ const promptIds = [...new Set(draft.prompt_ids ?? [])];+ const { data: prompts, error: promptsErr } = promptIds.length+ ? await supabaseAdmin+ .from('prompts')+ .select('id, text')+ .in('id', promptIds.slice(0, MAX_TARGETS))+ : { data: [], error: null };+ if (promptsErr) throw new Error(promptsErr.message);++ const payload = {+ source: CONTENT_DRAFT_ACTION_KIND,+ draftId: draft.id,+ opportunityId: draft.opportunity_id ?? null,+ title: draft.title || null,+ method: draft.method,+ pageType: draft.page_type ?? null,+ // Measured on the draft's page once published (basket-metrics.js); a+ // new page has its address only then.+ pages: draft.source_url ? [draft.source_url] : [],+ promptIds,+ targetEntity: 'prompts',+ targetCount: promptIds.length,+ targets: (prompts ?? []).map((p) => ({ id: p.id, label: p.text })),+ contentExists: draft.method === 'optimize',+ };++ const category = 'growth';+ const impact = 'medium';+ const { data: action, error } = await supabaseAdmin+ .from('actions')+ .insert({+ brand_id: brandId,+ category,+ kind: CONTENT_DRAFT_ACTION_KIND,+ definition_version: 1,+ impact,+ payload,+ kpi_keys: KPI_KEYS,+ baseline: {},+ dedup_key: dedupKey,+ ...(await priorityOnCreate({ kind: CONTENT_DRAFT_ACTION_KIND, category, impact, payload })),+ })+ .select('id, action_no')+ .single();+ if (error) {+ // Two sends at once: the other one opened it (the open-action dedup index, 00084).+ if (error.code === '23505') {+ const winner = await openAction();+ if (winner) {+ return { actionId: winner.id, actionNo: Number(winner.action_no), created: false };+ }+ }+ throw new Error(error.message);+ }++ const sources = await resolveBrandSources(brandId);+ const plan = planTasks(+ { id: CONTENT_DRAFT_ACTION_KIND, tasks: contentDraftTasks(draft.method) },+ { sources, payload },+ );+ const { error: tasksErr } = await supabaseAdmin.from('action_tasks').insert(+ plan.map((item) => ({+ action_id: action.id,+ position: item.position,+ task_key: item.taskKey,+ task_version: item.version,+ mode: item.mode,+ permission: item.permission,+ depends_on: item.dependsOn,+ title_params: item.titleParams,+ status: 'todo',+ })),+ );+ if (tasksErr) throw new Error(tasksErr.message);++ await supabaseAdmin.from('action_events').insert({+ action_id: action.id,+ event: 'created',+ actor_id: userId,+ data: {+ source: CONTENT_DRAFT_ACTION_KIND,+ draftId: draft.id,+ method: draft.method,+ taskCount: plan.length,+ },+ });++ // The draft remembers its action (00208), for the editor and the Library.+ const { error: linkErr } = await supabaseAdmin+ .from('content_drafts')+ .update({ action_id: action.id })+ .eq('id', draft.id);+ if (linkErr) throw new Error(linkErr.message);++ return { actionId: action.id, actionNo: Number(action.action_no), created: true };+}diff --git a/server/src/lib/action-center/from-content-draft.test.js b/server/src/lib/action-center/from-content-draft.test.jsnew file mode 100644index 000000000..e684158e2--- /dev/null+++ b/server/src/lib/action-center/from-content-draft.test.js@@ -0,0 +1,170 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * "Team" in the Content Editor's Start (CE-015): a draft sent to the Action+ * Center as one action, with a new page's or an existing page's tasks, linked+ * back to the draft, and found again when sent twice.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';+const DRAFT = '44444444-4444-4444-4444-444444444444';++let draftRow;+let openRow;+let inserted;+let updated;++function table(name) {+ const state = { name, op: 'select', filters: {} };+ const result = () => {+ if (name === 'content_drafts') {+ if (state.op === 'update') return { data: null, error: null };+ return { data: draftRow, error: null };+ }+ if (name === 'actions') {+ if (state.op === 'insert') return { data: { id: 'a1', action_no: 214 }, error: null };+ return { data: openRow, error: null };+ }+ if (name === 'prompts') {+ return {+ data: (state.filters.id ?? []).map((id) => ({ id, text: `prompt ${id}` })),+ error: null,+ };+ }+ return { data: null, error: null };+ };+ const chain = {+ select: () => chain,+ eq: (col, val) => ((state.filters[col] = val), chain),+ in: (col, val) => ((state.filters[col] = val), chain),+ insert: (row) => {+ state.op = 'insert';+ inserted.push({ table: name, row });+ return chain;+ },+ update: (row) => {+ state.op = 'update';+ updated.push({ table: name, row, filters: state.filters });+ return chain;+ },+ maybeSingle: async () => result(),+ single: async () => result(),+ then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),+ };+ return chain;+}++vi.mock('../../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));+vi.mock('./priority-data.js', () => ({ priorityOnCreate: async () => ({ priority_score: 50 }) }));+vi.mock('./sources.js', () => ({ resolveBrandSources: async () => ({}) }));++const { contentDraftTasks, sendContentDraftToActionCenter } =+ await import('./from-content-draft.js');++beforeEach(() => {+ draftRow = {+ id: DRAFT,+ brand_id: BRAND,+ title: 'CRM for real estate teams',+ method: 'create',+ page_type: 'solution_page',+ prompt_ids: ['p1', 'p2', 'p1'],+ source_url: null,+ opportunity_id: null,+ };+ openRow = null;+ inserted = [];+ updated = [];+});++const insertedInto = (name) => inserted.filter((i) => i.table === name).map((i) => i.row);++describe('contentDraftTasks', () => {+ it('plans a new page’s work, or an existing page’s, from the library', () => {+ expect(contentDraftTasks('create')).toEqual([+ 'create_content_brief',+ 'create_content_draft',+ 'add_internal_links',+ 'publish_content',+ 'validate_ai_visibility',+ ]);+ expect(contentDraftTasks('optimize')).toEqual([+ 'optimize_content',+ 'add_internal_links',+ 'publish_content',+ 'validate_ai_visibility',+ ]);+ });+});++describe('sendContentDraftToActionCenter', () => {+ it('opens one action for the draft, with its prompts and tasks, and links the draft to it', async () => {+ await expect(+ sendContentDraftToActionCenter(BRAND, { draftId: DRAFT, userId: 'u1' }),+ ).resolves.toEqual({ actionId: 'a1', actionNo: 214, created: true });+ const [action] = insertedInto('actions');+ expect(action).toMatchObject({+ brand_id: BRAND,+ kind: 'content_draft',+ category: 'growth',+ impact: 'medium',+ dedup_key: `content_draft:${DRAFT}`,+ kpi_keys: ['ai_visibility', 'citations', 'mentions'],+ priority_score: 50,+ payload: {+ source: 'content_draft',+ draftId: DRAFT,+ title: 'CRM for real estate teams',+ method: 'create',+ pageType: 'solution_page',+ pages: [],+ promptIds: ['p1', 'p2'],+ targetEntity: 'prompts',+ targetCount: 2,+ targets: [+ { id: 'p1', label: 'prompt p1' },+ { id: 'p2', label: 'prompt p2' },+ ],+ contentExists: false,+ },+ });+ const tasks = insertedInto('action_tasks')[0];+ expect(tasks.map((t) => t.task_key)).toEqual(contentDraftTasks('create'));+ expect(tasks.every((t) => t.status === 'todo')).toBe(true);+ expect(insertedInto('action_events')[0]).toMatchObject({+ action_id: 'a1',+ event: 'created',+ actor_id: 'u1',+ data: { source: 'content_draft', draftId: DRAFT, method: 'create' },+ });+ expect(updated).toEqual([+ { table: 'content_drafts', row: { action_id: 'a1' }, filters: { id: DRAFT } },+ ]);+ });++ it('measures an optimize draft on the page it optimizes', async () => {+ draftRow = { ...draftRow, method: 'optimize', source_url: 'https://acme.example/pricing' };+ await sendContentDraftToActionCenter(BRAND, { draftId: DRAFT, userId: 'u1' });+ expect(insertedInto('actions')[0].payload).toMatchObject({+ pages: ['https://acme.example/pricing'],+ contentExists: true,+ });+ expect(insertedInto('action_tasks')[0][0].task_key).toBe('optimize_content');+ });++ it('returns the action still open when the draft is sent again', async () => {+ openRow = { id: 'a0', action_no: 200 };+ await expect(+ sendContentDraftToActionCenter(BRAND, { draftId: DRAFT, userId: 'u1' }),+ ).resolves.toEqual({ actionId: 'a0', actionNo: 200, created: false });+ expect(inserted).toEqual([]);+ });++ it('says so for a draft that isn’t the brand’s', async () => {+ draftRow = null;+ await expect(+ sendContentDraftToActionCenter(BRAND, { draftId: DRAFT, userId: 'u1' }),+ ).rejects.toMatchObject({ status: 404 });+ expect(inserted).toEqual([]);+ });+});diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.jsindex 23ec66d0c..be337bdb6 100644--- a/server/src/lib/action-center/priority.js+++ b/server/src/lib/action-center/priority.js@@ -351,7 +351,9 @@ function sentByHand(action) {subject: { entity: 'platforms', count: gaps.length },};}- if (action.kind === 'content_opportunity') {+ // A draft sent from the Content Editor (CE-015) is the same work as an+ // opportunity's page: content for its prompts.+ if (action.kind === 'content_opportunity' || action.kind === 'content_draft') {return {change: 'gap',severity: 0.45,diff --git a/server/src/lib/action-center/priority.test.js b/server/src/lib/action-center/priority.test.jsindex 91ee77d35..449659384 100644--- a/server/src/lib/action-center/priority.test.js+++ b/server/src/lib/action-center/priority.test.js@@ -304,6 +304,22 @@ describe('scorePriority', () => {);expect(content.reason.subject).toEqual({ entity: 'prompts', count: 4 });expect(content.score).toBeGreaterThan(0);+ // A draft sent from the Content Editor's Start (CE-015) is the same work.+ const draft = scorePriority(+ {+ action: action({+ kind: 'content_draft',+ category: 'growth',+ impact: 'medium',+ created_at: daysAgo(0),+ payload: { promptIds: ['p1'], targetEntity: 'prompts', targetCount: 3 },+ }),+ prompts: demand([['p1', 300, 'how-to']]),+ },+ NOW,+ );+ expect(draft.reason).toMatchObject({ change: 'gap', subject: { entity: 'prompts', count: 3 } });+ expect(draft.score).toBeGreaterThan(0);});it('scores pages sent from AI Traffic on their list, sessions and value (AT-006)', () => {diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex 942857b43..31dfdfcdd 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -240,9 +240,11 @@ export async function validateAction(action, { now = new Date() } = {}) {// An Improve action (PROMPT-004) likewise, on its one prompt, and a topic// gap (VIS-010) or opportunity (VIS-011) sent from Insights on the topic's// prompts, answers sent from Mentions (MS-08) on their prompts, and pages- // sent from AI Traffic (AT-006) on those pages.+ // sent from AI Traffic (AT-006) on those pages. A draft sent from the+ // Content Editor (CE-015) on its prompts and its page.if (action.kind === 'content_opportunity' ||+ action.kind === 'content_draft' ||action.kind === 'prompt_improve' ||action.kind === 'topic_competitor_gap' ||action.kind === 'topic_opportunity' ||diff --git a/server/src/lib/action-center/validate.test.js b/server/src/lib/action-center/validate.test.jsindex ef131be92..2addc1996 100644--- a/server/src/lib/action-center/validate.test.js+++ b/server/src/lib/action-center/validate.test.js@@ -290,6 +290,27 @@ describe('validateAction', () => {expect(patch.validation.scope).toEqual({ kind: 'basket', prompts: 0, pages: 2 });});+ it('measures a draft sent from the Content Editor on its prompts and page (CE-015)', async () => {+ const writes = mockWrites();+ rpc.mockResolvedValue({ data: {}, error: null });++ await validateAction(+ action({+ kind: 'content_draft',+ kpi_keys: ['ai_visibility', 'citations', 'mentions'],+ payload: {+ promptIds: ['p1', 'p2', 'p3'],+ pages: ['https://acme.example/pricing'],+ },+ }),+ { now: NOW },+ );++ expect(rpc).toHaveBeenCalledWith('opportunity_basket_metrics', expect.anything());+ const patch = writes.updated.find((w) => w.table === 'actions').patch;+ expect(patch.validation.scope).toEqual({ kind: 'basket', prompts: 3, pages: 1 });+ });+it('records the verdict on the action trail', async () => {const writes = mockWrites();rpc.mockResolvedValue({ data: { total_citations: 10 }, error: null });diff --git a/server/src/routes/action-center-content-drafts.test.js b/server/src/routes/action-center-content-drafts.test.jsnew file mode 100644index 000000000..eb73adda1--- /dev/null+++ b/server/src/routes/action-center-content-drafts.test.js@@ -0,0 +1,120 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for "Team" in the Content Editor's Start (CE-015):+ * POST /api/action-center/content-drafts. The action itself is tested in+ * from-content-draft.test.js; here, what the route lets through: ids in the+ * format seeded data uses, and a caller from the brand's organization.+ */++const assertBrandAccess = vi.fn();+const sendContentDraftToActionCenter = vi.fn();++let server;+let baseUrl;++async function startApp() {+ vi.resetModules();+ vi.doMock('../config/supabase.js', () => ({ default: {} }));+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess }));+ vi.doMock('../lib/action-center/priority-data.js', () => ({ rescoreActionsForSignal: vi.fn() }));+ vi.doMock('../lib/plan-guard.js', () => ({ PlanLimitError: class extends Error {} }));+ vi.doMock('../lib/action-center/task-writer/index.js', () => ({+ TaskWriterError: class extends Error {},+ isTaskWriterEnabled: () => false,+ writeTasksForAction: vi.fn(),+ }));+ vi.doMock('../lib/action-center/task-send.js', () => ({+ TaskSendError: class extends Error {},+ loadTask: vi.fn(),+ sendTaskToContent: vi.fn(),+ sendTaskToWebhook: vi.fn(),+ }));+ vi.doMock('../lib/action-center/from-traffic-pages.js', () => ({+ MAX_TRAFFIC_PAGES: 50,+ TRAFFIC_PAGE_REASONS: ['cited_not_clicked', 'no_ai_traffic'],+ sendTrafficPagesToActionCenter: vi.fn(),+ }));+ vi.doMock('../lib/action-center/from-content-draft.js', () => ({+ sendContentDraftToActionCenter,+ }));++ const { default: router } = await import('./action-center.js');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/action-center', router);++ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/action-center`;+}++// Seeded ids aren't RFC 4122 versions; the route must still take them.+const BRAND = '33333333-3333-3333-3333-333333333333';+const DRAFT = '44444444-4444-4444-4444-444444444444';++const post = (body) =>+ fetch(`${baseUrl}/content-drafts`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ assertBrandAccess.mockReset().mockResolvedValue({});+ sendContentDraftToActionCenter.mockReset();+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /api/action-center/content-drafts', () => {+ it('sends the draft for a member and says whether it was created', async () => {+ sendContentDraftToActionCenter.mockResolvedValue({+ actionId: 'a1',+ actionNo: 214,+ created: true,+ });+ const res = await post({ brandId: BRAND, draftId: DRAFT });+ expect(res.status).toBe(201);+ expect(await res.json()).toEqual({ actionId: 'a1', actionNo: 214, created: true });+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');+ expect(sendContentDraftToActionCenter).toHaveBeenCalledWith(BRAND, {+ draftId: DRAFT,+ userId: 'u1',+ });++ sendContentDraftToActionCenter.mockResolvedValue({+ actionId: 'a1',+ actionNo: 214,+ created: false,+ });+ expect((await post({ brandId: BRAND, draftId: DRAFT })).status).toBe(200);+ });++ it('rejects a body without ids, and a caller outside the brand', async () => {+ expect((await post({ brandId: BRAND })).status).toBe(400);+ expect((await post({ brandId: 'nope', draftId: DRAFT })).status).toBe(400);+ expect(sendContentDraftToActionCenter).not.toHaveBeenCalled();++ assertBrandAccess.mockRejectedValue(Object.assign(new Error('Unauthorized'), { status: 403 }));+ expect((await post({ brandId: BRAND, draftId: DRAFT })).status).toBe(403);+ expect(sendContentDraftToActionCenter).not.toHaveBeenCalled();+ });++ it('passes on a draft the brand doesn’t have', async () => {+ sendContentDraftToActionCenter.mockRejectedValue(+ Object.assign(new Error('Draft not found'), { status: 404 }),+ );+ expect((await post({ brandId: BRAND, draftId: DRAFT })).status).toBe(404);+ });+});diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.jsindex a62f0f8ab..52ea45942 100644--- a/server/src/routes/action-center.js+++ b/server/src/routes/action-center.js@@ -20,6 +20,7 @@ import {TRAFFIC_PAGE_REASONS,sendTrafficPagesToActionCenter,} from '../lib/action-center/from-traffic-pages.js';+import { sendContentDraftToActionCenter } from '../lib/action-center/from-content-draft.js';const router = Router();@@ -269,4 +270,41 @@ router.post('/pages', async (req, res) => {}});+const contentDraftSchema = z.object({+ // guid, not uuid: seeded ids aren't RFC 4122 versions.+ brandId: z.guid(),+ draftId: z.guid(),+});++/**+ * POST /api/action-center/content-drafts+ * Body: { brandId, draftId }+ *+ * "Team" in the Content Editor's Start (CE-015): the draft sent as an action+ * for someone on the team to write. Sending it again returns the action+ * already open.+ */+router.post('/content-drafts', async (req, res) => {+ try {+ const parsed = contentDraftSchema.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });+ }+ const { brandId, draftId } = parsed.data;+ await assertBrandAccess(brandId, req.user.id);+ const result = await sendContentDraftToActionCenter(brandId, {+ draftId,+ userId: req.user.id,+ });+ return res.status(result.created ? 201 : 200).json(result);+ } catch (error) {+ const status = error.status || 500;+ req.log.error({ err: error }, 'content draft action error');+ return res.status(status).json({+ error: 'Failed to send to the Action Center',+ details: error.message,+ });+ }+});+export default router;diff --git a/supabase/migrations/00208_content_draft_action.sql b/supabase/migrations/00208_content_draft_action.sqlnew file mode 100644index 000000000..f6cc7c0c0--- /dev/null+++ b/supabase/migrations/00208_content_draft_action.sql@@ -0,0 +1,57 @@+-- ============================================================================+-- 00208: a draft sent to the Action Center (Content Editor, CE-015)+-- ============================================================================+-- Start asks who does the page (Content Editor spec v2 §5): Me opens the+-- editor; Team sends it to the Action Center as an action (§15), for someone+-- on the team to write. The draft keeps the action it was sent as:+--+-- * content_drafts.action_id: the action, set by the server when it+-- creates it (from-content-draft.js). Like the draft's author and+-- scores, it is the server's to write: guard_content_draft_server_columns+-- (00204) is redefined to keep members from setting or changing it, so a+-- draft can't claim another action.++alter table public.content_drafts+ add column if not exists action_id uuid references public.actions(id) on delete set null;++comment on column public.content_drafts.action_id is+ 'Content Editor (CE-015): the Action Center action the draft was sent as (Start › Team). Server-set.';++create index if not exists content_drafts_action_idx+ on public.content_drafts (action_id)+ where action_id is not null;++create or replace function public.guard_content_draft_server_columns()+returns trigger+language plpgsql+set search_path = ''+as $$+begin+ -- A role that bypasses RLS is server-side (service role, migrations).+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then+ return new;+ end if;++ if tg_op = 'INSERT' then+ if new.score_before is not null or new.score_after is not null then+ raise exception 'content draft scores are set server-side'+ using errcode = '42501';+ end if;+ if new.action_id is not null then+ raise exception 'content draft action is set server-side'+ using errcode = '42501';+ end if;+ elsif new.brand_id is distinct from old.brand_id+ or new.author is distinct from old.author+ or new.created_by is distinct from old.created_by+ or new.created_at is distinct from old.created_at+ or new.score_before is distinct from old.score_before+ or new.score_after is distinct from old.score_after+ or new.action_id is distinct from old.action_id+ then+ raise exception 'content draft column is managed server-side'+ using errcode = '42501';+ end if;+ return new;+end;+$$;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 2efd18d36..54afd50ee 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -29070,3 +29070,64 @@ grant execute on function public.content_page_overlap(uuid, uuid[], timestamptz)comment on function public.content_page_overlap(uuid, uuid[], timestamptz) is'Content Editor (CE-015): the brand''s own pages cited for these prompts since p_since, with prompts in common, citations and Google position, for Start''s overlap check. Security definer with an organization check.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00208_content_draft_action.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00208: a draft sent to the Action Center (Content Editor, CE-015)+-- ============================================================================+-- Start asks who does the page (Content Editor spec v2 §5): Me opens the+-- editor; Team sends it to the Action Center as an action (§15), for someone+-- on the team to write. The draft keeps the action it was sent as:+--+-- * content_drafts.action_id: the action, set by the server when it+-- creates it (from-content-draft.js). Like the draft's author and+-- scores, it is the server's to write: guard_content_draft_server_columns+-- (00204) is redefined to keep members from setting or changing it, so a+-- draft can't claim another action.++alter table public.content_drafts+ add column if not exists action_id uuid references public.actions(id) on delete set null;++comment on column public.content_drafts.action_id is+ 'Content Editor (CE-015): the Action Center action the draft was sent as (Start › Team). Server-set.';++create index if not exists content_drafts_action_idx+ on public.content_drafts (action_id)+ where action_id is not null;++create or replace function public.guard_content_draft_server_columns()+returns trigger+language plpgsql+set search_path = ''+as $$+begin+ -- A role that bypasses RLS is server-side (service role, migrations).+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then+ return new;+ end if;++ if tg_op = 'INSERT' then+ if new.score_before is not null or new.score_after is not null then+ raise exception 'content draft scores are set server-side'+ using errcode = '42501';+ end if;+ if new.action_id is not null then+ raise exception 'content draft action is set server-side'+ using errcode = '42501';+ end if;+ elsif new.brand_id is distinct from old.brand_id+ or new.author is distinct from old.author+ or new.created_by is distinct from old.created_by+ or new.created_at is distinct from old.created_at+ or new.score_before is distinct from old.score_before+ or new.score_after is distinct from old.score_after+ or new.action_id is distinct from old.action_id+ then+ raise exception 'content draft column is managed server-side'+ using errcode = '42501';+ end if;+ return new;+end;+$$;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 34b67d28f..b8262639d 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1366,6 +1366,16 @@"demandValue": "{count, plural, one {# prompt} other {# prompts}} · ~{volume}/mo","volume": "~{volume}/mo"},+ "contentDraft": {+ "source": "Source",+ "sourceValue": "Content Editor",+ "openDraft": "Open draft",+ "pageType": "Page type",+ "page": "Page",+ "newPage": "A new page",+ "prompts": "Prompts it should answer",+ "promptsValue": "{count, plural, one {# prompt} other {# prompts}}"+ },"mentionReview": {"source": "Source","sourceValue": "Mentions & Sentiment › Mentions",@@ -2104,6 +2114,14 @@"citedDescription": "Sent from AI Traffic Analytics: AI answers cited {count, plural, one {this page} other {these pages}} {citations, plural, one {# time} other {# times}} in the range, and none sent a visit.","noAiDescription": "Sent from AI Traffic Analytics: {count, plural, one {a page} other {# pages}} with visitors or in your sitemap that got no AI visit in the range.","goal": "Earn AI-referred visits to these pages."+ },+ "content_draft": {+ "title": "Write a page for {targets}",+ "titleGeneric": "Write a page",+ "createTitle": "Write: {title}",+ "optimizeTitle": "Optimize: {title}",+ "description": "Sent from the Content Editor: a draft for someone on the team to write, with its page type and the prompts it should answer.",+ "goal": "Publish the page and get the brand into AI answers for these prompts."}},"actionTasks": {@@ -3191,7 +3209,29 @@"detectedPage": "Picked from the page.","openEditor": "Open editor","pageUnread": "Couldn't read {page}: the draft starts with its title.",- "failed": "Couldn't start the draft. Try again."+ "failed": "Couldn't start the draft. Try again.",+ "sendToTeam": "Send to Action Center",+ "sent": "Sent to the Action Center",+ "sentDescription": "Action #{number}: the draft waits in the Library for whoever writes it.",+ "openAction": "Open",+ "sendFailed": "The draft is in the Library, but it couldn't be sent to the Action Center.",+ "openDraft": "Open draft"+ },+ "who": {+ "label": "Who does it",+ "me": {+ "title": "Me",+ "hint": "Open the editor"+ },+ "agent": {+ "title": "Agent",+ "hint": "Drafts, I review",+ "soon": "Comes with the Content Agent"+ },+ "team": {+ "title": "Team",+ "hint": "Send to Action Center"+ }},"overlap": {"label": "Overlap check",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsxindex 7b7205448..850fff4c8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx@@ -98,6 +98,7 @@ export default function ContentLibraryPage() {onOpenChange={setStarting}brandId={activeBrandId}siteType={siteTypeOf(activeBrand ?? {})}+ onSent={() => setAttempt((n) => n + 1)}/><Tabs value={tab} onValueChange={(v) => changeTab(v as LibraryTab)}>diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex feff0bf73..d0f3a9956 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -72,6 +72,7 @@ import { TopicGapContext } from './topic-gap-context';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 { hasActiveWebhook, sendActionTask } from '@/lib/actions/action-task-send';import { RegenerateTasks, taskWriterEnabled } from './regenerate-tasks';@@ -580,6 +581,11 @@ export function ActionDrawer({<Separator /><TrafficPagesContext payload={action.payload ?? {}} /></>+ ) : action.kind === 'content_draft' ? (+ <>+ <Separator />+ <ContentDraftContext payload={action.payload ?? {}} />+ </>) : opportunityId ? (<><Separator />diff --git a/web/src/components/action-center/content-draft-context.test.tsx b/web/src/components/action-center/content-draft-context.test.tsxnew file mode 100644index 000000000..f9dd860eb--- /dev/null+++ b/web/src/components/action-center/content-draft-context.test.tsx@@ -0,0 +1,66 @@+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 { ContentDraftContext } from './content-draft-context';++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+}));++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++async function render(payload: Record<string, unknown>) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <ContentDraftContext payload={payload} />+ </NextIntlClientProvider>,+ );+ });+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('ContentDraftContext', () => {+ it('opens the draft, and names its page type, page and prompts (CE-015)', async () => {+ await render({+ draftId: 'd9',+ pageType: 'pricing',+ pages: ['https://northwind.example/pricing/'],+ targetCount: 4,+ });+ expect(container.querySelector('a')!.getAttribute('href')).toBe('/dashboard/content/editor/d9');+ expect(container.textContent).toContain('Content Editor');+ expect(container.textContent).toContain('Pricing');+ expect(container.textContent).toContain('/pricing');+ expect(container.textContent).toContain('4 prompts');+ });++ it('says a draft for a new page is one', async () => {+ await render({ draftId: 'd9', pages: [], targetCount: 0 });+ expect(container.textContent).toContain('A new page');+ expect(container.textContent).not.toContain('Prompts it should answer');+ });+});diff --git a/web/src/components/action-center/content-draft-context.tsx b/web/src/components/action-center/content-draft-context.tsxnew file mode 100644index 000000000..378e3abd6--- /dev/null+++ b/web/src/components/action-center/content-draft-context.tsx@@ -0,0 +1,60 @@+'use client';++import { useTranslations } from 'next-intl';+import { ExternalLink } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { contentEditorPath, isPageType } from '@/lib/content/drafts';+import { pagePath } from '@/lib/content/overlap';++/**+ * What a draft sent from the Content Editor's Start carries (CE-015): the+ * draft to open, its page type, the page it optimizes (or a new page), and+ * how many prompts it should answer.+ */+export function ContentDraftContext({ payload }: { payload: Record<string, unknown> }) {+ const t = useTranslations('actionCenter.actionsPage.drawer.contentDraft');+ const tTypes = useTranslations('contentEditor.pageTypes');+ const draftId = typeof payload.draftId === 'string' ? payload.draftId : null;+ const pageType = typeof payload.pageType === 'string' ? payload.pageType : null;+ const page =+ Array.isArray(payload.pages) && typeof payload.pages[0] === 'string' ? payload.pages[0] : null;+ const prompts = typeof payload.targetCount === 'number' ? payload.targetCount : 0;++ return (+ <section className="space-y-3">+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('source')}</p>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <span>{t('sourceValue')}</span>+ {draftId && (+ <Link+ href={contentEditorPath(draftId)}+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"+ >+ {t('openDraft')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ )}+ </div>+ </div>+ {isPageType(pageType) && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('pageType')}</p>+ <p className="mt-1">{tTypes(pageType)}</p>+ </div>+ )}+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('page')}</p>+ <p className="mt-1 truncate" title={page ?? undefined}>+ {page ? pagePath(page) : t('newPage')}+ </p>+ </div>+ {prompts > 0 && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('prompts')}</p>+ <p className="mt-1 tabular-nums">{t('promptsValue', { count: prompts })}</p>+ </div>+ )}+ </section>+ );+}diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsxindex a0c64568c..e298a8810 100644--- a/web/src/components/content/new-content-dialog.test.tsx+++ b/web/src/components/content/new-content-dialog.test.tsx@@ -10,13 +10,16 @@ const getContentStartOptions = vi.fn();const createContentDraft = vi.fn();const getContentOverlap = vi.fn();const importContentPage = vi.fn();+const sendContentDraftToActionCenter = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({+ sendContentDraftToActionCenter: (...args: unknown[]) => sendContentDraftToActionCenter(...args),importContentPage: (...args: unknown[]) => importContentPage(...args),getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),createContentDraft: (...args: unknown[]) => createContentDraft(...args),getContentOverlap: (...args: unknown[]) => getContentOverlap(...args),}));const push = vi.fn();+const onSent = vi.fn();vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push }) }));const toast = vi.hoisted(() =>Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn() }),@@ -63,7 +66,13 @@ async function render(siteType: SiteType = 'b2b') {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages}>- <NewContentDialog open onOpenChange={vi.fn()} brandId="b1" siteType={siteType} />+ <NewContentDialog+ open+ onOpenChange={vi.fn()}+ brandId="b1"+ siteType={siteType}+ onSent={onSent}+ /></NextIntlClientProvider>,);});@@ -97,6 +106,8 @@ beforeEach(() => {createContentDraft.mockReset().mockResolvedValue('d9');getContentOverlap.mockReset().mockResolvedValue({ totalPrompts: 2, pages: [] });importContentPage.mockReset().mockResolvedValue({ error: 'failed' });+ sendContentDraftToActionCenter.mockReset();+ onSent.mockReset();toast.warning.mockReset();push.mockReset();toast.error.mockReset();@@ -433,4 +444,67 @@ describe('New content', () => {expect(document.body.textContent).toContain('Safe to create');});});++ describe('who does it', () => {+ async function startNewPage() {+ await render();+ await click(button('Pick an opportunity'));+ const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(+ (o) => o.textContent === 'Northwind vs HubSpot',+ );+ await click(option);+ await click(button('Continue'));+ await act(async () => {});+ }+ const whoOption = (name: string) =>+ [+ ...document.querySelectorAll<HTMLElement>('[aria-labelledby="start-who"] [role="radio"]'),+ ].find((r) => r.textContent?.startsWith(name))!;++ it('opens the editor for me, and offers the agent only once it exists', async () => {+ await startNewPage();+ expect(whoOption('Me').getAttribute('aria-checked')).toBe('true');+ const agent = whoOption('Agent') as HTMLButtonElement;+ expect(agent.disabled).toBe(true);+ expect(agent.textContent).toContain('Comes with the Content Agent');+ expect(button('Open editor')).toBeDefined();+ });++ it('sends the draft to the Action Center for the team, and keeps it in the Library', async () => {+ sendContentDraftToActionCenter.mockResolvedValue({+ actionId: 'a1',+ actionNo: 214,+ created: true,+ });+ await startNewPage();+ await click(whoOption('Team'));+ await click(button('Send to Action Center'));++ expect(createContentDraft.mock.calls[0][1]).toMatchObject({ method: 'create' });+ expect(sendContentDraftToActionCenter).toHaveBeenCalledWith('b1', 'd9');+ expect(push).not.toHaveBeenCalled();+ expect(onSent).toHaveBeenCalled();+ const [message, options] = toast.success.mock.calls[0];+ expect(message).toBe('Sent to the Action Center');+ expect(options.description).toBe(+ 'Action #214: the draft waits in the Library for whoever writes it.',+ );+ options.action.onClick();+ expect(push).toHaveBeenCalledWith('/dashboard/action-center/actions?action=a1');+ });++ it('says the draft is kept when sending it fails, and opens it on request', async () => {+ sendContentDraftToActionCenter.mockResolvedValue({ error: 'Failed to send' });+ await startNewPage();+ await click(whoOption('Team'));+ await click(button('Send to Action Center'));+ const [message, options] = toast.error.mock.calls[0];+ expect(message).toBe(+ "The draft is in the Library, but it couldn't be sent to the Action Center.",+ );+ expect(onSent).toHaveBeenCalled();+ options.action.onClick();+ expect(push).toHaveBeenCalledWith('/dashboard/content/editor/d9');+ });+ });});diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsxindex 87e2b4e21..e9ac84ddf 100644--- a/web/src/components/content/new-content-dialog.tsx+++ b/web/src/components/content/new-content-dialog.tsx@@ -34,6 +34,7 @@ import {getContentOverlap,getContentStartOptions,importContentPage,+ sendContentDraftToActionCenter,} from '@/lib/actions/content-drafts';import { MAX_ATTACHMENT_BYTES, textToHtml } from '@/lib/content/attachments';import { cleanHtml } from '@/lib/content/clean-html';@@ -108,6 +109,10 @@ interface StartChoice {choice: OverlapChoice;}+/** Who does the page (Start, CE-015): the person, the Content Agent, or the team. */+type Who = 'me' | 'agent' | 'team';+const WHO: Who[] = ['me', 'agent', 'team'];+/** The overlap check for one source: null while it runs. */interface OverlapRead {key: string;@@ -126,11 +131,14 @@ export function NewContentDialog({onOpenChange,brandId,siteType,+ onSent,}: {open: boolean;onOpenChange: (open: boolean) => void;brandId: string;siteType: SiteType;+ /** A draft was sent to the Action Center: the Library lists it. */+ onSent?: () => void;}) {const t = useTranslations('contentEditor.newContent');const tTypes = useTranslations('contentEditor.pageTypes');@@ -151,6 +159,7 @@ export function NewContentDialog({const [reading, setReading] = useState(false);const [start, setStart] = useState<StartChoice | null>(null);const [opening, setOpening] = useState(false);+ const [who, setWho] = useState<Who>('me');const [overlapRead, setOverlapRead] = useState<OverlapRead | null>(null);const [overlapAttempt, setOverlapAttempt] = useState(0);const fileRef = useRef<HTMLInputElement>(null);@@ -212,6 +221,7 @@ export function NewContentDialog({setStart(null);setOpening(false);setOverlapRead(null);+ setWho('me');};const changeOpen = (next: boolean) => {if (!next) reset();@@ -378,6 +388,10 @@ export function NewContentDialog({bodyHtml,sourceUrl: existing?.url ?? start.sourceUrl,});+ if (who === 'team') {+ await sendToTeam(id);+ return;+ }router.push(contentEditorPath(id));} catch (err) {console.error('Failed to start a draft:', err);@@ -386,6 +400,31 @@ export function NewContentDialog({}};+ /**+ * Team: the draft goes to the Action Center as an action for someone to+ * write; it stays in the Library either way.+ */+ const sendToTeam = async (id: string) => {+ const sent = await sendContentDraftToActionCenter(brandId, id);+ changeOpen(false);+ onSent?.();+ if ('error' in sent) {+ toast.error(t('start.sendFailed'), {+ description: sent.error,+ action: { label: t('start.openDraft'), onClick: () => router.push(contentEditorPath(id)) },+ });+ return;+ }+ toast.success(t('start.sent'), {+ description: t('start.sentDescription', { number: sent.actionNo }),+ duration: 10_000,+ action: {+ label: t('start.openAction'),+ onClick: () => router.push(`/dashboard/action-center/actions?action=${sent.actionId}`),+ },+ });+ };+return (<Dialog open={open} onOpenChange={changeOpen}><DialogContent className="sm:max-w-xl">@@ -449,6 +488,48 @@ export function NewContentDialog({}}/>)}+ <div className="space-y-2">+ <Label id="start-who">{t('who.label')}</Label>+ <div+ role="radiogroup"+ aria-labelledby="start-who"+ className="grid grid-cols-3 gap-1.5"+ >+ {WHO.map((value) => {+ // The Content Agent comes in its own update (CE-018/022).+ const soon = value === 'agent';+ return (+ <button+ key={value}+ type="button"+ role="radio"+ aria-checked={who === value}+ aria-disabled={soon || undefined}+ disabled={soon}+ title={soon ? t('who.agent.soon') : undefined}+ onClick={() => setWho(value)}+ className={cn(+ 'flex items-start gap-2 rounded-xl border px-3 py-2.5 text-left transition-colors hover:bg-muted/50 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent',+ who === value && 'border-foreground ring-1 ring-inset ring-foreground',+ )}+ >+ <span+ className={cn(+ 'mt-0.5 h-4 w-4 shrink-0 rounded-full border-[1.5px] border-muted-foreground/50',+ who === value && 'border-[5px] border-foreground',+ )}+ />+ <span className="min-w-0">+ <span className="block text-sm font-medium">{t(`who.${value}.title`)}</span>+ <span className="block text-xs text-muted-foreground">+ {soon ? t('who.agent.soon') : t(`who.${value}.hint`)}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ </div><DialogFooter><Button variant="ghost" onClick={() => setStart(null)} disabled={opening}><ArrowLeft className="h-4 w-4" />@@ -456,7 +537,7 @@ export function NewContentDialog({</Button><Button onClick={() => void openEditor()} disabled={opening}>{opening && <Loader2 className="h-4 w-4 animate-spin" />}- {t('start.openEditor')}+ {t(who === 'team' ? 'start.sendToTeam' : 'start.openEditor')}</Button></DialogFooter></>diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex 4ad65c7bf..5ffc9f810 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -54,8 +54,8 @@ describe('actionTexts', () => {expect(() => actionGoal(kind, t)).not.toThrow();});- it('holds copy for all sixty-two definitions and the six person-sent kinds', () => {- expect(ACTION_KINDS).toHaveLength(68);+ it('holds copy for all sixty-two definitions and the seven person-sent kinds', () => {+ expect(ACTION_KINDS).toHaveLength(69);});it('names pages sent from AI Traffic after their list and page, or how many (AT-006)', () => {@@ -165,6 +165,30 @@ describe('actionTexts', () => {expect(texts.title).toBe('Expand the tool list');});+ it('names a draft sent from the Content Editor after its page (CE-015)', () => {+ const write = actionTexts(+ action({+ kind: 'content_draft',+ payload: { title: 'CRM for real estate teams', method: 'create' },+ }),+ t,+ );+ expect(write.title).toBe('Write: CRM for real estate teams');+ expect(write.description).toBe(messages.actionCenter.actionTexts.content_draft.description);+ const optimize = actionTexts(+ action({ kind: 'content_draft', payload: { title: 'Pricing', method: 'optimize' } }),+ t,+ );+ expect(optimize.title).toBe('Optimize: Pricing');+ // An untitled draft is named by its prompts, as every kind is.+ expect(+ actionTexts(+ action({ kind: 'content_draft', payload: { targetCount: 3, targetEntity: 'prompts' } }),+ t,+ ).title,+ ).not.toBe('');+ });+/*** The specification's title rule: "Recover 7 lost citations", never* "Recover citations". Every definition's title names its targets.diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 27a1e7c52..3c8ad817c 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -71,6 +71,18 @@ export function actionTexts(if (action.kind === 'content_opportunity' && typeof p.title === 'string' && p.title) {return { title: p.title, description: t(`${action.kind}.description`) };}+ // A draft sent from the Content Editor (CE-015) is named after its page.+ if (action.kind === 'content_draft' && typeof p.title === 'string' && p.title) {+ return {+ title: t(+ p.method === 'optimize' ? 'content_draft.optimizeTitle' : 'content_draft.createTitle',+ {+ title: p.title,+ },+ ),+ description: t('content_draft.description'),+ };+ }// An Improve action carries its own title and "why", written from the// prompt's platform states when it was sent (PROMPT-004).if (action.kind === 'prompt_improve' && typeof p.title === 'string' && p.title) {@@ -225,6 +237,7 @@ const PERSON_SENT_KINDS: string[] = ['topic_opportunity','mention_review','traffic_pages',+ 'content_draft',];/** Compact evidence chips under the title: signal count plus the kind's owndiff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex 8a901ddd3..c5cfd84cb 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -112,7 +112,9 @@ export type ActionKind =// Sent by a person from answers on the Mentions tab (MS-08).| 'mention_review'// Sent by a person from AI Traffic's Pages section (AT-006).- | 'traffic_pages';+ | 'traffic_pages'+ // Sent by a person from the Content Editor's Start, as Team (CE-015).+ | 'content_draft';export type TaskStatus =| 'todo'@@ -248,6 +250,7 @@ export const ACTION_KINDS: readonly ActionKind[] = ['topic_opportunity','mention_review','traffic_pages',+ 'content_draft',];/**diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.tsindex a4bb60d9c..a1415ce67 100644--- a/web/src/lib/actions/content-drafts-start.test.ts+++ b/web/src/lib/actions/content-drafts-start.test.ts@@ -57,8 +57,13 @@ vi.mock('@/lib/supabase/server', () => ({})),}));-const { createContentDraft, getContentOverlap, getContentStartOptions, importContentPage } =- await import('./content-drafts');+const {+ createContentDraft,+ getContentOverlap,+ getContentStartOptions,+ importContentPage,+ sendContentDraftToActionCenter,+} = await import('./content-drafts');const inserted = () => calls.find((call) => call.op === 'insert')?.value as Record<string, unknown>;@@ -406,3 +411,44 @@ describe('importContentPage', () => {vi.unstubAllGlobals();});});++describe('sendContentDraftToActionCenter', () => {+ it('asks the API to send the draft, with the member’s session', async () => {+ const fetchMock = vi.fn(+ async () =>+ new Response(JSON.stringify({ actionId: 'a1', actionNo: 214, created: true }), {+ status: 201,+ }),+ );+ vi.stubGlobal('fetch', fetchMock);+ await expect(sendContentDraftToActionCenter(BRAND, OPPORTUNITY)).resolves.toEqual({+ actionId: 'a1',+ actionNo: 214,+ created: true,+ });+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toMatch(/\/api\/action-center\/content-drafts$/);+ expect(init.headers).toMatchObject({ Authorization: 'Bearer jwt' });+ expect(JSON.parse(init.body as string)).toEqual({ brandId: BRAND, draftId: OPPORTUNITY });+ vi.unstubAllGlobals();+ });++ it('returns why it failed, and sends nothing for a malformed id', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(+ async () => new Response(JSON.stringify({ details: 'Draft not found' }), { status: 404 }),+ ),+ );+ await expect(sendContentDraftToActionCenter(BRAND, OPPORTUNITY)).resolves.toEqual({+ error: 'Draft not found',+ });+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ await expect(sendContentDraftToActionCenter(BRAND, 'nope')).resolves.toEqual({+ error: 'invalid',+ });+ expect(fetchMock).not.toHaveBeenCalled();+ vi.unstubAllGlobals();+ });+});diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 80b013b01..520cb0b74 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -318,6 +318,48 @@ export async function importContentPage(}}+/**+ * "Team" in Start (CE-015): the draft sent to the Action Center as an action+ * for someone on the team to write (the API's from-content-draft.js), or the+ * one still open if it was sent already. Returned, not thrown: production+ * hides a server action's errors.+ */+export async function sendContentDraftToActionCenter(+ brandId: string,+ id: string,+): Promise<{ actionId: string; actionNo: number; created: boolean } | { error: string }> {+ if (!draftId.safeParse(brandId).success || !draftId.safeParse(id).success) {+ return { error: 'invalid' };+ }+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'Not authenticated' };+ try {+ const res = await fetch(`${API_BASE_URL}/api/action-center/content-drafts`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ brandId, draftId: id }),+ });+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ if (!res.ok) {+ return { error: String(body.details || body.error || `Server error: ${res.status}`) };+ }+ return {+ actionId: String(body.actionId),+ actionNo: Number(body.actionNo),+ created: Boolean(body.created),+ };+ } catch (err) {+ console.error('Failed to send a draft to the Action Center:', err);+ return { error: 'failed' };+ }+}+const overlapSource = startInput.shape.source;/**diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex ce556553f..be5d34280 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -827,6 +827,7 @@ export type Database = {}content_drafts: {Row: {+ action_id: string | nullauthor: stringbody_html: stringbrand_id: string@@ -846,6 +847,7 @@ export type Database = {updated_at: string}Insert: {+ action_id?: string | nullauthor?: stringbody_html?: stringbrand_id: string@@ -865,6 +867,7 @@ export type Database = {updated_at?: string}Update: {+ action_id?: string | nullauthor?: stringbody_html?: stringbrand_id?: string