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): send a Content Editor page to the brand's webhook from the editor header (Send to CMS #1331, part 2: web) (#1438)
Cihan5697552d5e80
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 1493e0c29..c92af9fc4 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4188,6 +4188,54 @@"md": "Export Markdown","failed": "Couldn't export the page. Try again."},+ "send": {+ "button": "Send to CMS",+ "hint": "Send the page to your CMS through the brand's webhook",+ "title": "Send to CMS",+ "description": "The page goes to the brand's webhook, for your workflow tool (Zapier, Make, n8n) to publish it in your CMS.",+ "placeholders": "{count, plural, one {# placeholder is} other {# placeholders are}} still open. Fill {count, plural, one {it} other {them}} first: none goes to your CMS.",+ "fillNow": "Fill now",+ "empty": "The page has nothing under its title yet. Write it first, then send it.",+ "noTitle": "Give the page a title first: your CMS needs one.",+ "unsaved": "The page has changes that aren't saved, so it wasn't sent.",+ "applyHtml": "Apply or discard your HTML changes first: they aren't in the page yet.",+ "readFailed": "Couldn't read this page's last send. Try again before sending, so it doesn't land in your CMS twice.",+ "retry": "Try again",+ "longTitle": "Shorten the title to 300 characters first: your CMS takes no more.",+ "fields": {+ "title": "Title",+ "slug": "Slug",+ "slugHint": "The page's address on your site, after the domain.",+ "slugInvalid": "Use letters, digits, dots, - and _ only, up to 200 characters.",+ "slugEmpty": "Add a slug: the page's address on your site, after the domain.",+ "metaTitle": "Meta title",+ "metaDescription": "Meta description",+ "characters": "{count, plural, one {# character} other {# characters}}"+ },+ "live": "Live at",+ "last": {+ "queued": "Last sent {when}, still on its way.",+ "sent": "Last sent {when}.",+ "failed": "The last send failed, {when}.",+ "published": "Published {when}."+ },+ "errors": {+ "no_webhook": "This brand has no webhook yet. Set one up in Webhook Settings on Content Opportunities.",+ "webhook_not_subscribed": "The brand's webhook doesn't receive \"Content page sent\". Turn it on in Webhook Settings on Content Opportunities.",+ "daily_limit": "This workspace has sent 200 pages in the last 24 hours. Try again later.",+ "forbidden": "Only admins and managers can send pages to the CMS.",+ "not_found": "This page isn't in the brand anymore.",+ "invalid": "The page couldn't go as it is. Check it and send again.",+ "invalidField": "Check the {field, select, slug {slug} metaTitle {meta title} metaDescription {meta description} title {title} other {page}} and send again.",+ "failed": "Couldn't send the page. Try again.",+ "webhookStatus": "The webhook answered {status} and didn't take the page. Check your workflow, then send again.",+ "webhookFailed": "The webhook didn't take the page: {reason}"+ },+ "cancel": "Cancel",+ "send": "Send",+ "sending": "Sending",+ "sent": "Sent to your CMS"+ },"rulesChip": "Rules {met}/{total}","rulesChipHint": "Rules this page meets now. Open the Rules tab.","author": {@@ -4382,7 +4430,10 @@"warningNoReason": "Trust {trust}, below 60. You can mark it ready, but Quality shows what would raise it.","warningExport": "Trust {trust}, below 60. {reason}. You can export it, but {count, plural, one {fixing it} other {fixing them}} first raises Trust to about {raised}.","warningNoReasonExport": "Trust {trust}, below 60. You can export it, but Quality shows what would raise it.",+ "warningSend": "Trust {trust}, below 60. {reason}. You can send it to your CMS, but {count, plural, one {fixing it} other {fixing them}} first raises Trust to about {raised}.",+ "warningNoReasonSend": "Trust {trust}, below 60. You can send it to your CMS, but Quality shows what would raise it.","continueExport": "Continue to export",+ "continueSend": "Continue to send","paste": {"title": "Ready to paste","notYet": "Not ready to paste yet",@@ -5057,6 +5108,7 @@"eventOpportunitySent": "Opportunity sent","eventDailyPulseCreated": "Daily Pulse created","eventActionTaskSent": "Action Center task sent",+ "eventContentDraftSent": "Content page sent","url": "Webhook URL","urlPlaceholder": "https://your-n8n-instance.com/webhook/...","secret": "Secret Key (optional)",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsxindex 41fc90446..560ce0d73 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx@@ -22,9 +22,14 @@ const WEBHOOK_EVENTS = [{ value: 'opportunity.sent', label: 'eventOpportunitySent' },{ value: 'daily_pulse.created', label: 'eventDailyPulseCreated' },{ value: 'action_task.sent', label: 'eventActionTaskSent' },+ { value: 'content_draft.sent', label: 'eventContentDraftSent' },] as const;-const DEFAULT_WEBHOOK_EVENTS = WEBHOOK_EVENTS.map(({ value }) => value);+// Pages sent to the CMS (#1331) are opt-in, as in the column's default: a+// workflow set up for opportunities doesn't expect them.+const DEFAULT_WEBHOOK_EVENTS = WEBHOOK_EVENTS.map(({ value }) => value).filter(+ (value) => value !== 'content_draft.sent',+);interface WebhookSettingsDialogProps {open: boolean;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsxindex be8367689..57aa083ab 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx@@ -98,7 +98,7 @@ async function render(image = 'https://cdn.acme.com/pour-over.jpg' as string | null,linksPending = 0,paste = clean,- mode = 'markReady' as 'markReady' | 'export',+ mode = 'markReady' as 'markReady' | 'export' | 'send',contentByline = null as string | null,title = 'How small teams forecast',} = {},@@ -364,6 +364,15 @@ describe('BeforePublish', () => {expect(onMarkReady).not.toHaveBeenCalled();});+ it('goes on to the Send dialog from Send to CMS, the warning saying so', async () => {+ await render(quality(), { mode: 'send' });+ expect(alert()!.textContent).toContain('You can send it to your CMS, but fixing them first');+ expect(alert()!.textContent).not.toContain('logged');+ await act(async () => button('Continue to send')!.click());+ expect(onContinue).toHaveBeenCalled();+ expect(onMarkReady).not.toHaveBeenCalled();+ });+it('goes to what would raise Trust from Export too', async () => {await render(quality(), { mode: 'export' });await act(async () => button('Fix first')!.click());diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsxindex b375b5a10..4450db2dd 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx@@ -58,9 +58,17 @@ export interface ReadyToPaste {* and schema), Ready to paste (no placeholders, images with alt text, links* that work), and for an article the JSON-LD to paste when the CMS doesn't* write one, from the page's facts only. Mark ready anyway is logged with- * the Trust the page had; on Export it goes on to Export. Rendered only- * while open.+ * the Trust the page had; on Export it goes on to Export, and on Send to CMS+ * to the Send dialog (#1331). Rendered only while open.*/+/** The below-60 warning, as each way on says what it does. */+const WARNING = { markReady: 'warning', export: 'warningExport', send: 'warningSend' } as const;+const WARNING_NO_REASON = {+ markReady: 'warningNoReason',+ export: 'warningNoReasonExport',+ send: 'warningNoReasonSend',+} as const;+export function BeforePublish({mode = 'markReady',paste,@@ -77,14 +85,14 @@ export function BeforePublish({onMarkReady,onFixFirst,}: {- /** Opened by Mark ready, or by Export. */- mode?: 'markReady' | 'export';+ /** Opened by Mark ready, by Export, or by Send to CMS. */+ mode?: 'markReady' | 'export' | 'send';paste: ReadyToPaste;/** Goes to the first placeholder, to fill it (Ready to paste's Fill now). */onFillNow: () => void;/** The byline line the brand puts in the content (Add byline to content), or null. */contentByline?: string | null;- /** Export's: goes on to it. */+ /** Export's and Send's: goes on to them. */onContinue?: () => void;onClose: () => void;quality: QualityRead;@@ -185,13 +193,15 @@ export function BeforePublish({<div className="min-w-0 space-y-1"><p>{fix- ? t(mode === 'export' ? 'warningExport' : 'warning', {+ ? t(WARNING[mode], {trust,reason: fix.line,count: fix.count,raised: trust + fix.gain,})- : t(mode === 'export' ? 'warningNoReasonExport' : 'warningNoReason', { trust })}+ : t(WARNING_NO_REASON[mode], {+ trust,+ })}</p>{mode === 'markReady' && <p className="text-xs opacity-80">{t('logged')}</p>}</div>@@ -290,9 +300,9 @@ export function BeforePublish({{t('fixFirst')}</Button>)}- {mode === 'export' ? (+ {mode !== 'markReady' ? (<Button ref={markRef} onClick={onContinue}>- {t('continueExport')}+ {mode === 'send' ? t('continueSend') : t('continueExport')}</Button>) : (<Buttondiff --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.tsxindex 9d3cd30a4..532de4eb8 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@@ -10,7 +10,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, Bot, Check, Copy, Download, PanelRight, Target, X } from 'lucide-react';+import { ArrowLeft, Bot, Check, Copy, Download, PanelRight, Send, Target, X } from 'lucide-react';import { Link, useRouter } from '@/i18n/navigation';import { Button } from '@/components/ui/button';import { buttonVariants } from '@/components/ui/button-variants';@@ -26,6 +26,7 @@ import { LoadingDots } from '@/components/ui/loading-dots';import { AiUsageBanner } from '@/components/ai-usage/ai-usage-banner';import { AiUsageMeter } from '@/components/ai-usage/ai-usage-meter';import { useAiUsage } from '@/components/providers/ai-usage-provider';+import { useUserRole } from '@/hooks/use-user-role';import { PLATFORM_LABELS } from '@/config/platform-labels';import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';import {@@ -134,6 +135,7 @@ import {type HeldEdit,} from './_cited-passages';import { ExportDialog, type ExportDestination } from './_export-dialog';+import { SendDialog } from './_send-dialog';import { ExportMenu } from './_export-menu';import { sourceDetail } from './_sources-tab';import { HistoryMenu } from './_history-menu';@@ -1588,10 +1590,47 @@ export function DraftEditor({// with Ready to paste read from the page as it is then (its links as they// are read).const [publishOpen, setPublishOpen] = useState<{- mode: 'markReady' | 'export';+ mode: 'markReady' | 'export' | 'send';html: string;} | null>(null);- const openBeforePublish = (mode: 'markReady' | 'export') => {+ // Send to CMS (#1331): admins and managers send the page to the brand's+ // webhook, as the page Export makes ready, past Before you publish once+ // Quality is live.+ const { canManage } = useUserRole();+ const [sendOpen, setSendOpen] = useState<{ html: string } | null>(null);+ const [preparing, setPreparing] = useState(false);+ // HTML edited in the HTML view and not applied isn't in the page to save.+ const htmlUnapplied = htmlSource !== null && htmlEdited;+ // What's waiting goes out first, as for Mark ready: the CMS gets the page+ // Ansvisor holds, the one its callback later marks Published. A page that+ // can't be saved (a teammate or the agent changed it meanwhile) isn't sent.+ const openSend = async () => {+ if (preparing) return;+ if (htmlUnapplied) {+ toast.error(t('send.applyHtml'));+ return;+ }+ setPreparing(true);+ const saved = await autosave.settle().then(+ () => true,+ () => false,+ );+ setPreparing(false);+ if (!saved) {+ toast.error(t('send.unsaved'));+ return;+ }+ setSendOpen({ html: pageToPublish() });+ };+ const startSend = () => {+ if (htmlUnapplied) {+ toast.error(t('send.applyHtml'));+ return;+ }+ if (quality) openBeforePublish('send');+ else void openSend();+ };+ const openBeforePublish = (mode: 'markReady' | 'export' | 'send') => {setPublishOpen({ mode, html: pageToPublish() });if (mode === 'markReady') nudgeAt('markReady');};@@ -2006,6 +2045,24 @@ export function DraftEditor({) : (<ExportMenu disabled={!editor} onExport={(format) => void exportPage(format)} />)}+ {canManage && (+ <HeaderTip label={t('send.button')} hint={t('send.hint')}>+ <Button+ variant="outline"+ size="icon-sm"+ disabled={+ !editor ||+ preparing ||+ autosave.state === 'conflict' ||+ autosave.state === 'too_large'+ }+ aria-label={t('send.button')}+ onClick={startSend}+ >+ {preparing ? <LoadingDots /> : <Send className="h-3.5 w-3.5" />}+ </Button>+ </HeaderTip>+ )}{/* The one black button. Marked, it reads Ready (a click moves it backto review); published, Published. Narrower than 1024px, ✓ alone. */}{status === 'ready' || status === 'published' ? (@@ -2358,6 +2415,25 @@ export function DraftEditor({/>)}+ {sendOpen && (+ <SendDialog+ draftId={draft.id}+ brandId={draft.brandId}+ title={title}+ html={sendOpen.html}+ sourceUrl={draft.sourceUrl}+ author={pageAuthor}+ // Until the authors are read, who it is by isn't known.+ teamByline={authorsRead ? t('author.organization', { brand: brandName }) : ''}+ byline={contentByline}+ onFillNow={() => {+ setSendOpen(null);+ fillFirstPlaceholder();+ }}+ onClose={() => setSendOpen(null)}+ />+ )}+{quality && publishOpen && readyToPaste && (<BeforePublishmode={publishOpen.mode}@@ -2368,8 +2444,10 @@ export function DraftEditor({}}contentByline={contentByline}onContinue={() => {+ const next = publishOpen.mode;setPublishOpen(null);- openExport();+ if (next === 'send') void openSend();+ else openExport();}}onClose={() => setPublishOpen(null)}quality={quality}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_send-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_send-dialog.test.tsxnew file mode 100644index 000000000..4dc023a57--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_send-dialog.test.tsx@@ -0,0 +1,277 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../../../messages/en.json';+import type { ContentAuthor } from '@/lib/content/authors';+import type { DraftCms } from '@/lib/content/cms-send-client';++const toast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));+const readDraftCms = vi.hoisted(() => vi.fn());+const sendPagesToCms = vi.hoisted(() => vi.fn());+vi.mock('@/lib/content/cms-send-client', () => ({ readDraftCms, sendPagesToCms }));++const { SendDialog } = await import('./_send-dialog');++/**+ * Send to CMS (#1331): the page to the brand's webhook, its slug and meta+ * filled from the page or what the draft kept, its placeholders first.+ */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const HTML = '<h1>Pour-over</h1>\n<p>Brew it slowly.</p>';+const ada = { id: 'a1', name: 'Ada Lovelace' } as ContentAuthor;+const neverSent: DraftCms = { fields: {}, publishedUrl: null, last: null };++let container: HTMLDivElement;+let root: Root;+const onFillNow = vi.fn();+const onClose = vi.fn();++async function render(over: Partial<Parameters<typeof SendDialog>[0]> = {}) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <SendDialog+ draftId="d1"+ brandId="brand-1"+ title="Pour-over"+ html={HTML}+ sourceUrl={null}+ author={ada}+ teamByline="Acme Team"+ byline={null}+ onFillNow={onFillNow}+ onClose={onClose}+ {...over}+ />+ </NextIntlClientProvider>,+ );+ });+}+const dialog = () => document.querySelector('[role="dialog"]')!;+const button = (name: string) =>+ [...dialog().querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === name)!;+const field = (id: string) => dialog().querySelector<HTMLInputElement>(`#${id}`)!;+const setValue = async (el: HTMLInputElement | HTMLTextAreaElement, value: string) => {+ const proto =+ el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;+ await act(async () => {+ Object.getOwnPropertyDescriptor(proto, 'value')!.set!.call(el, value);+ el.dispatchEvent(new Event('input', { bubbles: true }));+ });+};+const alert = () => dialog().querySelector('[role="alert"]')?.textContent;++beforeEach(() => {+ onFillNow.mockReset();+ onClose.mockReset();+ toast.success.mockReset();+ readDraftCms.mockReset().mockResolvedValue(neverSent);+ sendPagesToCms.mockReset().mockResolvedValue({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'sent' }],+ });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('SendDialog', () => {+ it('fills the fields from the page and sends it without its H1', async () => {+ await render({ byline: 'By Ada Lovelace' });+ expect(readDraftCms).toHaveBeenCalledWith('d1');+ expect(field('cms-slug').value).toBe('pour-over');+ expect(field('cms-meta-title').value).toBe('Pour-over');+ expect(field('cms-meta-description').value).toBe('Brew it slowly.');+ expect(dialog().textContent).toContain('15 characters');++ await act(async () => button('Send').click());+ expect(sendPagesToCms).toHaveBeenCalledWith('brand-1', [+ {+ draftId: 'd1',+ title: 'Pour-over',+ slug: 'pour-over',+ metaTitle: 'Pour-over',+ metaDescription: 'Brew it slowly.',+ // The brand's byline line stays; the CMS's title field carries the H1.+ html: '<p>By Ada Lovelace</p>\n<p>Brew it slowly.</p>',+ author: 'Ada Lovelace',+ featuredImage: null,+ },+ ]);+ expect(toast.success).toHaveBeenCalledWith('Sent to your CMS');+ expect(onClose).toHaveBeenCalled();+ });++ it('starts from what the draft kept and says where the page went live', async () => {+ readDraftCms.mockResolvedValue({+ fields: { slug: 'coffee', metaTitle: 'Coffee, slowly' },+ publishedUrl: 'https://example.com/coffee',+ last: { status: 'published', at: '2026-10-24T10:00:00Z', error: null },+ });+ await render();+ expect(field('cms-slug').value).toBe('coffee');+ expect(field('cms-meta-title').value).toBe('Coffee, slowly');+ expect(field('cms-meta-description').value).toBe('Brew it slowly.');+ const live = dialog().querySelector<HTMLAnchorElement>('a[href="https://example.com/coffee"]');+ expect(live?.closest('p')?.textContent).toBe('Live at https://example.com/coffee');+ });++ it('says how the last send went while the page isn’t live', async () => {+ readDraftCms.mockResolvedValue({+ ...neverSent,+ last: { status: 'failed', at: '2026-10-24T10:00:00Z', error: 'The webhook answered 500' },+ });+ await render();+ expect(dialog().textContent).toContain('The last send failed, Oct 24, 2026, 10:00 AM.');+ });++ it('holds the send while a placeholder is open, and goes to it', async () => {+ await render({ html: '<h1>Pour-over</h1>\n<p>Use [figure] g of coffee.</p>' });+ expect(dialog().textContent).toContain('1 placeholder is still open.');+ expect(button('Send').disabled).toBe(true);+ await act(async () => button('Fill now').click());+ expect(onFillNow).toHaveBeenCalled();+ });++ it('asks for a slug that can go: a slash is fixed, an empty one asked for', async () => {+ await render();+ await setValue(field('cms-slug'), 'blog/coffee');+ expect(field('cms-slug').getAttribute('aria-invalid')).toBe('true');+ expect(dialog().textContent).toContain('Use letters, digits, dots, - and _ only');+ expect(button('Send').disabled).toBe(true);++ await setValue(field('cms-slug'), '');+ expect(field('cms-slug').hasAttribute('aria-invalid')).toBe(false);+ expect(dialog().textContent).toContain("Add a slug: the page's address on your site");+ expect(button('Send').disabled).toBe(true);+ });++ it('holds a page with nothing to publish, or no title', async () => {+ await render({ html: '<h1>Pour-over</h1><p></p>' });+ expect(dialog().textContent).toContain('The page has nothing under its title yet.');+ expect(button('Send').disabled).toBe(true);+ await render({ title: ' ' });+ expect(dialog().textContent).toContain('Give the page a title first');+ expect(button('Send').disabled).toBe(true);+ });++ it('holds the send while the last send can’t be read, and reads it again', async () => {+ // Unread, a page sent before under another slug could land in the CMS twice.+ readDraftCms.mockRejectedValueOnce(new Error('offline'));+ await render();+ expect(alert()).toBe(+ "Couldn't read this page's last send. Try again before sending, so it doesn't land in your CMS twice.Try again",+ );+ expect(button('Send').disabled).toBe(true);+ let answer: (read: DraftCms) => void = () => {};+ readDraftCms.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));+ const retry = dialog().querySelector<HTMLButtonElement>('[aria-label="Try again"]')!;+ retry.focus();+ await act(async () => retry.click());+ expect(readDraftCms).toHaveBeenCalledTimes(2);+ // Reading again, it stays where it is (and focus with it), and Send waits.+ expect(retry.isConnected).toBe(true);+ expect(retry.disabled).toBe(true);+ expect(button('Send').disabled).toBe(true);+ await act(async () => answer({ ...neverSent, fields: { slug: 'coffee' } }));+ expect(alert()).toBeUndefined();+ expect(field('cms-slug').value).toBe('coffee');+ expect(button('Send').disabled).toBe(false);+ });++ it('holds the send the same way when the read answers nothing (before 00262)', async () => {+ readDraftCms.mockResolvedValueOnce(null);+ await render();+ expect(alert()).toContain("Couldn't read this page's last send.");+ expect(dialog().querySelector('[aria-label="Try again"]')).not.toBeNull();+ expect(button('Send').disabled).toBe(true);+ });++ it('keeps the person’s changes when the kept fields come in after them', async () => {+ let answer: (read: DraftCms) => void = () => {};+ readDraftCms.mockReturnValue(new Promise((resolve) => (answer = resolve)));+ await render();+ // Not sent before the kept fields are read.+ expect(button('Send').disabled).toBe(true);+ await setValue(field('cms-slug'), 'my-coffee');+ await act(async () => answer({ ...neverSent, fields: { slug: 'coffee' } }));+ expect(field('cms-slug').value).toBe('my-coffee');+ expect(button('Send').disabled).toBe(false);+ });++ it('still takes the kept slug when the person changed another field first', async () => {+ let answer: (read: DraftCms) => void = () => {};+ readDraftCms.mockReturnValue(new Promise((resolve) => (answer = resolve)));+ await render();+ await setValue(field('cms-meta-description'), 'My own words.');+ await act(async () =>+ answer({ ...neverSent, fields: { slug: 'coffee', metaDescription: 'Kept words.' } }),+ );+ // The slug it was sent under before, or the CMS could get the page twice.+ expect(field('cms-slug').value).toBe('coffee');+ expect(dialog().querySelector<HTMLTextAreaElement>('#cms-meta-description')!.value).toBe(+ 'My own words.',+ );+ });++ it('says why the page didn’t go, and stays open', async () => {+ await render();+ sendPagesToCms.mockResolvedValueOnce({+ ok: false,+ code: 'webhook_not_subscribed',+ field: null,+ });+ await act(async () => button('Send').click());+ expect(alert()).toBe(+ 'The brand\'s webhook doesn\'t receive "Content page sent". Turn it on in Webhook Settings on Content Opportunities.',+ );++ sendPagesToCms.mockResolvedValueOnce({ ok: false, code: 'invalid', field: 'pages.0.slug' });+ await act(async () => button('Send').click());+ expect(alert()).toBe('Check the slug and send again.');++ sendPagesToCms.mockResolvedValueOnce({ ok: false, code: 'workspace', field: null });+ await act(async () => button('Send').click());+ expect(alert()).toBe("This brand isn't in your workspace. Switch to one of your brands.");++ // What the webhook answered, in the app's words; else why it wasn't reached.+ const failed = { id: 'x1', draftId: 'd1', status: 'failed' };+ sendPagesToCms.mockResolvedValueOnce({+ ok: true,+ deliveries: [{ ...failed, http_status: 500, error: 'The webhook answered 500' }],+ });+ await act(async () => button('Send').click());+ expect(alert()).toBe(+ "The webhook answered 500 and didn't take the page. Check your workflow, then send again.",+ );+ sendPagesToCms.mockResolvedValueOnce({+ ok: true,+ deliveries: [{ ...failed, http_status: null, error: 'The webhook could not be reached' }],+ });+ await act(async () => button('Send').click());+ expect(alert()).toBe("The webhook didn't take the page: The webhook could not be reached");++ // The webhook took it (2xx), then the workflow called back failed: its reason.+ sendPagesToCms.mockResolvedValueOnce({+ ok: true,+ deliveries: [{ ...failed, http_status: 200, error: 'Slug already taken' }],+ });+ await act(async () => button('Send').click());+ expect(alert()).toBe("The webhook didn't take the page: Slug already taken");++ // Changing a field clears what went wrong.+ await setValue(field('cms-meta-title'), 'Coffee');+ expect(alert()).toBeUndefined();+ expect(onClose).not.toHaveBeenCalled();+ expect(toast.success).not.toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_send-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_send-dialog.tsxnew file mode 100644index 000000000..9585af3c2--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_send-dialog.tsx@@ -0,0 +1,334 @@+'use client';++import { useEffect, useMemo, useRef, useState } from 'react';+import { useFormatter, useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { AlertTriangle } from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { LoadingDots } from '@/components/ui/loading-dots';+import { Textarea } from '@/components/ui/textarea';+import type { ContentAuthor } from '@/lib/content/authors';+import {+ META_DESCRIPTION_MAX,+ META_TITLE_MAX,+ cmsFields,+ cmsFieldsProblem,+ cmsPage,+ cmsPageProblem,+ type CmsFields,+} from '@/lib/content/cms-send';+import {+ readDraftCms,+ sendPagesToCms,+ type CmsSendError,+ type DraftCms,+} from '@/lib/content/cms-send-client';+import { exportPlaceholders, pageFields, titlePlaceholders } from '@/lib/content/ready-to-publish';++/**+ * Send to CMS (#1331): the page to the brand's webhook, for the workspace's+ * CMS or automation to publish. Its slug and meta are filled from the page,+ * or what the draft kept, and editable; they stay on the draft. The page+ * goes as Export makes it ready (CE-057): no placeholder goes, so they are+ * filled first. Rendered only while open, on the page as it was then.+ */+export function SendDialog({+ draftId,+ brandId,+ title,+ html,+ sourceUrl,+ author,+ teamByline,+ byline,+ onFillNow,+ onClose,+}: {+ draftId: string;+ brandId: string;+ title: string;+ /** The page as Copy HTML gives it (publishableHtml). */+ html: string;+ sourceUrl: string | null;+ author: ContentAuthor | null;+ /** The team byline; empty while the authors aren't read. */+ teamByline: string;+ /** The byline line the brand puts in the content, or null. */+ byline: string | null;+ /** Goes to the first placeholder, to fill it. */+ onFillNow: () => void;+ onClose: () => void;+}) {+ const t = useTranslations('contentEditor.editor.send');+ const tFailure = useTranslations('apiFailure');+ const format = useFormatter();+ const page = useMemo(+ () => pageFields({ title, html, sourceUrl, author, teamByline }),+ [title, html, sourceUrl, author, teamByline],+ );+ const placeholders = useMemo(+ () => exportPlaceholders(html) + titlePlaceholders(title, html),+ [html, title],+ );+ const pageProblem = useMemo(() => cmsPageProblem(title, html), [title, html]);+ // Undefined while the draft's kept fields are read; null when they couldn't be.+ const [kept, setKept] = useState<DraftCms | null | undefined>(undefined);+ const [attempt, setAttempt] = useState(0);+ const [retrying, setRetrying] = useState(false);+ const [fields, setFields] = useState<CmsFields>(() => cmsFields(page, null));+ // The fields the person changed: a ref, so the read that comes in after a+ // change sees it. The rest take what the draft kept (its slug above all,+ // or the CMS could get the page twice).+ const touched = useRef(new Set<keyof CmsFields>());+ const [sending, setSending] = useState(false);+ const [problem, setProblem] = useState<+ { code: CmsSendError; field: string | null } | { status: number } | { failed: string } | null+ >(null);++ useEffect(() => {+ let cancelled = false;+ readDraftCms(draftId)+ .then((read) => {+ if (cancelled) return;+ setKept(read);+ setRetrying(false);+ // What the draft kept, in each field the person hasn't changed.+ if (!read) return;+ const fromKept = cmsFields(page, read.fields);+ setFields((prev) => ({+ slug: touched.current.has('slug') ? prev.slug : fromKept.slug,+ metaTitle: touched.current.has('metaTitle') ? prev.metaTitle : fromKept.metaTitle,+ metaDescription: touched.current.has('metaDescription')+ ? prev.metaDescription+ : fromKept.metaDescription,+ }));+ })+ .catch(() => {+ if (cancelled) return;+ setKept(null);+ setRetrying(false);+ });+ return () => {+ cancelled = true;+ };+ // Read as it opens, and on Try again; the fields it fills are the person's after that.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [draftId, attempt]);++ const change = (key: keyof CmsFields, value: string) => {+ touched.current.add(key);+ setProblem(null);+ setFields((prev) => ({ ...prev, [key]: value }));+ };+ const wrong = cmsFieldsProblem(fields);+ // An empty slug (a title in another script gives none) asks for one, not a fix.+ const slugEmpty = fields.slug.trim() === '';+ const slugWrong = wrong === 'slug' && !slugEmpty;++ const send = async () => {+ setSending(true);+ setProblem(null);+ const result = await sendPagesToCms(brandId, [+ cmsPage({ draftId, title, html, fields, page, byline }),+ ]);+ setSending(false);+ if (!result.ok) {+ setProblem({ code: result.code, field: result.field });+ return;+ }+ const [delivery] = result.deliveries;+ if (delivery?.status === 'failed') {+ // What the webhook answered when it refused the page; else why it+ // failed: not reached, or the workflow's own reason in a callback+ // after it took the page (a 2xx).+ const refused =+ delivery.http_status && (delivery.http_status < 200 || delivery.http_status > 299);+ setProblem(+ refused+ ? { status: delivery.http_status! }+ : { failed: delivery.error ?? t('errors.failed') },+ );+ return;+ }+ toast.success(t('sent'));+ onClose();+ };++ const problemText = (shown: NonNullable<typeof problem>) => {+ if ('status' in shown) return t('errors.webhookStatus', { status: shown.status });+ if ('failed' in shown) return t('errors.webhookFailed', { reason: shown.failed });+ const { code, field } = shown;+ if (code === 'session' || code === 'workspace' || code === 'busy') return tFailure(code);+ // The server names the path ("pages.0.slug"); the field is its last part.+ if (code === 'invalid' && field) {+ return t('errors.invalidField', { field: field.split('.').pop() ?? 'other' });+ }+ return t(`errors.${code}`);+ };++ const live = kept?.publishedUrl ?? null;+ const last = kept?.last ?? null;++ return (+ <Dialog open onOpenChange={(open) => !open && !sending && onClose()}>+ <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ <DialogDescription>{t('description')}</DialogDescription>+ </DialogHeader>++ {pageProblem && (+ <div className="flex items-center gap-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200">+ <AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />+ <span className="min-w-0 flex-1">{t(pageProblem)}</span>+ </div>+ )}++ {placeholders > 0 && (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200">+ <AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />+ <span className="min-w-0 flex-1">{t('placeholders', { count: placeholders })}</span>+ <Button size="sm" variant="outline" onClick={onFillNow}>+ {t('fillNow')}+ </Button>+ </div>+ )}++ <div className="space-y-3">+ <div className="space-y-1">+ <p className="text-xs font-medium text-muted-foreground">{t('fields.title')}</p>+ <p className="text-sm [overflow-wrap:anywhere]">{title.trim() || '—'}</p>+ </div>+ <div className="space-y-1">+ <Label htmlFor="cms-slug">{t('fields.slug')}</Label>+ <Input+ id="cms-slug"+ required+ value={fields.slug}+ onChange={(e) => change('slug', e.target.value)}+ aria-invalid={slugWrong || undefined}+ aria-describedby="cms-slug-hint"+ />+ <p+ id="cms-slug-hint"+ className={+ slugWrong+ ? 'text-xs text-red-700 dark:text-red-400'+ : 'text-xs text-muted-foreground'+ }+ >+ {slugWrong+ ? t('fields.slugInvalid')+ : slugEmpty+ ? t('fields.slugEmpty')+ : t('fields.slugHint')}+ </p>+ </div>+ <div className="space-y-1">+ <Label htmlFor="cms-meta-title">{t('fields.metaTitle')}</Label>+ <Input+ id="cms-meta-title"+ value={fields.metaTitle}+ maxLength={META_TITLE_MAX}+ onChange={(e) => change('metaTitle', e.target.value)}+ />+ </div>+ <div className="space-y-1">+ <Label htmlFor="cms-meta-description">{t('fields.metaDescription')}</Label>+ <Textarea+ id="cms-meta-description"+ value={fields.metaDescription}+ maxLength={META_DESCRIPTION_MAX}+ rows={3}+ onChange={(e) => change('metaDescription', e.target.value)}+ />+ <p className="text-xs text-muted-foreground">+ {t('fields.characters', { count: fields.metaDescription.trim().length })}+ </p>+ </div>+ </div>++ {(live || last) && (+ <p className="text-xs text-muted-foreground">+ {live ? (+ <>+ {t('live')}{' '}+ <a+ href={live}+ target="_blank"+ rel="noreferrer noopener"+ className="font-medium text-foreground underline underline-offset-2 [overflow-wrap:anywhere]"+ >+ {live}+ </a>+ </>+ ) : (+ last &&+ t(`last.${last.status}`, {+ when: format.dateTime(new Date(last.at), {+ dateStyle: 'medium',+ timeStyle: 'short',+ }),+ })+ )}+ </p>+ )}++ {/* Unread, a page sent before under another slug could land in the+ CMS twice: the send waits for the read (as the bulk send does). */}+ {kept === null && (+ <div+ role="alert"+ className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-sm text-red-700 dark:text-red-400"+ >+ <span className="min-w-0 flex-1">{t('readFailed')}</span>+ {/* Kept in place while it reads again, so focus stays on it. */}+ <Button+ size="sm"+ variant="outline"+ disabled={retrying}+ aria-label={t('retry')}+ onClick={() => {+ setRetrying(true);+ setAttempt((n) => n + 1);+ }}+ >+ {retrying ? <LoadingDots /> : t('retry')}+ </Button>+ </div>+ )}++ {problem && (+ <p role="alert" className="text-sm text-red-700 dark:text-red-400">+ {problemText(problem)}+ </p>+ )}++ <DialogFooter className="gap-2">+ <Button variant="outline" disabled={sending} onClick={onClose}>+ {t('cancel')}+ </Button>+ <Button+ disabled={+ sending || pageProblem !== null || placeholders > 0 || wrong !== null || !kept+ }+ onClick={() => void send()}+ >+ {sending && <LoadingDots className="mr-1" />}+ {sending ? t('sending') : t('send')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}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.tsxindex 4ea69476f..eda68d2c5 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@@ -4,7 +4,7 @@ import { NextIntlClientProvider } from 'next-intl';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../../../messages/en.json';import type { Editor } from '@tiptap/core';-import { RoleProvider } from '@/components/providers/role-provider';+import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';import type { ContentDraft } from '@/lib/content/drafts';import type { DraftSuggestion } from '@/lib/content/suggestions';import { passageKey, type CitedPassage } from '@/lib/content/cited-passages';@@ -129,6 +129,9 @@ vi.mock('mammoth', () => ({vi.mock('sonner', () => ({ toast }));const saveBlob = vi.hoisted(() => vi.fn());vi.mock('@/lib/download', () => ({ saveBlob }));+const readDraftCms = vi.hoisted(() => vi.fn());+const sendPagesToCms = vi.hoisted(() => vi.fn());+vi.mock('@/lib/content/cms-send-client', () => ({ readDraftCms, sendPagesToCms }));(globalThis as typeof globalThis & {@@ -202,11 +205,11 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({let container: HTMLDivElement;let root: Root;-async function renderPage() {+async function renderPage(role: TeamRole = 'admin') {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages}>- <RoleProvider role="admin">+ <RoleProvider role={role}><ContentEditorPage /></RoleProvider></NextIntlClientProvider>,@@ -2971,6 +2974,161 @@ describe('the side panel', () => {});});+ describe('Send to CMS (#1331)', () => {+ beforeEach(() => {+ readDraftCms.mockReset().mockResolvedValue({ fields: {}, publishedUrl: null, last: null });+ sendPagesToCms.mockReset().mockResolvedValue({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'sent' }],+ });+ getContentAuthors.mockResolvedValue({+ authors: [],+ brands: [{ id: 'b1', name: 'Acme' }],+ me: { id: 'u1', role: 'admin' },+ });+ });+ afterEach(() => {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ });+ const dialog = () => document.querySelector('[role="dialog"]');+ const inDialog = (name: string) =>+ [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')].find(+ (b) => b.textContent === name,+ )!;++ it('sends the page to the brand’s webhook from the header', async () => {+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ await act(async () => button('Send to CMS')!.click());+ expect(dialog()!.textContent).toContain('Send to CMS');+ expect(document.querySelector<HTMLInputElement>('#cms-slug')!.value).toBe(+ 'pipeline-forecasting',+ );+ await act(async () => inDialog('Send').click());+ expect(sendPagesToCms).toHaveBeenCalledWith('b1', [+ expect.objectContaining({+ draftId: 'd1',+ title: 'Pipeline forecasting',+ slug: 'pipeline-forecasting',+ html: '<p>Teams trust it.</p>',+ // Authors come with Quality (CE-038): while it is off, none goes.+ author: null,+ }),+ ]);+ expect(dialog()).toBeNull();+ });++ it('opens Before you publish first while Quality is on', async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';+ getContentDraft.mockResolvedValue(draft({ pageType: 'blog_post' }));+ await renderPage();+ await act(async () => button('Send to CMS')!.click());+ expect(dialog()!.textContent).toContain('Before you publish');+ expect(readDraftCms).not.toHaveBeenCalled();+ await act(async () => inDialog('Continue to send').click());+ expect(dialog()!.textContent).toContain('Meta description');+ expect(readDraftCms).toHaveBeenCalledWith('d1');+ // Closed, so no open dialog is left for the tests after.+ await act(async () => inDialog('Cancel').click());+ expect(dialog()).toBeNull();+ });++ const editAsHtml = async (html: string) => {+ await act(async () => button('Edit as HTML')!.click());+ const source = container.querySelector('textarea')!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(+ source,+ html,+ );+ source.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await act(async () => button('Back to visual')!.click());+ };++ it('saves what is waiting before it sends, as Mark ready does', async () => {+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ await editAsHtml('<h1>Pipeline forecasting</h1><p>Edited.</p>');+ expect(saveContentDraft).not.toHaveBeenCalled();+ await act(async () => button('Send to CMS')!.click());+ await act(async () => {});+ expect(saveContentDraft).toHaveBeenCalledWith(+ 'd1',+ expect.objectContaining({ bodyHtml: '<h1>Pipeline forecasting</h1><p>Edited.</p>' }),+ );+ expect(saveContentDraft.mock.invocationCallOrder[0]).toBeLessThan(+ readDraftCms.mock.invocationCallOrder[0],+ );+ expect(document.querySelector<HTMLTextAreaElement>('#cms-meta-description')!.value).toBe(+ 'Edited.',+ );+ await act(async () => inDialog('Cancel').click());+ expect(dialog()).toBeNull();+ });++ it('sends no page it can’t save', async () => {+ // A teammate or the agent changed the page meanwhile: this tab's version can't go.+ saveContentDraft.mockResolvedValue({ ok: false, reason: 'conflict' });+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ await editAsHtml('<h1>Pipeline forecasting</h1><p>Edited.</p>');+ await act(async () => button('Send to CMS')!.click());+ await act(async () => {});+ expect(toast.error).toHaveBeenCalledWith(+ "The page has changes that aren't saved, so it wasn't sent.",+ );+ expect(dialog()).toBeNull();+ expect(readDraftCms).not.toHaveBeenCalled();+ });++ it('waits for HTML edited in the HTML view to be applied', async () => {+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ await act(async () => button('Edit as HTML')!.click());+ const source = container.querySelector('textarea')!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(+ source,+ '<h1>Pipeline forecasting</h1><p>Not applied.</p>',+ );+ source.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await act(async () => button('Send to CMS')!.click());+ expect(toast.error).toHaveBeenCalledWith(+ "Apply or discard your HTML changes first: they aren't in the page yet.",+ );+ expect(dialog()).toBeNull();+ expect(saveContentDraft).not.toHaveBeenCalled();+ });++ it('takes one click while it saves', async () => {+ let saved: (value: unknown) => void = () => {};+ saveContentDraft.mockReturnValue(new Promise((resolve) => (saved = resolve)));+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ await editAsHtml('<h1>Pipeline forecasting</h1><p>Edited.</p>');+ await act(async () => button('Send to CMS')!.click());+ expect(button('Send to CMS')!.disabled).toBe(true);+ await act(async () => button('Send to CMS')!.click());+ expect(saveContentDraft).toHaveBeenCalledTimes(1);+ await act(async () => saved({ ok: true, updatedAt: '2026-10-20T10:01:00Z', bodyHash: 'h1' }));+ await act(async () => {});+ expect(dialog()!.textContent).toContain('Send to CMS');+ await act(async () => inDialog('Cancel').click());+ });++ it('is for admins and managers only', async () => {+ getContentDraft.mockResolvedValue(draft());+ await renderPage('analyst');+ expect(button('Send to CMS')).toBeUndefined();+ await act(async () => root.unmount());+ root = createRoot(container);+ await renderPage('manager');+ expect(button('Send to CMS')).toBeDefined();+ });+ });+describe('Export (CE-057)', () => {beforeEach(() => {process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';@@ -3356,8 +3514,12 @@ describe('the side panel', () => {await renderPage();await act(async () => nextButton()!.click());expect(basket()).not.toBeNull();- const elsewhere = document.createElement('button');- document.body.append(elsewhere);+ // The page's own text, as a reader clicks back into it: a button put in+ // the document after the basket opened reads as another app's, which a+ // popover doesn't close for.+ const elsewhere = container.querySelector<HTMLElement>('.ProseMirror')!;+ // ProseMirror reads a click's place from the point: jsdom has none.+ document.elementFromPoint = () => null;try {await act(async () => {elsewhere.focus();@@ -3369,7 +3531,7 @@ describe('the side panel', () => {expect(basket()).toBeNull();expect(document.activeElement).toBe(elsewhere);} finally {- elsewhere.remove();+ delete (document as { elementFromPoint?: unknown }).elementFromPoint;}});diff --git a/web/src/lib/actions/content-webhook.test.ts b/web/src/lib/actions/content-webhook.test.tsnew file mode 100644index 000000000..5e4cda776--- /dev/null+++ b/web/src/lib/actions/content-webhook.test.ts@@ -0,0 +1,48 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The brand's webhook keeps the events it is subscribed to: Content page+ * sent (#1331) among them, anything else left out.+ */++let upserts: unknown[];++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ from: () => {+ let value: Record<string, unknown> = {};+ const chain: Record<string, unknown> = {+ upsert: (v: Record<string, unknown>) => ((value = v), upserts.push(v), chain),+ select: () => chain,+ single: async () => ({ data: { id: 'w1', ...value }, error: null }),+ };+ return chain;+ },+ })),+}));++const { saveWebhookConfig } = await import('./content');++beforeEach(() => {+ upserts = [];+});++describe('saveWebhookConfig', () => {+ it('keeps Content page sent and leaves out what no webhook sends', async () => {+ const saved = await saveWebhookConfig('brand-1', {+ webhookUrl: 'https://hooks.example/abc',+ events: ['content_draft.sent', 'opportunity.sent', 'content_draft.sent', 'page.deleted'],+ });+ expect(upserts).toEqual([+ expect.objectContaining({ events: ['content_draft.sent', 'opportunity.sent'] }),+ ]);+ expect(saved.events).toEqual(['content_draft.sent', 'opportunity.sent']);+ });++ it('needs one event it sends', async () => {+ await expect(+ saveWebhookConfig('brand-1', { webhookUrl: 'https://hooks.example/abc', events: ['x'] }),+ ).rejects.toThrow('Select at least one webhook event.');+ expect(upserts).toEqual([]);+ });+});diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.tsindex a53ee295e..8899f9913 100644--- a/web/src/lib/actions/content.ts+++ b/web/src/lib/actions/content.ts@@ -605,7 +605,12 @@ export async function saveWebhookConfig(},): Promise<WebhookConfig> {const supabase = await createClient();- const allowedEvents = ['opportunity.sent', 'daily_pulse.created', 'action_task.sent'];+ const allowedEvents = [+ 'opportunity.sent',+ 'daily_pulse.created',+ 'action_task.sent',+ 'content_draft.sent',+ ];const events = Array.from(new Set(config.events)).filter((event) =>allowedEvents.includes(event),);diff --git a/web/src/lib/content/cms-send-client.test.ts b/web/src/lib/content/cms-send-client.test.tsnew file mode 100644index 000000000..dca048e89--- /dev/null+++ b/web/src/lib/content/cms-send-client.test.ts@@ -0,0 +1,167 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { CmsPage } from './cms-send';++/**+ * Send to CMS from the browser (#1331): through the API's proxy with the+ * session's token, its errors as the server names them, and the draft's kept+ * fields and last send read when the dialog opens.+ */++let session: { access_token: string } | null;+let reads: Record<string, { data: unknown; error: unknown }>;+const filters: [string, string, unknown][] = [];++vi.mock('@/config/api', () => ({ BROWSER_API_BASE_URL: '/api/aeo' }));+vi.mock('@/lib/supabase/client', () => ({+ createClient: () => ({+ auth: { getSession: async () => ({ data: { session } }) },+ from: (table: string) => {+ const chain: Record<string, unknown> = {+ select: () => chain,+ eq: (col: string, v: unknown) => (filters.push([table, col, v]), chain),+ order: () => chain,+ limit: () => chain,+ maybeSingle: async () => reads[table],+ };+ return chain;+ },+ }),+}));++const { readDraftCms, sendPagesToCms } = await import('./cms-send-client');++const page: CmsPage = {+ draftId: 'd1',+ title: 'Pour-over',+ slug: 'pour-over',+ metaTitle: 'Pour-over',+ metaDescription: 'Brew it slowly.',+ html: '<p>Brew it slowly.</p>',+ author: null,+ featuredImage: null,+};+const fetchMock = vi.fn();+const answer = (status: number, body: unknown) =>+ fetchMock.mockResolvedValueOnce({ ok: status < 400, status, json: async () => body });++beforeEach(() => {+ session = { access_token: 'token-1' };+ filters.length = 0;+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ vi.spyOn(console, 'error').mockImplementation(() => {});+});+afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('sendPagesToCms', () => {+ it('posts the pages with the session’s token and gives what was sent', async () => {+ answer(200, { batchId: 'b1', deliveries: [{ id: 'x1', draftId: 'd1', status: 'sent' }] });+ const result = await sendPagesToCms('brand-1', [page]);+ expect(fetchMock).toHaveBeenCalledWith('/api/aeo/api/content-drafts/send', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer token-1' },+ body: JSON.stringify({ brandId: 'brand-1', pages: [page] }),+ });+ expect(result).toEqual({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'sent' }],+ });+ });++ it('gives the server’s reason, and the field a 400 names', async () => {+ answer(409, { code: 'webhook_not_subscribed' });+ expect(await sendPagesToCms('brand-1', [page])).toEqual({+ ok: false,+ code: 'webhook_not_subscribed',+ field: null,+ });+ answer(400, { code: 'invalid', field: 'pages.0.slug' });+ expect(await sendPagesToCms('brand-1', [page])).toEqual({+ ok: false,+ code: 'invalid',+ field: 'pages.0.slug',+ });+ });++ it('reads the session, another workspace and the rate limiter as other calls do', async () => {+ answer(401, { error: 'Unauthorized' });+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ code: 'session' });+ answer(403, { error: 'Not in your workspace', code: 'not_in_workspace' });+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ code: 'workspace' });+ answer(429, { message: 'Too many requests' });+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ code: 'busy' });+ // A send's own reason first: the day's limit is a 429 too.+ answer(429, { code: 'daily_limit' });+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ code: 'daily_limit' });+ session = null;+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ code: 'session' });+ expect(fetchMock).toHaveBeenCalledTimes(4);+ });++ it('reads an unknown code, a body that isn’t JSON or no answer as failed', async () => {+ answer(409, { code: 'conflict' });+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ ok: false, code: 'failed' });+ fetchMock.mockResolvedValueOnce({+ ok: false,+ status: 502,+ json: async () => Promise.reject(new Error('not JSON')),+ });+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ ok: false, code: 'failed' });+ fetchMock.mockRejectedValueOnce(new Error('offline'));+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ ok: false, code: 'failed' });+ // No route yet (the API before the send was deployed).+ answer(404, {});+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ ok: false, code: 'failed' });+ });+});++describe('readDraftCms', () => {+ it('gives the kept fields, where the page went live and its last send', async () => {+ reads = {+ content_drafts: {+ data: {+ slug: 'coffee',+ meta_title: null,+ meta_description: 'Slowly.',+ published_url: 'https://example.com/coffee',+ },+ error: null,+ },+ content_draft_deliveries: {+ data: {+ status: 'sent',+ created_at: '2026-10-24T10:00:00Z',+ sent_at: '2026-10-24T10:00:02Z',+ error: null,+ },+ error: null,+ },+ };+ expect(await readDraftCms('d1')).toEqual({+ fields: { slug: 'coffee', metaTitle: undefined, metaDescription: 'Slowly.' },+ publishedUrl: 'https://example.com/coffee',+ last: { status: 'sent', at: '2026-10-24T10:00:02Z', error: null },+ });+ expect(filters).toEqual([+ ['content_drafts', 'id', 'd1'],+ ['content_draft_deliveries', 'draft_id', 'd1'],+ ]);+ });++ it('gives no last send when its read fails, and null when the draft’s does', async () => {+ reads = {+ content_drafts: {+ data: { slug: null, meta_title: null, meta_description: null, published_url: null },+ error: null,+ },+ content_draft_deliveries: { data: null, error: { message: 'no such table' } },+ };+ expect((await readDraftCms('d1'))?.last).toBeNull();+ // Before its columns are there (00262), the dialog fills the fields from the page.+ reads.content_drafts = { data: null, error: { message: 'column "slug" does not exist' } };+ expect(await readDraftCms('d1')).toBeNull();+ });+});diff --git a/web/src/lib/content/cms-send-client.ts b/web/src/lib/content/cms-send-client.tsnew file mode 100644index 000000000..95d8520fe--- /dev/null+++ b/web/src/lib/content/cms-send-client.ts@@ -0,0 +1,134 @@+import { BROWSER_API_BASE_URL } from '@/config/api';+import { apiFailure } from '@/lib/api-failure';+import { createClient } from '@/lib/supabase/client';+import type { CmsFields, CmsPage } from '@/lib/content/cms-send';++/**+ * Send to CMS from the browser (#1331), through the API's same-origin proxy:+ * not a server action, whose body is limited to 1 MB (25 pages are more) and+ * which Next runs one at a time, behind the editor's own.+ */++/** Why a send didn't go, as the server names it. */+export type CmsSendError =+ | 'no_webhook'+ | 'webhook_not_subscribed'+ | 'daily_limit'+ | 'forbidden'+ | 'not_found'+ | 'invalid'+ | 'failed'+ // Not a send's own: the session, another workspace's brand, the rate limiter.+ | 'session'+ | 'workspace'+ | 'busy';++export interface CmsDelivery {+ id: string;+ draftId: string;+ status: 'queued' | 'sent' | 'failed' | 'published';+ /** What the webhook answered, when it did. */+ http_status?: number | null;+ /** Why it failed, as the server wrote it ("The webhook could not be reached"). */+ error?: string | null;+}++export type CmsSendResult =+ | { ok: true; deliveries: CmsDelivery[] }+ | { ok: false; code: CmsSendError; field: string | null };++/** A send's own reasons, by the server's code. */+const KNOWN: readonly CmsSendError[] = [+ 'no_webhook',+ 'webhook_not_subscribed',+ 'daily_limit',+ 'forbidden',+ 'not_found',+ 'invalid',+];++/** The reasons any call can fail for, as the other calls read them (BUG-001). */+const GENERAL: readonly CmsSendError[] = ['session', 'workspace', 'busy'];++/** Sends pages of one brand to its webhook: one is sent before this answers, more go on. */+export async function sendPagesToCms(brandId: string, pages: CmsPage[]): Promise<CmsSendResult> {+ try {+ const {+ data: { session },+ } = await createClient().auth.getSession();+ if (!session) return { ok: false, code: 'session', field: null };+ const res = await fetch(`${BROWSER_API_BASE_URL}/api/content-drafts/send`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ brandId, pages }),+ });+ const body = (await res.json().catch(() => ({}))) as {+ code?: string;+ field?: string | null;+ deliveries?: CmsDelivery[];+ };+ if (!res.ok) {+ const general = apiFailure(res.status, body);+ const code =+ KNOWN.find((c) => c === body.code) ?? GENERAL.find((c) => c === general) ?? 'failed';+ return { ok: false, code, field: body.field ?? null };+ }+ return { ok: true, deliveries: body.deliveries ?? [] };+ } catch (err) {+ console.error('Failed to send to the CMS:', err);+ return { ok: false, code: 'failed', field: null };+ }+}++/** What a draft keeps of its sends: its slug and meta, where it went live, and its last send. */+export interface DraftCms {+ fields: Partial<CmsFields>;+ publishedUrl: string | null;+ last: { status: CmsDelivery['status']; at: string; error: string | null } | null;+}++/**+ * The draft's kept fields and last send, read when the Send dialog opens.+ * Null when they can't be read: the dialog then holds Send, with Try again+ * (a page sent before under another slug could otherwise land twice).+ */+export async function readDraftCms(draftId: string): Promise<DraftCms | null> {+ const supabase = createClient();+ const [draft, last] = await Promise.all([+ supabase+ .from('content_drafts')+ .select('slug, meta_title, meta_description, published_url')+ .eq('id', draftId)+ .maybeSingle(),+ supabase+ .from('content_draft_deliveries')+ .select('status, created_at, sent_at, error')+ .eq('draft_id', draftId)+ .order('created_at', { ascending: false })+ .limit(1)+ .maybeSingle(),+ ]);+ if (draft.error || !draft.data) {+ if (draft.error) console.error('Failed to read the page’s CMS fields:', draft.error);+ return null;+ }+ const delivery = last.error ? null : last.data;+ return {+ fields: {+ slug: draft.data.slug ?? undefined,+ metaTitle: draft.data.meta_title ?? undefined,+ metaDescription: draft.data.meta_description ?? undefined,+ },+ publishedUrl: draft.data.published_url,+ last: delivery+ ? {+ status: delivery.status as CmsDelivery['status'],+ at: delivery.sent_at ?? delivery.created_at,+ error: delivery.error,+ }+ : null,+ };+}diff --git a/web/src/lib/content/cms-send.test.ts b/web/src/lib/content/cms-send.test.tsnew file mode 100644index 000000000..6211a8808--- /dev/null+++ b/web/src/lib/content/cms-send.test.ts@@ -0,0 +1,158 @@+import { describe, expect, it } from 'vitest';+import { cmsFields, cmsFieldsProblem, cmsPage, cmsPageProblem, type CmsFields } from './cms-send';+import type { PageFields } from './ready-to-publish';++/**+ * Send to CMS (#1331): the fields a send starts with, when they can't go,+ * and the page as the server takes it.+ */++const page: PageFields = {+ metaTitle: 'Pour-over coffee',+ metaDescription: 'Brew it slowly.',+ slug: 'pour-over-coffee',+ author: 'Ada Lovelace',+ featuredImage: null,+};+const fields: CmsFields = {+ slug: 'pour-over-coffee',+ metaTitle: 'Pour-over coffee',+ metaDescription: 'Brew it slowly.',+};++describe('cmsFields', () => {+ it('cuts the page’s meta title at a word near 60 characters, not a kept one', () => {+ const cut = (metaTitle: string) => cmsFields({ ...page, metaTitle }, null).metaTitle;+ const long = `${'Pour-over coffee at home: '.repeat(4)}a guide`;+ // At the last space that fits, without the colon the cut leaves.+ expect(cut(long)).toBe('Pour-over coffee at home: Pour-over coffee at home');+ expect(cmsFields({ ...page, metaTitle: long }, { metaTitle: long }).metaTitle).toBe(long);+ // Exactly 60 stays whole.+ expect(cut('a'.repeat(60))).toBe('a'.repeat(60));+ // A no-break space is a space too.+ expect(cut(`${'b'.repeat(40)}\u00a0${'c'.repeat(30)}`)).toBe('b'.repeat(40));+ // No space past half: cut at 60 characters, never inside an emoji.+ const emoji = `${'d'.repeat(59)}☕️☕️`;+ expect(Array.from(cut(emoji))).toHaveLength(60);+ expect(cut(`${'e'.repeat(59)}😀x`)).toBe(`${'e'.repeat(59)}😀`);+ });++ it('starts from what the draft kept, else from the page', () => {+ expect(cmsFields(page, null)).toEqual(fields);+ expect(cmsFields(page, { slug: 'coffee', metaDescription: '' })).toEqual({+ ...fields,+ slug: 'coffee',+ });+ });+});++describe('cmsFieldsProblem', () => {+ it('takes letters of any script, digits, dots, - and _ in a slug', () => {+ expect(cmsFieldsProblem(fields)).toBeNull();+ expect(cmsFieldsProblem({ ...fields, slug: 'çay-demleme_2.0' })).toBeNull();+ expect(cmsFieldsProblem({ ...fields, slug: ' coffee ' })).toBeNull();+ });++ it('names the field that cannot go', () => {+ expect(cmsFieldsProblem({ ...fields, slug: '' })).toBe('slug');+ expect(cmsFieldsProblem({ ...fields, slug: 'pour over' })).toBe('slug');+ expect(cmsFieldsProblem({ ...fields, slug: 'blog/coffee' })).toBe('slug');+ expect(cmsFieldsProblem({ ...fields, slug: '..' })).toBe('slug');+ expect(cmsFieldsProblem({ ...fields, slug: 'a'.repeat(201) })).toBe('slug');+ expect(cmsFieldsProblem({ ...fields, metaTitle: 'a'.repeat(301) })).toBe('metaTitle');+ expect(cmsFieldsProblem({ ...fields, metaDescription: 'a'.repeat(501) })).toBe(+ 'metaDescription',+ );+ });+});++describe('cmsPageProblem', () => {+ it('needs a title the CMS takes, and something under the H1', () => {+ expect(cmsPageProblem('Pour-over', '<h1>Pour-over</h1><p>Brew it.</p>')).toBeNull();+ expect(+ cmsPageProblem('Pour-over', '<h1>Pour-over</h1><img src="https://cdn.example/a.jpg">'),+ ).toBeNull();+ expect(cmsPageProblem(' ', '<p>Brew it.</p>')).toBe('noTitle');+ expect(cmsPageProblem('a'.repeat(301), '<p>Brew it.</p>')).toBe('longTitle');+ // A new page: its H1 and an empty paragraph.+ expect(cmsPageProblem('Pour-over', '<h1>Pour-over</h1><p></p>')).toBe('empty');+ expect(cmsPageProblem('Pour-over', '')).toBe('empty');+ });+});++describe('cmsPage', () => {+ const html =+ '<h1>Pour-over</h1>\n<p>Brew it slowly.</p>\n<img src="https://cdn.example/cup.jpg" alt="A cup">';++ it('sends the page without its H1, its fields trimmed', () => {+ expect(+ cmsPage({+ draftId: 'd1',+ title: ' Pour-over ',+ html,+ fields: { slug: ' coffee ', metaTitle: ' Coffee ', metaDescription: ' Slowly. ' },+ page: { ...page, featuredImage: 'https://cdn.example/cup.jpg' },+ byline: null,+ }),+ ).toEqual({+ draftId: 'd1',+ title: 'Pour-over',+ slug: 'coffee',+ metaTitle: 'Coffee',+ metaDescription: 'Slowly.',+ html: '<p>Brew it slowly.</p>\n<img src="https://cdn.example/cup.jpg" alt="A cup">',+ author: 'Ada Lovelace',+ featuredImage: { src: 'https://cdn.example/cup.jpg', alt: 'A cup' },+ });+ });++ it('keeps the brand’s byline line, which went under the H1', () => {+ const sent = cmsPage({+ draftId: 'd1',+ title: 'Pour-over',+ html,+ fields,+ page,+ byline: 'By Ada',+ });+ expect(sent.html.startsWith('<p>By Ada</p>\n<p>Brew it slowly.</p>')).toBe(true);+ });++ it('sends no author while none is known, and only an https featured image', () => {+ const sent = cmsPage({+ draftId: 'd1',+ title: 'Pour-over',+ html: '<p>Brew it.</p><img src="http://cdn.example/cup.jpg">',+ fields,+ page: { ...page, author: '', featuredImage: 'http://cdn.example/cup.jpg' },+ byline: null,+ });+ expect(sent.author).toBeNull();+ expect(sent.featuredImage).toBeNull();+ });++ it('keeps the author, alt text and image within what the server takes', () => {+ const src = 'https://cdn.example/cup.jpg';+ const sent = cmsPage({+ draftId: 'd1',+ title: 'Pour-over',+ html: `<p>Brew it.</p><img src="${src}" alt="${'a'.repeat(600)}">`,+ fields,+ page: { ...page, author: 'b'.repeat(250), featuredImage: src },+ byline: null,+ });+ expect(sent.author).toBe('b'.repeat(200));+ expect(sent.featuredImage).toEqual({ src, alt: 'a'.repeat(500) });+ const long = `https://cdn.example/${'c'.repeat(2048)}.jpg`;+ expect(+ cmsPage({+ draftId: 'd1',+ title: 'Pour-over',+ html: `<p>Brew it.</p><img src="${long}">`,+ fields,+ page: { ...page, featuredImage: long },+ byline: null,+ }).featuredImage,+ ).toBeNull();+ });+});diff --git a/web/src/lib/content/cms-send.ts b/web/src/lib/content/cms-send.tsnew file mode 100644index 000000000..b2309cf3d--- /dev/null+++ b/web/src/lib/content/cms-send.ts@@ -0,0 +1,143 @@+import {+ fragment,+ withByline,+ withoutLeadingH1,+ type PageFields,+} from '@/lib/content/ready-to-publish';++/**+ * Send to CMS (#1331): a Content Editor page as the server takes it+ * (POST /api/content-drafts/send) and sends to the brand's webhook. The HTML+ * is the page ready to paste (CE-057: publishableHtml, placeholders filled),+ * with the brand's byline line and without its H1, which the CMS's own title+ * field carries; slug and meta are filled from the page and what the person+ * changed wins.+ */++export interface CmsPage {+ draftId: string;+ title: string;+ slug: string;+ metaTitle: string;+ metaDescription: string;+ html: string;+ author: string | null;+ featuredImage: { src: string; alt: string } | null;+}++/** The fields a send fills in, editable in the Send dialog and kept on the draft. */+export interface CmsFields {+ slug: string;+ metaTitle: string;+ metaDescription: string;+}++/** As the server's: letters, digits, '-', '_' and single dots. */+const SLUG_PATTERN = /^(?!.*\.\.)[\p{L}\p{N}._-]+$/u;+export const META_TITLE_MAX = 300;+export const META_DESCRIPTION_MAX = 500;+// The server's other limits, which the page itself fills.+const TITLE_MAX = 300;+const AUTHOR_MAX = 200;+const ALT_MAX = 500;+const IMAGE_SRC_MAX = 2048;++/** A meta title from the page stops about here, at a word, as search results cut it (#1331). */+const META_TITLE_PREFILL = 60;++/**+ * Text up to `max` characters, cut at the last space that fits (any space,+ * a no-break one too), or at `max` with none past half, never inside a+ * character (an emoji); without the punctuation a cut leaves at its end.+ */+function upToWord(text: string, max: number): string {+ const chars = Array.from(text);+ if (chars.length <= max) return text;+ let space = -1;+ for (let i = max; i >= 0; i--) {+ if (/\s/u.test(chars[i])) {+ space = i;+ break;+ }+ }+ const cut = chars.slice(0, space > max / 2 ? space : max).join('');+ return cut.replace(/[\s,:;|–—-]+$/u, '');+}++/**+ * What a send starts with: what the draft keeps, else what the page gives,+ * its meta title cut at a word near 60 characters.+ */+export function cmsFields(fields: PageFields, kept: Partial<CmsFields> | null): CmsFields {+ return {+ slug: kept?.slug || fields.slug,+ metaTitle: kept?.metaTitle || upToWord(fields.metaTitle, META_TITLE_PREFILL),+ metaDescription: kept?.metaDescription || fields.metaDescription,+ };+}++/** Why the fields can't go as they are, or null. */+export function cmsFieldsProblem(+ fields: CmsFields,+): 'slug' | 'metaTitle' | 'metaDescription' | null {+ if (!SLUG_PATTERN.test(fields.slug.trim()) || fields.slug.trim().length > 200) return 'slug';+ if (fields.metaTitle.trim().length > META_TITLE_MAX) return 'metaTitle';+ if (fields.metaDescription.trim().length > META_DESCRIPTION_MAX) return 'metaDescription';+ return null;+}++/**+ * Why the page can't go yet, or null: the CMS needs a title, and a page+ * with no words or image under its H1 has nothing to publish.+ */+export function cmsPageProblem(+ title: string,+ html: string,+): 'noTitle' | 'longTitle' | 'empty' | null {+ if (!title.trim()) return 'noTitle';+ if (title.trim().length > TITLE_MAX) return 'longTitle';+ const body = fragment(withoutLeadingH1(html));+ if (!body.textContent?.trim() && !body.querySelector('img')) return 'empty';+ return null;+}++/** The image's alt text, where the page shows it. */+function altOf(html: string, src: string): string {+ const image = [...fragment(html).querySelectorAll('img')].find(+ (img) => img.getAttribute('src') === src,+ );+ return image?.getAttribute('alt') ?? '';+}++/** The page as it goes to the CMS. `html` is publishableHtml's, its placeholders filled. */+export function cmsPage({+ draftId,+ title,+ html,+ fields,+ page,+ byline,+}: {+ draftId: string;+ title: string;+ html: string;+ fields: CmsFields;+ /** pageFields' read of the page: its author and featured image. */+ page: PageFields;+ /** The byline line the brand puts in the content, or null. */+ byline: string | null;+}): CmsPage {+ const withLine = byline ? withByline(html, byline) : html;+ const src = page.featuredImage;+ const image = src?.startsWith('https://') && src.length <= IMAGE_SRC_MAX ? src : null;+ return {+ draftId,+ title: title.trim(),+ slug: fields.slug.trim(),+ metaTitle: fields.metaTitle.trim(),+ metaDescription: fields.metaDescription.trim(),+ html: withoutLeadingH1(withLine),+ author: page.author.trim().slice(0, AUTHOR_MAX) || null,+ featuredImage: image ? { src: image, alt: altOf(html, image).slice(0, ALT_MAX) } : null,+ };+}diff --git a/web/src/lib/content/ready-to-publish.test.ts b/web/src/lib/content/ready-to-publish.test.tsindex 368350526..adea26d89 100644--- a/web/src/lib/content/ready-to-publish.test.ts+++ b/web/src/lib/content/ready-to-publish.test.ts@@ -265,6 +265,19 @@ describe('pageFields', () => {).toBe('');});+ it('cuts a long title’s slug at a word, up to 80 characters', () => {+ const slug = (title: string) =>+ pageFields({ title, html: '', sourceUrl: null, author: null, teamByline: '' }).slug;+ expect(+ slug(+ 'Defend the coffee subscription comparison with up-to-date pricing and shipping details',+ ),+ ).toBe('defend-the-coffee-subscription-comparison-with-up-to-date-pricing-and-shipping');+ // A word that ends at 80 stays whole; one word longer than 80 is cut.+ expect(slug(`${'a'.repeat(80)} b`)).toBe('a'.repeat(80));+ expect(slug('b'.repeat(90))).toBe('b'.repeat(80));+ });+it('cuts a first sentence too long to fit at a word', () => {const long = `${'Pour slowly '.repeat(20)}now.`;const { metaDescription } = pageFields({diff --git a/web/src/lib/content/ready-to-publish.ts b/web/src/lib/content/ready-to-publish.tsindex 93d4d2c9c..cd2af7d16 100644--- a/web/src/lib/content/ready-to-publish.ts+++ b/web/src/lib/content/ready-to-publish.ts@@ -400,7 +400,11 @@ function slugOf(title: string, sourceUrl: string | null): string {// Not an address, or not one to read: the title's slug.}}- return slugify(title).slice(0, 80).replace(/-+$/, '');+ const slug = slugify(title);+ if (slug.length <= 80) return slug;+ // Cut at a word, not inside one: it becomes the page's address (Send to CMS).+ const cut = slug.slice(0, 81).lastIndexOf('-');+ return slug.slice(0, cut > 0 ? cut : 80).replace(/-+$/, '');}/**diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex c0738f036..3634fb5d3 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -990,14 +990,19 @@ export type Database = {created_by: string | nullid: stringmethod: string+ meta_description: string | null+ meta_title: string | nullopportunity_id: string | nullpage_type: string | nullpage_type_source: stringprompt_ids: string[]+ published_at: string | null+ published_url: string | nullrules: Json | nullsource_url: string | nullscore_after: number | nullscore_before: number | null+ slug: string | nullstatus: stringtitle: stringupdated_at: string@@ -1018,14 +1023,19 @@ export type Database = {created_by?: string | nullid?: stringmethod?: string+ meta_description?: string | null+ meta_title?: string | nullopportunity_id?: string | nullpage_type?: string | nullpage_type_source?: stringprompt_ids?: string[]+ published_at?: string | null+ published_url?: string | nullrules?: Json | nullsource_url?: string | nullscore_after?: number | nullscore_before?: number | null+ slug?: string | nullstatus?: stringtitle?: stringupdated_at?: string@@ -1046,14 +1056,19 @@ export type Database = {created_by?: string | nullid?: stringmethod?: string+ meta_description?: string | null+ meta_title?: string | nullopportunity_id?: string | nullpage_type?: string | nullpage_type_source?: stringprompt_ids?: string[]+ published_at?: string | null+ published_url?: string | nullrules?: Json | nullsource_url?: string | nullscore_after?: number | nullscore_before?: number | null+ slug?: string | nullstatus?: stringtitle?: stringupdated_at?: string@@ -1229,6 +1244,95 @@ export type Database = {},]}+ content_draft_deliveries: {+ Row: {+ batch_id: string | null+ brand_id: string+ created_at: string+ draft_id: string | null+ error: string | null+ external_id: string | null+ http_status: number | null+ id: string+ organization_id: string+ published_at: string | null+ published_url: string | null+ response_excerpt: string | null+ sent_at: string | null+ sent_by: string | null+ slug: string | null+ status: string+ title: string+ }+ Insert: {+ batch_id?: string | null+ brand_id: string+ created_at?: string+ draft_id?: string | null+ error?: string | null+ external_id?: string | null+ http_status?: number | null+ id?: string+ organization_id: string+ published_at?: string | null+ published_url?: string | null+ response_excerpt?: string | null+ sent_at?: string | null+ sent_by?: string | null+ slug?: string | null+ status?: string+ title: string+ }+ Update: {+ batch_id?: string | null+ brand_id?: string+ created_at?: string+ draft_id?: string | null+ error?: string | null+ external_id?: string | null+ http_status?: number | null+ id?: string+ organization_id?: string+ published_at?: string | null+ published_url?: string | null+ response_excerpt?: string | null+ sent_at?: string | null+ sent_by?: string | null+ slug?: string | null+ status?: string+ title?: string+ }+ Relationships: [+ {+ foreignKeyName: "content_draft_deliveries_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "content_draft_deliveries_draft_id_fkey"+ columns: ["draft_id"]+ isOneToOne: false+ referencedRelation: "content_drafts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "content_draft_deliveries_organization_id_fkey"+ columns: ["organization_id"]+ isOneToOne: false+ referencedRelation: "organizations"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "content_draft_deliveries_sent_by_fkey"+ columns: ["sent_by"]+ isOneToOne: false+ referencedRelation: "profiles"+ referencedColumns: ["id"]+ },+ ]+ }content_draft_ready_log: {Row: {created_at: string