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): fit the editor header to its width, its icon buttons labelled on hover and focus (Next step basket, part 2) (#1429)
Cihan1e257581b3ef
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 59debaa3d..3c1f697ce 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3555,6 +3555,18 @@"applied": "HTML applied · formatting cleaned","appliedUnsafe": "HTML applied · {count, plural, one {# unsafe tag} other {# unsafe tags}} removed"},+ "header": {+ "rename": "{title} · click to rename it in the page",+ "running": "{count, plural, one {# running} other {# running}}",+ "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.",+ "backInReview": "Back in review.",+ "backInReviewFailed": "Couldn't move it back to review.",+ "notReady": "Its status is now {status}, so it stays.",+ "renameInHtml": "Rename it in the HTML view's text, or close the view to rename it in the page."+ },"markReady": "Mark ready","copyHtml": "Copy HTML","copyHtmlHint": "Copy the page as HTML to publish, HTML blocks and schema included",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 e8848787f..77c8ec31d 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@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useFormatter, useTranslations } from 'next-intl';import { toast } from 'sonner';import { EditorContent, useEditor } from '@tiptap/react';+import type { Node as PmNode } from '@tiptap/pm/model';import { TextSelection, type Transaction } from '@tiptap/pm/state';import StarterKit from '@tiptap/starter-kit';import { TableKit } from '@tiptap/extension-table';@@ -31,6 +32,7 @@ import {getDraftSuggestions,keepAgentBeforeVersion,markContentDraftReady,+ unmarkContentDraftReady,restoreDraftVersion,setContentDraftAuthor,setContentDraftPageType,@@ -133,6 +135,7 @@ import { HtmlBlock, copyToClipboard } from './_html-block';import { OwnCopies, ownCopyHtml } from './_own-copies';import { NextNudge, useNextNudge } from './_next-nudge';import { PageInfoStrip, pageInfoKey } from './_page-info';+import { HeaderTip } from './_header-tip';import { NextStepButton, readSkips, wordsUnderTitle, writeSkips } from './_next-step';import { useTodoCopy, type QualityRead } from './_quality-tab';import { PageTypeMenu } from './_page-type-menu';@@ -254,6 +257,7 @@ export function DraftEditor({const flashTimer = useRef<ReturnType<typeof setTimeout>>(undefined);useEffect(() => () => clearTimeout(pageReadTimer.current), []);const [status, setStatus] = useState(draft.status);+ const tDraftStatus = useTranslations('contentEditor.status');const [marking, setMarking] = useState(false);// The Content Agent couldn't finish the page Start gave it (CE-015).const [agentFailed, setAgentFailed] = useState(draft.agentState === 'failed');@@ -1740,6 +1744,57 @@ export function DraftEditor({}};+ /**+ * Ready, clicked (Next step spec §3b): the page goes back to review, while+ * it is still ready (published meanwhile from the Library, it says so). The+ * task Mark ready completed stays done.+ */+ const [unmarking, setUnmarking] = useState(false);+ const unmarkReady = async () => {+ if (unmarking) return;+ setUnmarking(true);+ try {+ const now = await unmarkContentDraftReady(draft.id);+ setStatus(now);+ if (now === 'in_review') toast(t('header.backInReview'));+ else toast(t('header.notReady', { status: tDraftStatus(now) }));+ } catch (err) {+ console.error('Failed to move the draft back to review:', err);+ toast.error(t('header.backInReviewFailed'));+ } finally {+ setUnmarking(false);+ }+ };+ /**+ * The header's title, clicked: the caret at the end of the block the title+ * is read from (draftTitleFromDoc: the first H1 with words, else the first+ * heading, else the first block with words), to rename it there.+ */+ const renameInPage = () => {+ if (!editor) return;+ // The HTML view holds the page: the title is renamed in its text there.+ if (htmlSource !== null) {+ toast(t('header.renameInHtml'));+ return;+ }+ const blocks: { node: PmNode; end: number }[] = [];+ editor.state.doc.forEach((node, offset) => {+ if (node.isTextblock && node.textContent.trim()) {+ blocks.push({ node, end: offset + node.nodeSize - 1 });+ }+ });+ const heading = (level?: number) =>+ blocks.find(+ ({ node }) =>+ node.type.name === 'heading' && (level === undefined || node.attrs.level === level),+ );+ const pick = heading(1) ?? heading() ?? blocks[0];+ const { doc } = editor.state;+ const at = pick ? TextSelection.near(doc.resolve(pick.end), -1) : TextSelection.atStart(doc);+ editor.view.dispatch(editor.state.tr.setSelection(at).scrollIntoView());+ editor.commands.focus(undefined, { scrollIntoView: false });+ };+// A version from History replaces the page: what's waiting is saved first,// as the server keeps the page it replaces, and the page can't change// while the restore runs.@@ -1788,6 +1843,10 @@ export function DraftEditor({}};+ // Why History waits (the HTML view holds the page, a restore runs), or null.+ const historyWaits =+ htmlSource !== null ? t('history.htmlOpen') : restoring ? t('history.restoring') : null;+return (<div className="flex min-h-0 flex-1 flex-col">{/* Two lines: the title and what you do with the page on top, which@@ -1803,10 +1862,34 @@ export function DraftEditor({><ArrowLeft className="h-4 w-4" /></Link>- <h1 className="min-w-0 truncate text-sm font-medium" title={title.trim() || undefined}>- {title.trim() || t('untitled')}- </h1>- <div className="ml-auto flex shrink-0 items-center gap-1.5 sm:gap-3">+ {/* The title takes the room left (at least ~140px from 1024px, 96px+ narrower; less while the save state needs its words), ends in "…",+ and never pushes, overlaps or wraps the buttons (Next step spec §3b). */}+ <div className="flex min-w-0 flex-1 items-center gap-2.5">+ <h1+ className={cn(+ 'shrink text-sm font-medium',+ autosave.state === 'conflict' ||+ autosave.state === 'too_large' ||+ autosave.state === 'failed'+ ? 'min-w-16'+ : 'min-w-24 lg:min-w-[140px]',+ )}+ >+ <button+ type="button"+ onClick={renameInPage}+ title={t('header.rename', { title: title.trim() || t('untitled') })}+ className="block max-w-full truncate rounded-sm text-left hover:underline hover:underline-offset-2 focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none"+ >+ {title.trim() || t('untitled')}+ </button>+ </h1>+ <span className="shrink-0">+ <SaveIndicator state={autosave.state} onRetry={() => void autosave.retry()} />+ </span>+ </div>+ <div className="flex shrink-0 items-center gap-1.5 sm:gap-2.5">{qualityOn && (<NextStepButtonnext={next}@@ -1832,57 +1915,99 @@ export function DraftEditor({}/>)}- <SaveIndicator state={autosave.state} onRetry={() => void autosave.retry()} />- <HistoryMenu- draftId={draft.id}- disabled={- htmlSource !== null- ? t('history.htmlOpen')- : restoring- ? t('history.restoring')- : null- }- onRestore={(version, label) => void restoreVersion(version, label)}- />- <Button- variant="outline"- size="sm"- onClick={copyPageHtml}- title={t('copyHtmlHint')}- aria-label={t('copyHtml')}- >- <Copy className="h-3.5 w-3.5" />- <span className="hidden xl:inline">{t('copyHtml')}</span>- </Button>- {quality ? (+ {/* The agent at work on this page: a click opens the basket, with its steps and Stop. */}+ {/* Fix open rules or the brief at work: the basket shows their steps and Stop. */}+ {qualityOn && agentWorking && (+ <HeaderTip label={t('header.running', { count: 1 })} hint={t('header.runningHint')}>+ <button+ type="button"+ onClick={() => {+ setNextFocus(true);+ setNextOpen(true);+ }}+ aria-label={t('header.running', { count: 1 })}+ className="inline-flex h-7 shrink-0 items-center gap-1.5 rounded-full border px-2 text-xs font-medium text-muted-foreground hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none"+ >+ <span+ aria-hidden+ className="h-1.5 w-1.5 animate-pulse rounded-full bg-emerald-500 motion-reduce:animate-none dark:bg-emerald-400"+ />+ {/* Narrower than 1024px, the dot alone: the count is on hover. */}+ <span className="hidden lg:inline">{t('header.running', { count: 1 })}</span>+ </button>+ </HeaderTip>+ )}+ <HeaderTip label={t('history.button')} hint={historyWaits ?? t('history.hint')}>+ <HistoryMenu+ draftId={draft.id}+ disabled={historyWaits}+ onRestore={(version, label) => void restoreVersion(version, label)}+ />+ </HeaderTip>+ <HeaderTip label={t('copyHtml')} hint={t('copyHtmlHint')}><Buttonvariant="outline"- size="sm"- disabled={!editor}- title={t('export.hint')}- aria-label={t('export.button')}- onClick={() => openBeforePublish('export')}+ size="icon-sm"+ onClick={copyPageHtml}+ aria-label={t('copyHtml')}>- <Download className="h-3.5 w-3.5" />- <span className="hidden sm:inline">{t('export.button')}</span>+ <Copy className="h-3.5 w-3.5" /></Button>+ </HeaderTip>+ {quality ? (+ <HeaderTip label={t('export.button')} hint={t('export.hint')}>+ <Button+ variant="outline"+ size="icon-sm"+ disabled={!editor}+ aria-label={t('export.button')}+ onClick={() => openBeforePublish('export')}+ >+ <Download className="h-3.5 w-3.5" />+ </Button>+ </HeaderTip>) : (<ExportMenu disabled={!editor} onExport={(format) => void exportPage(format)} />)}- <Button- size="sm"- // A page that can't be saved can't be marked ready; the save state says why.- disabled={- !canMarkReady ||- marking ||- autosave.state === 'conflict' ||- autosave.state === 'too_large'- }- onClick={() => (quality ? openBeforePublish('markReady') : void markReady())}- >- {marking ? <LoadingDots /> : !canMarkReady && <Check className="h-3.5 w-3.5" />}- {t('markReady')}- </Button>+ {/* The one black button. Marked, it reads Ready (a click moves it back+ to review); published, Published. Narrower than 1024px, ✓ alone. */}+ {status === 'ready' || status === 'published' ? (+ <HeaderTip+ label={tDraftStatus(status)}+ hint={status === 'ready' ? t('header.readyHint') : t('header.publishedHint')}+ >+ <Button+ variant="outline"+ size="sm"+ // Published stays focusable, so its tip says where to change it.+ disabled={status === 'published' || unmarking}+ focusableWhenDisabled+ aria-label={+ status === 'ready' ? t('header.readyLabel') : tDraftStatus('published')+ }+ onClick={() => void 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" />}+ <span className="hidden lg:inline">{tDraftStatus(status)}</span>+ </Button>+ </HeaderTip>+ ) : (+ <HeaderTip label={t('markReady')} narrowOnly>+ <Button+ size="sm"+ // A page that can't be saved can't be marked ready; the save state says why.+ disabled={+ marking || autosave.state === 'conflict' || autosave.state === 'too_large'+ }+ aria-label={t('markReady')}+ onClick={() => (quality ? openBeforePublish('markReady') : void markReady())}+ >+ {marking ? <LoadingDots /> : <Check className="h-3.5 w-3.5 lg:hidden" />}+ <span className="hidden lg:inline">{t('markReady')}</span>+ </Button>+ </HeaderTip>+ )}<Buttonvariant="ghost"size="icon-sm"@@ -2287,9 +2412,21 @@ function SaveIndicator({ state, onRetry }: { state: SaveState; onRetry: () => vo</span>);}+ // Narrower than 1024px, a dot: the words stay for screen readers and on hover.return (- <span className="text-xs text-muted-foreground" role="status">- {t(state)}+ <span+ className="flex items-center gap-1.5 text-xs text-muted-foreground"+ role="status"+ title={t(state)}+ >+ <span+ aria-hidden+ className={cn(+ 'h-1.5 w-1.5 rounded-full lg:hidden',+ state === 'saved' ? 'bg-emerald-500 dark:bg-emerald-400' : 'bg-muted-foreground',+ )}+ />+ <span className="sr-only lg:not-sr-only">{t(state)}</span></span>);}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_header-tip.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_header-tip.test.tsxnew file mode 100644index 000000000..8ffb78293--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_header-tip.test.tsx@@ -0,0 +1,87 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { HeaderTip } from './_header-tip';++/**+ * The header's icon buttons show their label on hover and keyboard focus,+ * close it with Escape, and give the hint to screen readers as the button's+ * description (Next step spec §3b).+ */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++async function render(narrowOnly = false) {+ await act(async () => {+ root.render(+ <HeaderTip label="Copy HTML" hint="Copy the page as HTML" narrowOnly={narrowOnly}>+ <button type="button" aria-label="Copy HTML" />+ </HeaderTip>,+ );+ });+}+const tip = () => document.querySelector('[data-slot="tooltip-content"]');+const wait = () => act(async () => new Promise((resolve) => setTimeout(resolve, 400)));++describe('HeaderTip', () => {+ it('gives the hint to screen readers as the button’s description', async () => {+ await render();+ const button = container.querySelector('button')!;+ const hint = document.getElementById(button.getAttribute('aria-describedby')!)!;+ expect(hint.textContent).toBe('Copy the page as HTML');+ expect(hint.hidden).toBe(true);+ });++ it('shows the label and hint on hover, and closes with Escape', async () => {+ await render();+ const trigger = container.querySelector('span')!;+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));+ trigger.dispatchEvent(new MouseEvent('mouseenter', { bubbles: false }));+ trigger.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ });+ await wait();+ expect(tip()!.textContent).toBe('Copy HTMLCopy the page as HTML');+ await act(async () => {+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));+ });+ await wait();+ expect(tip()).toBeNull();+ });++ it('shows on keyboard focus', async () => {+ await render();+ await act(async () => {+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', bubbles: true }));+ container.querySelector('button')!.focus();+ });+ await wait();+ expect(tip()!.textContent).toBe('Copy HTMLCopy the page as HTML');+ });++ it('shows only narrower than 1024px for a button that shows its label where there is room', async () => {+ await render(true);+ const trigger = container.querySelector('span')!;+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));+ trigger.dispatchEvent(new MouseEvent('mouseenter', { bubbles: false }));+ trigger.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ });+ await wait();+ expect(tip()!.className).toContain('lg:hidden');+ });+});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.tsxnew file mode 100644index 000000000..fe9785c2b--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_header-tip.tsx@@ -0,0 +1,44 @@+'use client';++import { cloneElement, useId, type ReactElement } from 'react';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { cn } from '@/lib/utils';++/**+ * An icon button's label in the editor header (Next step spec §3b): the+ * app's tooltip, under the button, on hover and on keyboard focus, and+ * closed with Escape. The button keeps its aria-label, and the hint is its+ * description for screen readers too. The tip sits on a span around the+ * button, so a disabled one (no pointer events) still shows why it waits.+ */+export function HeaderTip({+ label,+ hint,+ narrowOnly = false,+ children,+}: {+ label: string;+ hint?: string;+ /** For a button that shows its label where there's room: the tip only narrower than 1024px. */+ narrowOnly?: boolean;+ /** The button; it gets the hint as its description. */+ children: ReactElement<{ 'aria-describedby'?: string }>;+}) {+ const hintId = useId();+ return (+ <Tooltip>+ <TooltipTrigger delay={300} closeDelay={0} render={<span className="inline-flex" />}>+ {hint ? cloneElement(children, { 'aria-describedby': hintId }) : children}+ {hint && (+ <span id={hintId} hidden>+ {hint}+ </span>+ )}+ </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>}+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsxindex fe68e8128..fff2a50de 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsx@@ -26,8 +26,11 @@ export function HistoryMenu({draftId,disabled,onRestore,+ 'aria-describedby': describedBy,}: {draftId: string;+ /** The header's hint for it (HeaderTip). */+ 'aria-describedby'?: string;/** Why it can't open now (the HTML view is open), or null. */disabled: string | null;onRestore: (version: DraftVersion, label: string) => void;@@ -64,13 +67,14 @@ export function HistoryMenu({return (<DropdownMenu onOpenChange={(open) => open && load()}><DropdownMenuTrigger- render={<Button variant="outline" size="sm" />}+ render={<Button variant="outline" size="icon-sm" />}disabled={disabled !== null}- title={disabled ?? t('hint')}+ // The header shows its label and hint on hover and focus; why it waits, here.+ title={disabled ?? undefined}aria-label={t('button')}+ aria-describedby={describedBy}><History className="h-3.5 w-3.5" />- <span className="hidden xl:inline">{t('button')}</span></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-80"><DropdownMenuGroup>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 3d1c5392c..c281f8dfc 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@@ -13,6 +13,7 @@ import ContentEditorPage from './page';const getContentDraft = vi.fn();const markContentDraftReady = vi.fn();+const unmarkContentDraftReady = vi.fn();const saveContentDraft = vi.fn();const setContentDraftPageType = vi.fn();const setContentDraftAuthor = vi.fn();@@ -70,6 +71,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({getContentResults: (...args: unknown[]) => getContentResults(...args),getContentDraft: (...args: unknown[]) => getContentDraft(...args),markContentDraftReady: (...args: unknown[]) => markContentDraftReady(...args),+ unmarkContentDraftReady: (...args: unknown[]) => unmarkContentDraftReady(...args),saveContentDraft: (...args: unknown[]) => saveContentDraft(...args),setContentDraftPageType: (...args: unknown[]) => setContentDraftPageType(...args),setContentDraftAuthor: (...args: unknown[]) => setContentDraftAuthor(...args),@@ -235,6 +237,7 @@ beforeEach(() => {root = createRoot(container);getContentDraft.mockReset();markContentDraftReady.mockReset();+ unmarkContentDraftReady.mockReset().mockResolvedValue('in_review');saveBlob.mockReset();setContentDraftPageType.mockReset().mockResolvedValue(undefined);setContentDraftAuthor.mockReset().mockResolvedValue(undefined);@@ -695,8 +698,72 @@ describe('the content editor', () => {expect(toast.success).toHaveBeenCalledWith("Marked ready. Publish it on your site when you're ready.",);- expect(container.querySelector('header')!.textContent).toContain('Ready');- expect(button('Mark ready')!.disabled).toBe(true);+ // Marked: Ready, in green, where Mark ready was; a click moves it back to review.+ expect(button('Mark ready')).toBeUndefined();+ const ready = button('Ready: click to move it back to review')!;+ expect(ready.textContent).toBe('Ready');+ await act(async () => ready.click());+ expect(unmarkContentDraftReady).toHaveBeenCalledWith('d1');+ expect(toast).toHaveBeenCalledWith('Back in review.');+ expect(button('Mark ready')!.disabled).toBe(false);+ });++ it('keeps Ready when moving it back fails, and a page published meanwhile published', async () => {+ getContentDraft.mockResolvedValue(draft({ status: 'ready' }));+ unmarkContentDraftReady.mockRejectedValueOnce(new Error('network'));+ await renderPage();+ await act(async () => button('Ready: click to move it back to review')!.click());+ expect(toast.error).toHaveBeenCalledWith("Couldn't move it back to review.");+ expect(button('Ready: click to move it back to review')).toBeDefined();++ unmarkContentDraftReady.mockResolvedValueOnce('published');+ 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');+ });++ it('says Published, not to be undone here, on a published page', async () => {+ getContentDraft.mockResolvedValue(draft({ status: 'published' }));+ await renderPage();+ expect(button('Mark ready')).toBeUndefined();+ // Disabled but focusable, so its tip says where to change it.+ expect(button('Published')!.getAttribute('aria-disabled')).toBe('true');+ });++ it("puts the caret at the end of the page's H1 when the title is clicked", async () => {+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ const title = container.querySelector<HTMLButtonElement>('header h1 button')!;+ expect(title.textContent).toBe('Pipeline forecasting');+ await act(async () => title.click());+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })+ .editor;+ // The H1 is the page's first block: its end is its text's length past its start.+ expect(editor.state.selection.from).toBe(1 + 'Pipeline forecasting'.length);+ });++ it('puts the caret where the title comes from with no H1, and asks for the page while HTML shows', async () => {+ getContentDraft.mockResolvedValue(+ draft({ bodyHtml: '<p></p><h2>Pipeline forecasting</h2><p>Teams trust it.</p>' }),+ );+ await renderPage();+ const title = container.querySelector<HTMLButtonElement>('header h1 button')!;+ await act(async () => title.click());+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })+ .editor;+ // The empty line (2 positions), then the H2's text.+ expect(editor.state.selection.from).toBe(2 + 1 + 'Pipeline forecasting'.length);++ await act(async () => button('Edit as HTML')!.click());+ await act(async () => title.click());+ expect(toast).toHaveBeenCalledWith(+ "Rename it in the HTML view's text, or close the view to rename it in the page.",+ );+ // History waits while the HTML view holds the page, and says why.+ const history = button('History')!;+ expect(document.getElementById(history.getAttribute('aria-describedby')!)!.textContent).toBe(+ 'Go back to the page to use History',+ );});it('links the action the draft is the work of, and says Ready completed its task', async () => {@@ -1490,7 +1557,7 @@ describe('the content editor', () => {expect(writeText).toHaveBeenLastCalledWith(code);const copyPage = [...container.querySelectorAll<HTMLButtonElement>('header button')].find(- (b) => b.textContent === 'Copy HTML',+ (b) => b.getAttribute('aria-label') === 'Copy HTML',)!;await act(async () => copyPage.click());// The block went in where the cursor was: the start, as nothing was clicked.@@ -2360,7 +2427,7 @@ describe('the side panel', () => {const writeText = vi.fn().mockResolvedValue(undefined);Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });const copyPage = [...container.querySelectorAll<HTMLButtonElement>('header button')].find(- (b) => b.textContent === 'Copy HTML',+ (b) => b.getAttribute('aria-label') === 'Copy HTML',)!;await act(async () => copyPage.click());expect(writeText).toHaveBeenLastCalledWith(@@ -3270,6 +3337,52 @@ describe('the side panel', () => {expect(nextButton()!.getAttribute('aria-label')).not.toBe('Next · Fix open rules');});+ it('says "1 running" while Fix open rules works, and opens the basket on it', async () => {+ getDraftSources.mockResolvedValue({+ data: {+ prompts: [],+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],+ citedPages: [],+ gscQueries: [],+ brandDomains: [],+ competitorDomains: [],+ },+ choices: [],+ });+ getDraftBrief.mockResolvedValue({+ brief: {+ goal: 'Win forecasting searches',+ audience: 'Sales leaders',+ outline: [],+ keywords: [],+ origin: 'rebuild',+ builtAt: '2026-10-21T10:00:00Z',+ builtFrom: { prompts: 0, fanouts: 1, pages: 0, queries: 0 },+ },+ });+ getContentDraft.mockResolvedValue(+ draft({+ method: 'create',+ pageType: 'blog_post',+ rules: {+ set: null,+ source: 'default',+ overrides: { length: { on: false } },+ textRules: [],+ },+ }),+ );+ fixDraftRules.mockReturnValue(new Promise(() => {}));+ await renderPage();+ expect(button('1 running')).toBeUndefined();+ await act(async () => nextButton()!.click());+ await act(async () => inBasket('Fix open rules')!.click());+ await act(async () => {});+ expect(basket()).toBeNull();+ await act(async () => button('1 running')!.click());+ expect(basket()!.textContent).toContain('Content Agent is working');+ });+it('stays out of the header while Quality is off', async () => {delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;getContentDraft.mockResolvedValue(diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsindex abec0a2b3..788b1c8c5 100644--- a/web/src/lib/actions/content-drafts.test.ts+++ b/web/src/lib/actions/content-drafts.test.ts@@ -90,6 +90,7 @@ const {saveContentDraft,setContentDraftAuthor,setContentDraftPageType,+ unmarkContentDraftReady,} = await import('./content-drafts');const { bodyHash } = await import('@/lib/content/editor');@@ -343,6 +344,38 @@ describe('setContentDraftAuthor', () => {});});+describe('unmarkContentDraftReady', () => {+ it('moves a ready draft back to review, and only a ready one', async () => {+ updated = { status: 'in_review' };+ await expect(unmarkContentDraftReady(DRAFT)).resolves.toBe('in_review');+ expect(calls[0]).toMatchObject({+ op: 'update',+ value: { status: 'in_review' },+ filters: [+ ['eq', 'id', DRAFT],+ ['eq', 'status', 'ready'],+ ],+ });+ });++ it('leaves a draft published meanwhile published, and says so', async () => {+ updated = null;+ row = {+ id: DRAFT,+ brand_id: 'b1',+ title: '',+ page_type: null,+ method: 'create',+ status: 'published',+ body_html: '',+ author: 'user',+ updated_at: '2026-10-20T15:00:00Z',+ };+ await expect(unmarkContentDraftReady(DRAFT)).resolves.toBe('published');+ await expect(unmarkContentDraftReady('d1')).rejects.toThrow('invalid');+ });+});+describe('markContentDraftReady', () => {it('moves a draft or an agent draft in review to ready', async () => {updated = { status: 'ready' };diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex dedbc3aab..b338d725b 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -1358,6 +1358,29 @@ export async function markContentDraftReady(return { status: current.status, tasksDone: 0 };}+/**+ * Ready, clicked in the editor's header (Next step spec §3b): the page goes+ * back to review, only while it is still ready. One published from the+ * Library meanwhile keeps its status. Returns the status the draft has after.+ * The task Mark ready completed stays done.+ */+export async function unmarkContentDraftReady(id: string): Promise<DraftStatus> {+ if (!draftId.safeParse(id).success) throw new Error('invalid');+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('content_drafts')+ .update({ status: 'in_review' })+ .eq('id', id)+ .eq('status', 'ready')+ .select('status')+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (data) return draftStatus(data.status);+ const current = await getContentDraft(id);+ if (!current) throw new Error('not_found');+ return current.status;+}+/*** Keeps the draft as it is now in its History (CE-018, 00215* content_draft_snapshot). A failure is logged, not thrown: the step it