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
fix(content): keep one H1 per page (#1370)
Cihanfa8ce77b1ded
diff --git a/server/src/lib/content-agent.js b/server/src/lib/content-agent.jsindex c7dce7d6c..031be4f5f 100644--- a/server/src/lib/content-agent.js+++ b/server/src/lib/content-agent.js@@ -160,6 +160,10 @@ const INSERT_TAGS = new Set([export function cleanInsertHtml(html) {const $ = cheerio.load(html || '', null, false);$('script, style, iframe, object, embed, noscript, template, head, title').remove();+ // The page has its H1, its title: an agent's heading is an H2 at most.+ $('h1').each((_, el) => {+ el.name = 'h2';+ });for (const el of $('*').get().reverse()) {if (!INSERT_TAGS.has(el.tagName?.toLowerCase())) {$(el).replaceWith($(el).contents());diff --git a/server/src/lib/content-agent.test.js b/server/src/lib/content-agent.test.jsindex 9715b4767..bc831729a 100644--- a/server/src/lib/content-agent.test.js+++ b/server/src/lib/content-agent.test.js@@ -392,6 +392,12 @@ describe('a replace on a heading', () => {});describe('cleanInsertHtml', () => {+ it('makes an agent’s H1 an H2: the page has its title', () => {+ expect(cleanInsertHtml('<h1 class="x">New title</h1><p>Text</p>')).toBe(+ '<h2>New title</h2><p>Text</p>',+ );+ });+it('keeps simple blocks without attributes and unwraps the rest', () => {expect(cleanInsertHtml('<div><h3 style="x">Q</h3><ol><li><em>a</em></li></ol><img src=x></div>'),diff --git a/server/src/lib/page-content.js b/server/src/lib/page-content.jsindex 813c89643..c32f04a38 100644--- a/server/src/lib/page-content.js+++ b/server/src/lib/page-content.js@@ -263,9 +263,16 @@ export function extractPageContent(html, pageUrl) {.filter((text) => text && text.length <= MAX_JSON_LD_LENGTH).slice(0, MAX_JSON_LD);- const h1 = clean($('h1').first().text());- const title =- h1 || clean($('meta[property="og:title"]').attr('content')) || clean($('title').first().text());+ // The H1s with words, and the page's order, before the frame goes: an+ // article's title often sits in its own <header>.+ const order = new Map(+ $('*')+ .toArray()+ .map((el, i) => [el, i]),+ );+ const worded = $('h1')+ .toArray()+ .filter((el) => clean($(el).text()));const body = $('body');body.find(FRAME).remove();@@ -280,7 +287,29 @@ export function extractPageContent(html, pageUrl) {!textArea || ($(el).closest(textArea).length === 0 && !$(el).find(textArea).length),).remove();- const heading = body.find('h1').first()[0] ?? null;+ // The title's H1, picked once: the last one with words before the text's+ // first paragraph (not a logo's or a site name's above it), else the first.+ // A byline, date or breadcrumb line above the title is no paragraph of it.+ const lead = textArea+ ? $(textArea)+ .find('p, li, pre, blockquote')+ .toArray()+ .find(+ (el) =>+ clean($(el).text()).length >= MIN_PARAGRAPH &&+ ![el, ...$(el).parentsUntil(textArea).toArray()].some((block) =>+ named($(block), PAGE_FURNITURE_WORDS),+ ),+ )+ : null;+ const titleH1 =+ (lead && worded.filter((el) => order.get(el) < order.get(lead)).at(-1)) || worded[0] || null;+ const title =+ clean(titleH1 ? $(titleH1).text() : '') ||+ clean($('meta[property="og:title"]').attr('content')) ||+ clean($('title').first().text());+ // Still on the page (not in a header that went with the frame).+ const heading = titleH1 && $(titleH1).closest('body').length > 0 ? titleH1 : null;const main = MAIN_SELECTORS.map((selector) => $(selector).toArray()).flat().find((el) => !textArea || el === textArea || $(el).find(textArea).length > 0);@@ -395,6 +424,13 @@ export function extractPageContent(html, pageUrl) {}});+ // One H1 per page, its title: any other becomes an H2, and one without+ // words (a logo) is no heading.+ for (const el of root.find('h1').toArray()) {+ if (el === heading) continue;+ if (!clean($(el).text())) $(el).replaceWith($(el).contents());+ else el.name = 'h2';+ }let content = (root.html() ?? '').trim();// A title above the content (a hero outside <main>) heads it, as the// draft's title is its first heading.diff --git a/server/src/lib/page-content.test.js b/server/src/lib/page-content.test.jsindex 391bbb0b5..01edf9b1f 100644--- a/server/src/lib/page-content.test.js+++ b/server/src/lib/page-content.test.js@@ -57,6 +57,66 @@ describe('extractPageContent', () => {expect(body.html).toBe('<p>Just text</p>');});+ it('keeps one H1, its first, and makes the others H2s', () => {+ const { html } = extractPageContent(+ '<body><main><h1>AEO vs SEO</h1><p>Intro.</p><h1>Key takeaways</h1><p>Short.</p></main></body>',+ 'https://acme.example/aeo',+ );+ expect(html).toBe('<h1>AEO vs SEO</h1><p>Intro.</p><h2>Key takeaways</h2><p>Short.</p>');+ });++ it('keeps the article’s H1, not a logo’s or a site name’s before it', () => {+ const lead = 'Forecasts that sales leaders trust, built from real activity. '.repeat(6);+ const logo = extractPageContent(+ `<body><div id="page"><div class="top"><h1><a href="/"><img alt="Acme" src="/logo.png"></a></h1></div><div class="content"><h1>Pipeline forecasting</h1><p>${lead}</p><p>${lead}</p></div></div></body>`,+ 'https://acme.example/forecasting',+ );+ expect(logo.html).toContain('<h1>Pipeline forecasting</h1>');+ expect(logo.html.match(/<h1/g)).toHaveLength(1);++ const branding = extractPageContent(+ `<body><main><div class="site-branding"><h1>Acme</h1></div><article><h1>Pipeline forecasting</h1><p>${lead}</p><p>${lead}</p></article></main></body>`,+ 'https://acme.example/forecasting',+ );+ expect(branding.html).toContain('<h2>Acme</h2>');+ expect(branding.html).toContain('<h1>Pipeline forecasting</h1>');+ });++ it('keeps an article’s H1 over a site name’s when a byline line comes first', () => {+ const lead = 'Forecasts that sales leaders trust, built from real activity. '.repeat(6);+ const { title, html } = extractPageContent(+ `<body><div class="site-branding"><h1>Acme</h1></div><article><p class="entry-meta">Published on October 22, 2026 by Ada Lovelace</p><h1>Pipeline forecasting</h1><p>${lead}</p><p>${lead}</p></article></body>`,+ 'https://acme.example/forecasting',+ );+ expect(title).toBe('Pipeline forecasting');+ expect(html).toContain('<h1>Pipeline forecasting</h1>');+ expect(html).not.toContain('<h1>Acme</h1>');+ });++ it('keeps the title H1 of an article and makes a section H1 in its text an H2', () => {+ const lead = 'Forecasts that sales leaders trust, built from real activity. '.repeat(6);+ const { title, html } = extractPageContent(+ `<body><header class="site"><h1><a href="/">Acme</a></h1></header><article><h1 class="entry-title">Pipeline forecasting</h1><div class="entry-content"><p>${lead}</p><h1>Why forecasts miss</h1><p>${lead}</p></div></article></body>`,+ 'https://acme.example/forecasting',+ );+ expect(title).toBe('Pipeline forecasting');+ expect(html.match(/<h1/g)).toHaveLength(1);+ expect(html).toMatch(/<h1[^>]*>Pipeline forecasting<\/h1>/);+ expect(html).toContain('<h2>Why forecasts miss</h2>');+ });++ it('takes the title from an article’s own header, not the site’s logo H1', () => {+ const lead = 'Forecasts that sales leaders trust, built from real activity. '.repeat(6);+ const { title, html } = extractPageContent(+ `<body><header class="site"><h1><a href="/">Acme</a></h1></header><article><header class="entry-header"><h1 class="entry-title">Pipeline forecasting</h1></header><div class="entry-content"><p>${lead}</p><p>${lead}</p></div></article></body>`,+ 'https://acme.example/forecasting',+ );+ expect(title).toBe('Pipeline forecasting');+ expect(html.startsWith('<h1>Pipeline forecasting</h1>')).toBe(true);+ expect(html.match(/<h1/g)).toHaveLength(1);+ expect(html).not.toContain('Acme');+ });+it('heads the content with the page title when its H1 sits outside it', () => {const { html, title } = extractPageContent('<head><title>Lisbon & more</title></head><body><div class="hero"><h1>Lisbon & Porto</h1></div><main><p>Days out.</p></main></body>',diff --git a/web/messages/en.json b/web/messages/en.jsonindex 66a41c082..54fd1cefa 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3620,6 +3620,7 @@"fixing": "Content Agent is working…","fixed": "{count, plural, one {Content Agent suggested # change} other {Content Agent suggested # changes}} · review them in the page","nothingToFix": "Content Agent found nothing it could change without new facts.",+ "notForAgent": "Content Agent doesn't change heading levels: make the extra H1s H2s in the toolbar.","decideFirst": "Accept or reject the open suggestions first.","citedLoading": "Reading which passages AI quotes, so the agent leaves them as they are…","fixErrors": {@@ -3694,6 +3695,7 @@"toolbar": {"label": "Formatting","h1": "Heading 1",+ "h1Taken": "A page has one H1, its title: use Heading 2 here","h2": "Heading 2","h3": "Heading 3","bold": "Bold",@@ -3984,6 +3986,7 @@"names": {"sentence": "Max sentence length","length": "Length",+ "oneH1": "One H1 per page","summary": "AI Overview summary at the top","h2Answer": "Direct answer under each H2","fanoutH2": "Use top fan-outs as H2s",@@ -4021,6 +4024,7 @@},"hints": {"length": "A target, not a minimum: within 20% of it meets the rule. A page well over it is open, and Apply rules with Agent shortens it a few passages at a time.",+ "oneH1": "A page has one H1, its title. Make any other H1 an H2 in the toolbar: Content Agent doesn't change heading levels.","summary": "A short summary under the H1 that answer engines can quote.","fanoutH2": "Takes the top fan-outs you keep in Sources, the most searched first, not every one.","internalLinks": "Links with descriptive anchor text to your own pages.",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 5cc02ca81..196a9f6c0 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@@ -59,7 +59,7 @@ import {import { PAGE_READ_DELAY_MS, draftTitleFromDoc, safeLinkHref } from '@/lib/content/editor';import { JsonLd } from '@/lib/content/json-ld-node';import { detectPageType } from '@/lib/content/page-types';-import { aiTracesFound, lengthWarns } from '@/lib/content/rules';+import { aiTracesFound, lengthWarns, openRulesForAgent } from '@/lib/content/rules';import { saveBlob } from '@/lib/download';import { cn } from '@/lib/utils';import { AgentBar } from './_agent-bar';@@ -89,6 +89,7 @@ import {type SuggestionDecision,type SuggestionLabels,} from './_suggestions';+import { ONE_H1_AS_IS, OneH1 } from './_one-h1';import { useDraftReads } from './_use-draft-reads';import { useDraftRules } from './_use-draft-rules';import { EditorToolbar } from './_toolbar';@@ -260,6 +261,7 @@ export function DraftEditor({onHeld: (edit) => setHeld((current) => current ?? edit),}),AgentSuggestions.configure({ onDecide: (id, decision) => onDecide.current(id, decision) }),+ OneH1,],content: draft.bodyHtml,// Rendered on the client only, so the server's HTML can't disagree with it.@@ -567,10 +569,12 @@ export function DraftEditor({toast(t('suggestions.decideFirst'));return;}- const open = rules.rules.filter(- ({ rule, status }) => rule.on && status.state === 'bad' && (!only || only.includes(rule.key)),- );- if (open.length === 0) return;+ const { forAgent: open, notForAgent } = openRulesForAgent(rules.rules, only);+ if (open.length === 0) {+ // Only rules it can't fix are open: say what to do instead.+ if (notForAgent.length) toast(t('suggestions.notForAgent'));+ return;+ }const pageText = editor.getText({ blockSeparator: '\n' });const request = {rules: open.map(({ rule, status }) => ({@@ -839,6 +843,8 @@ export function DraftEditor({editor.chain().setMeta(CITED_EDIT_ALLOWED, true)+ // The version as it was, its H1s too: the page on the server is it.+ .setMeta(ONE_H1_AS_IS, true).setContent(restored.bodyHtml, { emitUpdate: false }).run();// The server has this page now: nothing from before it is still todiff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_one-h1.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_one-h1.test.tsnew file mode 100644index 000000000..82c00c1dd--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_one-h1.test.ts@@ -0,0 +1,78 @@+import { Editor } from '@tiptap/core';+import StarterKit from '@tiptap/starter-kit';+import { afterEach, describe, expect, it } from 'vitest';+import { ONE_H1_AS_IS, OneH1, h1Positions } from './_one-h1';++let editor: Editor | null = null;+afterEach(() => {+ editor?.destroy();+ editor = null;+});++const open = (content: string) => {+ editor = new Editor({ extensions: [StarterKit, OneH1], content });+ return editor;+};++/** The page, without the empty line the editor keeps after a last heading. */+const html = (e: Editor) => e.getHTML().replace(/(<p><\/p>)+$/, '');++/** One H1 per page: a second one, however it comes, is an H2. */+describe('OneH1', () => {+ it('makes a pasted or inserted H1 an H2, keeping the page’s own', () => {+ const e = open('<h1>Title</h1><p>Text</p>');+ e.commands.insertContentAt(e.state.doc.content.size, '<h1>Pasted</h1><p>More</p>');+ expect(html(e)).toBe('<h1>Title</h1><p>Text</p><h2>Pasted</h2><p>More</p>');++ // Above the title too: the title stays the H1.+ e.commands.insertContentAt(0, '<h1>Above</h1>');+ expect(html(e)).toBe('<h2>Above</h2><h1>Title</h1><p>Text</p><h2>Pasted</h2><p>More</p>');+ });++ it('turns Heading 1 on a second block into Heading 2', () => {+ const e = open('<h1>Title</h1><p>Text</p>');+ e.chain().setTextSelection(9).toggleHeading({ level: 1 }).run();+ expect(html(e)).toBe('<h1>Title</h1><h2>Text</h2>');+ });++ it('lets a page without one have its H1, and a whole new page keep its first', () => {+ const e = open('<p>Text</p>');+ e.chain().setTextSelection(1).toggleHeading({ level: 1 }).run();+ expect(html(e)).toBe('<h1>Text</h1>');++ // The HTML view writes the page anew.+ e.commands.setContent('<h1>One</h1><p>a</p><h1>Two</h1>');+ expect(html(e)).toBe('<h1>One</h1><p>a</p><h2>Two</h2>');+ });++ it('leaves a page that already had two as it was, for the person to fix', () => {+ const e = open('<h1>One</h1><p>a</p><h1>Two</h1>');+ e.commands.insertContentAt(4, ' more');+ expect(html(e)).toBe('<h1>One more</h1><p>a</p><h1>Two</h1>');+ });++ it('keeps the title when an H1 lands right at its start', () => {+ const e = open('<h1>Title</h1><p>Text</p>');+ e.commands.insertContentAt(1, '<h1>New</h1>');+ expect(html(e)).toContain('<h1>Title</h1>');+ expect(html(e).match(/<h1>/g)).toHaveLength(1);+ });++ it('restores a version from History as it was', () => {+ const e = open('<h1>Title</h1><p>Text</p>');+ e.chain().setMeta(ONE_H1_AS_IS, true).setContent('<h1>One</h1><h1>Two</h1>').run();+ expect(html(e)).toBe('<h1>One</h1><h1>Two</h1>');+ });++ it('never lets an empty H1 line stay over the title', () => {+ const e = open('<h1></h1><p>Text</p>');+ e.commands.insertContentAt(e.state.doc.content.size, '<h1>Title</h1>');+ expect(html(e)).toContain('<h1>Title</h1>');+ expect(h1Positions(e.state.doc)).toHaveLength(1);+ });++ it('finds the H1s in lists and cells too', () => {+ const e = open('<h1>A</h1><ul><li><h1>B</h1></li></ul>');+ expect(h1Positions(e.state.doc)).toHaveLength(2);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_one-h1.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_one-h1.tsnew file mode 100644index 000000000..9bdc78b5e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_one-h1.ts@@ -0,0 +1,70 @@+import { Extension } from '@tiptap/core';+import type { Node as PmNode } from '@tiptap/pm/model';+import { Plugin, PluginKey } from '@tiptap/pm/state';++/**+ * One H1 per page: the H1 is the page's title. A change that gives a page a+ * second H1, typed, pasted, written in the HTML view or accepted from the+ * agent, makes the new one an H2, and the H1 the page had stays. A page that+ * already had several (an older draft, or a version restored from History)+ * keeps them until the person changes them; the Rules tab's "One H1 per+ * page" says so.+ */++/** Meta on a transaction that writes a page as it was (History's restore): left as it is. */+export const ONE_H1_AS_IS = 'oneH1AsIs';++/**+ * Where a page's H1s with words start, in order: an empty H1 line is no+ * title, so it never counts or stays over one with words.+ */+export function h1Positions(doc: PmNode): number[] {+ const found: number[] = [];+ doc.descendants((node, pos) => {+ if (node.type.name === 'heading' && node.attrs.level === 1 && node.textContent.trim()) {+ found.push(pos);+ }+ // Headings may sit in lists or cells; a paragraph's text holds none.+ return !node.isTextblock;+ });+ return found;+}++export const OneH1 = Extension.create({+ name: 'oneH1',++ addProseMirrorPlugins() {+ return [+ new Plugin({+ key: new PluginKey('oneH1'),+ appendTransaction(transactions, oldState, newState) {+ if (!transactions.some((tr) => tr.docChanged)) return null;+ if (transactions.some((tr) => tr.getMeta(ONE_H1_AS_IS))) return null;+ const after = h1Positions(newState.doc);+ if (after.length <= 1) return null;+ const before = h1Positions(oldState.doc);+ if (after.length <= before.length) return null;+ // The H1s the page had: by their words, else where they are now;+ // with none, its first.+ const kept = new Set<number>();+ for (const pos of before) {+ const text = oldState.doc.nodeAt(pos)!.textContent;+ const mapped = transactions.reduce((at, tr) => tr.mapping.map(at), pos);+ const same = after.find(+ (at) => !kept.has(at) && newState.doc.nodeAt(at)!.textContent === text,+ );+ const found = same ?? (after.includes(mapped) ? mapped : undefined);+ if (found !== undefined) kept.add(found);+ }+ if (kept.size === 0) kept.add(after[0]);+ const tr = newState.tr;+ for (const pos of after) {+ if (kept.has(pos)) continue;+ tr.setNodeMarkup(pos, undefined, { ...newState.doc.nodeAt(pos)!.attrs, level: 2 });+ }+ return tr;+ },+ }),+ ];+ },+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsxindex f0378eff9..e4f46aa54 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx@@ -38,6 +38,7 @@ import type { DraftRulesState } from './_use-draft-rules';/** Rules with an explanation on hover (spec §10). */const HINTED = new Set(['length',+ 'oneH1','summary','fanoutH2','internalLinks',@@ -362,11 +363,16 @@ function RuleRow({return (<li className={cn('px-3 py-2', !rule.on && 'opacity-60')}><div className="flex items-center gap-2">- <Switch- on={rule.on}- label={t('toggle', { name })}- onToggle={() => onChange({ on: !rule.on })}- />+ {rule.fixed ? (+ // Always on: the editor keeps it, so it has no switch.+ <span aria-hidden="true" className="w-7 shrink-0" />+ ) : (+ <Switch+ on={rule.on}+ label={t('toggle', { name })}+ onToggle={() => onChange({ on: !rule.on })}+ />+ )}<spanclassName="min-w-0 flex-1 text-xs"title={HINTED.has(rule.key) ? t(`hints.${rule.key}`) : undefined}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsxindex 03a83154d..101108262 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx@@ -40,6 +40,7 @@ import { formatNumber } from '@/lib/format';import { safeImageSrc, safeLinkHref } from '@/lib/content/editor';import { cn } from '@/lib/utils';import { HtmlBlockDialog } from './_html-block';+import { h1Positions } from './_one-h1';/*** Where the insert menu shows: the cursor on an empty paragraph between the@@ -88,6 +89,8 @@ export function EditorToolbar({editor,selector: ({ editor: e }) => ({h1: e.isActive('heading', { level: 1 }),+ // A page has one H1: another can't be made while it has one.+ h1Taken: !e.isActive('heading', { level: 1 }) && h1Positions(e.state.doc).length > 0,h2: e.isActive('heading', { level: 2 }),h3: e.isActive('heading', { level: 3 }),bold: e.isActive('bold'),@@ -105,6 +108,10 @@ export function EditorToolbar({});const chain = () => editor.chain().focus();+ /** Why a tool can't be used now, by its key. */+ const off: Record<string, string | undefined> = {+ h1: state.h1Taken ? t('h1Taken') : undefined,+ };const insertTable = () => chain().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run();const tools: { key: string; icon: LucideIcon; on: boolean; run: () => void; text?: string }[][] =[@@ -190,9 +197,10 @@ export function EditorToolbar({{group.map((tool) => (<ToolButtonkey={tool.key}- label={t(tool.key)}+ label={off[tool.key] ?? t(tool.key)}pressed={!htmlView && tool.on}disabled={htmlView}+ blocked={!!off[tool.key]}onClick={tool.run}><tool.icon className="h-4 w-4" />@@ -307,12 +315,15 @@ function ToolButton({label,pressed,disabled,+ blocked,onClick,children,}: {label: string;pressed?: boolean;disabled?: boolean;+ /** Can't be used here, but still says why on hover (a disabled button can't). */+ blocked?: boolean;onClick: () => void;children: React.ReactNode;}) {@@ -322,13 +333,15 @@ function ToolButton({title={label}aria-label={label}aria-pressed={pressed}+ aria-disabled={blocked || undefined}disabled={disabled}// Keep the editor's selection: a click on the toolbar mustn't move focus first.onMouseDown={(e) => e.preventDefault()}- onClick={onClick}+ onClick={blocked ? undefined : onClick}className={cn('flex h-7 min-w-7 items-center justify-center rounded-md px-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-40',pressed && 'bg-muted text-foreground',+ blocked && 'cursor-not-allowed opacity-40 hover:bg-transparent hover:text-muted-foreground',)}>{children}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 7c65cebf2..a52e913be 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@@ -255,6 +255,23 @@ describe('the content editor', () => {expect(container.querySelector('.ProseMirror h1')!.textContent).toBe('Pipeline forecasting');});+ it('keeps one H1: Heading 1 is off outside the title', async () => {+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })+ .editor;++ await act(async () => void editor.commands.setTextSelection(editor.state.doc.content.size - 2));+ // Off, yet still says why on hover.+ const off = button('A page has one H1, its title: use Heading 2 here')!;+ expect(off.getAttribute('aria-disabled')).toBe('true');+ expect(off.title).toBe('A page has one H1, its title: use Heading 2 here');+ await act(async () => off.click());+ expect(editor.getHTML()).not.toContain('<h1>Teams trust it.</h1>');+ await act(async () => void editor.commands.setTextSelection(2));+ expect(button('Heading 1')!.getAttribute('aria-disabled')).toBeNull();+ });+it('tags a new page as one', async () => {getContentDraft.mockResolvedValue(draft({@@ -1886,6 +1903,23 @@ describe('the side panel', () => {}});+ it('leaves a second H1 out of what the agent is asked, saying how to fix it', async () => {+ getContentDraft.mockResolvedValue(+ draft({ bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams trust it.</p><h1>Again</h1>' }),+ );+ await openRules();+ expect(panel()!.textContent).toContain('One H1 per page');+ // Always on: the editor keeps it, so it has no switch.+ expect(panel()!.querySelector('[aria-label="One H1 per page: on or off"]')).toBeNull();+ expect(panel()!.querySelector('[aria-label="Length: on or off"]')).not.toBeNull();++ await act(async () => panelButton('Apply rules with Agent').click());+ await act(async () => {});+ const asked = fixDraftRules.mock.calls[0][2].rules.map((r: { key: string }) => r.key);+ expect(asked).not.toContain('oneH1');+ expect(asked.length).toBeGreaterThan(0);+ });+it('fixes only the AI traces from their rule', async () => {getContentDraft.mockResolvedValue(traced);await openRules();diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsxindex 641e897bf..52ba5224b 100644--- a/web/src/components/content/new-content-dialog.test.tsx+++ b/web/src/components/content/new-content-dialog.test.tsx@@ -356,6 +356,29 @@ describe('New content', () => {expect(getContentOverlap).not.toHaveBeenCalled();});+ it('keeps one H1 in a pasted page, its first, the others H2s', async () => {+ await render();+ await click(radio('Optimize content'));+ await click(tab('Paste text'));+ const box = document.querySelector('textarea')!;+ const paste = new Event('paste', { bubbles: true, cancelable: true });+ Object.defineProperty(paste, 'clipboardData', {+ value: {+ getData: (type: string) =>+ type === 'text/html'+ ? '<h1>Returns policy</h1><p>30 days.</p><h1>Key points</h1><p>Free.</p>'+ : '',+ },+ });+ await act(async () => box.dispatchEvent(paste));+ await click(button('Continue'));+ await click(button('Open editor'));++ expect(createContentDraft.mock.calls[0][1].bodyHtml).toBe(+ '<h1>Returns policy</h1><p>30 days.</p><h2>Key points</h2><p>Free.</p>',+ );+ });+it('takes typed plain text as paragraphs, and a blog post when nothing tells the type', async () => {await render();await click(radio('Optimize content'));diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsxindex 06d270ea1..860a21600 100644--- a/web/src/components/content/new-content-dialog.tsx+++ b/web/src/components/content/new-content-dialog.tsx@@ -50,6 +50,7 @@ import { memberLabel } from '@/lib/action-center/display';import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';import { MAX_ATTACHMENT_BYTES, textToHtml } from '@/lib/content/attachments';import { cleanHtml } from '@/lib/content/clean-html';+import { oneH1Html } from '@/lib/content/one-h1';import { NO_DRAFT_RULES } from '@/lib/content/rules';import {contentEditorPath,@@ -356,10 +357,12 @@ export function NewContentDialog({}));const bring = (- html: string,+ incoming: string,imagesRemoved: number,origin: { fileName?: string; sourceUrl?: string; title?: string } = {},) => {+ // One H1 per page, its title, whichever way the page comes in.+ const html = oneH1Html(incoming);const fallback = origin.title || (origin.fileName ? fileTitle(origin.fileName) : '');const summary = summarizeContent(html, fallback);if (!summary.characters) {diff --git a/web/src/lib/content/agent-suggestions.test.ts b/web/src/lib/content/agent-suggestions.test.tsindex 67c6991a5..b74121d83 100644--- a/web/src/lib/content/agent-suggestions.test.ts+++ b/web/src/lib/content/agent-suggestions.test.ts@@ -34,6 +34,12 @@ describe('cleanInsertHtml', () => {),).toBe('<h2>FAQ</h2><p>How long? 3 min</p>');});++ it('makes an agent’s H1 an H2: the page has its title', () => {+ expect(cleanInsertHtml('<h1 class="x">New title</h1><p>Text</p>')).toBe(+ '<h2>New title</h2><p>Text</p>',+ );+ });});describe('keepAgentSuggestions', () => {diff --git a/web/src/lib/content/agent-suggestions.ts b/web/src/lib/content/agent-suggestions.tsindex a157f9b4e..91f4ef0c4 100644--- a/web/src/lib/content/agent-suggestions.ts+++ b/web/src/lib/content/agent-suggestions.ts@@ -61,6 +61,8 @@ export function cleanInsertHtml(html: string): string {return sanitizeHtml(html ?? '', {allowedTags: ['h2', 'h3', 'h4', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'b', 'i', 'br'],allowedAttributes: {},+ // The page has its H1, its title: an agent's heading is an H2 at most.+ transformTags: { h1: 'h2' },nonTextTags: ['script', 'style', 'textarea', 'option', 'noscript', 'template', 'title'],}).trim();}diff --git a/web/src/lib/content/agent-write.test.ts b/web/src/lib/content/agent-write.test.tsindex 5e60f79e7..8a019b7dc 100644--- a/web/src/lib/content/agent-write.test.ts+++ b/web/src/lib/content/agent-write.test.ts@@ -70,6 +70,8 @@ describe('agentWriteRequest', () => {const keys = request.rules.map((rule) => rule.key);expect(keys).not.toContain('faq');expect(keys).not.toContain('feedMatch');+ // Heading levels are the editor's: one H1 isn't the agent's to keep.+ expect(keys).not.toContain('oneH1');expect(keys).toContain('aiTraces');expect(request.rules.find((rule) => rule.key === 'length')).toEqual({key: 'length',diff --git a/web/src/lib/content/agent-write.ts b/web/src/lib/content/agent-write.tsindex e7db0da8a..8d1360d0a 100644--- a/web/src/lib/content/agent-write.ts+++ b/web/src/lib/content/agent-write.ts@@ -5,6 +5,7 @@ import { rebuildSources, type RebuildSources } from './brief';import { MAX_PASSAGES } from './cited-passages';import { isPageType, type DraftMethod } from './drafts';import {+ NOT_FOR_AGENT,activeRules,effectiveRules,ruleLength,@@ -93,7 +94,9 @@ export async function agentWriteRequest(const rules = (inEffect?.rules ??activeRules(ruleSet(setType, { language: draft.language }), effective).filter((rule) => rule.on)- ).filter((rule) => rule.check !== 'feed');+ )+ // Heading levels are the editor's (one H1), never the agent's.+ .filter((rule) => rule.check !== 'feed' && !NOT_FOR_AGENT.has(rule.key));const textRules =inEffect?.textRules ?? effective.textRules.filter((rule) => rule.on).map((rule) => rule.text);const length = ruleLength(rules, setType);diff --git a/web/src/lib/content/one-h1.test.ts b/web/src/lib/content/one-h1.test.tsnew file mode 100644index 000000000..bacc4c68d--- /dev/null+++ b/web/src/lib/content/one-h1.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import { oneH1Html } from './one-h1';++/** A page coming in whole keeps one H1, its title. */+describe('oneH1Html', () => {+ it('keeps the first H1 with words and makes the others H2s', () => {+ expect(oneH1Html('<h1>Title</h1><p>a</p><h1>Key <em>takeaways</em></h1><p>b</p>')).toBe(+ '<h1>Title</h1><p>a</p><h2>Key <em>takeaways</em></h2><p>b</p>',+ );+ });++ it('unwraps an H1 without words, so a logo never takes the title', () => {+ expect(oneH1Html('<h1><img src="/logo.png" alt=""></h1><h1>Title</h1>')).toBe(+ '<img src="/logo.png" alt=""><h1>Title</h1>',+ );+ });++ it('leaves a page with one H1, or none, as it was', () => {+ expect(oneH1Html('<h1>Title</h1><h2>A</h2>')).toBe('<h1>Title</h1><h2>A</h2>');+ expect(oneH1Html('<p>Just text</p>')).toBe('<p>Just text</p>');+ });+});diff --git a/web/src/lib/content/one-h1.ts b/web/src/lib/content/one-h1.tsnew file mode 100644index 000000000..49bbb66c9--- /dev/null+++ b/web/src/lib/content/one-h1.ts@@ -0,0 +1,22 @@+/**+ * A page's HTML with one H1, its title, as the editor keeps it+ * (editor/_one-h1.ts): the first H1 with words stays, any later one becomes+ * an H2, and one without words (a logo) is unwrapped. For a page that comes+ * in whole: a paste, a file or an imported page in New content.+ */+export function oneH1Html(html: string): string {+ const doc = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');+ let titled = false;+ for (const h1 of [...doc.body.querySelectorAll('h1')]) {+ if (!h1.textContent?.trim()) {+ h1.replaceWith(...h1.childNodes);+ } else if (titled) {+ const h2 = doc.createElement('h2');+ h2.append(...h1.childNodes);+ h1.replaceWith(h2);+ } else {+ titled = true;+ }+ }+ return doc.body.innerHTML;+}diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.tsindex 98260e07f..ab93a86d1 100644--- a/web/src/lib/content/rules.test.ts+++ b/web/src/lib/content/rules.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from 'vitest';import {NO_DRAFT_RULES,+ NOT_FOR_AGENT,+ openRulesForAgent,activeRules,effectiveRules,splitRules,@@ -171,6 +173,44 @@ describe('length and structure', () => {});});+ it('wants one H1 per page, and leaves the agent out of it', () => {+ expect(check('oneH1', '<h1>T</h1><h2>A</h2>')).toEqual({ state: 'ok' });+ expect(check('oneH1', '<p>No title yet.</p>')).toEqual({ state: 'ok' });+ expect(check('oneH1', '<h1>T</h1><p>x</p><h1>Again</h1>')).toEqual({+ state: 'bad',+ code: 'found',+ count: 2,+ });+ // An empty H1 line is no title; an HTML block's H1 is the page's.+ expect(check('oneH1', '<h1>T</h1><h1></h1>')).toEqual({ state: 'ok' });+ expect(+ check('oneH1', `<h1>T</h1><div data-html-block="${btoa('<h1>Hero</h1>')}"></div>`),+ ).toEqual({ state: 'bad', code: 'found', count: 2 });+ // The agent changes words, never a heading's level.+ expect(NOT_FOR_AGENT.has('oneH1')).toBe(true);+ expect(ruleSet('blog_post').some((r) => r.key === 'oneH1')).toBe(true);+ // Always on: a draft's or a saved set's "off" doesn't turn it off.+ const [oneH1] = activeRules(+ ruleSet('blog_post').filter((r) => r.key === 'oneH1'),+ { overrides: { oneH1: { on: false } } },+ );+ expect(oneH1.on).toBe(true);+ });++ it('asks the agent only for what it can fix, and names the rest', () => {+ const rules = activeRules(ruleSet('blog_post'), NO_DRAFT_RULES);+ const p = page('<h1>T</h1><p>delve</p><h1>Again</h1>', 30);+ const statuses = rules.map((r) => ({ rule: r, status: checkRule(r, p, ctx) }));+ const all = openRulesForAgent(statuses);+ expect(all.forAgent.some(({ rule }) => rule.key === 'oneH1')).toBe(false);+ expect(all.notForAgent.map(({ rule }) => rule.key)).toEqual(['oneH1']);+ // Asked for one rule only, the rest stay out.+ const one = openRulesForAgent(statuses, ['aiTraces']);+ expect(one.forAgent.map(({ rule }) => rule.key)).toEqual(['aiTraces']);+ expect(one.notForAgent).toEqual([]);+ expect(openRulesForAgent(statuses, ['oneH1']).forAgent).toEqual([]);+ });+it('wants a short summary under the H1, and a short answer under each H2', () => {expect(check('summary', '<h1>T</h1><h2>A</h2>')).toEqual({ state: 'bad', code: 'missing' });expect(check('summary', `<h1>T</h1><p>${'word '.repeat(60)}</p>`)).toEqual({@@ -467,8 +507,8 @@ describe('rulesMet', () => {const p = page('<h1>T</h1><p>Short summary.</p>', 10);const statuses = rules.map((r) => ({ rule: r, status: checkRule(r, p, ctx) }));const { met, total } = rulesMet(statuses);- // 16 shared rules: sentence off; tone, language and keywords (none set) can't say.- expect(total).toBe(12);+ // 17 shared rules: sentence off; tone, language and keywords (none set) can't say.+ expect(total).toBe(13);expect(met).toBeGreaterThan(0);expect(met).toBeLessThan(total);});diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.tsindex d0eb61164..31209e132 100644--- a/web/src/lib/content/rules.ts+++ b/web/src/lib/content/rules.ts@@ -3,6 +3,7 @@ import { LANGUAGES } from '@/config/prompt-options';import { classifyDomain, normalizeDomain } from '@/lib/citations/classify';import { PAGE_TYPES, type PageType } from '@/lib/content/drafts';import { lengthTarget } from '@/lib/content/editor';+import { decodeHtmlBlock } from '@/lib/content/html-allowlist';import { wordsOf } from '@/lib/content/sources';/**@@ -36,6 +37,8 @@ export interface RuleDef {unit?: RuleUnit;/** How it is checked: from the page as written, by AI, or against the product feed. */check: 'page' | 'ai' | 'feed';+ /** Always on, without a switch: a rule the editor itself keeps. */+ fixed?: true;}const SHARED_RULES: RuleDef[] = [@@ -55,6 +58,8 @@ const SHARED_RULES: RuleDef[] = [unit: 'characters',check: 'page',},+ // The editor keeps it too: a second H1 becomes an H2 (_one-h1.ts).+ { key: 'oneH1', group: 'structure', kind: 'switch', value: '', check: 'page', fixed: true },{key: 'summary',group: 'structure',@@ -393,7 +398,7 @@ export function activeRules(defs: RuleDef[], rules: Pick<DraftRules, 'overrides'const current = override?.value ?? def.value;return {...def,- on: override?.on ?? true,+ on: def.fixed ? true : (override?.on ?? true),current,changed: (override?.on !== undefined && override.on !== true) || current !== def.value,};@@ -430,6 +435,8 @@ export interface PageRead {text: string;/** The editor's character count, as the toolbar shows it. */characters: number;+ /** H1s with words inside the page's HTML blocks. */+ htmlBlockH1s?: number;}const BLOCK_TAGS = 'h1, h2, h3, p, li, table, ol, ul, blockquote';@@ -452,6 +459,17 @@ export function readPage(html: string, characters: number): PageRead {links: [...el.querySelectorAll('a[href]')].map((a) => a.getAttribute('href') ?? ''),});}+ // An HTML block's H1s are the page's too (One H1 per page): the editor+ // doesn't rewrite them, so the rule says so.+ let htmlBlockH1s = 0;+ for (const el of doc.body.querySelectorAll('[data-html-block]')) {+ const inner = decodeHtmlBlock(el.getAttribute('data-html-block') ?? '');+ if (!inner) continue;+ const block = new DOMParser().parseFromString(inner, 'text/html');+ htmlBlockH1s += [...block.body.querySelectorAll('h1')].filter((h) =>+ h.textContent?.trim(),+ ).length;+ }return {blocks,text: blocks@@ -459,6 +477,7 @@ export function readPage(html: string, characters: number): PageRead {.map((b) => b.text).join(' '),characters,+ htmlBlockH1s,};}@@ -607,6 +626,29 @@ export function lengthBand(target: number): { min: number; max: number } {const atLeast = (have: number, want: number): RuleStatus =>have >= want ? { state: 'ok' } : { state: 'bad', code: 'partOf', count: have, of: want };+/**+ * Rules the Content Agent can't fix: it changes words and adds blocks, never+ * a heading's level, so a page's extra H1s are made H2s in the editor.+ */+export const NOT_FOR_AGENT = new Set(['oneH1']);++/**+ * The rules on that the page doesn't meet (of `only`, when given): the ones+ * the Content Agent is asked to fix, and those it can't.+ */+export function openRulesForAgent<T extends { rule: ActiveRule; status: RuleStatus }>(+ rules: T[],+ only?: string[],+): { forAgent: T[]; notForAgent: T[] } {+ const open = rules.filter(+ ({ rule, status }) => rule.on && status.state === 'bad' && (!only || only.includes(rule.key)),+ );+ return {+ forAgent: open.filter(({ rule }) => !NOT_FOR_AGENT.has(rule.key)),+ notForAgent: open.filter(({ rule }) => NOT_FOR_AGENT.has(rule.key)),+ };+}+/** Checks one rule against the page as written. */export function checkRule(rule: ActiveRule, page: PageRead, ctx: RuleContext): RuleStatus {if (rule.check === 'feed') return { state: 'info', code: 'needsFeed' };@@ -698,6 +740,11 @@ export function checkRule(rule: ActiveRule, page: PageRead, ctx: RuleContext): R);case 'outboundLinks':return atLeast(links.filter(outbound).length, n);+ case 'oneH1': {+ // One H1, the page's title: more blur what the page is about.+ const h1s = blocks.filter((b) => b.tag === 'h1' && b.text).length + (page.htmlBlockH1s ?? 0);+ return h1s > 1 ? { state: 'bad', code: 'found', count: h1s } : { state: 'ok' };+ }case 'datedPoint': {const first100 = page.text.split(/\s+/).slice(0, 100).join(' ');return /\b(19|20)\d{2}\b/.test(first100)