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 the Library's selected pages to the CMS together (Send to CMS #1331, part 3b: bulk) (#1440)
Cihan281c2266116e
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 7862b4264..9b008ed6f 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3391,6 +3391,49 @@"openLive": "Published {when}: open the live page in a new tab","answered": "The webhook answered {status}."},+ "bulk": {+ "selected": "{count, plural, one {# page selected} other {# pages selected}}",+ "sendSelected": "Send to CMS",+ "clear": "Clear",+ "tooMany": "Up to {max} pages a send",+ "selectAll": "Select all pages listed",+ "selectRow": "Select {title}",+ "title": "{count, plural, one {Send # page to your CMS} other {Send # pages to your CMS}}",+ "description": "Each page goes to the brand's webhook as it is ready to publish, with the slug and meta of its last send, else the page's. Open a page in the editor to change them.",+ "readFailed": "Couldn't read the pages. Try again.",+ "retry": "Try again",+ "notFound": "A page was archived or deleted since you picked it. Close this, pick the pages again and send.",+ "invalidPage": "\u201c{title}\u201d can't go as it is: check its {field, select, slug {slug} metaTitle {meta title} metaDescription {meta description} title {title} html {page} other {page}} in the editor.",+ "untitled": "Untitled",+ "fixHint": "A page that can't go is left out: open it in the editor to fix it.",+ "ready": "Ready",+ "problems": {+ "noTitle": "No title",+ "longTitle": "Title over 300 characters",+ "empty": "Nothing to publish yet",+ "tooLong": "Over a million characters",+ "placeholders": "Placeholders to fill",+ "slug": "Needs a slug",+ "metaTitle": "Meta title over 300 characters",+ "metaDescription": "Meta description over 500 characters"+ },+ "notSent": "Not sent",+ "waiting": "Waiting",+ "queued": "Sending…",+ "failed": "Failed",+ "answered": "Webhook answered {status}",+ "sent": "Sent",+ "progress": "Sending: {done} of {total} done.",+ "summary": "{sent, plural, one {# page sent} other {# pages sent}}{failed, plural, =0 {.} one {, # failed.} other {, # failed.}}",+ "stillGoing": "The rest are still going: the Library shows each page's send as it lands.",+ "waitedOut": "The pages before {count, plural, one {it} other {them}} were still going after 30 minutes, so {count, plural, one {# page wasn't} other {# pages weren't}} sent. Send {count, plural, one {it} other {them}} again once they have gone.",+ "closedUnsent": "{count, plural, one {# page wasn't sent} other {# pages weren't sent}}: the dialog closed while the pages before {count, plural, one {it} other {them}} were still going. Send {count, plural, one {it} other {them}} again from the Library.",+ "skipped": "{count, plural, one {# page wasn't sent} other {# pages weren't sent}}: the workspace has sent 200 pages in the last 24 hours. Try again later.",+ "close": "Close",+ "cancel": "Cancel",+ "send": "{count, plural, one {Send # page} other {Send # pages}}",+ "sending": "Sending"+ },"deleteDialog": {"title": "Delete “{title}”?","description": "It leaves the Library for good, with its versions and suggestions. An Action Center task it was sent as stays. This can't be undone.",@@ -4207,6 +4250,7 @@"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.",+ "tooLong": "The page is over a million characters: shorten it to send it.","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.",@@ -4238,6 +4282,7 @@"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.",+ "too_large": "Too much to send in one go. Send fewer pages, or shorter ones.","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}"},diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.test.tsxnew file mode 100644index 000000000..cc485e7a8--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.test.tsx@@ -0,0 +1,408 @@+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 { CmsSource } from '@/lib/content/cms-send';+import type { ContentDraftListItem } from '@/lib/content/drafts';++const readCmsSources = vi.hoisted(() => vi.fn());+vi.mock('./_cms-sources', () => ({ readCmsSources }));+const toast = vi.hoisted(() => vi.fn());+vi.mock('sonner', () => ({ toast }));+const readKeptFields = vi.hoisted(() => vi.fn());+const readDeliveries = vi.hoisted(() => vi.fn());+const sendPagesToCms = vi.hoisted(() => vi.fn());+vi.mock('@/lib/content/cms-send-client', () => ({+ readKeptFields,+ readDeliveries,+ sendPagesToCms,+}));+// One request a page, so a test can refuse the second.+const oneByOne = vi.hoisted(() => ({ on: false }));+vi.mock('@/lib/content/cms-send', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/lib/content/cms-send')>();+ return {+ ...actual,+ cmsSendGroups: (pages: Parameters<typeof actual.cmsSendGroups>[0]) =>+ oneByOne.on ? pages.map((page) => [page]) : actual.cmsSendGroups(pages),+ };+});++const { BulkSendDialog } = await import('./_bulk-send-dialog');++/**+ * Send to CMS for the Library's selected rows (#1331): the pages that can+ * go, why the others can't, and their sends as the server makes them.+ */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const draft = (id: string, title: string) => ({ id, title }) as ContentDraftListItem;+const source = (id: string, title: string, body: string): CmsSource => ({+ draftId: id,+ title,+ html: `<h1>${title}</h1>\n${body}`,+ sourceUrl: null,+ author: null,+ teamByline: '',+ byline: null,+});+const drafts = [+ draft('d1', 'Pour-over'),+ draft('d2', 'Cold brew'),+ draft('d3', 'Espresso'),+ draft('d4', 'Latte art'),+];++let container: HTMLDivElement;+let root: Root;+const onClose = vi.fn();++async function render() {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <BulkSendDialog+ brandId="brand-1"+ drafts={drafts}+ brandName="Acme"+ brandLanguage="en"+ onClose={onClose}+ />+ </NextIntlClientProvider>,+ );+ });+}+const dialog = () => document.querySelector('[role="dialog"]')!;+const button = (name: string) =>+ [...dialog().querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === name)!;+/** Time going on, a read at a time: each read's answer renders before the next. */+async function tick(ms: number) {+ for (let left = ms; left > 0; left -= 2_000) {+ await act(async () => void (await vi.advanceTimersByTimeAsync(Math.min(2_000, left))));+ }+}+const lines = () => [...dialog().querySelectorAll('li')].map((li) => li.textContent);++beforeEach(() => {+ oneByOne.on = false;+ onClose.mockReset();+ readCmsSources.mockReset().mockResolvedValue(+ new Map([+ ['d1', source('d1', 'Pour-over', '<p>Brew it slowly.</p>')],+ ['d2', source('d2', 'Cold brew', '<p>Steep it [hours] hours.</p>')],+ ['d3', source('d3', 'Espresso', '<p>Pull a shot.</p>')],+ // d4 was deleted meanwhile: left out.+ ]),+ );+ readKeptFields.mockReset().mockResolvedValue(new Map([['d3', { slug: 'espresso-guide' }]]));+ readDeliveries.mockReset();+ toast.mockReset();+ sendPagesToCms.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.useRealTimers();+});++describe('BulkSendDialog', () => {+ it('sends the pages that can go, and reads their sends until they have gone', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ sendPagesToCms.mockResolvedValue({+ ok: true,+ deliveries: [+ { id: 'x1', draftId: 'd1', status: 'queued' },+ { id: 'x3', draftId: 'd3', status: 'queued' },+ ],+ skipped: 0,+ });+ readDeliveries+ .mockResolvedValueOnce([+ { id: 'x1', draftId: 'd1', status: 'sent', http_status: 200, error: null },+ { id: 'x3', draftId: 'd3', status: 'queued', http_status: null, error: null },+ ])+ .mockResolvedValueOnce([+ { id: 'x1', draftId: 'd1', status: 'sent', http_status: 200, error: null },+ // Deleted while it went: its send reads back with no draft.+ { id: 'x3', draftId: '', status: 'failed', http_status: 500, error: 'No' },+ ]);+ await render();+ expect(readCmsSources).toHaveBeenCalledWith(+ expect.objectContaining({ brandId: 'brand-1', draftIds: ['d1', 'd2', 'd3', 'd4'] }),+ );+ // The pages read: d4 was deleted meanwhile.+ expect(dialog().textContent).toContain('Send 3 pages to your CMS');+ expect(lines()).toEqual(['Pour-overReady', 'Cold brewPlaceholders to fill', 'EspressoReady']);+ expect(dialog().textContent).toContain("A page that can't go is left out");++ await act(async () => button('Send 2 pages').click());+ const [, pages] = sendPagesToCms.mock.calls[0] as [string, { draftId: string; slug: string }[]];+ expect(sendPagesToCms).toHaveBeenCalledTimes(1);+ expect(pages.map((page) => [page.draftId, page.slug])).toEqual([+ ['d1', 'pour-over'],+ // What it kept from its last send.+ ['d3', 'espresso-guide'],+ ]);+ expect(dialog().textContent).toContain('Sending: 0 of 2 done.');++ await act(async () => void (await vi.advanceTimersByTimeAsync(2_000)));+ expect(readDeliveries).toHaveBeenCalledWith(['x1', 'x3']);+ expect(dialog().textContent).toContain('Sending: 1 of 2 done.');+ await act(async () => void (await vi.advanceTimersByTimeAsync(2_000)));+ expect(dialog().querySelector('[role="status"]')!.textContent).toBe('1 page sent, 1 failed.');+ expect(lines()).toEqual([+ 'Pour-overSent',+ 'Cold brewPlaceholders to fill',+ 'EspressoWebhook answered 500',+ ]);+ // Done: no more reads.+ await act(async () => void (await vi.advanceTimersByTimeAsync(10_000)));+ expect(readDeliveries).toHaveBeenCalledTimes(2);++ await act(async () => button('Close').click());+ expect(onClose).toHaveBeenCalled();+ });++ it('says why nothing went, and keeps the pages to send again', async () => {+ sendPagesToCms.mockResolvedValue({ ok: false, code: 'webhook_not_subscribed', field: null });+ await render();+ await act(async () => button('Send 2 pages').click());+ expect(dialog().querySelector('[role="alert"]')!.textContent).toBe(+ 'The brand\'s webhook doesn\'t receive "Content page sent". Turn it on in Webhook Settings on Content Opportunities.',+ );+ expect(button('Send 2 pages').disabled).toBe(false);+ });++ it('keeps what went when a later request is refused for the day', async () => {+ oneByOne.on = true;+ sendPagesToCms+ .mockResolvedValueOnce({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'sent' }],+ skipped: 0,+ })+ .mockResolvedValueOnce({ ok: false, code: 'daily_limit', field: null });+ await render();+ await act(async () => button('Send 2 pages').click());+ expect(sendPagesToCms).toHaveBeenCalledTimes(2);+ expect(dialog().querySelector('[role="status"]')!.textContent).toBe('1 page sent.');+ expect(lines()).toEqual(['Pour-overSent', 'Cold brewPlaceholders to fill', 'EspressoNot sent']);+ expect(dialog().querySelector('[role="alert"]')!.textContent).toBe(+ 'This workspace has sent 200 pages in the last 24 hours. Try again later.',+ );+ });++ it('posts the next request once the last one’s pages have gone, one page at a time', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ oneByOne.on = true;+ sendPagesToCms+ .mockResolvedValueOnce({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'queued' }],+ skipped: 0,+ })+ .mockResolvedValueOnce({+ ok: true,+ deliveries: [{ id: 'x3', draftId: 'd3', status: 'sent' }],+ skipped: 0,+ });+ readDeliveries+ .mockResolvedValueOnce([{ id: 'x1', draftId: 'd1', status: 'queued' }])+ // A read that fails is read again.+ .mockResolvedValueOnce(null)+ .mockResolvedValue([{ id: 'x1', draftId: 'd1', status: 'sent' }]);+ await render();+ await act(async () => void button('Send 2 pages').click());+ expect(sendPagesToCms).toHaveBeenCalledTimes(1);+ // What went shows while the next waits, and the dialog can be closed.+ expect(lines()).toEqual([+ 'Pour-overSending…',+ 'Cold brewPlaceholders to fill',+ 'EspressoWaiting',+ ]);+ expect(dialog().querySelector('[role="status"]')!.textContent).toBe('Sending: 0 of 2 done.');+ expect(button('Close')).toBeDefined();+ await act(async () => void (await vi.advanceTimersByTimeAsync(2_000)));+ expect(readDeliveries).toHaveBeenCalledWith(['x1']);+ await act(async () => void (await vi.advanceTimersByTimeAsync(2_000)));+ expect(sendPagesToCms).toHaveBeenCalledTimes(1);+ await act(async () => void (await vi.advanceTimersByTimeAsync(2_000)));+ expect(sendPagesToCms).toHaveBeenCalledTimes(2);+ expect(dialog().querySelector('[role="status"]')!.textContent).toBe('2 pages sent.');+ });++ it('posts no more once the pages before are still going after 30 minutes', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ oneByOne.on = true;+ sendPagesToCms.mockResolvedValueOnce({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'queued' }],+ skipped: 0,+ });+ readDeliveries.mockResolvedValue([{ id: 'x1', draftId: 'd1', status: 'queued' }]);+ await render();+ await act(async () => void button('Send 2 pages').click());+ await act(async () => void (await vi.advanceTimersByTimeAsync(30 * 60_000 + 2_000)));+ expect(sendPagesToCms).toHaveBeenCalledTimes(1);+ expect(lines()).toEqual([+ 'Pour-overSending…',+ 'Cold brewPlaceholders to fill',+ 'EspressoNot sent',+ ]);+ expect(dialog().textContent).toContain(+ "The pages before it were still going after 30 minutes, so 1 page wasn't sent.",+ );+ });++ it('posts no more once closed while a request waits, and says how many didn’t go', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ oneByOne.on = true;+ sendPagesToCms.mockResolvedValueOnce({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'queued' }],+ skipped: 0,+ });+ readDeliveries.mockResolvedValue([{ id: 'x1', draftId: 'd1', status: 'queued' }]);+ await render();+ await act(async () => void button('Send 2 pages').click());+ act(() => root.unmount());+ readDeliveries.mockResolvedValue([{ id: 'x1', draftId: 'd1', status: 'sent' }]);+ await act(async () => void (await vi.advanceTimersByTimeAsync(10_000)));+ expect(sendPagesToCms).toHaveBeenCalledTimes(1);+ expect(toast).toHaveBeenCalledWith(+ "1 page wasn't sent: the dialog closed while the pages before it were still going. Send it again from the Library.",+ );+ root = createRoot(container);+ });++ it('posts no more once closed while a one-page request is out', async () => {+ oneByOne.on = true;+ let answer: (value: unknown) => void = () => {};+ sendPagesToCms.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));+ await render();+ await act(async () => void button('Send 2 pages').click());+ act(() => root.unmount());+ // A single page goes at once: it comes back sent, not queued.+ await act(async () =>+ answer({ ok: true, deliveries: [{ id: 'x1', draftId: 'd1', status: 'sent' }], skipped: 0 }),+ );+ expect(sendPagesToCms).toHaveBeenCalledTimes(1);+ expect(toast).toHaveBeenCalledWith(+ "1 page wasn't sent: the dialog closed while the pages before it were still going. Send it again from the Library.",+ );+ root = createRoot(container);+ });++ it('says Failed, not the 200 the webhook answered, when the workflow then failed', async () => {+ sendPagesToCms.mockResolvedValue({+ ok: true,+ deliveries: [+ { id: 'x1', draftId: 'd1', status: 'failed', http_status: 200, error: 'Slug taken' },+ ],+ skipped: 0,+ });+ await render();+ await act(async () => button('Send 2 pages').click());+ expect(lines()[0]).toBe('Pour-overFailed');+ });++ it('posts no more requests once the day’s sends are used up', async () => {+ oneByOne.on = true;+ sendPagesToCms.mockResolvedValueOnce({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'queued' }],+ skipped: 1,+ });+ await render();+ await act(async () => void button('Send 2 pages').click());+ expect(sendPagesToCms).toHaveBeenCalledTimes(1);+ expect(readDeliveries).not.toHaveBeenCalled();+ expect(dialog().textContent).toContain("2 pages weren't sent");+ });++ it('says how many pages the day’s sends left out', async () => {+ sendPagesToCms.mockResolvedValue({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'sent' }],+ skipped: 1,+ });+ await render();+ await act(async () => button('Send 2 pages').click());+ expect(dialog().textContent).toContain(+ "1 page wasn't sent: the workspace has sent 200 pages in the last 24 hours.",+ );+ });++ it('says when the pages couldn’t be read, and reads them again', async () => {+ readCmsSources.mockRejectedValueOnce(new Error('offline'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ await render();+ expect(dialog().querySelector('[role="alert"]')!.textContent).toBe(+ "Couldn't read the pages. Try again.",+ );+ expect(button('Send 0 pages')).toBeUndefined();+ await act(async () => button('Try again').click());+ expect(readCmsSources).toHaveBeenCalledTimes(2);+ expect(button('Send 2 pages').disabled).toBe(false);+ });++ it('names the page a refusal names, and says when one went meanwhile', async () => {+ oneByOne.on = true;+ sendPagesToCms.mockResolvedValueOnce({ ok: false, code: 'invalid', field: 'pages.0.html' });+ await render();+ await act(async () => button('Send 2 pages').click());+ expect(dialog().querySelector('[role="alert"]')!.textContent).toBe(+ "\u201cPour-over\u201d can't go as it is: check its page in the editor.",+ );+ sendPagesToCms.mockResolvedValue({ ok: false, code: 'not_found', field: null });+ await act(async () => button('Send 2 pages').click());+ expect(dialog().querySelector('[role="alert"]')!.textContent).toContain(+ 'A page was archived or deleted since you picked it.',+ );+ });++ it('leaves the rest to the Library after three minutes, reading on through a failed read', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ sendPagesToCms.mockResolvedValue({+ ok: true,+ deliveries: [+ { id: 'x1', draftId: 'd1', status: 'queued' },+ { id: 'x3', draftId: 'd3', status: 'queued' },+ ],+ skipped: 0,+ });+ readDeliveries.mockResolvedValue(null);+ await render();+ await act(async () => button('Send 2 pages').click());+ await tick(60_000);+ expect(dialog().textContent).toContain('Sending: 0 of 2 done.');+ await tick(2 * 60_000 + 4_000);+ expect(dialog().querySelector('[role="status"]')!.textContent).toBe(+ "0 pages sent. The rest are still going: the Library shows each page's send as it lands.",+ );+ const reads = readDeliveries.mock.calls.length;+ await tick(10_000);+ expect(readDeliveries).toHaveBeenCalledTimes(reads);+ });++ it('stops reading once closed', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ sendPagesToCms.mockResolvedValue({+ ok: true,+ deliveries: [{ id: 'x1', draftId: 'd1', status: 'queued' }],+ skipped: 0,+ });+ await render();+ await act(async () => button('Send 2 pages').click());+ act(() => root.unmount());+ await act(async () => void (await vi.advanceTimersByTimeAsync(10_000)));+ expect(readDeliveries).not.toHaveBeenCalled();+ root = createRoot(container);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.tsxnew file mode 100644index 000000000..8d91f969a--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_bulk-send-dialog.tsx@@ -0,0 +1,459 @@+'use client';++import { useEffect, useRef, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { AlertTriangle, Check } from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { LoadingDots } from '@/components/ui/loading-dots';+import { bulkCmsItems, cmsSendGroups, type BulkItem } from '@/lib/content/cms-send';+import {+ readDeliveries,+ readKeptFields,+ sendPagesToCms,+ type CmsDelivery,+ type CmsSendError,+} from '@/lib/content/cms-send-client';+import type { ContentDraftListItem } from '@/lib/content/drafts';+import { readCmsSources } from './_cms-sources';++/** How often the sends going on in the background are read. */+const POLL_MS = 2_000;+/** After this long, the Library takes over showing them. */+const POLL_FOR_MS = 3 * 60_000;++/**+ * How long the next request waits for the last one's pages: as long as the+ * server lets a send stay queued (00262), past which it reads as interrupted.+ */+const GROUP_WAIT_MS = 30 * 60_000;++/**+ * Waits until these sends aren't queued any more, reading them every+ * POLL_MS (a read that fails is read again), for up to GROUP_WAIT_MS: one+ * page at a time (#1331), so the next request goes once the last one's+ * pages have gone. Each read goes to `onRead`. 'out' when the wait ran out,+ * 'closed' once `closed()` says the dialog was.+ */+async function gone(+ ids: string[],+ onRead: (read: CmsDelivery[]) => void,+ closed: () => boolean,+): Promise<'gone' | 'out' | 'closed'> {+ const until = Date.now() + GROUP_WAIT_MS;+ while (Date.now() < until) {+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));+ if (closed()) return 'closed';+ const read = await readDeliveries(ids).catch(() => null);+ if (!read) continue;+ onRead(read);+ if (!read.some((delivery) => delivery.status === 'queued')) return 'gone';+ }+ return 'out';+}++interface Refusal {+ code: CmsSendError;+ field: string | null;+ title: string | null;+}++type Phase =+ | { kind: 'reading' }+ | { kind: 'readFailed' }+ | { kind: 'ready' }+ | { kind: 'sending' }+ /** `waiting`: the pages of requests still to post, as their draft ids. */+ | { kind: 'going'; since: number; waiting: string[] }+ | { kind: 'done'; stillGoing: boolean; waitedOut: number };++/**+ * Send to CMS for the Library's selected rows (#1331): each page as the Send+ * dialog would send it unchanged, its slug and meta from its last send or the+ * page; one that can't go says why, to fix in the editor. The pages go in as+ * few requests as their size allows; the server sends each request's one by+ * one in the background, read here until they have gone. Closing leaves them+ * going, and the Library's rows follow them.+ */+export function BulkSendDialog({+ brandId,+ drafts,+ brandName,+ brandLanguage,+ onClose,+}: {+ brandId: string;+ /** The selected rows, at most CMS_PAGES_PER_SEND. */+ drafts: ContentDraftListItem[];+ brandName: string;+ brandLanguage: string | null | undefined;+ onClose: () => void;+}) {+ const t = useTranslations('contentEditor.library.bulk');+ const tEditor = useTranslations('contentEditor.editor');+ const tFailure = useTranslations('apiFailure');+ const [phase, setPhase] = useState<Phase>({ kind: 'reading' });+ const [items, setItems] = useState<BulkItem[]>([]);+ // The sends made, as last read, by draft.+ const [sent, setSent] = useState<Map<string, CmsDelivery>>(new Map());+ // Pages past the workspace's sends for the day.+ const [skipped, setSkipped] = useState(0);+ // Why a request was refused; with the page its `pages.N` named, when it named one.+ const [failure, setFailure] = useState<Refusal | null>(null);+ const [attempt, setAttempt] = useState(0);++ useEffect(() => {+ let cancelled = false;+ const ids = drafts.map((draft) => draft.id);+ Promise.all([+ readCmsSources({+ brandId,+ draftIds: ids,+ brandName,+ brandLanguage,+ teamByline: (brand) => tEditor('author.organization', { brand }),+ }),+ readKeptFields(ids),+ ])+ .then(([sources, kept]) => {+ if (cancelled) return;+ // In the Library's order; a page gone meanwhile is left out.+ const ordered = ids.flatMap((id) => {+ const source = sources.get(id);+ return source ? [source] : [];+ });+ setItems(bulkCmsItems(ordered, kept));+ setPhase({ kind: 'ready' });+ })+ .catch((err) => {+ console.error('Failed to read the pages to send:', err);+ if (!cancelled) setPhase({ kind: 'readFailed' });+ });+ return () => {+ cancelled = true;+ };+ // Read as it opens, for the rows selected then, and on Try again.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [attempt]);++ // While the server sends them, they are read now and then.+ const going = phase.kind === 'going' ? phase : null;+ useEffect(() => {+ // While a request waits for the last one's pages, send() reads them.+ if (!going || going.waiting.length) return;+ let cancelled = false;+ const timer = setTimeout(async () => {+ const read = await readDeliveries([...sent.values()].map((d) => d.id)).catch(() => null);+ if (cancelled) return;+ // By the send's id: a page deleted meanwhile reads back with no draft.+ const byId = new Map((read ?? []).map((delivery) => [delivery.id, delivery]));+ const next = new Map(+ [...sent].map(([draftId, delivery]) => {+ const now = byId.get(delivery.id);+ return [draftId, now ? { ...now, draftId } : delivery] as const;+ }),+ );+ setSent(next);+ const left = [...next.values()].some((d) => d.status === 'queued');+ if (!left) setPhase({ kind: 'done', stillGoing: false, waitedOut: 0 });+ else if (Date.now() - going.since > POLL_FOR_MS) {+ setPhase({ kind: 'done', stillGoing: true, waitedOut: 0 });+ }+ }, POLL_MS);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [going, sent]);++ const ready = items.filter((item) => item.page !== null);++ // Closed (or left) while a request waits: the requests after it don't go.+ const closed = useRef(false);+ useEffect(() => {+ closed.current = false;+ return () => {+ closed.current = true;+ };+ }, []);++ const send = async () => {+ setPhase({ kind: 'sending' });+ setFailure(null);+ const made = new Map<string, CmsDelivery>();+ let notSent = 0;+ let stopped: Refusal | null = null;+ // The day's sends used up: the requests after it would get none either.+ let capped = false;+ // Pages left unposted because the ones before them were still going.+ let waitedOut = 0;+ const groups = cmsSendGroups(ready.flatMap((item) => (item.page ? [item.page] : [])));+ for (const [i, group] of groups.entries()) {+ // Closed since the last request (a page sent at once, or a read in+ // flight): the rest don't go.+ if (i > 0 && closed.current) {+ toast(t('closedUnsent', { count: groups.slice(i).flat().length }));+ return;+ }+ // Once a send was refused (the day's sends used up), the rest wait too.+ if (stopped || capped) {+ notSent += group.length;+ continue;+ }+ const result = await sendPagesToCms(brandId, group);+ if (!result.ok) {+ // The page a refusal names ("pages.2.html"), as the group's own.+ const index = Number(/^pages\.(\d+)\./.exec(result.field ?? '')?.[1] ?? NaN);+ stopped = {+ code: result.code,+ field: result.field,+ title: Number.isInteger(index) ? (group[index]?.title ?? null) : null,+ };+ notSent += group.length;+ continue;+ }+ for (const delivery of result.deliveries) made.set(delivery.draftId, delivery);+ notSent += result.skipped;+ if (result.skipped > 0) capped = true;+ const queued = result.deliveries.filter((d) => d.status === 'queued').map((d) => d.id);+ const rest = groups.slice(i + 1);+ if (!queued.length || !rest.length || capped) continue;+ // Pages too long for one request: the next waits for this one's to go,+ // what went shown meanwhile. Closing the dialog stops the rest: else+ // they'd go up to half an hour later with nothing showing it.+ setSent(new Map(made));+ setSkipped(notSent);+ setPhase({+ kind: 'going',+ since: Date.now(),+ waiting: rest.flat().map((page) => page.draftId),+ });+ const went = await gone(+ queued,+ (read) => {+ const byId = new Map(read.map((delivery) => [delivery.id, delivery]));+ for (const [draftId, delivery] of made) {+ const now = byId.get(delivery.id);+ if (now) made.set(draftId, { ...now, draftId });+ }+ setSent(new Map(made));+ },+ () => closed.current,+ );+ const unposted = rest.reduce((count, later) => count + later.length, 0);+ if (went === 'closed') {+ toast(t('closedUnsent', { count: unposted }));+ return;+ }+ // Still going past the server's own limit: the rest aren't posted beside them.+ if (went === 'out') {+ waitedOut = unposted;+ break;+ }+ }+ setSent(made);+ setSkipped(notSent);+ setFailure(stopped);+ if (made.size === 0) {+ // Nothing went: what was refused, and the pages as they were.+ setPhase({ kind: 'ready' });+ return;+ }+ const left = [...made.values()].some((d) => d.status === 'queued');+ setPhase(+ left && !waitedOut+ ? { kind: 'going', since: Date.now(), waiting: [] }+ : { kind: 'done', stillGoing: left, waitedOut },+ );+ };++ const failureText = ({ code, field, title }: Refusal) => {+ if (code === 'session' || code === 'workspace' || code === 'busy') return tFailure(code);+ // A page archived or deleted since the dialog read it.+ if (code === 'not_found') return t('notFound');+ if (code === 'invalid' && field) {+ const named = field.split('.').pop() ?? 'other';+ return title+ ? t('invalidPage', { title, field: named })+ : tEditor('send.errors.invalidField', { field: named });+ }+ return tEditor(`send.errors.${code}`);+ };++ const counts = {+ sent: [...sent.values()].filter((d) => d.status === 'sent' || d.status === 'published').length,+ failed: [...sent.values()].filter((d) => d.status === 'failed').length,+ going: [...sent.values()].filter((d) => d.status === 'queued').length,+ };+ const busy = phase.kind === 'reading' || phase.kind === 'sending';+ const after = phase.kind === 'going' || phase.kind === 'done';++ return (+ <Dialog open onOpenChange={(open) => !open && phase.kind !== 'sending' && onClose()}>+ <DialogContent className="max-h-[calc(100dvh-2rem)] grid-cols-[minmax(0,1fr)] overflow-y-auto sm:max-w-lg">+ <DialogHeader>+ {/* The pages read, once read: one deleted meanwhile is left out. */}+ <DialogTitle>+ {t('title', { count: phase.kind === 'reading' ? drafts.length : items.length })}+ </DialogTitle>+ <DialogDescription>{t('description')}</DialogDescription>+ </DialogHeader>++ {phase.kind === 'reading' ? (+ <div className="flex items-center justify-center py-8" aria-busy="true">+ <LoadingDots size="md" className="text-muted-foreground" />+ </div>+ ) : phase.kind === 'readFailed' ? (+ <p role="alert" className="text-sm text-red-700 dark:text-red-400">+ {t('readFailed')}+ </p>+ ) : (+ <ul className="max-h-72 divide-y overflow-y-auto rounded-lg border">+ {items.map((item) => (+ <li key={item.draftId} className="flex items-center gap-3 px-3 py-2 text-sm">+ <span className="min-w-0 flex-1 truncate">+ {item.title.trim() || t('untitled')}+ </span>+ <ItemState+ item={item}+ delivery={sent.get(item.draftId)}+ after={after}+ sending={phase.kind === 'sending'}+ waiting={going?.waiting.includes(item.draftId) ?? false}+ />+ </li>+ ))}+ </ul>+ )}++ {phase.kind === 'ready' && items.some((item) => item.problem) && (+ <p className="text-xs text-muted-foreground">{t('fixHint')}</p>+ )}+ {after && (+ <p role="status" className="text-sm">+ {going+ ? t('progress', {+ done: counts.sent + counts.failed,+ total: sent.size + going.waiting.length,+ })+ : t('summary', { sent: counts.sent, failed: counts.failed })}+ {phase.kind === 'done' && phase.stillGoing && (+ <span className="text-muted-foreground"> {t('stillGoing')}</span>+ )}+ </p>+ )}+ {phase.kind === 'done' && phase.waitedOut > 0 && (+ <p className="text-sm text-amber-800 dark:text-amber-300">+ {t('waitedOut', { count: phase.waitedOut })}+ </p>+ )}+ {skipped > 0 && !failure && (+ <p className="text-sm text-amber-800 dark:text-amber-300">+ {t('skipped', { count: skipped })}+ </p>+ )}+ {failure && (+ <p role="alert" className="text-sm text-red-700 dark:text-red-400">+ {failureText(failure)}+ </p>+ )}++ <DialogFooter className="gap-2">+ {after ? (+ <Button onClick={onClose}>{t('close')}</Button>+ ) : phase.kind === 'readFailed' ? (+ <>+ <Button variant="outline" onClick={onClose}>+ {t('cancel')}+ </Button>+ <Button+ onClick={() => {+ setPhase({ kind: 'reading' });+ setAttempt((n) => n + 1);+ }}+ >+ {t('retry')}+ </Button>+ </>+ ) : (+ <>+ <Button variant="outline" disabled={phase.kind === 'sending'} onClick={onClose}>+ {t('cancel')}+ </Button>+ <Button disabled={busy || ready.length === 0} onClick={() => void send()}>+ {phase.kind === 'sending' && <LoadingDots className="mr-1" />}+ {phase.kind === 'sending' ? t('sending') : t('send', { count: ready.length })}+ </Button>+ </>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++/** A page's line: why it can't go, or how its send went. */+function ItemState({+ item,+ delivery,+ after,+ sending,+ waiting,+}: {+ item: BulkItem;+ delivery: CmsDelivery | undefined;+ after: boolean;+ sending: boolean;+ /** Its request waits for the last one's pages to go. */+ waiting: boolean;+}) {+ const t = useTranslations('contentEditor.library.bulk');+ const muted = 'shrink-0 text-xs text-muted-foreground';+ if (item.problem) {+ return (+ <span className="flex shrink-0 items-center gap-1 text-xs text-amber-800 dark:text-amber-300">+ <AlertTriangle className="h-3.5 w-3.5" aria-hidden="true" />+ {t(`problems.${item.problem}`)}+ </span>+ );+ }+ if (sending) return <LoadingDots className="shrink-0 text-muted-foreground" />;+ if (!after) {+ return (+ <span className={`flex items-center gap-1 ${muted}`}>+ <Check className="h-3.5 w-3.5" aria-hidden="true" />+ {t('ready')}+ </span>+ );+ }+ if (!delivery) return <span className={muted}>{t(waiting ? 'waiting' : 'notSent')}</span>;+ if (delivery.status === 'queued') return <span className={muted}>{t('queued')}</span>;+ if (delivery.status === 'failed') {+ return (+ <span+ className="shrink-0 text-right text-xs text-red-700 dark:text-red-400"+ title={delivery.error ?? undefined}+ >+ {/* What the webhook answered when it refused the page; a workflow's+ failure after a 2xx is Failed, its reason on hover. */}+ {delivery.http_status && (delivery.http_status < 200 || delivery.http_status > 299)+ ? t('answered', { status: delivery.http_status })+ : t('failed')}+ </span>+ );+ }+ return (+ <span className="flex shrink-0 items-center gap-1 text-xs text-green-700 dark:text-green-400">+ <Check className="h-3.5 w-3.5" aria-hidden="true" />+ {t('sent')}+ </span>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_cms-sources.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_cms-sources.tsnew file mode 100644index 000000000..d4ad5a98b--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_cms-sources.ts@@ -0,0 +1,54 @@+import { getContentAuthors } from '@/lib/actions/content-authors';+import { getContentDraftPages, type DraftPage } from '@/lib/actions/content-drafts';+import { cmsSource, type CmsSource } from '@/lib/content/cms-send';+import { DRAFT_PAGES_PER_CALL } from '@/lib/content/drafts';+import { qualityPhase } from '@/lib/content/quality';++/**+ * Library pages for Send to CMS (#1331), made ready as the editor makes its+ * own: their author and the brand's byline line once Quality is live. Read a+ * slice at a time, as the Library's Export reads them; a page gone meanwhile+ * is left out.+ */+export async function readCmsSources({+ brandId,+ draftIds,+ brandName,+ brandLanguage,+ teamByline,+}: {+ brandId: string;+ draftIds: string[];+ brandName: string;+ brandLanguage: string | null | undefined;+ teamByline: (brand: string) => string;+}): Promise<Map<string, CmsSource>> {+ const readPages = async () => {+ const pages: DraftPage[] = [];+ let queue = draftIds;+ while (queue.length > 0) {+ const read = await getContentDraftPages(brandId, queue.slice(0, DRAFT_PAGES_PER_CALL));+ pages.push(...read.pages);+ queue = [...read.rest, ...queue.slice(DRAFT_PAGES_PER_CALL)];+ }+ return pages;+ };+ const [pages, authors] = await Promise.all([+ readPages(),+ qualityPhase() >= 1 ? getContentAuthors().catch(() => null) : Promise.resolve(null),+ ]);+ const name = authors?.brands.find((b) => b.id === brandId)?.name ?? brandName;+ return new Map(+ pages.map((page) => [+ page.id,+ cmsSource({+ page,+ authors,+ brandId,+ brandName: name,+ brandLanguage,+ teamByline: teamByline(name),+ }),+ ]),+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsxindex 483546b84..72ccb6ebf 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx@@ -18,6 +18,7 @@ import {import { Link } from '@/i18n/navigation';import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';import { Badge } from '@/components/ui/badge';+import { Checkbox } from '@/components/ui/checkbox';import {DropdownMenu,DropdownMenuContent,@@ -73,25 +74,33 @@ export interface LibraryRowActions {onSend: (draft: ContentDraftListItem) => void;}+/** The rows picked for a bulk Send to CMS (#1331): admins and managers, drafts not archived. */+export interface LibrarySelection {+ selected: ReadonlySet<string>;+ onToggle: (ids: string[], on: boolean) => void;+}+/*** The Library's list (CE-002): one row per draft, the latest changed first.* Columns: Content · Type · Method (Create / Optimize) · By (a person or the* Content Agent) · Status · Created · Updated. A row opens the draft in the* editor; its menu sets the status and, for admins and managers, sends it* to the CMS (#1331), archives or deletes it (00233). Beside its status, its- * last send to the CMS.+ * last send to the CMS; with a selection, a box to pick rows to send together.*/export function LibraryTable({drafts,tab,actions,cms,+ selection,}: {drafts: ContentDraftListItem[];tab: LibraryTab;actions: LibraryRowActions;/** Each draft's last send to the CMS; none for a draft never sent. */cms: ReadonlyMap<string, CmsStatus>;+ selection?: LibrarySelection;}) {const t = useTranslations('contentEditor.library');const tTypes = useTranslations('contentEditor.pageTypes');@@ -108,11 +117,22 @@ export function LibraryTable({);}+ const ids = drafts.map((draft) => draft.id);+ const picked = selection ? ids.filter((id) => selection.selected.has(id)).length : 0;return (<Table><TableHeader><TableRow>- <TableHead className="pl-6">{t('columns.content')}</TableHead>+ {selection && (+ <TableHead className="w-10 pl-4 pr-0">+ <Checkbox+ aria-label={t('bulk.selectAll')}+ checked={picked === 0 ? false : picked === ids.length ? true : 'indeterminate'}+ onCheckedChange={(checked) => selection.onToggle(ids, checked === true)}+ />+ </TableHead>+ )}+ <TableHead className={selection ? 'pl-2' : 'pl-6'}>{t('columns.content')}</TableHead><TableHead>{t('columns.type')}</TableHead><TableHead>{t('columns.method')}</TableHead><TableHead>{t('columns.by')}</TableHead>@@ -129,7 +149,18 @@ export function LibraryTable({const sent = cms.get(draft.id);return (<TableRow key={draft.id}>- <TableCell className="max-w-[180px] pl-6 xl:max-w-[320px]">+ {selection && (+ <TableCell className="w-10 pl-4 pr-0">+ <Checkbox+ aria-label={t('bulk.selectRow', { title: draft.title.trim() || t('untitled') })}+ checked={selection.selected.has(draft.id)}+ onCheckedChange={(checked) => selection.onToggle([draft.id], checked === true)}+ />+ </TableCell>+ )}+ <TableCell+ className={`max-w-[180px] xl:max-w-[320px] ${selection ? 'pl-2' : 'pl-6'}`}+ ><Linkhref={contentEditorPath(draft.id)}className="block truncate font-medium hover:underline"diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsxindex 6eb4ebaea..09a27f61e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx@@ -48,7 +48,13 @@ vi.mock('@/lib/download', () => ({ saveBlob }));const readCmsStatuses = vi.hoisted(() => vi.fn());const readDraftCms = vi.hoisted(() => vi.fn());const sendPagesToCms = vi.hoisted(() => vi.fn());-vi.mock('@/lib/content/cms-send-client', () => ({ readCmsStatuses, readDraftCms, sendPagesToCms }));+vi.mock('@/lib/content/cms-send-client', () => ({+ readCmsStatuses,+ readDraftCms,+ sendPagesToCms,+ readKeptFields: vi.fn(async () => new Map()),+ readDeliveries: vi.fn(async () => []),+}));vi.mock('@/lib/actions/content-authors', () => ({ getContentAuthors: vi.fn(async () => null) }));/** jsdom's Blob has no text(): read it as a browser's FileReader would. */@@ -183,8 +189,9 @@ describe('the Content Library', () => {expect(tab('In review').textContent).toBe('In review2');expect(tab('Ready').textContent).toBe('Ready0');+ // After each row's box to pick it (admins and managers).const rows = [...container.querySelectorAll('tbody tr')].map((tr) =>- [...tr.querySelectorAll('td')].map((td) => td.textContent),+ [...tr.querySelectorAll('td')].slice(1).map((td) => td.textContent),);// Created and Updated where the AEO score was; the last cell is the row menu.expect(rows[0]).toEqual([@@ -209,6 +216,8 @@ describe('the Content Library', () => {expect(rows[2][3]).toBe('[email protected]');expect(rows[2][5]).toBe('Dec 30, 2025');expect([...container.querySelectorAll('thead th')].map((th) => th.textContent)).toEqual([+ // The box to pick every row listed.+ '','Content','Type','Method',@@ -266,7 +275,7 @@ describe('the Content Library', () => {]);await renderPage();const status = [...container.querySelectorAll('tbody tr')].map(- (tr) => tr.querySelectorAll('td')[4].textContent,+ (tr) => tr.querySelectorAll('td')[5].textContent,);expect(status).toEqual(['Agent writing…', 'Agent failed', 'Ready']);expect(getContentDrafts).toHaveBeenCalledTimes(1);@@ -274,7 +283,7 @@ describe('the Content Library', () => {getContentDrafts.mockResolvedValue([row({ status: 'in_review', author: 'agent' })]);await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));expect(getContentDrafts).toHaveBeenCalledTimes(2);- expect(container.querySelector('tbody tr td:nth-child(5)')!.textContent).toBe('In review');+ expect(container.querySelector('tbody tr td:nth-child(6)')!.textContent).toBe('In review');await act(async () => void (await vi.advanceTimersByTimeAsync(10_000)));expect(getContentDrafts).toHaveBeenCalledTimes(2);} finally {@@ -532,6 +541,111 @@ describe('Send to CMS from a Library row (#1331)', () => {});});+describe('picking rows to send together (#1331)', () => {+ const box = (label: string) =>+ container.querySelector<HTMLButtonElement>(`[role="checkbox"][aria-label="${label}"]`);+ const barButton = (name: string) =>+ [...container.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent === name,+ );++ it('sends the rows picked from the bar, then clears them and reads the sends again', async () => {+ getContentDrafts.mockResolvedValue([row({}), row({ id: 'd2', title: 'Churn guide' })]);+ await renderPage();+ expect(barButton('Send to CMS')).toBeUndefined();+ await act(async () => box('Select Churn guide')!.click());+ expect(container.textContent).toContain('1 page selected');+ expect(box('Select all pages listed')!.getAttribute('data-state')).toBe('indeterminate');++ await act(async () => barButton('Send to CMS')!.click());+ await act(async () => {});+ const dialog = document.querySelector('[role="dialog"]')!;+ expect(dialog.textContent).toContain('Send 1 page to your CMS');+ expect(getContentDraftPages).toHaveBeenCalledWith('brand-1', ['d2']);++ const close = [...dialog.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent === 'Cancel',+ )!;+ await act(async () => close.click());+ expect(document.querySelector('[role="dialog"]')).toBeNull();+ expect(container.textContent).not.toContain('page selected');+ expect(readCmsStatuses).toHaveBeenCalledTimes(2);+ });++ it('takes up to 25 pages a send', async () => {+ getContentDrafts.mockResolvedValue(+ Array.from({ length: 26 }, (_, i) => row({ id: `d${i}`, title: `Draft ${i}` })),+ );+ await renderPage();+ await act(async () => box('Select all pages listed')!.click());+ expect(container.textContent).toContain('26 pages selected');+ expect(container.textContent).toContain('Up to 25 pages a send');+ expect(barButton('Send to CMS')!.disabled).toBe(true);++ await act(async () => box('Select Draft 0')!.click());+ expect(barButton('Send to CMS')!.disabled).toBe(false);+ await act(async () => barButton('Clear')!.click());+ expect(container.textContent).not.toContain('pages selected');+ });++ it('reads the rows’ sends again while a page is on its way', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ getContentDrafts.mockResolvedValue([row({})]);+ const status = (state: string) =>+ new Map([+ [+ 'd1',+ {+ status: state,+ at: '2026-10-24T10:00:00Z',+ httpStatus: null,+ error: null,+ publishedUrl: null,+ },+ ],+ ]);+ readCmsStatuses.mockResolvedValueOnce(status('queued')).mockResolvedValue(status('sent'));+ await renderPage();+ expect(readCmsStatuses).toHaveBeenCalledTimes(1);+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));+ expect(readCmsStatuses).toHaveBeenCalledTimes(2);+ // Sent: no more reads.+ await act(async () => void (await vi.advanceTimersByTimeAsync(20_000)));+ expect(readCmsStatuses).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('drops the rows picked when the tab changes', async () => {+ getContentDrafts.mockResolvedValue([row({}), row({ id: 'd2', title: 'Churn guide' })]);+ await renderPage();+ await act(async () => box('Select Churn guide')!.click());+ expect(container.textContent).toContain('1 page selected');+ await act(async () => tab('In review').click());+ await act(async () => tab('All').click());+ expect(container.textContent).not.toContain('page selected');+ expect(box('Select Churn guide')!.getAttribute('data-state')).toBe('unchecked');+ });++ it('has no boxes for members, nor under Archived', async () => {+ role.canManage = false;+ getContentDrafts.mockResolvedValue([row({})]);+ await renderPage();+ expect(container.querySelector('[role="checkbox"]')).toBeNull();++ act(() => root.unmount());+ root = createRoot(container);+ role.canManage = true;+ window.history.replaceState(null, '', '/dashboard/content/library?tab=archived');+ getContentDrafts.mockResolvedValue([row({ archivedAt: '2026-10-21T08:00:00Z' })]);+ await renderPage();+ expect(container.textContent).toContain('Pipeline forecasting');+ expect(container.querySelector('[role="checkbox"]')).toBeNull();+ });+});+describe('a Library row’s menu (00233)', () => {const menuItems = async (title: string) => {const trigger = container.querySelector<HTMLElement>(`[aria-label="Actions for ${title}"]`)!;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsxindex fc9b5d135..d43e89594 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx@@ -3,7 +3,7 @@import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';-import { Plus } from 'lucide-react';+import { Plus, Send } from 'lucide-react';import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';import {@@ -27,16 +27,14 @@ import { NewContentDialog } from '@/components/content/new-content-dialog';import { SendDialog } from '@/components/content/send-to-cms-dialog';import { useUserRole } from '@/hooks/use-user-role';import { useRouter } from '@/i18n/navigation';-import { getContentAuthors } from '@/lib/actions/content-authors';import {archiveContentDraft,deleteContentDraft,- getContentDraftPages,getContentDrafts,markContentDraftReady,setContentDraftStatus,} from '@/lib/actions/content-drafts';-import { cmsSource, type CmsSource } from '@/lib/content/cms-send';+import { CMS_PAGES_PER_SEND, type CmsSource } from '@/lib/content/cms-send';import { readCmsStatuses, type CmsStatus } from '@/lib/content/cms-send-client';import {AGENT_POLL_MS,@@ -51,49 +49,15 @@ import {type LibraryTab,} from '@/lib/content/drafts';import { siteTypeOf } from '@/lib/content/page-types';-import { qualityPhase } from '@/lib/content/quality';import { formatNumber } from '@/lib/format';import { readUrlChoice, writeUrlParams } from '@/lib/url-state';import { useBrandStore } from '@/stores/use-brand-store';+import { BulkSendDialog } from './_bulk-send-dialog';+import { readCmsSources } from './_cms-sources';import { LibraryExportMenu, useLibraryExport } from './_library-export';-import { LibraryTable, type LibraryRowActions } from './_library-table';+import { LibraryTable, type LibraryRowActions, type LibrarySelection } from './_library-table';import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';-/**- * A row's page for Send to CMS, made ready as the editor makes its own: its- * author and the brand's byline line once Quality is live. Null when the- * page is gone.- */-async function readSendSource({- brandId,- draftId,- brandName,- brandLanguage,- teamByline,-}: {- brandId: string;- draftId: string;- brandName: string;- brandLanguage: string | null | undefined;- teamByline: (brand: string) => string;-}): Promise<CmsSource | null> {- const [{ pages }, authors] = await Promise.all([- getContentDraftPages(brandId, [draftId]),- qualityPhase() >= 1 ? getContentAuthors().catch(() => null) : Promise.resolve(null),- ]);- const page = pages[0];- if (!page) return null;- const name = authors?.brands.find((b) => b.id === brandId)?.name ?? brandName;- return cmsSource({- page,- authors,- brandId,- brandName: name,- brandLanguage,- teamByline: teamByline(name),- });-}-/** A read of the brand's drafts: null until it comes back. */interface LibraryRead {brandId: string;@@ -131,6 +95,18 @@ export default function ContentLibraryPage() {const [sending, setSending] = useState<{ brandId: string; source: CmsSource } | null>(null);// Each draft's last send, beside its status; read with the list.const [cms, setCms] = useState<ReadonlyMap<string, CmsStatus>>(new Map());+ // The rows picked to send together, for the brand they were picked in.+ const [picked, setPicked] = useState<{ brandId: string | null; ids: ReadonlySet<string> }>({+ brandId: null,+ ids: new Set(),+ });+ // The bulk Send dialog's rows, as they were picked when it opened, and their brand.+ const [bulk, setBulk] = useState<{+ brandId: string;+ brandName: string;+ brandLanguage: string | null | undefined;+ drafts: ContentDraftListItem[];+ } | null>(null);useEffect(() => {// eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount@@ -179,6 +155,14 @@ export default function ContentLibraryPage() {cancelled = true;};}, [readIds, cmsAttempt]);+ // While a page is on its way to the CMS (a bulk send going on), its row's+ // send is read again now and then, as the list is while the agent writes.+ const cmsGoing = [...cms.values()].some((status) => status.status === 'queued');+ useEffect(() => {+ if (!cmsGoing) return;+ const timer = setTimeout(() => setCmsAttempt((n) => n + 1), AGENT_POLL_MS);+ return () => clearTimeout(timer);+ }, [cmsGoing, cms]);const reload = () => setAttempt((n) => n + 1);const titleOf = (draft: ContentDraftListItem) => draft.title.trim() || t('untitled');@@ -214,16 +198,19 @@ export default function ContentLibraryPage() {// The draft's brand stays the send's, should the brand switch meanwhile.const brandId = activeBrandId;setPreparing(true);- const source = await readSendSource({+ const source = await readCmsSources({brandId,- draftId: draft.id,+ draftIds: [draft.id],brandName: activeBrand?.name ?? '',brandLanguage: activeBrand?.language,teamByline: (brand) => tEditor('author.organization', { brand }),- }).catch((err) => {- console.error('Failed to read the page to send:', err);- return null;- });+ }).then(+ (sources) => sources.get(draft.id) ?? null,+ (err) => {+ console.error('Failed to read the page to send:', err);+ return null;+ },+ );setPreparing(false);if (source) setSending({ brandId, source });else toast.error(t('rowMenu.sendFailed'));@@ -259,12 +246,15 @@ export default function ContentLibraryPage() {setDeletePending(false);};+ const clearPicked = () => setPicked({ brandId: null, ids: new Set() });const changeTab = (next: LibraryTab) => {setTab(next);+ clearPicked();writeUrlParams({ tab: next }, { tab: 'all' });};const changeCreated = (next: CreatedRange) => {setCreated(next);+ clearPicked();writeUrlParams({ created: next }, { created: 'all' });};@@ -282,6 +272,24 @@ export default function ContentLibraryPage() {const counts = current?.counts ?? null;const inTab = drafts ? draftsInTab(drafts, tab) : [];const listed = draftsCreatedIn(inTab, created);+ // Picked rows still listed (a read may have moved some), never archived ones.+ const pickedIds = picked.brandId === activeBrandId ? picked.ids : new Set<string>();+ const pickedDrafts = listed.filter((draft) => pickedIds.has(draft.id) && !draft.archivedAt);+ const selection: LibrarySelection | undefined =+ canManage && tab !== 'archived'+ ? {+ selected: pickedIds,+ onToggle: (ids, on) => {+ const next = new Set(pickedIds);+ for (const id of ids) {+ if (on) next.add(id);+ else next.delete(id);+ }+ setPicked({ brandId: activeBrandId, ids: next });+ },+ }+ : undefined;+ const tooMany = pickedDrafts.length > CMS_PAGES_PER_SEND;return (<div className="space-y-6">@@ -346,6 +354,40 @@ export default function ContentLibraryPage() {</div><Card className="py-0">+ {selection && pickedDrafts.length > 0 && (+ <div className="flex flex-wrap items-center gap-2 border-b bg-muted/50 px-4 py-2">+ <span className="text-xs text-muted-foreground">+ {t('bulk.selected', { count: pickedDrafts.length })}+ </span>+ {tooMany && (+ <span className="text-xs text-amber-800 dark:text-amber-300">+ {t('bulk.tooMany', { max: CMS_PAGES_PER_SEND })}+ </span>+ )}+ <div className="ml-auto flex items-center gap-1">+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5 text-xs"+ disabled={tooMany}+ onClick={() =>+ setBulk({+ brandId: activeBrandId,+ brandName: activeBrand?.name ?? '',+ brandLanguage: activeBrand?.language,+ drafts: pickedDrafts,+ })+ }+ >+ <Send className="h-3 w-3" />+ {t('bulk.sendSelected')}+ </Button>+ <Button variant="ghost" size="sm" className="h-7 text-xs" onClick={clearPicked}>+ {t('bulk.clear')}+ </Button>+ </div>+ </div>+ )}<CardContent className="px-0">{current?.failed ? (<div className="flex flex-col items-center gap-3 px-6 py-12 text-center">@@ -370,10 +412,30 @@ export default function ContentLibraryPage() {{t('created.empty')}</p>) : (- <LibraryTable drafts={listed} tab={tab} actions={rowActions} cms={cms} />+ <LibraryTable+ drafts={listed}+ tab={tab}+ actions={rowActions}+ cms={cms}+ selection={selection}+ />)}</CardContent></Card>+ {bulk && (+ <BulkSendDialog+ brandId={bulk.brandId}+ drafts={bulk.drafts}+ brandName={bulk.brandName}+ brandLanguage={bulk.brandLanguage}+ // The sends going on show in the rows as they land.+ onClose={() => {+ setBulk(null);+ clearPicked();+ setCmsAttempt((n) => n + 1);+ }}+ />+ )}{sending && (<SendDialogdraftId={sending.source.draftId}diff --git a/web/src/components/content/send-to-cms-dialog.test.tsx b/web/src/components/content/send-to-cms-dialog.test.tsxindex 018098463..0a6cb3e10 100644--- a/web/src/components/content/send-to-cms-dialog.test.tsx+++ b/web/src/components/content/send-to-cms-dialog.test.tsx@@ -162,6 +162,10 @@ describe('SendDialog', () => {await render({ title: ' ' });expect(dialog().textContent).toContain('Give the page a title first');expect(button('Send').disabled).toBe(true);+ // Past what the server takes.+ await render({ html: `<h1>Pour-over</h1><p>${'a'.repeat(1_000_000)}</p>` });+ expect(dialog().textContent).toContain('The page is over a million characters');+ expect(button('Send').disabled).toBe(true);});it('holds the send while the last send can’t be read, and reads it again', async () => {diff --git a/web/src/lib/content/cms-send-client.test.ts b/web/src/lib/content/cms-send-client.test.tsindex a3108e46e..bd0a80bd8 100644--- a/web/src/lib/content/cms-send-client.test.ts+++ b/web/src/lib/content/cms-send-client.test.ts@@ -10,7 +10,7 @@ import type { CmsPage } from './cms-send';let session: { access_token: string } | null;let reads: Record<string, { data: unknown; error: unknown }>;const filters: [string, string, unknown][] = [];-/** Each draft's last send, read by draft ids: each read's answer, in turn. */+/** Reads by ids (each draft's last send, kept fields, sends): each read's answer, in turn. */let statusReads: { data: unknown; error: unknown }[];const statusIds: string[][] = [];const rpcs: string[] = [];@@ -28,16 +28,19 @@ vi.mock('@/lib/supabase/client', () => ({const chain: Record<string, unknown> = {select: () => chain,eq: (col: string, v: unknown) => (filters.push([table, col, v]), chain),+ in: (_col: string, ids: string[]) => (statusIds.push(ids), chain),order: () => chain,limit: () => chain,maybeSingle: async () => reads[table],+ then: (resolve: (r: unknown) => void) => resolve(statusReads.shift()),};return chain;},}),}));-const { readCmsStatuses, readDraftCms, sendPagesToCms } = await import('./cms-send-client');+const { readCmsStatuses, readDeliveries, readDraftCms, readKeptFields, sendPagesToCms } =+ await import('./cms-send-client');const page: CmsPage = {draftId: 'd1',@@ -80,7 +83,11 @@ describe('sendPagesToCms', () => {expect(result).toEqual({ok: true,deliveries: [{ id: 'x1', draftId: 'd1', status: 'sent' }],+ skipped: 0,});+ // Past the workspace's sends for the day: the pages left over.+ answer(200, { deliveries: [{ id: 'x2', draftId: 'd1', status: 'queued' }], skipped: 3 });+ expect(await sendPagesToCms('brand-1', [page])).toMatchObject({ ok: true, skipped: 3 });});it('gives the server’s reason, and the field a 400 names', async () => {@@ -98,6 +105,15 @@ describe('sendPagesToCms', () => {});});+ it('says when a request was more than the API’s proxy takes', async () => {+ answer(413, {});+ expect(await sendPagesToCms('brand-1', [page])).toEqual({+ ok: false,+ code: 'too_large',+ field: null,+ });+ });+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' });@@ -281,3 +297,41 @@ describe('readCmsStatuses', () => {expect(statusIds).toHaveLength(1);});});++describe('readKeptFields and readDeliveries', () => {+ it('reads the slug and meta each draft kept, none when they can’t be read', async () => {+ statusReads = [+ {+ data: [+ { id: 'd1', slug: 'coffee', meta_title: null, meta_description: 'Slowly.' },+ { id: 'd2', slug: null, meta_title: null, meta_description: null },+ ],+ error: null,+ },+ ];+ expect([...(await readKeptFields(['d1', 'd2'])).entries()]).toEqual([+ ['d1', { slug: 'coffee', metaTitle: undefined, metaDescription: 'Slowly.' }],+ ['d2', { slug: undefined, metaTitle: undefined, metaDescription: undefined }],+ ]);+ expect(statusIds).toEqual([['d1', 'd2']]);+ // Unread, a page sent before would go with another slug: the send waits.+ statusReads = [{ data: null, error: { message: 'column "slug" does not exist' } }];+ await expect(readKeptFields(['d1'])).rejects.toThrow('column "slug" does not exist');+ expect((await readKeptFields([])).size).toBe(0);+ });++ it('reads the sends as they are now, null when they can’t be read', async () => {+ statusReads = [+ {+ data: [{ id: 'x1', draft_id: 'd1', status: 'failed', http_status: 500, error: 'No' }],+ error: null,+ },+ ];+ expect(await readDeliveries(['x1'])).toEqual([+ { id: 'x1', draftId: 'd1', status: 'failed', http_status: 500, error: 'No' },+ ]);+ statusReads = [{ data: null, error: { message: 'offline' } }];+ expect(await readDeliveries(['x1'])).toBeNull();+ expect(await readDeliveries([])).toEqual([]);+ });+});diff --git a/web/src/lib/content/cms-send-client.ts b/web/src/lib/content/cms-send-client.tsindex 6ca54b626..5eac17a81 100644--- a/web/src/lib/content/cms-send-client.ts+++ b/web/src/lib/content/cms-send-client.ts@@ -18,6 +18,8 @@ export type CmsSendError =| 'not_found'| 'invalid'| 'failed'+ // More than the API's proxy takes in one request (413).+ | 'too_large'// Not a send's own: the session, another workspace's brand, the rate limiter.| 'session'| 'workspace'@@ -34,7 +36,8 @@ export interface CmsDelivery {}export type CmsSendResult =- | { ok: true; deliveries: CmsDelivery[] }+ /** `skipped`: pages past the workspace's sends for the day, not sent. */+ | { ok: true; deliveries: CmsDelivery[]; skipped: number }| { ok: false; code: CmsSendError; field: string | null };/** A send's own reasons, by the server's code. */@@ -69,14 +72,16 @@ export async function sendPagesToCms(brandId: string, pages: CmsPage[]): Promisecode?: string;field?: string | null;deliveries?: CmsDelivery[];+ skipped?: number;};if (!res.ok) {+ if (res.status === 413) return { ok: false, code: 'too_large', field: null };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 ?? [] };+ return { ok: true, deliveries: body.deliveries ?? [], skipped: body.skipped ?? 0 };} catch (err) {console.error('Failed to send to the CMS:', err);return { ok: false, code: 'failed', field: null };@@ -197,3 +202,47 @@ export async function readDraftCms(draftId: string): Promise<DraftCms | null> {last: delivery ? lastSend(delivery) : null,};}++/**+ * The slug and meta each draft kept from its last send, for a bulk send+ * (the dialog's single read is readDraftCms); none for a draft that kept+ * none. Throws when they can't be read: sent with the page's own slug, a+ * page sent before could land in the CMS twice.+ */+export async function readKeptFields(draftIds: string[]): Promise<Map<string, Partial<CmsFields>>> {+ const kept = new Map<string, Partial<CmsFields>>();+ if (!draftIds.length) return kept;+ const { data, error } = await createClient()+ .from('content_drafts')+ .select('id, slug, meta_title, meta_description')+ .in('id', draftIds);+ if (error) throw new Error(error.message);+ for (const row of data ?? []) {+ kept.set(row.id, {+ slug: row.slug ?? undefined,+ metaTitle: row.meta_title ?? undefined,+ metaDescription: row.meta_description ?? undefined,+ });+ }+ return kept;+}++/** Sends as they are now, by id: a bulk send's, while they go. Null when they can't be read. */+export async function readDeliveries(ids: string[]): Promise<CmsDelivery[] | null> {+ if (!ids.length) return [];+ const { data, error } = await createClient()+ .from('content_draft_deliveries')+ .select('id, draft_id, status, http_status, error')+ .in('id', ids);+ if (error) {+ console.error('Failed to read the sends:', error);+ return null;+ }+ return (data ?? []).map((row) => ({+ id: row.id,+ draftId: row.draft_id ?? '',+ status: row.status as CmsDelivery['status'],+ http_status: row.http_status,+ error: row.error,+ }));+}diff --git a/web/src/lib/content/cms-send.test.ts b/web/src/lib/content/cms-send.test.tsindex ba41f781c..ea935cdb5 100644--- a/web/src/lib/content/cms-send.test.ts+++ b/web/src/lib/content/cms-send.test.ts@@ -6,8 +6,12 @@ import {cmsFieldsProblem,cmsPage,cmsPageProblem,+ bulkCmsItems,+ cmsSendGroups,cmsSource,type CmsFields,+ type CmsPage,+ type CmsSource,} from './cms-send';import type { PageFields } from './ready-to-publish';@@ -86,6 +90,7 @@ describe('cmsPageProblem', () => {// 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');+ expect(cmsPageProblem('Pour-over', `<p>${'a'.repeat(1_000_000)}</p>`)).toBe('tooLong');});});@@ -219,3 +224,88 @@ describe('cmsSource', () => {expect(source({ authors: null })).toMatchObject({ author: null, teamByline: '', byline: null });});});++describe('bulkCmsItems', () => {+ const source = (over: Partial<CmsSource>): CmsSource => ({+ draftId: 'd1',+ title: 'Pour-over',+ html: '<h1>Pour-over</h1>\n<p>Brew it slowly.</p>',+ sourceUrl: null,+ author: null,+ teamByline: 'Acme Team',+ byline: null,+ ...over,+ });++ it('gives each page as the Send dialog would send it, or why it can’t go', () => {+ const items = bulkCmsItems(+ [+ source({}),+ source({ draftId: 'd2', html: '<h1>Pour-over</h1><p>Use [figure] g.</p>' }),+ source({ draftId: 'd3', html: '<h1>Pour-over</h1><p></p>' }),+ source({ draftId: 'd4', title: '東京ガイド', html: '<h1>東京ガイド</h1><p>東京</p>' }),+ source({ draftId: 'd5', title: ' ' }),+ ],+ new Map(),+ );+ expect(items.map((item) => [item.draftId, item.problem])).toEqual([+ ['d1', null],+ ['d2', 'placeholders'],+ ['d3', 'empty'],+ // A title in another script gives no slug: added in the editor.+ ['d4', 'slug'],+ ['d5', 'noTitle'],+ ]);+ expect(items[0].page).toMatchObject({+ draftId: 'd1',+ slug: 'pour-over',+ metaDescription: 'Brew it slowly.',+ html: '<p>Brew it slowly.</p>',+ author: 'Acme Team',+ });+ expect(items.slice(1).every((item) => item.page === null)).toBe(true);+ });++ it('takes the slug and meta the page kept from its last send', () => {+ const [item] = bulkCmsItems(+ [source({ draftId: 'd4', title: '東京ガイド', html: '<h1>東京ガイド</h1><p>東京</p>' })],+ new Map([['d4', { slug: 'tokyo-guide', metaTitle: 'Tokyo' }]]),+ );+ expect(item.problem).toBeNull();+ expect(item.page).toMatchObject({ slug: 'tokyo-guide', metaTitle: 'Tokyo' });+ });+});++describe('cmsSendGroups', () => {+ const sized = (id: string, chars: number): CmsPage => ({+ draftId: id,+ title: 'T',+ slug: 't',+ metaTitle: '',+ metaDescription: '',+ html: 'x'.repeat(chars),+ author: null,+ featuredImage: null,+ });++ it('puts the pages in as few requests as their size allows, in order', () => {+ const groups = cmsSendGroups(+ // A page's JSON is about 120 characters past its HTML.+ [sized('a', 300), sized('b', 300), sized('c', 900), sized('d', 100)],+ 1000,+ );+ expect(groups.map((group) => group.map((page) => page.draftId))).toEqual([+ ['a', 'b'],+ // A page past the budget goes alone, never split.+ ['c'],+ ['d'],+ ]);+ expect(cmsSendGroups([])).toEqual([]);+ // By the bytes sent: a letter outside ASCII takes two or three.+ expect(cmsSendGroups([sized('a', 200), sized('b', 0)], 500)).toHaveLength(1);+ expect(+ cmsSendGroups([{ ...sized('a', 0), html: 'ç'.repeat(200) }, sized('b', 0)], 500),+ ).toHaveLength(2);+ expect(cmsSendGroups([sized('a', 10), sized('b', 10)])).toHaveLength(1);+ });+});diff --git a/web/src/lib/content/cms-send.ts b/web/src/lib/content/cms-send.tsindex a4bbc01ef..cfce6968a 100644--- a/web/src/lib/content/cms-send.ts+++ b/web/src/lib/content/cms-send.ts@@ -3,7 +3,10 @@ import type { AuthorsRead, ContentAuthor } from '@/lib/content/authors';import { publishableHtml } from '@/lib/content/clean-html';import {bylineText,+ exportPlaceholders,fragment,+ pageFields,+ titlePlaceholders,withByline,withoutLeadingH1,type PageFields,@@ -42,6 +45,7 @@ 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 HTML_MAX = 1_000_000;const AUTHOR_MAX = 200;const ALT_MAX = 500;const IMAGE_SRC_MAX = 2048;@@ -91,15 +95,17 @@ export function cmsFieldsProblem(}/**- * 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.+ * Why the page can't go yet, or null: the CMS needs a title, a page with no+ * words or image under its H1 has nothing to publish, and the server takes+ * a page up to a million characters.*/export function cmsPageProblem(title: string,html: string,-): 'noTitle' | 'longTitle' | 'empty' | null {+): 'noTitle' | 'longTitle' | 'empty' | 'tooLong' | null {if (!title.trim()) return 'noTitle';if (title.trim().length > TITLE_MAX) return 'longTitle';+ if (html.length > HTML_MAX) return 'tooLong';const body = fragment(withoutLeadingH1(html));if (!body.textContent?.trim() && !body.querySelector('img')) return 'empty';return null;@@ -196,3 +202,80 @@ export function cmsPage({featuredImage: image ? { src: image, alt: altOf(html, image).slice(0, ALT_MAX) } : null,};}++/** As the server's: the pages one send takes. */+export const CMS_PAGES_PER_SEND = 25;+/**+ * About as much as one request carries: the browser's go through the API's+ * proxy, a serverless function whose body is capped at 4.5 MB.+ */+const SEND_BODY_BUDGET = 3_000_000;++/** Why a page of a bulk send can't go as it is, or null. */+export type BulkProblem =+ | 'noTitle'+ | 'longTitle'+ | 'empty'+ | 'tooLong'+ | 'placeholders'+ | 'slug'+ | 'metaTitle'+ | 'metaDescription';++export interface BulkItem {+ draftId: string;+ title: string;+ problem: BulkProblem | null;+ /** The page as it goes; null when it can't. */+ page: CmsPage | null;+}++/**+ * A bulk send's pages, each as the Send dialog would send it unchanged: its+ * slug and meta what it kept from its last send, else the page's; or why it+ * can't go (filled in the editor, where its fields can be changed too).+ */+export function bulkCmsItems(+ sources: CmsSource[],+ kept: ReadonlyMap<string, Partial<CmsFields>>,+): BulkItem[] {+ return sources.map((source) => {+ const { draftId, title, html } = source;+ const page = pageFields(source);+ const fields = cmsFields(page, kept.get(draftId) ?? null);+ const problem =+ cmsPageProblem(title, html) ??+ (exportPlaceholders(html) + titlePlaceholders(title, html) > 0 ? 'placeholders' : null) ??+ cmsFieldsProblem(fields);+ return {+ draftId,+ title,+ problem,+ page: problem ? null : cmsPage({ draftId, title, html, fields, page, byline: source.byline }),+ };+ });+}++/**+ * The pages in sends a request each can carry, in order, by their bytes as+ * sent: a long page goes alone, never split. Each request is a send of its+ * own on the server, its pages one after another; the bulk dialog posts the+ * next once the last one's pages have gone, so groups don't go side by side.+ */+export function cmsSendGroups(pages: CmsPage[], budget = SEND_BODY_BUDGET): CmsPage[][] {+ const groups: CmsPage[][] = [];+ const encoder = new TextEncoder();+ let size = 0;+ for (const page of pages) {+ const pageSize = encoder.encode(JSON.stringify(page)).length;+ const last = groups.at(-1);+ if (last && size + pageSize <= budget) {+ last.push(page);+ size += pageSize;+ } else {+ groups.push([page]);+ size = pageSize;+ }+ }+ return groups;+}