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): let a brand add the byline to its exported content (CE-057) (#1427)
Cihanf1a46ce7b2fa
diff --git a/supabase/migrations/00261_brand_content_byline.sql b/supabase/migrations/00261_brand_content_byline.sqlnew file mode 100644index 000000000..e1fc4f4d9--- /dev/null+++ b/supabase/migrations/00261_brand_content_byline.sql@@ -0,0 +1,14 @@+-- ============================================================================+-- 00261: Add byline to content, per brand (Content Editor Quality, CE-057)+-- ============================================================================+-- The author is page metadata: a CMS's own author field shows the byline,+-- and nothing of it goes into the content (Quality spec §9). For a CMS with+-- no author support (rare), a brand can opt in: its exports then put one+-- byline line under the H1. Off by default. Admins and managers change it,+-- as the rest of a brand (brands: admin/manager update).++alter table public.brands+ add column if not exists content_byline boolean not null default false;++comment on column public.brands.content_byline is+ 'Content Editor Quality (CE-057): add one byline line under the H1 in exports, for a CMS with no author field. Off by default.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 5afaf7374..b7bd9eb24 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -38037,3 +38037,21 @@ create policy "content_draft_ready_log: member insert"comment on table public.content_draft_ready_log is'Content Editor Quality (CE-041): each "Mark ready anyway" past the Trust < 60 warning — the Trust the page had, the check the warning named and its count, who and when. Added by members as themselves for a ready draft; never changed.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00261_brand_content_byline.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00261: Add byline to content, per brand (Content Editor Quality, CE-057)+-- ============================================================================+-- The author is page metadata: a CMS's own author field shows the byline,+-- and nothing of it goes into the content (Quality spec §9). For a CMS with+-- no author support (rare), a brand can opt in: its exports then put one+-- byline line under the H1. Off by default. Admins and managers change it,+-- as the rest of a brand (brands: admin/manager update).++alter table public.brands+ add column if not exists content_byline boolean not null default false;++comment on column public.brands.content_byline is+ 'Content Editor Quality (CE-057): add one byline line under the H1 in exports, for a CMS with no author field. Off by default.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex c5206098b..448bde66d 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4136,6 +4136,7 @@"by": "By {name}","change": "By {name}: change who the page is by","hint": "Who the page is by: page metadata your CMS shows, not part of the content.",+ "hintInContent": "Who the page is by: this brand adds the byline to content, so exports put \"By …\" under the H1.","title": "Author · page metadata","organization": "{brand} Team","organizationHint": "Organization byline",@@ -4144,6 +4145,7 @@"manage": "Manage authors","failed": "Couldn't change the author.","pageInfo": "Page info · shown by your CMS, not part of the content",+ "pageInfoInContent": "Page info · exports put the \"By …\" line under the H1","titleAt": "{title}, {brand}","updated": "Updated {date}"},@@ -4220,6 +4222,7 @@"slug": "Slug","author": "Author","authorValue": "{name} → your CMS author field",+ "authorInContent": "{name} → in the content, under the H1 (Add byline to content)","featuredImage": "Featured image","noImage": "None in the page","noSlug": "None from the title: set it in your CMS",@@ -4270,6 +4273,8 @@"author": {"ok": "Author for your CMS","okDetail": "Set {name} as the page's author in your CMS. Its template shows the byline; nothing is added to the content.",+ "inContentTitle": "Byline in the content",+ "inContent": "Exports put \"{line}\" under the H1: this brand adds the byline to content, for a CMS with no author field.","unknown": "The authors couldn't be read here, so the code below leaves the author out. Set the page's author in your CMS.","none": "No author yet","noneDetail": "The page goes out as {byline}, with the brand's Organization schema. A real author raises E-E-A-T."@@ -6565,6 +6570,9 @@"defaultsHint": "Every new page of the brand gets this author. You can pick another on any page.","defaultsManagers": "Admins and managers set the defaults.","defaultFailed": "Couldn't set the default author.",+ "bylineInContent": "Add byline to content",+ "bylineInContentHint": "Add byline to content is only for a CMS with no author field: the brand's exports then put one \"By …\" line under the H1. Off, the byline stays in your CMS's author field.",+ "bylineFailed": "Couldn't change Add byline to content.","organizationByline": "{brand} Team","fields": {"name": "Full name",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_author-menu.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_author-menu.tsxindex 1180c0c92..0ee997e78 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_author-menu.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_author-menu.tsx@@ -39,6 +39,7 @@ export function AuthorMenu({onPick,open,onOpenChange,+ inContent = false,}: {brandId: string;brandName: string;@@ -48,6 +49,8 @@ export function AuthorMenu({/** Open from outside too: Quality's Pick author. */open?: boolean;onOpenChange?: (open: boolean) => void;+ /** The brand adds the byline to content (CE-057): exports carry it. */+ inContent?: boolean;}) {const t = useTranslations('contentEditor.editor.author');const author = authors.find((a) => a.id === authorId) ?? null;@@ -57,7 +60,7 @@ export function AuthorMenu({<DropdownMenu open={open} onOpenChange={(next) => onOpenChange?.(next)}><DropdownMenuTriggeraria-label={t('change', { name })}- title={t('hint')}+ title={inContent ? t('hintInContent') : t('hint')}className={cn(badgeVariants({ variant: 'outline' }),'max-w-56 cursor-pointer gap-1 font-normal hover:bg-muted',diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsxindex 391c02b45..004050a4d 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx@@ -98,6 +98,7 @@ async function render(linksPending = 0,paste = clean,mode = 'markReady' as 'markReady' | 'export',+ contentByline = null as string | null,title = 'How small teams forecast',} = {},) {@@ -108,6 +109,7 @@ async function render(mode={mode}paste={paste}onFillNow={onFillNow}+ contentByline={contentByline}onContinue={onContinue}onClose={() => {}}quality={q}@@ -368,6 +370,16 @@ describe('BeforePublish', () => {expect(onContinue).not.toHaveBeenCalled();});+ it('says the exports put the byline under the H1 for a brand that adds it to content', async () => {+ await render(quality(), { contentByline: 'By Ada Lovelace' });+ expect(rows()[0]).toBe(+ 'Byline in the content · check itExports put "By Ada Lovelace" under the H1: this brand adds the byline to content, for a CMS with no author field.',+ );+ // The line as it goes out, in the brand's language.+ await render(quality(), { contentByline: 'Yazar: Ada Lovelace' });+ expect(rows()[0]).toContain('Exports put "Yazar: Ada Lovelace" under the H1');+ });+it("gives no Article for a page that isn't one", async () => {await render(quality(), { pageType: 'product_page' });expect(rows()).toEqual([diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsxindex 90bf36abb..eace0bdd7 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx@@ -65,6 +65,7 @@ export function BeforePublish({mode = 'markReady',paste,onFillNow,+ contentByline = null,onContinue,onClose,quality,@@ -81,6 +82,8 @@ export function BeforePublish({paste: ReadyToPaste;/** Goes to the first placeholder, to fill it (Ready to paste's Fill now). */onFillNow: () => void;+ /** The byline line the brand puts in the content (Add byline to content), or null. */+ contentByline?: string | null;/** Export's: goes on to it. */onContinue?: () => void;onClose: () => void;@@ -139,8 +142,10 @@ export function BeforePublish({: author? {state: 'check',- title: t('author.ok'),- detail: t('author.okDetail', { name: author.name }),+ title: contentByline ? t('author.inContentTitle') : t('author.ok'),+ detail: contentByline+ ? t('author.inContent', { line: contentByline })+ : t('author.okDetail', { name: author.name }),}: {state: 'missing',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 8835b8389..168d4f9b3 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@@ -78,9 +78,11 @@ import { firstImage } from '@/lib/content/page-schema';import { PLACEHOLDER, pagePlaceholders, placeholderIn } from '@/lib/content/placeholders';import {blankCode,+ bylineText,exportPlaceholders,pasteChecks,titlePlaceholders,+ withByline,} from '@/lib/content/ready-to-publish';import { detectPageType } from '@/lib/content/page-types';import { BAND_CLASSES, qualityAverage, qualityBand, qualityPhase } from '@/lib/content/quality';@@ -507,6 +509,10 @@ export function DraftEditor({readable?.score ?? null,]);const hasAuthors = (authorsRead?.authors.length ?? 0) > 0;+ // Add byline to content (CE-057): the brand's CMS has no author field, so+ // its exports carry one byline line under the H1.+ const bylineInContent =+ authorsRead?.brands.find((b) => b.id === draft.brandId)?.bylineInContent ?? false;// What only the person can do (CE-040), and the nudge to the first of it// when the agent's run ends, after Accept all and on Mark ready.// The placeholders the agent left (CE-044): the person fills them. Once@@ -591,7 +597,7 @@ export function DraftEditor({pageInfoKey,byline? {- label: t('author.pageInfo'),+ label: bylineInContent ? t('author.pageInfoInContent') : t('author.pageInfo'),byline,initials: authorInitials(pageAuthor?.name ?? brandName),photoUrl: pageAuthor?.photoUrl ?? null,@@ -599,7 +605,7 @@ export function DraftEditor({: null,),);- }, [editor, byline, pageAuthor?.name, pageAuthor?.photoUrl, brandName, t]);+ }, [editor, byline, bylineInContent, pageAuthor?.name, pageAuthor?.photoUrl, brandName, t]);const pickAuthor = async (next: string | null) => {if (next === authorId) return;const pick = ++authorPick.current;@@ -1348,6 +1354,13 @@ export function DraftEditor({publishableHtml(htmlSource !== null ? htmlFromSource(htmlSource) : (editor?.getHTML() ?? draft.bodyHtml),);+ // The byline line a brand with Add byline to content puts under the H1,+ // in the page's language (its Language rule, else the brand's), as+ // Readability reads it: the language the writer writes the page in.+ const contentByline =+ bylineInContent && authorsRead+ ? bylineText(language, pageAuthor?.name ?? null, brandName)+ : null;// Export (CE-057), once Quality is live: where it goes, its checks and fields.// The page as it was when Export opened: what it shows stays still while open.const [exportOpen, setExportOpen] = useState<{@@ -1364,7 +1377,11 @@ export function DraftEditor({setExportOpen({ html, destination: 'html' });return;}- void copyToClipboard(html, t('copyHtmlDone'), t('copyHtmlFailed', { html: '</> HTML' }));+ void copyToClipboard(+ contentByline ? withByline(html, contentByline) : html,+ t('copyHtmlDone'),+ t('copyHtmlFailed', { html: '</> HTML' }),+ );};/** Export: the page as Copy HTML gives it, as a Word, HTML or Markdown file. */@@ -1713,6 +1730,7 @@ export function DraftEditor({onPick={(next) => void pickAuthor(next)}open={authorMenuOpen}onOpenChange={setAuthorMenuOpen}+ inContent={bylineInContent}/>)}<DraftMethodBadge method={draft.method} />@@ -1956,6 +1974,7 @@ export function DraftEditor({author={pageAuthor}// Until the authors are read, who it is by isn't known.teamByline={authorsRead ? t('author.organization', { brand: brandName }) : ''}+ byline={contentByline}checks={pasteChecks(exportOpen.html, linkChecks)}linksPending={linksPending}initialDestination={exportOpen.destination}@@ -1974,6 +1993,7 @@ export function DraftEditor({setPublishOpen(null);fillFirstPlaceholder();}}+ contentByline={contentByline}onContinue={() => {setPublishOpen(null);openExport();diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.test.tsxindex a071761ad..8d02715a4 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.test.tsx@@ -65,6 +65,7 @@ async function render(over: Partial<Parameters<typeof ExportDialog>[0]> = {}) {sourceUrl={null}author={ada}teamByline="Acme Team"+ byline={null}checks={checks}linksPending={0}onFillNow={onFillNow}@@ -289,6 +290,31 @@ describe('ExportDialog', () => {expect(fields.front).toHaveProperty('lastmod', expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/));});+ it("puts the brand's byline line under the H1, not in the page fields", async () => {+ vi.stubGlobal('ClipboardItem', undefined);+ document.execCommand = vi.fn(() => false);+ await render({ html: '<h1>Pour-over</h1><p>Done.</p>', byline: 'By Ada Lovelace' });+ await act(async () => button('Copy for Webflow')!.click());+ expect(writeText).toHaveBeenCalledWith('<p>By Ada Lovelace</p><p>Done.</p>');+ expect(dialog().textContent).toContain('Meta descriptionDone.');+ expect(dialog().textContent).toContain(+ 'AuthorAda Lovelace → in the content, under the H1 (Add byline to content)',+ );+ await act(async () => destination('Word').click());+ await act(async () => button('Download Word')!.click());+ expect(draftExportBlob).toHaveBeenCalledWith(+ 'docx',+ 'Pour-over',+ '<h1>Pour-over</h1><p>By Ada Lovelace</p><p>Done.</p>',+ expect.anything(),+ );+ await act(async () => destination('HTML').click());+ await act(async () => button('Copy HTML')!.click());+ expect(writeText).toHaveBeenLastCalledWith(+ '<h1>Pour-over</h1><p>By Ada Lovelace</p><p>Done.</p>',+ );+ });+it("opens on HTML for Copy HTML, and copies the page's HTML as it is", async () => {await render({ html: '<p>Done.</p>', initialDestination: 'html' });expect(destination('HTML').getAttribute('aria-checked')).toBe('true');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsxindex 6147d911c..b8a5d351d 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx@@ -26,6 +26,7 @@ import {exportPlaceholders,pageFields,titlePlaceholders,+ withByline,withoutLeadingH1,withoutPlaceholders,type PasteChecks,@@ -112,6 +113,7 @@ export function ExportDialog({sourceUrl,author,teamByline,+ byline,checks,linksPending,initialDestination,@@ -128,6 +130,8 @@ export function ExportDialog({author: ContentAuthor | null;/** The team byline; empty while the authors aren't read. */teamByline: string;+ /** The byline line the brand puts in the content (Add byline to content), or null. */+ byline: string | null;checks: PasteChecks;/** The page's links whose read may still come. */linksPending: number;@@ -163,7 +167,12 @@ export function ExportDialog({() => pageFields({ title, html: content, sourceUrl, author, teamByline }),[title, content, sourceUrl, author, teamByline],);- const out = TITLE_FIELD.has(destination) ? withoutLeadingH1(content) : content;+ // The brand's byline line under the H1 (the fields read the page without it).+ const withLine = useMemo(+ () => (byline ? withByline(content, byline) : content),+ [byline, content],+ );+ const out = TITLE_FIELD.has(destination) ? withoutLeadingH1(withLine) : withLine;const pick = (next: ExportDestination) => {setDestination(next);@@ -217,7 +226,7 @@ export function ExportDialog({const name = title.trim() || t('untitled');try {saveBlob(- await draftExportBlob(format, name, content, exportFields),+ await draftExportBlob(format, name, withLine, exportFields),draftExportFileName(name, format),);} catch (err) {@@ -305,7 +314,7 @@ export function ExportDialog({label: t('fields.author'),value: fields.author || null,shown: fields.author- ? t('fields.authorValue', { name: fields.author })+ ? t(byline ? 'fields.authorInContent' : 'fields.authorValue', { name: fields.author }): t('fields.noAuthor'),},{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 f74384655..bd352dc0a 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@@ -3022,6 +3022,46 @@ describe('the side panel', () => {);});+ it('puts the byline under the H1 for a brand that adds it to content, and says so', async () => {+ const writeText = vi.fn().mockResolvedValue(undefined);+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });+ getContentAuthors.mockResolvedValue({+ authors: [],+ brands: [{ id: 'b1', name: 'Acme', bylineInContent: true }],+ me: { id: 'u1', role: 'analyst' },+ });+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ expect(container.textContent).toContain(+ 'Page info · exports put the "By …" line under the H1',+ );+ await act(async () => button('Copy HTML')!.click());+ expect(writeText).toHaveBeenCalledWith(+ '<h1>Pipeline forecasting</h1>\n<p>By Acme Team</p>\n<p>Teams trust it.</p>',+ );+ });++ it("writes the byline in the brand's language", async () => {+ brandState.brands = [{ id: 'b1', language: 'tr' } as never, { id: 'b2' }];+ try {+ const writeText = vi.fn().mockResolvedValue(undefined);+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });+ getContentAuthors.mockResolvedValue({+ authors: [],+ brands: [{ id: 'b1', name: 'Acme', bylineInContent: true }],+ me: { id: 'u1', role: 'analyst' },+ });+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ await act(async () => button('Copy HTML')!.click());+ expect(writeText).toHaveBeenCalledWith(+ '<h1>Pipeline forecasting</h1>\n<p>Yazar: Acme Ekibi</p>\n<p>Teams trust it.</p>',+ );+ } finally {+ brandState.brands = [{ id: 'b1' }, { id: 'b2' }];+ }+ });+it('copies at once with no placeholder, and keeps the menu while Quality is off', async () => {const writeText = vi.fn().mockResolvedValue(undefined);Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });diff --git a/web/src/components/settings/authors-section.test.tsx b/web/src/components/settings/authors-section.test.tsxindex 8c93bd3ef..7c0a46002 100644--- a/web/src/components/settings/authors-section.test.tsx+++ b/web/src/components/settings/authors-section.test.tsx@@ -16,6 +16,7 @@ const actions = vi.hoisted(() => ({saveContentAuthor: vi.fn(),deleteContentAuthor: vi.fn(),setDefaultAuthor: vi.fn(),+ setBrandByline: vi.fn(),}));vi.mock('@/lib/actions/content-authors', () => actions);const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));@@ -87,6 +88,7 @@ beforeEach(() => {actions.saveContentAuthor.mockResolvedValue({ id: BOB });actions.deleteContentAuthor.mockResolvedValue(undefined);actions.setDefaultAuthor.mockResolvedValue(undefined);+ actions.setBrandByline.mockResolvedValue(undefined);container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -113,6 +115,10 @@ const buttons = (name: string) =>const row = (name: string) =>[...container.querySelectorAll('li')].find((li) => li.textContent?.includes(name))!;const trigger = () => container.querySelector<HTMLElement>(`[aria-labelledby="default-${ACME}"]`)!;+const byline = () =>+ [...container.querySelectorAll<HTMLElement>('[role="checkbox"]')].find((c) =>+ c.closest('label')?.textContent?.includes('Add byline to content'),+ )!;const isMe = () =>[...document.querySelectorAll<HTMLElement>('[role="checkbox"]')].find((c) =>c.closest('label')?.textContent?.includes('This author is me'),@@ -176,6 +182,44 @@ describe('AuthorsSection', () => {expect(actions.setDefaultAuthor).toHaveBeenCalledWith(ACME, null);});+ it("lets a manager add the byline to a brand's content, off by default (CE-057)", async () => {+ await render();+ expect(byline().getAttribute('aria-checked')).toBe('false');+ expect(byline().hasAttribute('data-disabled')).toBe(true);+ expect(container.textContent).toContain('only for a CMS with no author field');++ actions.getContentAuthors.mockResolvedValue(workspace('manager'));+ await act(async () => root.unmount());+ root = createRoot(container);+ await render();+ await click(byline());+ expect(actions.setBrandByline).toHaveBeenCalledWith(ACME, true);+ expect(actions.getContentAuthors).toHaveBeenCalledTimes(3);++ expect(byline().getAttribute('aria-describedby')).toBe(`default-${ACME}`);++ // Held while it saves; switched off, it sends false.+ actions.getContentAuthors.mockResolvedValue({+ ...workspace('manager'),+ brands: [{ id: ACME, name: 'Acme', bylineInContent: true }],+ });+ let saved: () => void = () => {};+ actions.setBrandByline.mockReturnValue(new Promise<void>((resolve) => (saved = resolve)));+ await act(async () => root.unmount());+ root = createRoot(container);+ await render();+ expect(byline().getAttribute('aria-checked')).toBe('true');+ await click(byline());+ expect(actions.setBrandByline).toHaveBeenLastCalledWith(ACME, false);+ expect(byline().getAttribute('aria-checked')).toBe('false');+ expect(byline().hasAttribute('data-disabled')).toBe(true);+ await act(async () => saved());++ actions.setBrandByline.mockRejectedValue(new Error('forbidden'));+ await click(byline());+ expect(toast.error).toHaveBeenCalledWith("Couldn't change Add byline to content.");+ });+it('adds an author, one profile link per line, and holds a link that is not https', async () => {actions.getContentAuthors.mockResolvedValue({...workspace('analyst'),diff --git a/web/src/components/settings/authors-section.tsx b/web/src/components/settings/authors-section.tsxindex bc3340f7c..0058fd393 100644--- a/web/src/components/settings/authors-section.tsx+++ b/web/src/components/settings/authors-section.tsx@@ -30,6 +30,7 @@ import {deleteContentAuthor,getContentAuthors,saveContentAuthor,+ setBrandByline,setDefaultAuthor,} from '@/lib/actions/content-authors';import {@@ -66,6 +67,8 @@ export function AuthorsSection() {const [busy, setBusy] = useState(false);/** A brand's default being saved: shown at once, the select held until it lands. */const [picking, setPicking] = useState<Record<string, string>>({});+ /** A brand's Add byline to content being saved, likewise. */+ const [bylining, setBylining] = useState<Record<string, boolean>>({});const load = useCallback(async () => {try {@@ -117,6 +120,22 @@ export function AuthorsSection() {}};+ const toggleByline = async (brandId: string, on: boolean) => {+ setBylining((prev) => ({ ...prev, [brandId]: on }));+ try {+ await setBrandByline(brandId, on);+ await load();+ } catch {+ toast.error(t('bylineFailed'));+ } finally {+ setBylining((prev) => {+ const next = { ...prev };+ delete next[brandId];+ return next;+ });+ }+ };+return (<Card><CardHeader>@@ -260,10 +279,22 @@ export function AuthorsSection() {</SelectContent></Select>{brand.id in picking && <LoadingDots className="text-muted-foreground" />}+ <label className="flex items-center gap-2 text-sm">+ <Checkbox+ checked={bylining[brand.id] ?? !!brand.bylineInContent}+ aria-describedby={`default-${brand.id}`}+ disabled={!canSetDefaults || brand.id in bylining}+ onCheckedChange={(checked) =>+ void toggleByline(brand.id, checked === true)+ }+ />+ {t('bylineInContent')}+ </label></li>);})}</ul>+ <p className="text-xs text-muted-foreground">{t('bylineInContentHint')}</p>{!canSetDefaults && (<p className="text-xs text-muted-foreground">{t('defaultsManagers')}</p>)}diff --git a/web/src/lib/actions/content-authors.test.ts b/web/src/lib/actions/content-authors.test.tsindex 2b3330656..e6d34a4f5 100644--- a/web/src/lib/actions/content-authors.test.ts+++ b/web/src/lib/actions/content-authors.test.ts@@ -57,8 +57,13 @@ vi.mock('@/lib/supabase/server', () => ({})),}));-const { deleteContentAuthor, getContentAuthors, saveContentAuthor, setDefaultAuthor } =- await import('./content-authors');+const {+ deleteContentAuthor,+ getContentAuthors,+ saveContentAuthor,+ setBrandByline,+ setDefaultAuthor,+} = await import('./content-authors');const writes = () => calls.filter((c) => c.op !== 'select');@@ -89,7 +94,10 @@ describe('getContentAuthors', () => {],error: null,};- answers['brands.select'] = { data: [{ id: ACME, name: 'Acme' }], error: null };+ answers['brands.select'] = {+ data: [{ id: ACME, name: 'Acme', content_byline: true }],+ error: null,+ };answers['content_drafts.select'] = { data: null, count: 2, error: null };answers['content_author_defaults.select'] = {data: [{ brand_id: ACME, author_id: ADA }],@@ -111,7 +119,7 @@ describe('getContentAuthors', () => {pages: 2,},],- brands: [{ id: ACME, name: 'Acme' }],+ brands: [{ id: ACME, name: 'Acme', bylineInContent: true }],me: { id: ME, role: 'analyst' },});});@@ -256,3 +264,17 @@ describe('setDefaultAuthor', () => {await expect(setDefaultAuthor(ACME, ADA)).rejects.toThrow(/row-level security/);});});++describe('setBrandByline', () => {+ it("turns a brand's Add byline to content on or off, and fails when RLS lets no row through", async () => {+ answers['brands.update'] = { data: [{ id: ACME }], error: null };+ await setBrandByline(ACME, true);+ expect(writes()).toEqual([+ { table: 'brands', op: 'update', row: { content_byline: true }, filters: [['id', ACME]] },+ ]);+ answers['brands.update'] = { data: [], error: null };+ await expect(setBrandByline(ACME, false)).rejects.toThrow('forbidden');+ await expect(setBrandByline('acme', true)).rejects.toThrow('invalid');+ expect(writes()).toHaveLength(2);+ });+});diff --git a/web/src/lib/actions/content-authors.ts b/web/src/lib/actions/content-authors.tsindex b1dd9d534..14856b24c 100644--- a/web/src/lib/actions/content-authors.ts+++ b/web/src/lib/actions/content-authors.ts@@ -44,7 +44,7 @@ export async function getContentAuthors(.order('name'),supabase.from('brands')- .select('id, name')+ .select('id, name, content_byline').eq('organization_id', profile.organization_id).order('name'),supabase.from('content_author_defaults').select('brand_id, author_id'),@@ -82,7 +82,11 @@ export async function getContentAuthors(defaultFor: defaults.filter((d) => d.author_id === row.id).map((d) => d.brand_id),pages: pages?.[i] ?? null,})),- brands: (brandsRes.data ?? []).map((b) => ({ id: b.id, name: b.name })),+ brands: (brandsRes.data ?? []).map((b) => ({+ id: b.id,+ name: b.name,+ bylineInContent: !!b.content_byline,+ })),me: { id: auth.user.id, role: profile.role ?? 'analyst' },};}@@ -164,6 +168,24 @@ export async function deleteContentAuthor(id: string): Promise<void> {if (!data?.length) throw new Error('forbidden');}+/**+ * Add byline to content (Quality spec §9, CE-057): a brand whose CMS has+ * no author field puts one byline line under the H1 in its exports. Admins+ * and managers (brands: admin/manager update); a brand they can't change+ * is refused.+ */+export async function setBrandByline(brandId: string, on: boolean): Promise<void> {+ if (!z.guid().safeParse(brandId).success || typeof on !== 'boolean') throw new Error('invalid');+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('brands')+ .update({ content_byline: on })+ .eq('id', brandId)+ .select('id');+ if (error) throw new Error(error.message);+ if (!data?.length) throw new Error('forbidden');+}+/** A brand's default author, or none (the organization byline): admins and managers. */export async function setDefaultAuthor(brandId: string, authorId: string | null): Promise<void> {if (!z.guid().safeParse(brandId).success || (authorId && !z.guid().safeParse(authorId).success)) {diff --git a/web/src/lib/content/authors.ts b/web/src/lib/content/authors.tsindex 439afa27e..e0ddf7ac1 100644--- a/web/src/lib/content/authors.ts+++ b/web/src/lib/content/authors.ts@@ -25,7 +25,8 @@ export interface ContentAuthor {export interface AuthorsRead {authors: ContentAuthor[];- brands: { id: string; name: string }[];+ /** The brands, and whether exports put the byline in the content (00261, CE-057). */+ brands: { id: string; name: string; bylineInContent?: boolean }[];/** The member reading: what they may change. */me: { id: string; role: string };}diff --git a/web/src/lib/content/ready-to-publish.test.ts b/web/src/lib/content/ready-to-publish.test.tsindex 9af58ac8c..5f883022a 100644--- a/web/src/lib/content/ready-to-publish.test.ts+++ b/web/src/lib/content/ready-to-publish.test.ts@@ -4,11 +4,13 @@ import type { LinkCheck } from './quality-checks';import { PLACEHOLDER } from './placeholders';import {blankCode,+ bylineText,exportPlaceholders,fragment,pageFields,pasteChecks,titlePlaceholders,+ withByline,withoutLeadingH1,withoutPlaceholders,} from './ready-to-publish';@@ -276,6 +278,72 @@ describe('pageFields', () => {});});+describe('withByline', () => {+ it('puts one byline line under the H1, or at the top of a page with none, as text', () => {+ expect(withByline('<h1>Pour-over</h1><p>Brew.</p>', 'By Ada Lovelace')).toBe(+ '<h1>Pour-over</h1><p>By Ada Lovelace</p><p>Brew.</p>',+ );+ expect(withByline('<p>Brew.</p><h1>Late</h1>', 'By <Acme> Team')).toBe(+ '<p>By <Acme> Team</p><p>Brew.</p><h1>Late</h1>',+ );+ expect(withByline('<h1>Pour-over</h1>\n<p>Brew.</p>', 'By Ada')).toBe(+ '<h1>Pour-over</h1>\n<p>By Ada</p>\n<p>Brew.</p>',+ );+ });++ it('keeps the rest as written, under an H1 an image comes before, and adds none twice or alone', () => {+ // An HTML block's code is not rewritten (a template would close <path/>).+ expect(withByline('<h1>Pour-over</h1><svg><path d="M0"/></svg>', 'By Ada')).toBe(+ '<h1>Pour-over</h1><p>By Ada</p><svg><path d="M0"/></svg>',+ );+ expect(+ withByline('<img src="https://cdn.acme.com/a.jpg"><h1>Pour-over</h1><p>Brew.</p>', 'By Ada'),+ ).toBe('<img src="https://cdn.acme.com/a.jpg"><h1>Pour-over</h1><p>By Ada</p><p>Brew.</p>');+ expect(withByline('<h1>Pour-over</h1>\n<p>By Ada</p>\n<p>Brew.</p>', 'By Ada')).toBe(+ '<h1>Pour-over</h1>\n<p>By Ada</p>\n<p>Brew.</p>',+ );+ expect(withByline('', 'By Ada')).toBe('');+ expect(withByline('<p></p>', 'By Ada')).toBe('<p></p>');+ });++ it("puts it under the lead's own H1: not an empty one above, nor one in a comment", () => {+ expect(withByline('<h1></h1>\n<h1>Pour-over</h1>\n<p>Brew.</p>', 'By Ada')).toBe(+ '<h1></h1>\n<h1>Pour-over</h1>\n<p>By Ada</p>\n<p>Brew.</p>',+ );+ expect(withByline('<!-- <h1>Old</h1> -->\n<h1>Pour-over</h1>\n<p>Brew.</p>', 'By Ada')).toBe(+ '<!-- <h1>Old</h1> -->\n<h1>Pour-over</h1>\n<p>By Ada</p>\n<p>Brew.</p>',+ );+ expect(+ withByline(+ '<script>document.write("<h1>x</h1>")</script>\n<H1 class="t">Pour-over</H1>\n<p>Brew.</p>',+ 'By Ada',+ ),+ ).toBe(+ '<script>document.write("<h1>x</h1>")</script>\n<H1 class="t">Pour-over</H1>\n<p>By Ada</p>\n<p>Brew.</p>',+ );+ });+});++describe('bylineText', () => {+ it("writes the line in the brand's language, by the author or the brand's team", () => {+ expect(bylineText(null, 'Ada Lovelace', 'Acme')).toBe('By Ada Lovelace');+ expect(bylineText('en-US', null, 'Acme')).toBe('By Acme Team');+ expect(bylineText('tr', 'Ayşe Yılmaz', 'Acme')).toBe('Yazar: Ayşe Yılmaz');+ expect(bylineText('tr', null, 'Acme')).toBe('Yazar: Acme Ekibi');+ expect(bylineText('pt-BR', 'Ana Silva', 'Acme')).toBe('Por Ana Silva');+ expect(bylineText('pt', null, 'Acme')).toBe('Pela equipe Acme');+ expect(bylineText('de', null, 'Acme')).toBe('Vom Acme-Team');+ expect(bylineText('fr', null, 'Acme')).toBe("Par l'équipe Acme");+ // A "$" in a name is written as it is.+ expect(bylineText('es', 'Ana $& Co', 'Acme')).toBe('Por Ana $& Co');+ });++ it('puts the name alone, or the brand alone, for a language not in the table', () => {+ expect(bylineText('ja', '山田太郎', 'Acme')).toBe('山田太郎');+ expect(bylineText('ar', null, 'Acme')).toBe('Acme');+ });+});+describe('withoutLeadingH1', () => {it('drops the H1 the title field holds, and nothing else', () => {expect(withoutLeadingH1('<h1>Pour-over</h1><p>Brew.</p><h1>Second</h1>')).toBe(diff --git a/web/src/lib/content/ready-to-publish.ts b/web/src/lib/content/ready-to-publish.tsindex f21306bad..e22c06bd6 100644--- a/web/src/lib/content/ready-to-publish.ts+++ b/web/src/lib/content/ready-to-publish.ts@@ -4,6 +4,7 @@ import { cleanHref, jsonLdText } from './html-allowlist';import { firstImage } from './page-schema';import { AGENT_PLACEHOLDER, PLACEHOLDER, placeholderIn } from './placeholders';import type { LinkCheck } from './quality-checks';+import { languageCode } from './readability';/*** Ready to publish (Content Editor Quality spec §7b, CE-057): what an export@@ -429,6 +430,86 @@ export function pageFields({};}+/**+ * The byline line in the page's language (Add byline to content): the+ * prefix with the author's name, or the team's line. It goes into the page,+ * so it is written in the page's language, not the app's. A language not+ * here gets the name alone, or the brand's.+ */+const BYLINES: Record<string, { by: string; team: string }> = {+ en: { by: 'By {name}', team: 'By {brand} Team' },+ tr: { by: 'Yazar: {name}', team: 'Yazar: {brand} Ekibi' },+ de: { by: 'Von {name}', team: 'Vom {brand}-Team' },+ fr: { by: 'Par {name}', team: "Par l'équipe {brand}" },+ es: { by: 'Por {name}', team: 'Por el equipo de {brand}' },+ pt: { by: 'Por {name}', team: 'Pela equipe {brand}' },+ it: { by: 'Di {name}', team: 'A cura del team {brand}' },+ nl: { by: 'Door {name}', team: 'Door het {brand}-team' },+ sv: { by: 'Av {name}', team: 'Av {brand}-teamet' },+};++/**+ * The byline line for a page in `language` (brands.language: "tr", "pt-BR",+ * English when unset): by its author, else by the brand's team.+ */+export function bylineText(+ language: string | null | undefined,+ author: string | null,+ brand: string,+): string {+ const forms = BYLINES[languageCode(language) ?? ''];+ // A function, so a "$" in a name is written as it is.+ if (author) return forms ? forms.by.replace('{name}', () => author) : author;+ return forms ? forms.team.replace('{brand}', () => brand) : brand;+}++/**+ * Where the end tag of the HTML's k-th H1 ends, counted from 0, or null.+ * Comments and code are blanked first (blankCode): an H1 there is no element.+ */+function h1End(html: string, k: number): number | null {+ const lower = blankCode(html).replace(/[A-Z]+/g, (s) => s.toLowerCase());+ let opened = -1;+ for (const m of lower.matchAll(/<(\/?)h1(?=[\s/>])/g)) {+ if (!m[1]) opened++;+ else if (opened === k) {+ const end = lower.indexOf('>', m.index);+ return end === -1 ? null : end + 1;+ }+ }+ return null;+}++/**+ * The byline in the content (Add byline to content, a brand's opt-in for a+ * CMS with no author field): one line under the page's H1, or at its top+ * when it opens with no H1. The rest of the HTML goes out as written; a+ * page that already has the line there, or has no words, gets none.+ */+export function withByline(html: string, byline: string): string {+ const root = fragment(html);+ // The page's first words: an image or code before them leaves them first.+ const lead = Array.from(root.children).find(+ (el) => !el.matches('script, style, template') && el.textContent?.trim(),+ );+ if (!lead) return html;+ const words = (el: Element | null) => (el?.textContent ?? '').replace(/\s+/g, ' ').trim();+ const line = root.ownerDocument.createElement('p');+ line.textContent = byline;+ // A page written one block a line (publishableHtml) keeps that.+ const gap = html.includes('\n') ? '\n' : '';+ if (lead.matches('h1')) {+ const next = lead.nextElementSibling;+ if (next?.matches('p') && words(next) === words(line)) return html;+ // The lead's own end tag: an empty H1 above it, or one in a comment or+ // a script, isn't it.+ const at = h1End(html, Array.from(root.querySelectorAll<Element>('h1')).indexOf(lead));+ if (at !== null) return html.slice(0, at) + gap + line.outerHTML + html.slice(at);+ }+ if (lead.matches('p') && words(lead) === words(line)) return html;+ return line.outerHTML + gap + html;+}+/** The page's leading H1, for a destination whose title field holds it. */export function withoutLeadingH1(html: string): string {const root = fragment(html);diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 2561d21a9..c0738f036 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -645,6 +645,7 @@ export type Database = {}brands: {Row: {+ content_byline: booleancreated_at: stringdescription: string | nullga_property_id: string | null@@ -669,6 +670,7 @@ export type Database = {updated_at: string}Insert: {+ content_byline?: booleancreated_at?: stringdescription?: string | nullga_property_id?: string | null@@ -693,6 +695,7 @@ export type Database = {updated_at?: string}Update: {+ content_byline?: booleancreated_at?: stringdescription?: string | nullga_property_id?: string | null