Skip to content

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.

feat(content): name the page's author in the editor's header and a Page info strip outside the page (CE-038) (#1413)

Cihan718dadd49031
diff --git a/supabase/migrations/00257_content_draft_author.sql b/supabase/migrations/00257_content_draft_author.sql
new file mode 100644
index 000000000..d4647f772
--- /dev/null
+++ b/supabase/migrations/00257_content_draft_author.sql
@@ -0,0 +1,58 @@
+-- ============================================================================
+-- 00257: a page's author (Content Editor Quality, CE-038)
+-- ============================================================================
+-- content_drafts.author_id: the real person the page is by (content_authors,
+-- 00256). It is page metadata: the editor shows it in its Page info strip,
+-- outside the page, and Ansvisor sends it to the CMS author field; it is
+-- never in the page's text. (The draft's `author` column, 'user' or 'agent',
+-- says who wrote the text: another thing.)
+--
+-- * A new draft gets its brand's default author (content_author_defaults),
+-- the server's drafts too; none means the organization byline
+-- ("{Brand} Team").
+-- * The author must be one of the brand's organization's.
+
+alter table public.content_drafts
+ add column if not exists author_id uuid
+ references public.content_authors(id) on delete set null;
+
+create index if not exists content_drafts_author
+ on public.content_drafts (author_id)
+ where author_id is not null;
+
+comment on column public.content_drafts.author_id is
+ 'Content Editor Quality (CE-038): the person the page is by (content_authors), page metadata — never the page''s text. A new draft gets its brand''s default; null is the organization byline.';
+
+-- As the member who writes (RLS reads their organization's defaults and
+-- authors); the server bypasses RLS and reads them all.
+create or replace function public.content_draft_author()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if tg_op = 'INSERT' and new.author_id is null then
+ select d.author_id into new.author_id
+ from public.content_author_defaults d
+ where d.brand_id = new.brand_id;
+ end if;
+ if new.author_id is not null
+ and (tg_op = 'INSERT' or new.author_id is distinct from old.author_id)
+ and not exists (
+ select 1
+ from public.content_authors a
+ join public.brands b on b.organization_id = a.organization_id
+ where a.id = new.author_id and b.id = new.brand_id
+ )
+ then
+ raise exception 'content draft author is not one of the brand''s organization'
+ using errcode = '23514';
+ end if;
+ return new;
+end;
+$$;
+
+drop trigger if exists content_drafts_author on public.content_drafts;
+create trigger content_drafts_author
+ before insert or update of author_id on public.content_drafts
+ for each row execute function public.content_draft_author();
diff --git a/supabase/schema.sql b/supabase/schema.sql
index b21146ce3..b2e62b2a7 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -37820,3 +37820,65 @@ grant select, insert, update, delete on public.content_author_defaults to authen
comment on table public.content_author_defaults is
'Content Editor Quality (CE-037): the author every new page of a brand gets; none means the organization byline. Admins and managers set it.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00257_content_draft_author.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00257: a page's author (Content Editor Quality, CE-038)
+-- ============================================================================
+-- content_drafts.author_id: the real person the page is by (content_authors,
+-- 00256). It is page metadata: the editor shows it in its Page info strip,
+-- outside the page, and Ansvisor sends it to the CMS author field; it is
+-- never in the page's text. (The draft's `author` column, 'user' or 'agent',
+-- says who wrote the text: another thing.)
+--
+-- * A new draft gets its brand's default author (content_author_defaults),
+-- the server's drafts too; none means the organization byline
+-- ("{Brand} Team").
+-- * The author must be one of the brand's organization's.
+
+alter table public.content_drafts
+ add column if not exists author_id uuid
+ references public.content_authors(id) on delete set null;
+
+create index if not exists content_drafts_author
+ on public.content_drafts (author_id)
+ where author_id is not null;
+
+comment on column public.content_drafts.author_id is
+ 'Content Editor Quality (CE-038): the person the page is by (content_authors), page metadata — never the page''s text. A new draft gets its brand''s default; null is the organization byline.';
+
+-- As the member who writes (RLS reads their organization's defaults and
+-- authors); the server bypasses RLS and reads them all.
+create or replace function public.content_draft_author()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if tg_op = 'INSERT' and new.author_id is null then
+ select d.author_id into new.author_id
+ from public.content_author_defaults d
+ where d.brand_id = new.brand_id;
+ end if;
+ if new.author_id is not null
+ and (tg_op = 'INSERT' or new.author_id is distinct from old.author_id)
+ and not exists (
+ select 1
+ from public.content_authors a
+ join public.brands b on b.organization_id = a.organization_id
+ where a.id = new.author_id and b.id = new.brand_id
+ )
+ then
+ raise exception 'content draft author is not one of the brand''s organization'
+ using errcode = '23514';
+ end if;
+ return new;
+end;
+$$;
+
+drop trigger if exists content_drafts_author on public.content_drafts;
+create trigger content_drafts_author
+ before insert or update of author_id on public.content_drafts
+ for each row execute function public.content_draft_author();
+
diff --git a/web/messages/en.json b/web/messages/en.json
index fa6568ba5..b34131908 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -4086,6 +4086,21 @@
},
"rulesChip": "Rules {met}/{total}",
"rulesChipHint": "Rules this page meets now. Open the Rules tab.",
+ "author": {
+ "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.",
+ "title": "Author · page metadata",
+ "organization": "{brand} Team",
+ "organizationHint": "Organization byline",
+ "default": "Default for this brand",
+ "realPeople": "Real people only. Content Agent can't add, edit or invent authors.",
+ "manage": "Manage authors",
+ "failed": "Couldn't change the author.",
+ "pageInfo": "Page info · shown by your CMS, not part of the content",
+ "titleAt": "{title}, {brand}",
+ "updated": "Updated {date}"
+ },
"qualityChip": "Quality {score}",
"qualityChipHint": "An Ansvisor estimate of this page's quality. Open Quality.",
"quality": {
@@ -6250,11 +6265,13 @@
"empty": "No authors yet. Until you add one, pages are by your brand's team.",
"you": "(you)",
"profiles": "{count, plural, =0 {No profile links} one {# profile link} other {# profile links}}",
+ "pages": "{count, plural, =0 {no pages yet} one {# page} other {# pages}}",
"defaultFor": "Default for {brands}",
"edit": "Edit",
"remove": "Remove",
"removeTitle": "Remove {name}?",
- "removeDescription": "They leave the authors list and any brand's default. Nothing on the pages themselves changes.",
+ "removeDescription": "They leave the authors list and any brand's default. {count, plural, =0 {No page in the Library is by them.} one {Their # page goes back to your brand's team byline.} other {Their # pages go back to your brand's team byline.}}",
+ "removeDescriptionUncounted": "They leave the authors list and any brand's default, and their pages go back to your brand's team byline.",
"removed": "{name} removed.",
"removeFailed": "Couldn't remove the author.",
"add": "Add author",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_author-menu.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_author-menu.test.tsx
new file mode 100644
index 000000000..93361ecb7
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_author-menu.test.tsx
@@ -0,0 +1,116 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+import type { ContentAuthor } from '@/lib/content/authors';
+
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, ...props }: { href: string } & Record<string, unknown>) => (
+ <a href={href} {...props} />
+ ),
+}));
+
+const { AuthorMenu, MANAGE_AUTHORS_PATH } = await import('./_author-menu');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const author = (over: Partial<ContentAuthor>): ContentAuthor => ({
+ id: 'a1',
+ name: 'Ada Lovelace',
+ title: 'Head of Content',
+ bio: null,
+ photoUrl: null,
+ sameAs: [],
+ userId: null,
+ createdBy: null,
+ defaultFor: [],
+ pages: 0,
+ ...over,
+});
+const AUTHORS = [
+ author({ defaultFor: ['b1'] }),
+ author({ id: 'a2', name: 'Bob Stone', title: null }),
+];
+
+let container: HTMLDivElement;
+let root: Root;
+const onPick = vi.fn();
+
+beforeEach(() => {
+ onPick.mockReset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ document.body.replaceChildren();
+});
+
+async function render(authorId: string | null) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <AuthorMenu
+ brandId="b1"
+ brandName="Acme"
+ authors={AUTHORS}
+ authorId={authorId}
+ onPick={onPick}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const trigger = () => container.querySelector<HTMLElement>('button')!;
+const items = () => [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')];
+
+async function click(el: Element | undefined) {
+ await act(async () => {
+ (el as HTMLElement).click();
+ });
+}
+
+/** Who the page is by (CE-038), in the editor's header. */
+describe('AuthorMenu', () => {
+ it("names the page's author, or the brand's team", async () => {
+ await render('a1');
+ expect(trigger().textContent).toBe('By Ada Lovelace');
+ await render(null);
+ expect(trigger().textContent).toBe('By Acme Team');
+ });
+
+ it('offers the workspace authors, the default marked, then the team byline', async () => {
+ await render('a2');
+ await click(trigger());
+ expect(items().map((i) => i.textContent)).toEqual([
+ 'Ada LovelaceHead of Content · Default for this brand',
+ 'Bob Stone',
+ 'Acme TeamOrganization byline',
+ ]);
+ expect(items()[1].getAttribute('aria-checked')).toBe('true');
+ expect(document.body.textContent).toContain(
+ "Real people only. Content Agent can't add, edit or invent authors.",
+ );
+ const manage = [...document.querySelectorAll('a')].find(
+ (a) => a.textContent === 'Manage authors',
+ );
+ expect(manage?.getAttribute('href')).toBe(MANAGE_AUTHORS_PATH);
+ });
+
+ it('picks an author, or the team byline as none', async () => {
+ await render('a2');
+ await click(trigger());
+ await click(items()[0]);
+ expect(onPick).toHaveBeenLastCalledWith('a1');
+
+ await click(trigger());
+ await click(items()[2]);
+ expect(onPick).toHaveBeenLastCalledWith(null);
+ });
+});
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.tsx
new file mode 100644
index 000000000..9d1d9fdb4
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_author-menu.tsx
@@ -0,0 +1,102 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { ChevronDown, Settings } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { badgeVariants } from '@/components/ui/badge';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import type { ContentAuthor } from '@/lib/content/authors';
+import { cn } from '@/lib/utils';
+
+/** The organization byline in the menu: no author. */
+const ORGANIZATION = 'organization';
+
+/** The address of Settings › Authors. */
+export const MANAGE_AUTHORS_PATH = '/dashboard/settings/authors';
+
+/**
+ * Who the page is by, in the editor's header (Quality spec §9, CE-038):
+ * "By {name} ▾", one of the workspace's real authors or the organization
+ * byline. Page metadata: the CMS author field gets it, the page's text
+ * never does. New pages get the brand's default; the Content Agent never
+ * picks one.
+ */
+export function AuthorMenu({
+ brandId,
+ brandName,
+ authors,
+ authorId,
+ onPick,
+}: {
+ brandId: string;
+ brandName: string;
+ authors: ContentAuthor[];
+ authorId: string | null;
+ onPick: (authorId: string | null) => void;
+}) {
+ const t = useTranslations('contentEditor.editor.author');
+ const author = authors.find((a) => a.id === authorId) ?? null;
+ const name = author?.name ?? t('organization', { brand: brandName });
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label={t('change', { name })}
+ title={t('hint')}
+ className={cn(
+ badgeVariants({ variant: 'outline' }),
+ 'max-w-56 cursor-pointer gap-1 font-normal hover:bg-muted',
+ )}
+ >
+ <span className="truncate">{t('by', { name })}</span>
+ <ChevronDown className="h-3 w-3 shrink-0 opacity-60" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-72">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t('title')}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={author?.id ?? ORGANIZATION}
+ onValueChange={(value) => onPick(value === ORGANIZATION ? null : value)}
+ >
+ {authors.map((a) => (
+ <DropdownMenuRadioItem key={a.id} value={a.id} closeOnClick>
+ <span className="min-w-0">
+ <span className="block truncate">{a.name}</span>
+ {(a.title || a.defaultFor.includes(brandId)) && (
+ <span className="block truncate text-xs text-muted-foreground">
+ {[a.title, a.defaultFor.includes(brandId) ? t('default') : null]
+ .filter(Boolean)
+ .join(' · ')}
+ </span>
+ )}
+ </span>
+ </DropdownMenuRadioItem>
+ ))}
+ <DropdownMenuRadioItem value={ORGANIZATION} closeOnClick>
+ <span className="min-w-0">
+ <span className="block truncate">{t('organization', { brand: brandName })}</span>
+ <span className="block text-xs text-muted-foreground">{t('organizationHint')}</span>
+ </span>
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <p className="px-1.5 py-1 text-xs text-muted-foreground">{t('realPeople')}</p>
+ <DropdownMenuItem render={<Link href={MANAGE_AUTHORS_PATH} />} className="text-xs">
+ <Settings className="h-3.5 w-3.5" />
+ {t('manage')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
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.tsx
index 563ecced3..133c92e6c 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
@@ -32,12 +32,15 @@ import {
keepAgentBeforeVersion,
markContentDraftReady,
restoreDraftVersion,
+ setContentDraftAuthor,
setContentDraftPageType,
startAgentWriting,
startPageRewrite,
} from '@/lib/actions/content-drafts';
+import { getContentAuthors } from '@/lib/actions/content-authors';
import { stopAgentRun } from '@/lib/content/agent-runs-client';
import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';
+import { authorInitials, type AuthorsRead } from '@/lib/content/authors';
import {
AGENT_POLL_MS,
CONTENT_LIBRARY_PATH,
@@ -78,6 +81,7 @@ import { cn } from '@/lib/utils';
import { useBrandStore } from '@/stores/use-brand-store';
import { AgentCard } from './_agent-card';
import { AgentDrafting, draftingKey } from './_agent-drafting';
+import { AuthorMenu } from './_author-menu';
import { FlashBlock, findBlock, flashKey } from './_flash-block';
import { useAgentRun } from './_use-agent-run';
import { WorkingDots } from './_working-dots';
@@ -95,6 +99,7 @@ import { sourceDetail } from './_sources-tab';
import { HistoryMenu } from './_history-menu';
import { HtmlBlock, copyToClipboard } from './_html-block';
import { OwnCopies, ownCopyHtml } from './_own-copies';
+import { PageInfoStrip, pageInfoKey } from './_page-info';
import { PageTypeMenu } from './_page-type-menu';
import type { AgentRewrite } from './_brief-tab';
import { ruleStatusDetail, type AgentFix, type PageRewrite } from './_rules-tab';
@@ -323,6 +328,7 @@ export function DraftEditor({
OneH1,
AgentDrafting,
FlashBlock,
+ PageInfoStrip,
],
content: draft.bodyHtml,
// Rendered on the client only, so the server's HTML can't disagree with it.
@@ -411,6 +417,79 @@ export function DraftEditor({
[qualityOn, pageHtml, language],
);
const qualityScore = qualityAverage([readable?.score ?? null]);
+
+ // Who the page is by (CE-038): page metadata, shown in the header and in a
+ // Page info strip outside the page; with Quality's first phase.
+ const [authorsRead, setAuthorsRead] = useState<AuthorsRead | null>(null);
+ const [authorId, setAuthorId] = useState(draft.authorId);
+ // The author the database holds, and the latest pick: a slower pick that
+ // fails after a later one landed doesn't roll the menu back.
+ const savedAuthor = useRef(draft.authorId);
+ const authorPick = useRef(0);
+ const [authorChangedAt, setAuthorChangedAt] = useState<string | null>(null);
+ useEffect(() => {
+ if (!qualityOn) return;
+ let live = true;
+ getContentAuthors()
+ .then((read) => live && setAuthorsRead(read))
+ .catch((err) => console.error('Failed to load the authors:', err));
+ return () => {
+ live = false;
+ };
+ }, [qualityOn]);
+ const storeBrandName = useBrandStore((s) => s.brands.find((b) => b.id === draft.brandId)?.name);
+ const brandName =
+ authorsRead?.brands.find((b) => b.id === draft.brandId)?.name ?? storeBrandName ?? '';
+ const pageAuthor = authorsRead?.authors.find((a) => a.id === authorId) ?? null;
+ const byline = authorsRead
+ ? [
+ t('author.by', {
+ name: pageAuthor?.name ?? t('author.organization', { brand: brandName }),
+ }),
+ pageAuthor?.title && t('author.titleAt', { title: pageAuthor.title, brand: brandName }),
+ t('author.updated', {
+ date: format.dateTime(
+ Math.max(
+ new Date(autosave.savedAt).getTime(),
+ authorChangedAt ? new Date(authorChangedAt).getTime() : 0,
+ ),
+ { dateStyle: 'medium' },
+ ),
+ }),
+ ]
+ .filter(Boolean)
+ .join(' · ')
+ : null;
+ useEffect(() => {
+ if (!editor || editor.isDestroyed) return;
+ editor.view.dispatch(
+ editor.state.tr.setMeta(
+ pageInfoKey,
+ byline
+ ? {
+ label: t('author.pageInfo'),
+ byline,
+ initials: authorInitials(pageAuthor?.name ?? brandName),
+ photoUrl: pageAuthor?.photoUrl ?? null,
+ }
+ : null,
+ ),
+ );
+ }, [editor, byline, pageAuthor?.name, pageAuthor?.photoUrl, brandName, t]);
+ const pickAuthor = async (next: string | null) => {
+ if (next === authorId) return;
+ const pick = ++authorPick.current;
+ setAuthorId(next);
+ try {
+ await setContentDraftAuthor(draft.id, next);
+ savedAuthor.current = next;
+ setAuthorChangedAt(new Date().toISOString());
+ } catch (err) {
+ console.error('Failed to set the author:', err);
+ if (pick === authorPick.current) setAuthorId(savedAuthor.current);
+ toast.error(t('author.failed'));
+ }
+ };
useEffect(() => {
attachRef.current = (files) => void attachments.attach(files);
onDecide.current = (id, decision) => void decide([id], decision);
@@ -1366,6 +1445,15 @@ export function DraftEditor({
sourceUrl={draft.sourceUrl}
onPick={(type) => void pickPageType(type)}
/>
+ {authorsRead && (
+ <AuthorMenu
+ brandId={draft.brandId}
+ brandName={brandName}
+ authors={authorsRead.authors}
+ authorId={authorId}
+ onPick={(next) => void pickAuthor(next)}
+ />
+ )}
<DraftMethodBadge method={draft.method} />
<DraftStatusBadge status={status} />
<button
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-info.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-info.test.ts
new file mode 100644
index 000000000..bc4814d29
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-info.test.ts
@@ -0,0 +1,112 @@
+import { Editor, Extension } from '@tiptap/core';
+import { Plugin } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import StarterKit from '@tiptap/starter-kit';
+import { afterEach, describe, expect, it } from 'vitest';
+import { PageInfoStrip, pageInfoAt, pageInfoKey } from './_page-info';
+
+let editor: Editor | null = null;
+afterEach(() => {
+ editor?.destroy();
+ editor = null;
+});
+
+const open = (content: string) => {
+ editor = new Editor({ extensions: [StarterKit, PageInfoStrip], content });
+ return editor;
+};
+
+const INFO = {
+ label: 'Page info · shown by your CMS, not part of the content',
+ byline: 'By Ada Lovelace · Head of Content, Acme · Updated Oct 23, 2026',
+ initials: 'AL',
+ photoUrl: null as string | null,
+};
+
+const show = (e: Editor, info: typeof INFO | null) =>
+ e.view.dispatch(e.state.tr.setMeta(pageInfoKey, info));
+
+/** The page's byline (CE-038): editor-only, outside the page. */
+describe('PageInfoStrip', () => {
+ it('shows the byline under the H1, outside the page', () => {
+ const e = open('<h1>Pipeline forecasting</h1><p>Teams trust it.</p>');
+ show(e, INFO);
+
+ const strip = e.view.dom.querySelector<HTMLElement>('[data-page-info]')!;
+ // One line, as the mockup: the author's initials, the byline, the label.
+ expect(strip.textContent).toBe(INFO.initials + INFO.byline + INFO.label);
+ expect(strip.contentEditable).toBe('false');
+ expect(strip.previousElementSibling?.tagName).toBe('H1');
+ // No save, export, Copy HTML or HTML view has it: they read the page.
+ expect(e.getHTML()).toBe('<h1>Pipeline forecasting</h1><p>Teams trust it.</p>');
+ expect(e.getText()).not.toContain('Page info');
+ });
+
+ it('follows the author, and leaves when there is none to show', () => {
+ const e = open('<h1>Title</h1><p>Text</p>');
+ show(e, INFO);
+ show(e, { ...INFO, byline: 'By Acme Team · Updated Oct 23, 2026' });
+ const strips = e.view.dom.querySelectorAll('[data-page-info]');
+ expect(strips).toHaveLength(1);
+ expect(strips[0].textContent).toContain('By Acme Team');
+
+ // Typing keeps it.
+ e.commands.insertContentAt(e.state.doc.content.size, '<p>More</p>');
+ expect(e.view.dom.querySelectorAll('[data-page-info]')).toHaveLength(1);
+
+ show(e, null);
+ expect(e.view.dom.querySelector('[data-page-info]')).toBeNull();
+ });
+
+ it("stays under the H1, above a suggestion's card for the next block", () => {
+ // A card the way _suggestions.ts draws one: before its block (side -1).
+ const Card = Extension.create({
+ name: 'card',
+ addProseMirrorPlugins: () => [
+ new Plugin({
+ props: {
+ decorations: (state) =>
+ DecorationSet.create(state.doc, [
+ Decoration.widget(
+ state.doc.firstChild!.nodeSize,
+ () => Object.assign(document.createElement('div'), { className: 'card' }),
+ { side: -1 },
+ ),
+ ]),
+ },
+ }),
+ ],
+ });
+ editor = new Editor({
+ extensions: [StarterKit, PageInfoStrip, Card],
+ content: '<h1>Title</h1><p>Text</p>',
+ });
+ show(editor, INFO);
+ const order = [...editor.view.dom.children].map((el) =>
+ el instanceof HTMLElement && 'pageInfo' in el.dataset
+ ? 'strip'
+ : el.classList.contains('card')
+ ? 'card'
+ : el.tagName,
+ );
+ expect(order).toEqual(['H1', 'strip', 'card', 'P']);
+ });
+
+ it("shows the author's photo instead of initials when they have one", () => {
+ const e = open('<h1>Title</h1><p>Text</p>');
+ show(e, { ...INFO, photoUrl: 'https://example.com/ada.jpg' });
+ const img = e.view.dom.querySelector<HTMLImageElement>('[data-page-info] img')!;
+ expect(img.src).toBe('https://example.com/ada.jpg');
+ expect(img.alt).toBe('');
+ expect(e.view.dom.querySelector('[data-page-info]')!.textContent).toBe(
+ INFO.byline + INFO.label,
+ );
+ });
+
+ it('goes at the top of a page that has no H1 first', () => {
+ expect(pageInfoAt(open('<p>Text</p><h1>Late title</h1>').state.doc)).toBe(0);
+ editor?.destroy();
+ const e = open('<h1>Title</h1><p>Text</p>');
+ expect(pageInfoAt(e.state.doc)).toBe(e.state.doc.firstChild!.nodeSize);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-info.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-info.ts
new file mode 100644
index 000000000..2de54a209
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-info.ts
@@ -0,0 +1,107 @@
+import { Extension } from '@tiptap/core';
+import type { Node as PmNode } from '@tiptap/pm/model';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+
+/**
+ * The page's byline in a grey "Page info" strip right under the H1 (Quality
+ * spec §9 and its full mockup, CE-038): the author is page metadata, which the CMS shows, never the
+ * page's text. A decoration, never the page's: no save, export, Copy, Copy
+ * HTML or HTML view has it.
+ */
+
+export interface PageInfo {
+ /** "Page info · shown by your CMS, not part of the content". */
+ label: string;
+ /** "By Ada Lovelace · Head of Content, Acme · Updated Oct 23, 2026". */
+ byline: string;
+ /** The author's initials, or the brand's for its team. */
+ initials: string;
+ /** The author's photo (https), when they have one. */
+ photoUrl: string | null;
+}
+
+export const pageInfoKey = new PluginKey<PageInfo | null>('pageInfo');
+
+function el<K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text: string) {
+ const node = document.createElement(tag);
+ node.className = className;
+ node.textContent = text;
+ return node;
+}
+
+/** One line, as the mockup draws it: the author's face, the byline, the label on the right. */
+function strip({ label, byline, initials, photoUrl }: PageInfo): HTMLElement {
+ const box = document.createElement('div');
+ box.className =
+ 'not-prose mt-1.5 mb-4 flex flex-wrap items-center gap-x-1.5 gap-y-1 rounded-lg border border-dashed bg-muted/40 px-2.5 py-1.5 leading-snug select-none';
+ box.contentEditable = 'false';
+ // The header's author menu says the same; a screen reader reading the page
+ // shouldn't take it for the page's text.
+ box.setAttribute('aria-hidden', 'true');
+ box.dataset.pageInfo = '';
+ const face = 'h-[22px] w-[22px] shrink-0 rounded-full';
+ if (photoUrl) {
+ const img = document.createElement('img');
+ img.className = `${face} object-cover`;
+ img.src = photoUrl;
+ img.alt = '';
+ img.referrerPolicy = 'no-referrer';
+ box.append(img);
+ } else {
+ box.append(
+ el(
+ 'span',
+ `${face} inline-flex items-center justify-center bg-muted text-[9px] font-semibold text-foreground`,
+ initials,
+ ),
+ );
+ }
+ // Spans and divs, not paragraphs: nothing that looks for the page's paragraphs finds it.
+ box.append(
+ el('span', 'text-[12.5px] text-muted-foreground [overflow-wrap:anywhere]', byline),
+ el('span', 'ml-auto text-[11px] text-muted-foreground/80', label),
+ );
+ return box;
+}
+
+/** Where the strip goes: under the H1 that opens the page, else at the top. */
+export function pageInfoAt(doc: PmNode): number {
+ const first = doc.firstChild;
+ return first?.type.name === 'heading' && first.attrs.level === 1 ? first.nodeSize : 0;
+}
+
+export const PageInfoStrip = Extension.create({
+ name: 'pageInfo',
+
+ addProseMirrorPlugins() {
+ return [
+ new Plugin<PageInfo | null>({
+ key: pageInfoKey,
+ state: {
+ init: () => null,
+ apply: (tr, value) => {
+ const meta = tr.getMeta(pageInfoKey) as PageInfo | null | undefined;
+ return meta === undefined ? value : meta;
+ },
+ },
+ props: {
+ decorations: (state) => {
+ const info = pageInfoKey.getState(state);
+ if (!info) return null;
+ return DecorationSet.create(state.doc, [
+ // Right under the H1: before a suggestion's card for the next
+ // block (side -1) and the agent's drafting card (side 1).
+ Decoration.widget(pageInfoAt(state.doc), () => strip(info), {
+ key: `page-info:${info.label}:${info.byline}:${info.photoUrl ?? info.initials}`,
+ side: -2,
+ ignoreSelection: true,
+ stopEvent: () => true,
+ }),
+ ]);
+ },
+ },
+ }),
+ ];
+ },
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts
index b562381bf..31d7b9c0a 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts
@@ -41,6 +41,8 @@ interface DraftContent {
*/
export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; bodyHtml: string }) {
const [state, setState] = useState<SaveState>('saved');
+ // When the page was last saved, from here or as loaded: the Page info strip's date.
+ const [savedAt, setSavedAt] = useState(loaded.updatedAt);
const pending = useRef<DraftContent | null>(null);
const saving = useRef(false);
const failed = useRef(false);
@@ -95,6 +97,7 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; b
return;
}
base.current = { updatedAt: result.updatedAt, bodyHash: result.bodyHash };
+ setSavedAt(result.updatedAt);
unconfirmed.current = null;
failed.current = false;
if (pending.current) {
@@ -158,6 +161,7 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; b
stopped.current = false;
unconfirmed.current = null;
base.current = { updatedAt: version.updatedAt, bodyHash: null };
+ setSavedAt(version.updatedAt);
loadedBody.current = version.bodyHtml;
if (!saving.current) setState('saved');
}, []);
@@ -190,5 +194,5 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; b
[draftId, baseVersion],
);
- return { state, schedule, retry: flush, settle, discard };
+ return { state, savedAt, schedule, retry: flush, settle, discard };
}
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.tsx
index 9fe096e36..c04de76dc 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
@@ -15,6 +15,11 @@ const getContentDraft = vi.fn();
const markContentDraftReady = vi.fn();
const saveContentDraft = vi.fn();
const setContentDraftPageType = vi.fn();
+const setContentDraftAuthor = vi.fn();
+const getContentAuthors = vi.fn();
+vi.mock('@/lib/actions/content-authors', () => ({
+ getContentAuthors: (...args: unknown[]) => getContentAuthors(...args),
+}));
const getContentImpact = vi.fn();
const getContentResults = vi.fn();
const getDraftSources = vi.fn();
@@ -62,6 +67,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({
markContentDraftReady: (...args: unknown[]) => markContentDraftReady(...args),
saveContentDraft: (...args: unknown[]) => saveContentDraft(...args),
setContentDraftPageType: (...args: unknown[]) => setContentDraftPageType(...args),
+ setContentDraftAuthor: (...args: unknown[]) => setContentDraftAuthor(...args),
}));
vi.mock('next/navigation', () => ({ useParams: () => ({ draftId: 'd1' }) }));
vi.mock('@/i18n/navigation', () => ({
@@ -153,6 +159,7 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({
status: 'in_review',
bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams trust it.</p>',
author: 'agent',
+ authorId: null,
rules: { set: null, source: null, overrides: {}, textRules: [] },
action: null,
agentState: null,
@@ -222,6 +229,8 @@ beforeEach(() => {
markContentDraftReady.mockReset();
saveBlob.mockReset();
setContentDraftPageType.mockReset().mockResolvedValue(undefined);
+ setContentDraftAuthor.mockReset().mockResolvedValue(undefined);
+ getContentAuthors.mockReset().mockResolvedValue(null);
saveContentDraft
.mockReset()
.mockResolvedValue({ ok: true, updatedAt: '2026-10-20T10:00:00Z', bodyHash: 'h0' });
@@ -2290,6 +2299,90 @@ describe('the side panel', () => {
});
});
+ describe('Author (CE-038)', () => {
+ const ada = {
+ id: 'a1',
+ name: 'Ada Lovelace',
+ title: 'Head of Content',
+ bio: null,
+ photoUrl: null,
+ sameAs: [],
+ userId: null,
+ createdBy: null,
+ defaultFor: ['b1'],
+ pages: 1,
+ };
+ beforeEach(() => {
+ getContentAuthors.mockResolvedValue({
+ authors: [ada],
+ brands: [{ id: 'b1', name: 'Acme' }],
+ me: { id: 'u1', role: 'analyst' },
+ });
+ });
+ afterEach(() => {
+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;
+ });
+ const byButton = () =>
+ [...container.querySelectorAll<HTMLButtonElement>('header button')].find((b) =>
+ b.textContent?.startsWith('By '),
+ );
+ const strip = () => container.querySelector<HTMLElement>('[data-page-info]');
+
+ it("shows no author until Quality's first phase is live", async () => {
+ getContentDraft.mockResolvedValue(draft({ authorId: 'a1' }));
+ await renderPage();
+ expect(getContentAuthors).not.toHaveBeenCalled();
+ expect(byButton()).toBeUndefined();
+ expect(strip()).toBeNull();
+ });
+
+ it('names the author in the header and a Page info strip outside the page', async () => {
+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';
+ getContentDraft.mockResolvedValue(draft({ authorId: 'a1' }));
+ await renderPage();
+ expect(byButton()!.textContent).toBe('By Ada Lovelace');
+ expect(strip()!.textContent).toBe(
+ 'ALBy Ada Lovelace · Head of Content, Acme · Updated Oct 20, 2026Page info · shown by your CMS, not part of the content',
+ );
+ expect(strip()!.previousElementSibling?.tagName).toBe('H1');
+
+ // Copy HTML (as export, save and the HTML view) reads the page: no strip.
+ 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',
+ )!;
+ await act(async () => copyPage.click());
+ expect(writeText).toHaveBeenLastCalledWith(
+ '<h1>Pipeline forecasting</h1>\n<p>Teams trust it.</p>',
+ );
+ });
+
+ it('sets the organization byline, and goes back when that fails', async () => {
+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';
+ getContentDraft.mockResolvedValue(draft({ authorId: 'a1' }));
+ await renderPage();
+ await act(async () => byButton()!.click());
+ const team = [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].find(
+ (item) => item.textContent?.startsWith('Acme Team'),
+ )!;
+ await act(async () => team.click());
+ expect(setContentDraftAuthor).toHaveBeenCalledWith('d1', null);
+ // Page metadata: the page itself isn't saved for it.
+ expect(saveContentDraft).not.toHaveBeenCalled();
+ expect(byButton()!.textContent).toBe('By Acme Team');
+ expect(strip()!.textContent).toContain('By Acme Team · Updated');
+
+ setContentDraftAuthor.mockRejectedValue(new Error('invalid'));
+ await act(async () => byButton()!.click());
+ const back = [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].find(
+ (item) => item.textContent?.startsWith('Ada Lovelace'),
+ )!;
+ await act(async () => back.click());
+ expect(byButton()!.textContent).toBe('By Acme Team');
+ });
+ });
+
describe('Run Agent: fix open rules', () => {
const traced = draft({
pageType: 'blog_post',
diff --git a/web/src/components/settings/authors-section.test.tsx b/web/src/components/settings/authors-section.test.tsx
index c392f5850..8c93bd3ef 100644
--- a/web/src/components/settings/authors-section.test.tsx
+++ b/web/src/components/settings/authors-section.test.tsx
@@ -46,6 +46,7 @@ function workspace(role: string): AuthorsRead {
userId: ME,
createdBy: OTHER,
defaultFor: [ACME],
+ pages: 3,
},
{
id: BOB,
@@ -57,6 +58,7 @@ function workspace(role: string): AuthorsRead {
userId: OTHER,
createdBy: OTHER,
defaultFor: [],
+ pages: 0,
},
{
id: CAL,
@@ -68,6 +70,7 @@ function workspace(role: string): AuthorsRead {
userId: null,
createdBy: ME,
defaultFor: [],
+ pages: 0,
},
],
brands: [{ id: ACME, name: 'Acme' }],
@@ -134,9 +137,12 @@ describe('AuthorsSection', () => {
"Real people only. Content Agent can't add, edit or invent authors.",
);
expect(row('Ada Lovelace').textContent).toContain('(you)');
- expect(row('Ada Lovelace').textContent).toContain('1 profile link · Default for Acme');
- expect(row('Bob Stone').textContent).toContain('No profile links');
+ expect(row('Ada Lovelace').textContent).toContain(
+ '1 profile link · 3 pages · Default for Acme',
+ );
+ expect(row('Bob Stone').textContent).toContain('No profile links · no pages yet');
expect(trigger().querySelector('[data-slot="select-value"]')!.textContent).toBe('Ada Lovelace');
+ expect(actions.getContentAuthors).toHaveBeenCalledWith({ pages: true });
});
it('lets a member edit the author they are and the ones they added, not the defaults', async () => {
@@ -257,12 +263,24 @@ describe('AuthorsSection', () => {
await render();
await click(row('Cal Freelance').querySelectorAll('button')[1]);
expect(document.body.textContent).toContain('Remove Cal Freelance?');
+ expect(document.body.textContent).toContain(
+ "They leave the authors list and any brand's default. No page in the Library is by them.",
+ );
expect(actions.deleteContentAuthor).not.toHaveBeenCalled();
await click(buttons('Remove').find((b) => !container.contains(b)));
expect(actions.deleteContentAuthor).toHaveBeenCalledWith(CAL);
});
+ it("says the author's pages go back to the team byline", async () => {
+ await render();
+ await click(row('Ada Lovelace').querySelectorAll('button')[1]);
+ expect(document.body.textContent).toContain('Remove Ada Lovelace?');
+ expect(document.body.textContent).toContain(
+ "Their 3 pages go back to your brand's team byline.",
+ );
+ });
+
it("says so when the authors can't be read", async () => {
actions.getContentAuthors.mockResolvedValue(null);
await render();
diff --git a/web/src/components/settings/authors-section.tsx b/web/src/components/settings/authors-section.tsx
index 36968419c..7d1c94119 100644
--- a/web/src/components/settings/authors-section.tsx
+++ b/web/src/components/settings/authors-section.tsx
@@ -33,6 +33,7 @@ import {
setDefaultAuthor,
} from '@/lib/actions/content-authors';
import {
+ authorInitials,
MAX_LINK_LENGTH,
MAX_PROFILES,
type AuthorInput,
@@ -67,7 +68,7 @@ export function AuthorsSection() {
const load = useCallback(async () => {
try {
- const next = await getContentAuthors();
+ const next = await getContentAuthors({ pages: true });
setRead(next);
setFailed(!next);
} catch {
@@ -167,6 +168,12 @@ export function AuthorsSection() {
)}
<p className="mt-0.5 text-xs text-muted-foreground [overflow-wrap:anywhere]">
{t('profiles', { count: author.sameAs.length })}
+ {author.pages !== null && (
+ <>
+ {' · '}
+ {t('pages', { count: author.pages })}
+ </>
+ )}
{author.defaultFor.length > 0 && (
<>
{' · '}
@@ -270,7 +277,11 @@ export function AuthorsSection() {
<DialogContent>
<DialogHeader>
<DialogTitle>{t('removeTitle', { name: removing?.name ?? '' })}</DialogTitle>
- <DialogDescription>{t('removeDescription')}</DialogDescription>
+ <DialogDescription>
+ {removing?.pages == null
+ ? t('removeDescriptionUncounted')
+ : t('removeDescription', { count: removing.pages })}
+ </DialogDescription>
</DialogHeader>
<DialogFooter>
<DialogClose render={<Button variant="outline" disabled={busy} />}>
@@ -309,11 +320,7 @@ export function AuthorsSection() {
/** The author's photo, or their initials. */
function AuthorPhoto({ author }: { author: ContentAuthor }) {
- const initials = author.name
- .split(/\s+/)
- .slice(0, 2)
- .map((part) => part[0]?.toUpperCase() ?? '')
- .join('');
+ const initials = authorInitials(author.name);
return author.photoUrl ? (
// eslint-disable-next-line @next/next/no-img-element -- any https host the person names
<img
diff --git a/web/src/lib/actions/content-authors.test.ts b/web/src/lib/actions/content-authors.test.ts
index f434ac718..2b3330656 100644
--- a/web/src/lib/actions/content-authors.test.ts
+++ b/web/src/lib/actions/content-authors.test.ts
@@ -19,8 +19,10 @@ interface Call {
}
let calls: Call[] = [];
/** What a write or read of each table answers. */
-let answers: Record<string, { data: unknown; error: null | { message: string; code?: string } }> =
- {};
+let answers: Record<
+ string,
+ { data: unknown; count?: number; error: null | { message: string; code?: string } }
+> = {};
function builder(table: string) {
const call: Call = { table, op: 'select', filters: [] };
@@ -36,6 +38,10 @@ function builder(table: string) {
call.filters.push([column, value]);
return chain;
},
+ is: (column: string, value: unknown) => {
+ call.filters.push([`is ${column}`, value]);
+ return chain;
+ },
order: () => chain,
single: async () => answer(),
maybeSingle: async () => answer(),
@@ -84,11 +90,12 @@ describe('getContentAuthors', () => {
error: null,
};
answers['brands.select'] = { data: [{ id: ACME, name: 'Acme' }], error: null };
+ answers['content_drafts.select'] = { data: null, count: 2, error: null };
answers['content_author_defaults.select'] = {
data: [{ brand_id: ACME, author_id: ADA }],
error: null,
};
- const read = await getContentAuthors();
+ const read = await getContentAuthors({ pages: true });
expect(read).toEqual({
authors: [
{
@@ -101,6 +108,7 @@ describe('getContentAuthors', () => {
userId: ME,
createdBy: OTHER,
defaultFor: [ACME],
+ pages: 2,
},
],
brands: [{ id: ACME, name: 'Acme' }],
@@ -108,6 +116,22 @@ describe('getContentAuthors', () => {
});
});
+ it("counts each author's Library pages only when asked", async () => {
+ answers['content_authors.select'] = {
+ data: [{ id: ADA, name: 'Ada', same_as: [], user_id: null, created_by: null }],
+ error: null,
+ };
+ expect((await getContentAuthors())!.authors[0].pages).toBeNull();
+ expect(calls.some((c) => c.table === 'content_drafts')).toBe(false);
+
+ answers['content_drafts.select'] = { data: null, count: 4, error: null };
+ expect((await getContentAuthors({ pages: true }))!.authors[0].pages).toBe(4);
+ expect(calls.find((c) => c.table === 'content_drafts')!.filters).toEqual([
+ ['author_id', ADA],
+ ['is archived_at', null],
+ ]);
+ });
+
it('reads nothing for a member without an organization', async () => {
answers['profiles.select'] = { data: { organization_id: null, role: 'admin' }, error: null };
expect(await getContentAuthors()).toBeNull();
diff --git a/web/src/lib/actions/content-authors.ts b/web/src/lib/actions/content-authors.ts
index c5dd1487e..b1dd9d534 100644
--- a/web/src/lib/actions/content-authors.ts
+++ b/web/src/lib/actions/content-authors.ts
@@ -17,8 +17,14 @@ const ALREADY_AUTHOR = '23505';
const AUTHOR_COLUMNS = 'id, name, title, bio, photo_url, same_as, user_id, created_by';
-/** The workspace's authors, its brands and the member reading; null when signed out. */
-export async function getContentAuthors(): Promise<AuthorsRead | null> {
+/**
+ * The workspace's authors, its brands and the member reading; null when
+ * signed out. `pages` counts each author's pages (Settings' column); the
+ * editor doesn't need it.
+ */
+export async function getContentAuthors(
+ options: { pages?: boolean } = {},
+): Promise<AuthorsRead | null> {
const supabase = await createClient();
const { data: auth } = await supabase.auth.getUser();
if (!auth.user) return null;
@@ -47,8 +53,24 @@ export async function getContentAuthors(): Promise<AuthorsRead | null> {
if (res.error) throw new Error(res.error.message);
}
const defaults = (defaultsRes.data ?? []) as { brand_id: string; author_id: string }[];
+ const rows = authorsRes.data ?? [];
+ // A workspace has a few authors: one count each, on content_drafts_author,
+ // of the pages the Library shows (not archived).
+ const pages = options.pages
+ ? await Promise.all(
+ rows.map(async (row) => {
+ const { count, error } = await supabase
+ .from('content_drafts')
+ .select('id', { count: 'exact', head: true })
+ .eq('author_id', row.id)
+ .is('archived_at', null);
+ if (error) throw new Error(error.message);
+ return count ?? 0;
+ }),
+ )
+ : null;
return {
- authors: (authorsRes.data ?? []).map((row) => ({
+ authors: rows.map((row, i) => ({
id: row.id,
name: row.name,
title: row.title,
@@ -58,6 +80,7 @@ export async function getContentAuthors(): Promise<AuthorsRead | null> {
userId: row.user_id,
createdBy: row.created_by,
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 })),
me: { id: auth.user.id, role: profile.role ?? 'analyst' },
diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.ts
index c787b0456..e365b9b9c 100644
--- a/web/src/lib/actions/content-drafts.test.ts
+++ b/web/src/lib/actions/content-drafts.test.ts
@@ -88,6 +88,7 @@ const {
markContentDraftReady,
restoreDraftVersion,
saveContentDraft,
+ setContentDraftAuthor,
setContentDraftPageType,
} = await import('./content-drafts');
const { bodyHash } = await import('@/lib/content/editor');
@@ -319,6 +320,29 @@ describe('setContentDraftPageType', () => {
});
});
+describe('setContentDraftAuthor', () => {
+ const AUTHOR = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
+
+ it('sets the person the page is by, or the organization byline', async () => {
+ updated = { id: DRAFT };
+ await setContentDraftAuthor(DRAFT, AUTHOR);
+ expect(calls[0]).toMatchObject({
+ op: 'update',
+ value: { author_id: AUTHOR },
+ filters: [['eq', 'id', DRAFT]],
+ });
+ await setContentDraftAuthor(DRAFT, null);
+ expect(calls[1]).toMatchObject({ op: 'update', value: { author_id: null } });
+ });
+
+ it('refuses an id that is not one, and says so when the draft isn’t the member’s', async () => {
+ await expect(setContentDraftAuthor(DRAFT, 'ada')).rejects.toThrow('invalid');
+ await expect(setContentDraftAuthor('d1', AUTHOR)).rejects.toThrow('invalid');
+ expect(calls).toEqual([]);
+ await expect(setContentDraftAuthor(DRAFT, AUTHOR)).rejects.toThrow('not_found');
+ });
+});
+
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.ts
index a91da88e3..51f180bcd 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -218,7 +218,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>
const { data, error } = await supabase
.from('content_drafts')
.select(
- `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, source_url, rules, action_id, agent_state, agent_state_at, agent_run, updated_at, ${BRAND_SITE}, actions(action_no)`,
+ `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, author_id, source_url, rules, action_id, agent_state, agent_state_at, agent_run, updated_at, ${BRAND_SITE}, actions(action_no)`,
)
.eq('id', id)
.maybeSingle();
@@ -236,6 +236,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>
status: draftStatus(data.status),
bodyHtml: data.body_html,
author: data.author === 'agent' ? 'agent' : 'user',
+ authorId: data.author_id,
rules: draftRulesSchema.safeParse(data.rules).data ?? NO_DRAFT_RULES,
action:
data.action_id && data.actions
@@ -1158,6 +1159,34 @@ export async function setContentDraftPageType(id: string, pageType: PageType): P
if (!data) throw new Error('not_found');
}
+/** 00257's refusal of an author from another organization (a check violation). */
+const OTHER_ORGANIZATION = '23514';
+
+/**
+ * The person a page is by (CE-038), or null for the organization byline:
+ * page metadata, never its text. The database takes only an author of the
+ * brand's organization (00257). A save over it isn't a conflict: the page
+ * is the same.
+ */
+export async function setContentDraftAuthor(id: string, authorId: string | null): Promise<void> {
+ if (
+ !draftId.safeParse(id).success ||
+ (authorId !== null && !z.guid().safeParse(authorId).success)
+ ) {
+ throw new Error('invalid');
+ }
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_drafts')
+ .update({ author_id: authorId })
+ .eq('id', id)
+ .select('id')
+ .maybeSingle();
+ if (error?.code === OTHER_ORGANIZATION) throw new Error('invalid');
+ if (error) throw new Error(error.message);
+ if (!data) throw new Error('not_found');
+}
+
/** The statuses the Library's row menu sets directly; Ready goes through markContentDraftReady. */
const ROW_STATUSES = ['draft', 'in_review', 'published'] as const;
diff --git a/web/src/lib/content/authors.ts b/web/src/lib/content/authors.ts
index 957faf40b..3ee506f15 100644
--- a/web/src/lib/content/authors.ts
+++ b/web/src/lib/content/authors.ts
@@ -19,6 +19,8 @@ export interface ContentAuthor {
createdBy: string | null;
/** The brands whose pages it is by when nobody picks another. */
defaultFor: string[];
+ /** The Library pages it is the author of (content_drafts.author_id, CE-038), when counted. */
+ pages: number | null;
}
export interface AuthorsRead {
@@ -28,6 +30,16 @@ export interface AuthorsRead {
me: { id: string; role: string };
}
+/** "Ada Lovelace" → "AL": an author's face without a photo. */
+export function authorInitials(name: string): string {
+ return name
+ .split(/\s+/)
+ .filter(Boolean)
+ .slice(0, 2)
+ .map((part) => part.charAt(0).toUpperCase())
+ .join('');
+}
+
/** The most profile links an author keeps (00256). */
export const MAX_PROFILES = 10;
/** The longest profile link; the table checks it too, with https (content_author_links_ok). */
diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.ts
index 63551cf74..785c6e6f0 100644
--- a/web/src/lib/content/drafts.ts
+++ b/web/src/lib/content/drafts.ts
@@ -152,6 +152,12 @@ export interface ContentDraft {
status: DraftStatus;
bodyHtml: string;
author: 'user' | 'agent';
+ /**
+ * The person the page is by (CE-038, content_authors): page metadata the
+ * editor shows outside the page and the CMS author field gets. Null is the
+ * organization byline ("{Brand} Team").
+ */
+ authorId: string | null;
/** What the person changed on the page's rules for this draft (CE-009). */
rules: DraftRules;
/** The Action Center action the draft is the work of (CE-022), shown as "from Action AC-214". */
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 0e750ddb2..7f4fbdfd9 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -979,6 +979,7 @@ export type Database = {
archived_at: string | null
archived_by: string | null
author: string
+ author_id: string | null
body_html: string
brief: Json | null
brand_id: string
@@ -1006,6 +1007,7 @@ export type Database = {
archived_at?: string | null
archived_by?: string | null
author?: string
+ author_id?: string | null
body_html?: string
brief?: Json | null
brand_id: string
@@ -1033,6 +1035,7 @@ export type Database = {
archived_at?: string | null
archived_by?: string | null
author?: string
+ author_id?: string | null
body_html?: string
brief?: Json | null
brand_id?: string
@@ -1053,6 +1056,13 @@ export type Database = {
updated_at?: string
}
Relationships: [
+ {
+ foreignKeyName: "content_drafts_author_id_fkey"
+ columns: ["author_id"]
+ isOneToOne: false
+ referencedRelation: "content_authors"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "content_drafts_opportunity_id_fkey"
columns: ["opportunity_id"]