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): ask where a page is live when it's marked published, and measure it there (CE-013, part 2: web) (#1511)
Cihana089eaca9c8c
diff --git a/docs/guides/content-editor.mdx b/docs/guides/content-editor.mdxindex 30a335db5..6d3353d73 100644--- a/docs/guides/content-editor.mdx+++ b/docs/guides/content-editor.mdx@@ -150,6 +150,7 @@ The Content Agent never changes these passages. If you edit one, the editor asks- **Add HTML** in the toolbar adds an HTML block: an embed, a widget or a form, kept exactly as written. Ansvisor never runs it. **Edit as HTML** shows the page's source; scripts, iframes and inline styles are removed when you switch back.- **Send to CMS** (admins and managers) sends the page to your workflow tool through the brand's webhook, for it to create the post in your CMS. See [Send to CMS](/guides/send-to-cms).- **Mark ready** saves the page, sets it to **Ready** and keeps a version in History. If the draft was sent to the Action Center, it also completes its task there. Ansvisor doesn't publish the page: copy or export it to your site, or send it to your CMS.+- **Mark published** (the Library's **Status** menu, or the header's **Next step** once the page is ready, when Quality is on): once the page is live, tell Ansvisor where. It asks for the live address, starting from the page it optimizes or your site with the page's slug, and the **Live page** tab measures that address from then. If the draft came from the Action Center, its Publish task is completed once all the action's work is live. On a published page, the header's **Published** button changes the address. A page your CMS reports live, or one published in Webflow, gets its address on its own. An archived page is restored first.- Click **Ready** in the header to move the page back to **In review**. A task that Mark ready completed is open again (**In Progress**), unless someone changed it in the Action Center since or the action is closed.## Library@@ -162,14 +163,14 @@ The **Library** lists the drafts by status, each tab with its count:| **In progress** | Drafts being written. || **In review** | Drafts the Content Agent wrote, waiting for a person. || **Ready** | Drafts marked ready. |-| **Published** | Drafts you marked as published. |+| **Published** | Drafts marked published, by you or your CMS. || **Archived** | Drafts sent to the archive. They keep their status for when they're restored. |The columns are Content, Type, Method (Create or Optimize), By (you, the Content Agent or a teammate), Status, Created and Updated. Click a row to open the draft in the editor. The **Created** filter narrows the list to the last 7, 30 or 90 days.### Row menu-- **Status**: set the draft to In progress, In review, Ready or Published. Ready works like the editor's Mark ready, and moving a ready or published draft back to In progress or In review opens its task again, as the editor's **Ready** does.+- **Status**: set the draft to In progress, In review, Ready or Published. Ready works like the editor's Mark ready. **Published** asks for the page's live address, as the editor's **Mark published** does (not for archived drafts). Moving a ready or published draft back to In progress or In review opens its task again, as the editor's **Ready** does; a published one also opens the action's Publish task again and stops its Live page being measured for the action.- **Export Word**, **Export HTML** or **Export Markdown** for that draft.- **Send to CMS** (admins and managers, not for archived drafts). Beside each row's status, an icon shows its last send: on its way, sent, failed or published. Tick several rows to send up to 25 at once. See [Send to CMS](/guides/send-to-cms).- **Send to Archive** or **Restore** (admins and managers).diff --git a/web/messages/en.json b/web/messages/en.jsonindex b78cfccf0..0201a3dfd 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3204,6 +3204,22 @@"openDetails": "Open topic details"},"contentEditor": {+ "publish": {+ "title": "Mark published",+ "description": "Where is the page live? Its Live page tab measures this address, and an action it came from counts its results from there.",+ "label": "Live address",+ "hint": "The page's full address on your site, as people open it.",+ "invalidUrl": "Give the page's full address, starting with https:// or http://.",+ "notFound": "This page isn't in the Library anymore.",+ "failed": "Couldn't mark the page published. Try again.",+ "done": "Published. The Live page tab measures it from now on.",+ "offDomain": "Published. The address isn't on the brand's domains, so its numbers won't show.",+ "addressNotKept": "Published. The address couldn't be saved yet, so the Live page tab can't measure it.",+ "unsaved": "The page has changes that aren't saved, so its live address can't be set yet.",+ "archived": "This page is archived. Restore it in the Library first.",+ "cancel": "Cancel",+ "save": "Mark published"+ },"plan": {"title": "Content plan","description": "What to create, optimize or protect next.",@@ -3670,7 +3686,8 @@"runningHint": "The Content Agent is working on this page. Click to follow its steps or stop it.","readyLabel": "Ready: click to move it back to review","readyHint": "Marked ready. Click to move it back to review.",- "publishedHint": "Published. Change its status in the Library.",+ "publishedHint": "Published. Click to give the address it's live at.",+ "publishedHintAt": "Live at {url}. Click to change the address.","backInReview": "Back in review.","backInReviewAction": "Back in review, and {count, plural, one {its task} other {its # tasks}} in Action AC-{no} {count, plural, one {is} other {are}} open again.","backInReviewFailed": "Couldn't move it back to review.",@@ -4078,7 +4095,8 @@}},"impact": {- "newPage": "This draft is a new page, not live yet, so there's nothing to measure. This tab shows the live page's numbers when a draft optimizes one.",+ "newPage": "This draft is a new page, not live yet, so there's nothing to measure. Mark it published with its live address, and this tab measures it from then.",+ "publishedNoAddress": "This page is marked published without its live address, so there's nothing to measure. Give the address with the header's Published button, and this tab measures it from then.","thisPage": "The live page today","notForecast": "How the live page does now, not a forecast of what this draft will get.","periodLabel": "Period",@@ -4435,6 +4453,7 @@"working": "Content Agent is working","stop": "Stop","marking": "Marking it ready…",+ "saving": "Saving the page first…","tipsTitle": "If you see…","tipLine": "{state} →","states": {@@ -4466,7 +4485,7 @@"proofTodo": "Only you can do this: {todo}.","check": "Links, schema, placeholders and Trust {gate}+, before you mark it ready.","checkRules": "The rules are met. Mark it ready when you are.",- "ready": "Every step is done. Export it for your CMS.",+ "ready": "Every step is done. Export it for your CMS, and mark it published once it's live.","published": "It's published. Export it again when the page changes."},"actions": {@@ -4480,7 +4499,8 @@"showTodos": "Show to-dos","beforePublish": "Before you publish","markReady": "Mark ready",- "export": "Export"+ "export": "Export",+ "markPublished": "Mark published"},"tips": {"longPage": "Page far longer than Length",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 13f77ece0..9766dadf1 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@@ -29,6 +29,8 @@ 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 { PublishDialog } from '@/components/content/publish-dialog';+import { readLiveUrl } from '@/lib/content/publish-client';import { SendDialog } from '@/components/content/send-to-cms-dialog';import { updateBrand } from '@/lib/actions/brand';import {@@ -348,6 +350,7 @@ export function DraftEditor({}) {const t = useTranslations('contentEditor.editor');const tNext = useTranslations('contentEditor.editor.nextStep');+ const tPublish = useTranslations('contentEditor.publish');const autosave = useDraftAutosave(draft.id, draft);const [title, setTitle] = useState(draft.title);// The page as written now, for the side panel's Sources.@@ -357,6 +360,10 @@ export function DraftEditor({const flashTimer = useRef<ReturnType<typeof setTimeout>>(undefined);useEffect(() => () => clearTimeout(pageReadTimer.current), []);const [status, setStatus] = useState(draft.status);+ // Where the page is live (CE-013), and Mark published open.+ const [liveUrl, setLiveUrl] = useState(draft.publishedUrl);+ const [askLive, setAskLive] = useState(false);+ const [preparingLive, setPreparingLive] = useState(false);const tDraftStatus = useTranslations('contentEditor.status');const [marking, setMarking] = useState(false);// The Content Agent couldn't finish the page Start gave it (CE-015).@@ -2709,6 +2716,28 @@ export function DraftEditor({}setSendOpen({ html: pageToPublish() });};+ /**+ * Mark published (CE-013), once the page is saved: the server keeps it in+ * History as published, as it stands in the database.+ */+ const openPublish = async () => {+ if (preparingLive || draft.archivedAt) return;+ if (htmlUnapplied) {+ toast.error(t('send.applyHtml'));+ return;+ }+ setPreparingLive(true);+ const saved = await autosave.settle().then(+ () => true,+ () => false,+ );+ setPreparingLive(false);+ if (!saved) {+ toast.error(tPublish('unsaved'));+ return;+ }+ setAskLive(true);+ };const startSend = () => {if (htmlUnapplied) {toast.error(t('send.applyHtml'));@@ -2857,16 +2886,21 @@ export function DraftEditor({return pageRewrite?.blocked ?? null;case 'fixRules':return agentFix.blocked;- // As the header's Mark ready is held.+ // As the header's Mark ready is held; an archived page is restored first, as in the Library.case 'beforePublish':case 'markReady':- return marking- ? t('nextStep.marking')- : autosave.state === 'conflict'- ? t('save.conflict')- : autosave.state === 'too_large'- ? t('save.tooLarge')- : null;+ case 'markPublished':+ return action === 'markPublished' && draft.archivedAt+ ? tPublish('archived')+ : preparingLive+ ? t('nextStep.saving')+ : marking+ ? t('nextStep.marking')+ : autosave.state === 'conflict'+ ? t('save.conflict')+ : autosave.state === 'too_large'+ ? t('save.tooLarge')+ : null;default:return null;}@@ -2910,6 +2944,9 @@ export function DraftEditor({case 'export':openExport();return;+ case 'markPublished':+ void openPublish();+ return;}};@@ -2925,6 +2962,8 @@ export function DraftEditor({try {const { status: now, tasksReopened } = await unmarkContentDraftReady(draft.id);setStatus(now);+ // Published from the Library meanwhile: its live address, for the Live page tab.+ if (now === 'published') void readLiveUrl(draft.id).then((url) => url && setLiveUrl(url));if (now !== 'in_review') toast(t('header.notReady', { status: tDraftStatus(now) }));else if (tasksReopened > 0 && draft.action) {toast(t('header.backInReviewAction', { no: draft.action.number, count: tasksReopened }));@@ -3193,22 +3232,31 @@ export function DraftEditor({</HeaderTip>)}{/* The one black button. Marked, it reads Ready (a click moves it back- to review); published, Published. Narrower than 1024px, ✓ alone. */}+ to review); published, Published (a click changes its live+ address, CE-013). Narrower than 1024px, ✓ alone. */}{status === 'ready' || status === 'published' ? (<HeaderTiplabel={tDraftStatus(status)}- hint={status === 'ready' ? t('header.readyHint') : t('header.publishedHint')}+ hint={+ status === 'ready'+ ? t('header.readyHint')+ : draft.archivedAt+ ? tPublish('archived')+ : liveUrl+ ? t('header.publishedHintAt', { url: liveUrl })+ : t('header.publishedHint')+ }><Buttonvariant="outline"size="sm"- // Published stays focusable, so its tip says where to change it.- disabled={status === 'published' || unmarking}+ // An archived page's address waits until it's restored, as in the Library.+ disabled={unmarking || (status === 'published' && !!draft.archivedAt)}focusableWhenDisabledaria-label={status === 'ready' ? t('header.readyLabel') : tDraftStatus('published')}- onClick={() => void unmarkReady()}+ onClick={() => void (status === 'published' ? openPublish() : unmarkReady())}className="border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 hover:text-emerald-800 disabled:opacity-100 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300 dark:hover:bg-emerald-900">{unmarking ? <LoadingDots /> : <Check className="h-3.5 w-3.5" />}@@ -3543,6 +3591,8 @@ export function DraftEditor({{panelOpen ? (<EditorSidePaneldraft={draft}+ liveUrl={liveUrl}+ published={status === 'published'}siteType={siteType}title={title}bodyHtml={pageHtml}@@ -3671,6 +3721,18 @@ export function DraftEditor({/>)}+ {askLive && (+ <PublishDialog+ draftId={draft.id}+ published={status === 'published'}+ onClose={() => setAskLive(false)}+ onPublished={(url) => {+ setStatus('published');+ setLiveUrl(url);+ }}+ />+ )}+{quality && publishOpen && readyToPaste && (<BeforePublishmode={publishOpen.mode}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_header-tip.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_header-tip.tsxindex fe9785c2b..811f0aedf 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_header-tip.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_header-tip.tsx@@ -37,7 +37,11 @@ export function HeaderTip({</TooltipTrigger><TooltipContent side="bottom" className={cn('max-w-60', narrowOnly && 'lg:hidden')}><span className="block font-medium">{label}</span>- {hint && <span className="mt-0.5 block text-muted-foreground">{hint}</span>}+ {hint && (+ <span className="mt-0.5 block text-muted-foreground [overflow-wrap:anywhere]">+ {hint}+ </span>+ )}</TooltipContent></Tooltip>);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsxindex 9380c0b54..7261c74aa 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx@@ -46,12 +46,15 @@ interface ImpactRead {export function ImpactTab({brandId,pageUrl,+ published = false,rebuilding = false,blocked = null,onUseLostPrompts,}: {brandId: string;pageUrl: string | null;+ /** Marked published: without an address, it's asked for, not called not live. */+ published?: boolean;/** Use lost prompts in this draft: they join its sources and the brief is rebuilt. */rebuilding?: boolean;/** Why the brief can't be rebuilt now (the agent is at work on the page), or null. */@@ -82,9 +85,14 @@ export function ImpactTab({};}, [brandId, pageUrl, period, attempt]);- // A new page has nothing to measure until it is live at an address.+ // A new page has nothing to measure until it is live at an address: one+ // marked published before CE-013 has none yet.if (!pageUrl) {- return <p className="text-sm text-muted-foreground">{t('newPage')}</p>;+ return (+ <p className="text-sm text-muted-foreground">+ {t(published ? 'publishedNoAddress' : 'newPage')}+ </p>+ );}const current = read?.period === period ? read : null;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.tsxindex 417443e7b..c9756b5f5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.tsx@@ -190,6 +190,7 @@ export function NextStepButton({const name = stepName(t, step.id, state);const now = path.findIndex((p) => p.state === 'now');const why = blocked(step.primary);+ const whyAlternative = step.alternative ? blocked(step.alternative) : null;const whyId = useId();// After Skip, the new step's button takes focus (Skip itself may be gone).const primaryRef = useRef<HTMLButtonElement>(null);@@ -271,7 +272,8 @@ export function NextStepButton({<Buttonvariant="outline"size="sm"- disabled={blocked(step.alternative) !== null}+ disabled={whyAlternative !== null}+ aria-describedby={!why && whyAlternative ? whyId : undefined}onClick={() => onAction(step.alternative!)}>{t(`actions.${step.alternative}`)}@@ -290,12 +292,14 @@ export function NextStepButton({</Button>)}</div>- {why && (+ {/* The step's own button first; else why the other one is held+ (Mark published on an archived page). */}+ {(why ?? whyAlternative) && (<pid={whyId}className="text-xs text-amber-700 [overflow-wrap:anywhere] dark:text-amber-400">- {why}+ {why ?? whyAlternative}</p>)}</div>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsxindex 956a8a08f..bb3956dd9 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx@@ -110,6 +110,8 @@ export function EditorPanelRail({ onOpen }: { onOpen: (tab: PanelTab) => void })*/export function EditorSidePanel({draft,+ liveUrl = null,+ published = false,siteType,title,bodyHtml,@@ -146,6 +148,13 @@ export function EditorSidePanel({handOff = null,}: {draft: ContentDraft;+ /**+ * Where the page is live, as the editor holds it (CE-013: marked published+ * since it opened): the Live page tab measures it, else the page it optimizes.+ */+ liveUrl?: string | null;+ /** Published, as the editor holds it: without an address, the Live page tab asks for it. */+ published?: boolean;/** The brand's business type as the editor holds it (Quality CE-056). */siteType: SiteType;/** The draft's title, page and type as written now: Sources and Brief read them. */@@ -529,8 +538,11 @@ export function EditorSidePanel({{opened.has('impact') && (<div hidden={tab !== 'impact'}><ImpactTab+ // Another address (marked published at it) reads anew, not the last one's numbers.+ key={liveUrl ?? draft.sourceUrl ?? 'none'}brandId={draft.brandId}- pageUrl={draft.sourceUrl}+ pageUrl={liveUrl ?? draft.sourceUrl}+ published={published}rebuilding={rebuilding}blocked={briefBlocked}onUseLostPrompts={(promptIds) => void rebuild({ addPrompts: promptIds })}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 0f333315b..90c395a60 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@@ -46,6 +46,11 @@ vi.mock('@/lib/actions/content-draft-inputs', () => ({saveDraftInputs: (...args: unknown[]) => saveDraftInputs(...args),}));const getContentImpact = vi.fn();+// Mark published (CE-013).+const publishPage = vi.hoisted(() => vi.fn());+const readPublishAddress = vi.hoisted(() => vi.fn(async () => 'https://acme.example.com/pipeline'));+const readLiveUrl = vi.hoisted(() => vi.fn(async () => 'https://acme.example.com/pipeline'));+vi.mock('@/lib/content/publish-client', () => ({ publishPage, readPublishAddress, readLiveUrl }));const getContentResults = vi.fn();const getDraftSources = vi.fn();const setDraftSourceIncluded = vi.fn();@@ -233,6 +238,7 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({pageTypeSource: 'user',siteType: 'b2b',sourceUrl: null,+ publishedUrl: null,method: 'optimize',status: 'in_review',bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams trust it.</p>',@@ -346,6 +352,8 @@ beforeEach(() => {.mockReset().mockResolvedValue({ ok: true, updatedAt: '2026-10-20T10:00:00Z', bodyHash: 'h0' });getContentImpact.mockReset().mockResolvedValue(null);+ publishPage.mockReset();+ readPublishAddress.mockReset().mockResolvedValue('https://acme.example.com/pipeline');getContentResults.mockReset().mockResolvedValue(null);getDraftSources.mockReset().mockResolvedValue(null);readAgentRun.mockReset().mockResolvedValue(null);@@ -957,15 +965,152 @@ describe('the content editor', () => {unmarkContentDraftReady.mockResolvedValueOnce({ status: 'published', tasksReopened: 0 });await act(async () => button('Ready: click to move it back to review')!.click());expect(toast).toHaveBeenCalledWith('Its status is now Published, so it stays.');- expect(button('Published')!.getAttribute('aria-disabled')).toBe('true');+ // Its live address, for the Live page tab.+ expect(readLiveUrl).toHaveBeenCalledWith('d1');+ // Published, a click opens its live address (CE-013).+ expect(button('Published')!.getAttribute('aria-disabled')).not.toBe('true');});- it('says Published, not to be undone here, on a published page', async () => {- getContentDraft.mockResolvedValue(draft({ status: 'published' }));+ it('says Published on a published page, a click away from its live address (CE-013)', async () => {+ getContentDraft.mockResolvedValue(+ draft({ status: 'published', publishedUrl: 'https://acme.example.com/pipeline' }),+ );await renderPage();expect(button('Mark ready')).toBeUndefined();- // Disabled but focusable, so its tip says where to change it.+ expect(button('Published')!.getAttribute('aria-disabled')).not.toBe('true');+ await act(async () => button('Published')!.click());+ expect(readPublishAddress).toHaveBeenCalledWith('d1');+ expect(document.querySelector('[role="dialog"]')!.textContent).toContain('Mark published');+ });++ it('holds Published on an archived page until it’s restored, as the Library does', async () => {+ getContentDraft.mockResolvedValue(+ draft({ status: 'published', archivedAt: '2026-10-25T10:00:00Z' }),+ );+ await renderPage();expect(button('Published')!.getAttribute('aria-disabled')).toBe('true');+ await act(async () => button('Published')!.click());+ expect(readPublishAddress).not.toHaveBeenCalled();+ });++ it('asks for the address of a page marked published without one on the Live page tab', async () => {+ getContentDraft.mockResolvedValue(draft({ status: 'published', method: 'create' }));+ const width = window.innerWidth;+ window.innerWidth = 1440;+ try {+ await renderPage();+ await pickTab('Live page');+ expect(container.textContent).toContain(+ "This page is marked published without its live address, so there's nothing to measure.",+ );+ expect(getContentImpact).not.toHaveBeenCalled();+ } finally {+ window.innerWidth = width;+ }+ });++ it('measures the address a page went live at on the Live page tab, not the page it optimized', async () => {+ getContentDraft.mockResolvedValue(+ draft({+ status: 'published',+ sourceUrl: 'https://acme.example.com/pricing',+ publishedUrl: 'https://acme.example.com/pricing-2026',+ }),+ );+ const width = window.innerWidth;+ window.innerWidth = 1440;+ try {+ await renderPage();+ await pickTab('Live page');+ expect(getContentImpact).toHaveBeenCalledWith(+ 'b1',+ 'https://acme.example.com/pricing-2026',+ 30,+ );+ } finally {+ window.innerWidth = width;+ }+ });++ it('marks a ready page published from Next step, and the Live page tab measures its address', async () => {+ getContentDraft.mockResolvedValue(draft({ status: 'ready', method: 'create' }));+ publishPage.mockResolvedValue({+ ok: true,+ publishedUrl: 'https://acme.example.com/pipeline',+ publishedAt: '2026-10-25T10:00:00Z',+ onBrandDomain: true,+ taskCompleted: false,+ });+ const width = window.innerWidth;+ window.innerWidth = 1440;+ // Next step comes with Quality.+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';+ try {+ getContentAuthors.mockResolvedValue({+ authors: [],+ brands: [{ id: 'b1', name: 'Acme' }],+ me: { id: 'u1', role: 'analyst' },+ });+ await renderPage();+ // The header's Next step: Ready to publish, Mark published beside Export.+ const next = [...container.querySelectorAll<HTMLButtonElement>('header button')].find((b) =>+ b.textContent?.startsWith('Next'),+ )!;+ await act(async () => {+ next.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ next.click();+ });+ await act(async () => {+ [...document.querySelectorAll<HTMLButtonElement>('button')]+ .find((b) => b.textContent === 'Mark published')!+ .click();+ });+ await act(async () => {+ [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')]+ .find((b) => b.textContent === 'Mark published')!+ .click();+ });+ expect(publishPage).toHaveBeenCalledWith('d1', 'https://acme.example.com/pipeline');+ expect(button('Published')).toBeDefined();+ await pickTab('Live page');+ expect(getContentImpact).toHaveBeenCalledWith('b1', 'https://acme.example.com/pipeline', 30);+ } finally {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ window.innerWidth = width;+ }+ });++ it('holds Next step’s Mark published on an archived page, saying why', async () => {+ getContentDraft.mockResolvedValue(+ draft({ status: 'ready', method: 'create', archivedAt: '2026-10-25T10:00:00Z' }),+ );+ const width = window.innerWidth;+ window.innerWidth = 1440;+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';+ try {+ getContentAuthors.mockResolvedValue({+ authors: [],+ brands: [{ id: 'b1', name: 'Acme' }],+ me: { id: 'u1', role: 'analyst' },+ });+ await renderPage();+ const next = [...container.querySelectorAll<HTMLButtonElement>('header button')].find((b) =>+ b.textContent?.startsWith('Next'),+ )!;+ await act(async () => {+ next.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ next.click();+ });+ const mark = [...document.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent === 'Mark published',+ )!;+ expect(mark.disabled).toBe(true);+ const why = document.getElementById(mark.getAttribute('aria-describedby')!);+ expect(why!.textContent).toBe('This page is archived. Restore it in the Library first.');+ } finally {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ window.innerWidth = width;+ }});it("puts the caret at the end of the page's H1 when the title is clicked", async () => {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 69f269b33..ac6975375 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@@ -237,7 +237,8 @@ function RowMenu({ draft, actions }: { draft: ContentDraftListItem; actions: Lib{DRAFT_STATUSES.map((status) => (<DropdownMenuItemkey={status}- disabled={status === draft.status}+ // An archived page is restored before it's marked live (CE-013).+ disabled={status === draft.status || (status === 'published' && !!draft.archivedAt)}onClick={() => actions.onStatus(draft, status)}><Checkdiff --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 546353d23..79775c8ec 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@@ -49,6 +49,10 @@ const readCmsStatuses = vi.hoisted(() => vi.fn());const readDraftCms = vi.hoisted(() => vi.fn());const sendPagesToCms = vi.hoisted(() => vi.fn());const refreshWebflowPublished = vi.hoisted(() => vi.fn());+// Mark published (CE-013).+const publishPage = vi.hoisted(() => vi.fn());+const readPublishAddress = vi.hoisted(() => vi.fn());+vi.mock('@/lib/content/publish-client', () => ({ publishPage, readPublishAddress }));vi.mock('@/lib/content/cms-send-client', () => ({readCmsStatuses,refreshWebflowPublished,@@ -126,6 +130,14 @@ beforeEach(() => {root = createRoot(container);getContentDrafts.mockReset();refreshWebflowPublished.mockReset().mockResolvedValue([]);+ readPublishAddress.mockReset().mockResolvedValue('https://acme.example/pipeline-forecasting');+ publishPage.mockReset().mockResolvedValue({+ ok: true,+ publishedUrl: 'https://acme.example/pipeline-forecasting',+ publishedAt: '2026-10-25T10:00:00Z',+ onBrandDomain: true,+ taskCompleted: false,+ });getContentStartOptions.mockReset().mockResolvedValue({opportunities: [],prompts: [],@@ -763,8 +775,20 @@ describe('a Library row’s menu (00233)', () => {expect(markContentDraftReady).toHaveBeenCalledWith('d1');expect(getContentDrafts).toHaveBeenCalledTimes(2);+ // Published asks where the page is live (CE-013), from where it can tell.await pick('Pipeline forecasting', 'Published');- expect(setContentDraftStatus).toHaveBeenCalledWith('d1', 'published');+ expect(setContentDraftStatus).not.toHaveBeenCalledWith('d1', 'published');+ expect(readPublishAddress).toHaveBeenCalledWith('d1');+ const dialog = document.querySelector('[role="dialog"]')!;+ expect(dialog.querySelector<HTMLInputElement>('#publish-url')!.value).toBe(+ 'https://acme.example/pipeline-forecasting',+ );+ const save = [...dialog.querySelectorAll('button')].find(+ (b) => b.textContent === 'Mark published',+ )!;+ await act(async () => save.click());+ expect(publishPage).toHaveBeenCalledWith('d1', 'https://acme.example/pipeline-forecasting');+ expect(getContentDrafts).toHaveBeenCalledTimes(3);});it('lets members set a status only', async () => {@@ -804,6 +828,14 @@ describe('a Library row’s menu (00233)', () => {await act(async () => tab('Archived').click());expect(container.textContent).toContain('Old pricing page');+ // An archived page is restored before it's marked live (CE-013).+ const published = (await menuItems('Old pricing page')).find(+ (el) => el.textContent === 'Published',+ )!;+ expect(published.hasAttribute('data-disabled')).toBe(true);+ await act(async () =>+ document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })),+ );await pick('Old pricing page', 'Restore');expect(archiveContentDraft).toHaveBeenLastCalledWith('d2', false);});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsxindex 9f3e574f9..d08c240af 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx@@ -24,6 +24,7 @@ import {import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { LoadingDots } from '@/components/ui/loading-dots';import { NewContentDialog } from '@/components/content/new-content-dialog';+import { PublishDialog } from '@/components/content/publish-dialog';import { SendDialog } from '@/components/content/send-to-cms-dialog';import { useUserRole } from '@/hooks/use-user-role';import { useRouter } from '@/i18n/navigation';@@ -97,6 +98,8 @@ export default function ContentLibraryPage() {// Send to CMS: while the row's page is read, then the dialog's page.const [preparing, setPreparing] = useState(false);const [sending, setSending] = useState<{ brandId: string; source: CmsSource } | null>(null);+ // Mark published open, on a draft (CE-013).+ const [publishing, setPublishing] = useState<string | 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.@@ -244,6 +247,11 @@ export default function ContentLibraryPage() {const rowActions: LibraryRowActions = {canManage,onStatus: (draft: ContentDraftListItem, status: DraftStatus) => {+ // Published asks where the page is live (CE-013): tracking starts there.+ if (status === 'published') {+ setPublishing(draft.id);+ return;+ }// Ready keeps a History version and completes the draft's task, as the editor's Mark ready.const change =status === 'ready'@@ -461,6 +469,16 @@ export default function ContentLibraryPage() {}}/>)}+ {publishing && (+ <PublishDialog+ draftId={publishing}+ // The row menu offers Published only to a page that isn't.+ published={false}+ onClose={() => setPublishing(null)}+ onPublished={reload}+ />+ )}+{sending && (<SendDialogdraftId={sending.source.draftId}diff --git a/web/src/components/content/publish-dialog.test.tsx b/web/src/components/content/publish-dialog.test.tsxnew file mode 100644index 000000000..b9104994e--- /dev/null+++ b/web/src/components/content/publish-dialog.test.tsx@@ -0,0 +1,164 @@+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';++const toast = vi.hoisted(() => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));+const publishPage = vi.hoisted(() => vi.fn());+const readPublishAddress = vi.hoisted(() => vi.fn());+vi.mock('@/lib/content/publish-client', () => ({ publishPage, readPublishAddress }));+// Published as before the publish route, on an API without it.+const setContentDraftStatus = vi.hoisted(() => vi.fn());+vi.mock('@/lib/actions/content-drafts', () => ({ setContentDraftStatus }));++const { PublishDialog } = await import('./publish-dialog');++/** Mark published (CE-013): the address the page is live at, where tracking starts. */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;+const onClose = vi.fn();+const onPublished = vi.fn();++async function render(published = false) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <PublishDialog+ draftId="d1"+ published={published}+ onClose={onClose}+ onPublished={onPublished}+ />+ </NextIntlClientProvider>,+ );+ });+}+const dialog = () => document.querySelector('[role="dialog"]')!;+const input = () => dialog().querySelector<HTMLInputElement>('#publish-url')!;+const save = () =>+ [...dialog().querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent === 'Mark published',+ )!;+async function type(value: string) {+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input(), value);+ input().dispatchEvent(new Event('input', { bubbles: true }));+ });+}++beforeEach(() => {+ onClose.mockReset();+ onPublished.mockReset();+ toast.success.mockReset();+ toast.warning.mockReset();+ setContentDraftStatus.mockReset().mockResolvedValue(undefined);+ readPublishAddress.mockReset().mockResolvedValue('https://acme.example/blog/cold-brew');+ publishPage.mockReset().mockResolvedValue({+ ok: true,+ publishedUrl: 'https://acme.example/blog/cold-brew',+ publishedAt: '2026-10-25T10:00:00Z',+ onBrandDomain: true,+ taskCompleted: true,+ });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.body.replaceChildren();+});++describe('PublishDialog', () => {+ it('starts from where the page is live, and marks it published there', async () => {+ await render();+ expect(readPublishAddress).toHaveBeenCalledWith('d1');+ expect(input().value).toBe('https://acme.example/blog/cold-brew');+ await type(' https://acme.example/blog/cold-brew-at-home ');+ await act(async () => save().click());+ expect(publishPage).toHaveBeenCalledWith('d1', 'https://acme.example/blog/cold-brew-at-home');+ expect(toast.success).toHaveBeenCalledWith(+ 'Published. The Live page tab measures it from now on.',+ );+ expect(onPublished).toHaveBeenCalledWith('https://acme.example/blog/cold-brew');+ expect(onClose).toHaveBeenCalled();+ });++ it('says an address off the brand’s domains won’t show numbers', async () => {+ publishPage.mockResolvedValue({+ ok: true,+ publishedUrl: 'https://medium.com/@acme/x',+ publishedAt: '2026-10-25T10:00:00Z',+ onBrandDomain: false,+ taskCompleted: false,+ });+ await render();+ await act(async () => save().click());+ expect(toast.warning).toHaveBeenCalledWith(+ "Published. The address isn't on the brand's domains, so its numbers won't show.",+ );+ });++ it('asks for a full address, and stays open, when it isn’t one', async () => {+ publishPage.mockResolvedValue({ ok: false, code: 'invalid_url' });+ await render();+ await type('acme.example/x');+ await act(async () => save().click());+ expect(dialog().querySelector('#publish-url-hint')!.textContent).toBe(+ "Give the page's full address, starting with https:// or http://.",+ );+ expect(input().getAttribute('aria-invalid')).toBe('true');+ expect(onClose).not.toHaveBeenCalled();+ await type('');+ expect(save().disabled).toBe(true);+ });++ it('marks the page published without its address on an API without the route, and says so', async () => {+ publishPage.mockResolvedValue({ ok: false, code: 'no_route' });+ await render();+ await act(async () => save().click());+ expect(setContentDraftStatus).toHaveBeenCalledWith('d1', 'published');+ expect(toast.warning).toHaveBeenCalledWith(+ "Published. The address couldn't be saved yet, so the Live page tab can't measure it.",+ );+ expect(onPublished).toHaveBeenCalledWith(null);+ expect(onClose).toHaveBeenCalled();+ });++ it('can’t change a published page’s address on an API without the route, nor fall back', async () => {+ publishPage.mockResolvedValue({ ok: false, code: 'no_route' });+ await render(true);+ await act(async () => save().click());+ expect(setContentDraftStatus).not.toHaveBeenCalled();+ expect(dialog().querySelector('#publish-url-hint')!.textContent).toBe(+ "Couldn't mark the page published. Try again.",+ );+ expect(onClose).not.toHaveBeenCalled();++ // A page gone is the route's own answer.+ publishPage.mockResolvedValue({ ok: false, code: 'not_found' });+ await act(async () => save().click());+ expect(dialog().querySelector('#publish-url-hint')!.textContent).toBe(+ "This page isn't in the Library anymore.",+ );+ });++ it('waits for the starting address, and starts empty without one', async () => {+ readPublishAddress.mockReturnValue(new Promise(() => {}));+ await render();+ expect(input().disabled).toBe(true);+ act(() => root.unmount());+ root = createRoot(container);+ readPublishAddress.mockResolvedValue('');+ await render();+ expect(input().value).toBe('');+ expect(save().disabled).toBe(true);+ });+});diff --git a/web/src/components/content/publish-dialog.tsx b/web/src/components/content/publish-dialog.tsxnew file mode 100644index 000000000..271bb189b--- /dev/null+++ b/web/src/components/content/publish-dialog.tsx@@ -0,0 +1,164 @@+'use client';++import { useEffect, useRef, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+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 { setContentDraftStatus } from '@/lib/actions/content-drafts';+import { publishPage, readPublishAddress } from '@/lib/content/publish-client';++/**+ * Mark published (CE-013): the person gives the address the page is live+ * at, and tracking starts there (the editor's Live page tab, a linked+ * action's results). It starts from where the page went live, else the page+ * it optimizes, else the brand's site with its slug. From the Library's+ * status menu and the editor; rendered only while open.+ *+ * An API without the publish route yet (the web goes out first): a page not+ * yet published becomes Published as before, without its address, and the+ * person is told; a published page's address can't be changed until then.+ */+export function PublishDialog({+ draftId,+ published,+ onClose,+ onPublished,+}: {+ draftId: string;+ /** Already published: the dialog changes its address. */+ published: boolean;+ onClose: () => void;+ /** Where the page is live now; null when the address couldn't be kept. */+ onPublished: (publishedUrl: string | null) => void;+}) {+ const t = useTranslations('contentEditor.publish');+ const tFailure = useTranslations('apiFailure');+ // Undefined while the starting address is read.+ const [url, setUrl] = useState<string | undefined>(undefined);+ const [saving, setSaving] = useState(false);+ const [problem, setProblem] = useState<string | null>(null);+ const input = useRef<HTMLInputElement>(null);++ useEffect(() => {+ let cancelled = false;+ readPublishAddress(draftId)+ .catch(() => '')+ .then((address) => {+ if (cancelled) return;+ setUrl((now) => now ?? address);+ // Disabled while it was read: the field takes focus once it can be typed in.+ requestAnimationFrame(() => input.current?.focus());+ });+ return () => {+ cancelled = true;+ };+ }, [draftId]);++ const save = async () => {+ if (!url?.trim()) return;+ setSaving(true);+ setProblem(null);+ const result = await publishPage(draftId, url.trim());+ if (!result.ok && result.code === 'no_route' && !published) {+ const kept = await setContentDraftStatus(draftId, 'published').then(+ () => true,+ (err) => {+ console.error('Failed to mark the page published:', err);+ return false;+ },+ );+ setSaving(false);+ if (!kept) {+ setProblem(t('failed'));+ return;+ }+ toast.warning(t('addressNotKept'));+ onPublished(null);+ onClose();+ return;+ }+ setSaving(false);+ if (!result.ok) {+ setProblem(+ result.code === 'invalid_url'+ ? t('invalidUrl')+ : result.code === 'session' || result.code === 'workspace' || result.code === 'busy'+ ? tFailure(result.code)+ : t(result.code === 'not_found' ? 'notFound' : 'failed'),+ );+ return;+ }+ if (result.onBrandDomain) toast.success(t('done'));+ else toast.warning(t('offDomain'));+ onPublished(result.publishedUrl);+ onClose();+ };++ return (+ <Dialog open onOpenChange={(open) => !open && !saving && onClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ <DialogDescription>{t('description')}</DialogDescription>+ </DialogHeader>+ <form+ className="space-y-1.5"+ // The address is checked by the API, its words from en.json, not the browser's.+ noValidate+ onSubmit={(e) => {+ e.preventDefault();+ if (!saving) void save();+ }}+ >+ <Label htmlFor="publish-url">{t('label')}</Label>+ <Input+ ref={input}+ id="publish-url"+ type="url"+ inputMode="url"+ autoComplete="url"+ placeholder="https://"+ disabled={url === undefined}+ value={url ?? ''}+ onChange={(e) => {+ setUrl(e.target.value);+ setProblem(null);+ }}+ aria-invalid={problem ? true : undefined}+ aria-describedby="publish-url-hint"+ />+ <p+ id="publish-url-hint"+ // Always there, so a problem in it is read out as it comes.+ aria-live="polite"+ className={+ problem ? 'text-xs text-red-700 dark:text-red-400' : 'text-xs text-muted-foreground'+ }+ >+ {problem ?? t('hint')}+ </p>+ </form>+ <DialogFooter className="gap-2">+ <Button variant="outline" disabled={saving} onClick={onClose}>+ {t('cancel')}+ </Button>+ <Button disabled={saving || !url?.trim()} onClick={() => void save()}>+ {saving && <LoadingDots className="mr-1" />}+ {t('save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/lib/actions/content-drafts-library.test.ts b/web/src/lib/actions/content-drafts-library.test.tsindex c9173a5f0..852d49b30 100644--- a/web/src/lib/actions/content-drafts-library.test.ts+++ b/web/src/lib/actions/content-drafts-library.test.ts@@ -17,9 +17,11 @@ let writeResult: { data: unknown; error: { code?: string; message: string } | nuvi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));const reopenDraftTasks = vi.hoisted(() => vi.fn());+const unpublishDraftWork = vi.hoisted(() => vi.fn());vi.mock('@/lib/content/action-drafts', async (importOriginal) => ({...(await importOriginal<typeof import('@/lib/content/action-drafts')>()),reopenDraftTasks,+ unpublishDraftWork,}));vi.mock('@/lib/supabase/server', () => ({createClient: vi.fn(async () => ({@@ -152,6 +154,34 @@ describe('the Library row menu (00233)', () => {reopenDraftTasks.mockClear();await setContentDraftStatus(DRAFT, 'published');expect(reopenDraftTasks).not.toHaveBeenCalled();+ // Only a published page leaves what its action measures.+ expect(unpublishDraftWork).not.toHaveBeenCalled();+ });++ it('takes a published page back in its action too: its Publish task and its live address', async () => {+ reopenDraftTasks.mockReset().mockResolvedValue(1);+ unpublishDraftWork.mockReset().mockResolvedValue(1);+ writeResult = {+ data: { id: DRAFT, status: 'published', brand_id: 'b1', method: 'create', action_id: 'a1' },+ error: null,+ };+ await setContentDraftStatus(DRAFT, 'in_review');+ expect(reopenDraftTasks).toHaveBeenCalledWith(+ expect.anything(),+ { id: DRAFT, brandId: 'b1', actionId: 'a1', method: 'create' },+ 'u1',+ );+ expect(unpublishDraftWork).toHaveBeenCalledWith(+ expect.anything(),+ { id: DRAFT, brandId: 'b1', actionId: 'a1' },+ 'u1',+ );+ // The status has changed either way.+ unpublishDraftWork.mockRejectedValueOnce(new Error('boom'));+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ await expect(setContentDraftStatus(DRAFT, 'draft')).resolves.toBeUndefined();+ expect(error).toHaveBeenCalled();+ error.mockRestore();});it('refuses Ready (it goes through Mark ready) and a malformed id, writing nothing', async () => {diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 0369845c6..cf48f41e4 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -98,6 +98,7 @@ import {findActionDraft,reopenDraftTasks,setDraftTasksStatus,+ unpublishDraftWork,type ActionDraft,} from '@/lib/content/action-drafts';import { supabaseAdmin } from '@/lib/supabase/admin';@@ -237,7 +238,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>const { data, error } = await supabase.from('content_drafts').select(- `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, author_id, reviewer_id, source_url, rules, kept_sources, author_real_at, author_profile_at, action_id, agent_state, agent_state_at, agent_run, updated_at, archived_at, quality_handoff, ${BRAND_SITE}, actions(action_no)`,+ `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, author_id, reviewer_id, source_url, published_url, rules, kept_sources, author_real_at, author_profile_at, action_id, agent_state, agent_state_at, agent_run, updated_at, archived_at, quality_handoff, ${BRAND_SITE}, actions(action_no)`,).eq('id', id).maybeSingle();@@ -251,6 +252,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>pageTypeSource: data.page_type_source === 'user' ? 'user' : 'detected',siteType: brandSiteType(data.brands),sourceUrl: data.source_url,+ publishedUrl: data.published_url ?? null,method: data.method as DraftMethod,status: draftStatus(data.status),bodyHtml: data.body_html,@@ -1471,7 +1473,9 @@ const ROW_STATUSES = ['draft', 'in_review', 'published'] as const;* editor's own status changes). Ready keeps a History version and completes* the draft's task, so it goes through markContentDraftReady instead. A* ready or published draft moved back to Draft or In review opens again the- * task Ready completed, as the editor's Ready does when clicked.+ * task Ready completed, as the editor's Ready does when clicked; a published+ * one also opens again the Publish task a page's publish completed, and+ * leaves what its action is measured on (unpublishDraftWork).*/export async function setContentDraftStatus(id: string,@@ -1498,6 +1502,34 @@ export async function setContentDraftStatus(if (!data) throw new Error('not_found');const wasDone = before.status === 'ready' || before.status === 'published';if (wasDone && status !== 'published') await reopenTasksOf(supabase, id, before);+ if (before.status === 'published' && status !== 'published') {+ await unpublishOf(supabase, id, before);+ }+}++/**+ * A published draft taken back, in its action (unpublishDraftWork). The+ * draft's status has changed either way: a failure is logged, and a task+ * left done can be changed in the drawer.+ */+async function unpublishOf(+ supabase: Awaited<ReturnType<typeof createClient>>,+ id: string,+ draft: { brand_id: string; action_id: string | null },+): Promise<void> {+ if (!draft.action_id) return;+ try {+ const {+ data: { user },+ } = await supabase.auth.getUser();+ await unpublishDraftWork(+ supabase,+ { id, brandId: draft.brand_id, actionId: draft.action_id },+ user?.id ?? null,+ );+ } catch (err) {+ console.error('Failed to take the page back in its action:', err);+ }}/**diff --git a/web/src/lib/content/action-drafts.test.ts b/web/src/lib/content/action-drafts.test.tsindex 92f1b3f41..0b52f1b91 100644--- a/web/src/lib/content/action-drafts.test.ts+++ b/web/src/lib/content/action-drafts.test.ts@@ -6,6 +6,7 @@ import {draftMethodForTask,findActionDraft,reopenDraftTasks,+ unpublishDraftWork,type ActionDraft,} from './action-drafts';@@ -20,6 +21,8 @@ interface Op {op: 'select' | 'update' | 'insert';value?: unknown;filters: [string, string, unknown][];+ /** An update that reads back the rows it wrote. */+ returning?: boolean;}let ops: Op[];let rows: Record<string, unknown[]>;@@ -29,7 +32,7 @@ const db = {const op: Op = { table, op: 'select', filters: [] };ops.push(op);const chain: Record<string, unknown> = {- select: () => chain,+ select: () => (op.op === 'update' && (op.returning = true), chain),eq: (col: string, v: unknown) => (op.filters.push(['eq', col, v]), chain),in: (col: string, v: unknown) => (op.filters.push(['in', col, v]), chain),is: (col: string, v: unknown) => (op.filters.push(['is', col, v]), chain),@@ -39,7 +42,10 @@ const db = {insert: (value: unknown) => ((op.op = 'insert'), (op.value = value), chain),maybeSingle: async () => ({ data: rows[table]?.[0] ?? null, error: null }),then: (resolve: (r: unknown) => void) =>- resolve({ data: op.op === 'select' ? (rows[table] ?? []) : null, error: null }),+ resolve({+ data: op.op === 'select' ? (rows[table] ?? []) : op.returning ? [{ id: 'row' }] : null,+ error: null,+ }),};return chain;},@@ -249,3 +255,86 @@ describe('reopenDraftTasks', () => {expect(ops.some((op) => op.table === 'action_events')).toBe(false);});});++describe('unpublishDraftWork', () => {+ const published = { id: 'd1', brandId: 'b1', actionId: 'act-1' };+ const live = (over: Record<string, unknown> = {}) => ({+ status: 'in_progress',+ updated_at: '2026-10-25T10:00:00Z',+ payload: {+ pages: ['https://acme.example/a'],+ publishedPages: { d1: 'https://acme.example/live', d2: 'https://acme.example/other' },+ },+ ...over,+ });+ const taskUpdates = () => ops.filter((op) => op.table === 'action_tasks' && op.op === 'update');+ const payloadWrites = () =>+ ops.filter(+ (op) =>+ op.table === 'actions' &&+ op.op === 'update' &&+ (op.value as { payload?: unknown }).payload !== undefined,+ );++ it('reopens the Publish task a page’s publish completed, and takes the page out of what the action measures', async () => {+ rows.actions = [live()];+ rows.action_tasks = [{ id: 't-publish', status: 'completed' }];+ // Completed by another page's publish, the last of the action's work to go live.+ rows.action_events = [+ { data: { taskId: 't-publish', to: 'completed', draftId: 'd2', publishedUrl: 'x' } },+ ];+ await expect(unpublishDraftWork(db, published, 'u1')).resolves.toBe(1);+ expect(ops[0].filters).toEqual([+ ['eq', 'id', 'act-1'],+ ['eq', 'brand_id', 'b1'],+ ['is', 'deleted_at', null],+ ]);+ expect(ops[1].filters).toContainEqual(['eq', 'task_key', 'publish_content']);+ expect(taskUpdates()).toEqual([+ expect.objectContaining({+ value: expect.objectContaining({ status: 'in_progress', skip_reason: null }),+ filters: [+ ['eq', 'action_id', 'act-1'],+ ['eq', 'id', 't-publish'],+ ],+ }),+ ]);+ // The other pages stay measured; written only if the action is as read.+ expect(payloadWrites()).toEqual([+ expect.objectContaining({+ value: expect.objectContaining({+ payload: {+ pages: ['https://acme.example/a'],+ publishedPages: { d2: 'https://acme.example/other' },+ },+ }),+ filters: [+ ['eq', 'id', 'act-1'],+ ['eq', 'updated_at', '2026-10-25T10:00:00Z'],+ ],+ }),+ ]);+ });++ it('leaves a Publish task a person completed last, and writes nothing for a page not measured', async () => {+ rows.actions = [live({ payload: { pages: [] } })];+ rows.action_tasks = [{ id: 't-publish', status: 'completed' }];+ rows.action_events = [{ data: { taskId: 't-publish', to: 'completed' } }];+ await expect(unpublishDraftWork(db, published, 'u1')).resolves.toBe(0);+ expect(taskUpdates()).toEqual([]);+ expect(payloadWrites()).toEqual([]);+ });++ it('keeps a closed action’s tasks but stops measuring the page, and leaves a deleted action', async () => {+ rows.actions = [live({ status: 'completed' })];+ rows.action_tasks = [{ id: 't-publish', status: 'completed' }];+ await expect(unpublishDraftWork(db, published, 'u1')).resolves.toBe(0);+ expect(ops.some((op) => op.table === 'action_tasks')).toBe(false);+ expect(payloadWrites()).toHaveLength(1);++ ops = [];+ rows.actions = [];+ await expect(unpublishDraftWork(db, published, 'u1')).resolves.toBe(0);+ expect(ops).toHaveLength(1);+ });+});diff --git a/web/src/lib/content/action-drafts.ts b/web/src/lib/content/action-drafts.tsindex 662517374..43b857439 100644--- a/web/src/lib/content/action-drafts.ts+++ b/web/src/lib/content/action-drafts.ts@@ -63,6 +63,8 @@ export function findActionDraft(const TASK_DONE = ['completed', 'skipped', 'failed'];/** A draft whose writing is done. */const DRAFT_DONE: DraftStatus[] = ['ready', 'published'];+/** Tries at writing an action's live pages when another write lands between (as the API's). */+const PAGE_WRITES = 3;/*** Moves an action's tasks to a status for a draft's work, as a change in the@@ -183,29 +185,143 @@ export async function reopenDraftTasks(const completed = (tasks ?? []).filter((task) => task.status === 'completed');if (!completed.length) return 0;- const { data: events, error: eventsError } = await db+ // A draft's Ready (or its publish) names its draft.+ const latest = await latestChanges(db, draft.actionId);+ const byReady = completed.filter((task) => {+ const change = latest.get(task.id);+ return change?.to === 'completed' && typeof change.draftId === 'string';+ });+ await setDraftTasksStatus(+ db,+ draft,+ byReady.map((task) => task.id),+ 'in_progress',+ actorId,+ );+ return byReady.length;+}++/** Each task's latest change in the action's History. */+async function latestChanges(+ db: SupabaseClient,+ actionId: string,+): Promise<Map<string, { to?: unknown; draftId?: unknown }>> {+ const { data: events, error } = await db.from('action_events').select('data')- .eq('action_id', draft.actionId)+ .eq('action_id', actionId).eq('event', 'task_status').order('created_at', { ascending: false });- if (eventsError) throw new Error(eventsError.message);- // Each task's latest change, newest first: a draft's Ready names its draft.+ if (error) throw new Error(error.message);+ // Newest first: the first change read for a task is its latest.const latest = new Map<string, { to?: unknown; draftId?: unknown }>();for (const event of events ?? []) {const data = event.data as { taskId?: unknown; to?: unknown; draftId?: unknown } | null;if (typeof data?.taskId === 'string' && !latest.has(data.taskId)) latest.set(data.taskId, data);}- const byReady = completed.filter((task) => {+ return latest;+}++/**+ * The draft's live address out of what its action is measured on+ * (payload.publishedPages, CE-013). Written only when the payload is still+ * as read, read again when another write landed first, as the API writes it.+ */+async function dropLivePage(+ db: SupabaseClient,+ draft: { id: string; actionId: string },+ action: { payload: unknown; updated_at: string },+): Promise<void> {+ let current = action;+ for (let attempt = 0; attempt < PAGE_WRITES; attempt++) {+ const payload =+ current.payload && typeof current.payload === 'object'+ ? (current.payload as Record<string, unknown>)+ : {};+ const live =+ payload.publishedPages && typeof payload.publishedPages === 'object'+ ? { ...(payload.publishedPages as Record<string, unknown>) }+ : {};+ if (!(draft.id in live)) return;+ delete live[draft.id];+ const { data, error } = await db+ .from('actions')+ .update({+ payload: { ...payload, publishedPages: live },+ updated_at: new Date().toISOString(),+ })+ .eq('id', draft.actionId)+ .eq('updated_at', current.updated_at)+ .select('id');+ if (error) throw new Error(error.message);+ if (data?.length) return;+ const { data: again, error: readError } = await db+ .from('actions')+ .select('payload, updated_at')+ .eq('id', draft.actionId)+ .maybeSingle();+ if (readError) throw new Error(readError.message);+ if (!again) return;+ current = again;+ }+ throw new Error('the action changed while its live page was taken out');+}++/**+ * A published page taken back (CE-013). Its action's work isn't all live+ * any more: a Publish task a page's publish completed goes back to in+ * progress, in the action's History; one a person completed last stays as+ * it is. And the action stops measuring the page at its live address. A+ * closed action (completed or dismissed) keeps its tasks but still stops+ * measuring it: a completed one is measured after it closes. A deleted+ * action (00168) is left as it is. Returns how many tasks it reopened.+ */+export async function unpublishDraftWork(+ db: SupabaseClient,+ draft: { id: string; brandId: string; actionId: string },+ actorId: string | null,+): Promise<number> {+ const { data: action, error: actionError } = await db+ .from('actions')+ .select('status, payload, updated_at')+ .eq('id', draft.actionId)+ .eq('brand_id', draft.brandId)+ .is('deleted_at', null)+ .maybeSingle();+ if (actionError) throw new Error(actionError.message);+ if (!action) return 0;+ const closed = CLOSED_ACTION_STATUSES.includes(action.status as ActionStatus);+ // The tasks first: an address that can't be taken out doesn't keep Publish done.+ const reopened = closed ? 0 : await reopenPublishTasks(db, draft, actorId);+ await dropLivePage(db, draft, action);+ return reopened;+}++/** The action's Publish tasks a page's publish completed (the trail names a draft), in progress again. */+async function reopenPublishTasks(+ db: SupabaseClient,+ draft: { id: string; brandId: string; actionId: string },+ actorId: string | null,+): Promise<number> {+ const { data: tasks, error: tasksError } = await db+ .from('action_tasks')+ .select('id, status')+ .eq('action_id', draft.actionId)+ .eq('task_key', 'publish_content');+ if (tasksError) throw new Error(tasksError.message);+ const completed = (tasks ?? []).filter((task) => task.status === 'completed');+ if (!completed.length) return 0;+ const latest = await latestChanges(db, draft.actionId);+ const byPublish = completed.filter((task) => {const change = latest.get(task.id);return change?.to === 'completed' && typeof change.draftId === 'string';});await setDraftTasksStatus(db,draft,- byReady.map((task) => task.id),+ byPublish.map((task) => task.id),'in_progress',actorId,);- return byReady.length;+ return byPublish.length;}diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.tsindex 69f9e16c3..1d1d2e569 100644--- a/web/src/lib/content/drafts.ts+++ b/web/src/lib/content/drafts.ts@@ -154,6 +154,11 @@ export interface ContentDraft {siteType: SiteType;/** The existing page an optimize draft is for, when Start picked one. */sourceUrl: string | null;+ /**+ * Where the page is live (CE-013): given when it was marked published, or+ * by its CMS (00262). The Live page tab measures it, else sourceUrl.+ */+ publishedUrl: string | null;method: DraftMethod;status: DraftStatus;bodyHtml: string;diff --git a/web/src/lib/content/next-step.test.ts b/web/src/lib/content/next-step.test.tsindex 76124e4f0..99bfba9d8 100644--- a/web/src/lib/content/next-step.test.ts+++ b/web/src/lib/content/next-step.test.ts@@ -154,7 +154,13 @@ describe('nextStep', () => {expect(nextStep(state({ quality: null })).step.primary).toBe('markReady');expect(ids(state({ quality: null }))).toHaveLength(4);const ready = state({ open: false, openRules: rules(3) });- expect(nextStep(ready).step).toMatchObject({ id: 'ready', primary: 'export' });+ // Marked ready: Mark published beside Export, for its live address (CE-013); published, Export alone.+ expect(nextStep(ready).step).toMatchObject({+ id: 'ready',+ primary: 'export',+ alternative: 'markPublished',+ });+ expect(nextStep({ ...ready, published: true }).step.alternative).toBeNull();expect(nextStep(ready).path.every((p) => p.state === 'done' || p.state === 'skipped')).toBe(true,);diff --git a/web/src/lib/content/next-step.ts b/web/src/lib/content/next-step.tsindex d39af9f28..42efba8fc 100644--- a/web/src/lib/content/next-step.ts+++ b/web/src/lib/content/next-step.ts@@ -37,7 +37,9 @@ export type NextAction =| 'showTodos'| 'beforePublish'| 'markReady'- | 'export';+ | 'export'+ // CE-013: the address the page went live at.+ | 'markPublished';/*** The most open rules "If you see…" names for Fix open rules alone: from@@ -223,7 +225,8 @@ function steps(s: NextStepState): NextStep[] {/*** The step to take now (the first whose state calls for it and that wasn't* skipped at that state), the path, and the tips. A page marked ready or- * published is ready to publish: Export.+ * published is ready to publish: Export; marked ready, Mark published beside+ * it, for its live address (CE-013).*/export function nextStep(s: NextStepState): NextPath {const due = s.open ? steps(s) : [];@@ -234,7 +237,12 @@ export function nextStep(s: NextStepState): NextPath {alternative: null,skippable: false,}- : { id: 'ready', primary: 'export', alternative: null, skippable: false };+ : {+ id: 'ready',+ primary: 'export',+ alternative: s.published ? null : 'markPublished',+ skippable: false,+ };const step = due.find((d) => !d.skippable || s.skipped[d.id] !== stepState(d.id, s)) ?? check;// The third step is the one the page needs: its Length, or its open rulesdiff --git a/web/src/lib/content/publish-client.test.ts b/web/src/lib/content/publish-client.test.tsnew file mode 100644index 000000000..0aa55d3e8--- /dev/null+++ b/web/src/lib/content/publish-client.test.ts@@ -0,0 +1,111 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** Mark published (CE-013), from the browser: the API writes the address. */++const reads = vi.hoisted(() => ({+ draft: null as Record<string, unknown> | null,+ domain: null as { domain: string } | null,+ filters: [] as [string, unknown][],+}));+vi.mock('@/lib/supabase/client', () => ({+ createClient: () => ({+ auth: { getSession: async () => ({ data: { session: { access_token: 'tok' } } }) },+ from: (table: string) => {+ const chain = {+ select: () => chain,+ eq: (col: string, value: unknown) => (reads.filters.push([col, value]), chain),+ limit: () => chain,+ maybeSingle: async () => ({+ data: table === 'content_drafts' ? reads.draft : reads.domain,+ error: null,+ }),+ };+ return chain;+ },+ }),+}));++const { publishPage, readLiveUrl, readPublishAddress } = await import('./publish-client');++const fetchMock = vi.fn();+beforeEach(() => {+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ reads.draft = null;+ reads.domain = null;+ reads.filters = [];+});+const answer = (status: number, body: unknown) =>+ fetchMock.mockResolvedValue(new Response(JSON.stringify(body), { status }));++describe('publishPage', () => {+ it('sends the address through the proxy with the session, and reads the answer', async () => {+ answer(200, {+ publishedUrl: 'https://acme.example/x',+ publishedAt: '2026-10-25T10:00:00Z',+ onBrandDomain: false,+ taskCompleted: true,+ });+ expect(await publishPage('d1', 'https://acme.example/x')).toEqual({+ ok: true,+ publishedUrl: 'https://acme.example/x',+ publishedAt: '2026-10-25T10:00:00Z',+ onBrandDomain: false,+ taskCompleted: true,+ });+ expect(fetchMock).toHaveBeenCalledWith('/api/aeo/api/content-drafts/d1/publish', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer tok' },+ body: JSON.stringify({ url: 'https://acme.example/x' }),+ });+ });++ it('names an address that isn’t one, a page gone, and the general reasons', async () => {+ answer(400, { code: 'invalid_url' });+ expect(await publishPage('d1', 'x')).toEqual({ ok: false, code: 'invalid_url' });+ answer(404, { code: 'not_found' });+ expect(await publishPage('d1', 'x')).toEqual({ ok: false, code: 'not_found' });+ // Any other 404 (Express's own "Cannot POST", no JSON): an API without the route.+ fetchMock.mockResolvedValue(new Response('<pre>Cannot POST</pre>', { status: 404 }));+ expect(await publishPage('d1', 'x')).toEqual({ ok: false, code: 'no_route' });+ answer(403, { code: 'not_in_workspace' });+ expect(await publishPage('d1', 'x')).toEqual({ ok: false, code: 'workspace' });+ answer(500, { code: 'failed' });+ expect(await publishPage('d1', 'x')).toEqual({ ok: false, code: 'failed' });+ });+});++describe('readPublishAddress', () => {+ it('starts from where the page went live, else the page it optimizes, else the brand’s site and its slug', async () => {+ reads.draft = {+ brand_id: 'b1',+ published_url: 'https://acme.example/live',+ source_url: 'https://acme.example/old',+ slug: 's',+ };+ expect(await readPublishAddress('d1')).toBe('https://acme.example/live');+ reads.draft = { ...reads.draft, published_url: null };+ expect(await readPublishAddress('d1')).toBe('https://acme.example/old');+ reads.draft = { ...reads.draft, source_url: null, slug: 'cold-brew' };+ reads.domain = { domain: 'https://www.acme.example/' };+ expect(await readPublishAddress('d1')).toBe('https://www.acme.example/cold-brew');+ // The brand's primary domain.+ expect(reads.filters).toContainEqual(['is_primary', true]);+ // No slug yet (never sent): the title's, never the site's home page.+ reads.draft = { ...reads.draft, slug: null, title: 'Cold Brew at Home' };+ expect(await readPublishAddress('d1')).toBe('https://www.acme.example/cold-brew-at-home');+ reads.draft = { ...reads.draft, title: '' };+ expect(await readPublishAddress('d1')).toBe('');+ reads.domain = null;+ expect(await readPublishAddress('d1')).toBe('');+ reads.draft = null;+ expect(await readPublishAddress('d1')).toBe('');+ });++ it('reads where the page is live now', async () => {+ reads.draft = { published_url: 'https://acme.example/live' };+ expect(await readLiveUrl('d1')).toBe('https://acme.example/live');+ reads.draft = null;+ expect(await readLiveUrl('d1')).toBeNull();+ });+});diff --git a/web/src/lib/content/publish-client.ts b/web/src/lib/content/publish-client.tsnew file mode 100644index 000000000..7f8bc365f--- /dev/null+++ b/web/src/lib/content/publish-client.ts@@ -0,0 +1,125 @@+import { BROWSER_API_BASE_URL } from '@/config/api';+import { apiFailure } from '@/lib/api-failure';+import { createClient } from '@/lib/supabase/client';+import { slugOf } from '@/lib/content/ready-to-publish';++/**+ * A page marked Published at its live address (CE-013), from the browser+ * through the API's proxy: the address is the server's to write, as a CMS's+ * is (00262), and a linked action gets the live page with it.+ */++export type PublishError =+ | 'invalid_url'+ | 'not_found'+ /** The API has no publish route yet (an API older than CE-013's). */+ | 'no_route'+ | 'session'+ | 'workspace'+ | 'busy'+ | 'failed';++export type PublishResult =+ | {+ ok: true;+ publishedUrl: string;+ publishedAt: string;+ /** Off the brand's domains, it's kept, but the Live page tab can't measure it. */+ onBrandDomain: boolean;+ /** The linked action's Publish task done (every page it names live). */+ taskCompleted: boolean;+ }+ | { ok: false; code: PublishError };++/** Where the page is live now (CE-013), or null: after it was published elsewhere meanwhile. */+export async function readLiveUrl(draftId: string): Promise<string | null> {+ const { data } = await createClient()+ .from('content_drafts')+ .select('published_url')+ .eq('id', draftId)+ .maybeSingle();+ return data?.published_url ?? null;+}++/** Marks the page Published at `url`. */+export async function publishPage(draftId: string, url: string): Promise<PublishResult> {+ try {+ const {+ data: { session },+ } = await createClient().auth.getSession();+ if (!session) return { ok: false, code: 'session' };+ const res = await fetch(+ `${BROWSER_API_BASE_URL}/api/content-drafts/${encodeURIComponent(draftId)}/publish`,+ {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ url }),+ },+ );+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ if (!res.ok) {+ if (body.code === 'invalid_url' || body.code === 'invalid')+ return { ok: false, code: 'invalid_url' };+ // A page gone is the route's own answer; any other 404 (Express's+ // "Cannot POST", no JSON) is an API without the route.+ if (res.status === 404 && body.code !== 'not_found') return { ok: false, code: 'no_route' };+ const general = apiFailure(res.status, body);+ return {+ ok: false,+ code:+ general === 'session' ||+ general === 'workspace' ||+ general === 'busy' ||+ general === 'not_found'+ ? general+ : 'failed',+ };+ }+ return {+ ok: true,+ publishedUrl: String(body.publishedUrl ?? url),+ publishedAt: String(body.publishedAt ?? new Date().toISOString()),+ onBrandDomain: body.onBrandDomain !== false,+ taskCompleted: body.taskCompleted === true,+ };+ } catch (err) {+ console.error('Failed to mark the page published:', err);+ return { ok: false, code: 'failed' };+ }+}++/**+ * The address the dialog starts from: where the page went live (a CMS's, or+ * one given before), else the page it optimizes, else the brand's site with+ * the page's slug (its last send's, else its title's: never the site's home+ * page, which the person would mark live with one click). Empty when none+ * can be read.+ */+export async function readPublishAddress(draftId: string): Promise<string> {+ const supabase = createClient();+ const { data: draft, error } = await supabase+ .from('content_drafts')+ .select('brand_id, title, published_url, source_url, slug')+ .eq('id', draftId)+ .maybeSingle();+ if (error || !draft) return '';+ if (draft.published_url) return draft.published_url;+ if (draft.source_url) return draft.source_url;+ const { data: domain } = await supabase+ .from('brand_domains')+ .select('domain')+ .eq('brand_id', draft.brand_id)+ .eq('is_primary', true)+ .limit(1)+ .maybeSingle();+ const host = String(domain?.domain ?? '')+ .trim()+ .replace(/^https?:\/\//i, '')+ .replace(/\/.*$/, '');+ const slug = draft.slug || slugOf(draft.title ?? '', null);+ if (!host || !slug) return '';+ return `https://${host}/${slug}`;+}diff --git a/web/src/lib/content/ready-to-publish.ts b/web/src/lib/content/ready-to-publish.tsindex c0ee96a68..56c27ac6a 100644--- a/web/src/lib/content/ready-to-publish.ts+++ b/web/src/lib/content/ready-to-publish.ts@@ -388,7 +388,7 @@ function description(root: HTMLElement): string {}/** A live page's own address part ("/blog/pour-over"), else the title as one. */-function slugOf(title: string, sourceUrl: string | null): string {+export function slugOf(title: string, sourceUrl: string | null): string {if (sourceUrl) {try {const parts = new URL(sourceUrl).pathname