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): add the Content group and its Library of drafts (#1256)

Cihan604455e48fdc
diff --git a/supabase/migrations/00204_content_drafts.sql b/supabase/migrations/00204_content_drafts.sql
new file mode 100644
index 000000000..c4038ab37
--- /dev/null
+++ b/supabase/migrations/00204_content_drafts.sql
@@ -0,0 +1,138 @@
+-- ============================================================================
+-- 00204: content drafts, the Content Library's rows (Content Editor, CE-002)
+-- ============================================================================
+-- The Content area writes and improves pages in Ansvisor (Content Editor spec
+-- v2). Every page someone, or an agent, writes or changes there is a draft:
+-- the Library lists them, the editor opens one.
+--
+-- * method: create (a new page) or optimize (an existing page).
+-- * status: draft → in_review (an agent's draft waiting for a person) →
+-- ready (Mark ready) → published (the person gives the live URL).
+-- Ansvisor never publishes on its own.
+-- * page_type: a key from the web's page type list (feature_page,
+-- product_page, destination_page…). Not an enum: a new page type must not
+-- take a migration.
+-- * author: who wrote it, a person or the Content Agent. created_by is the
+-- person who started it (null for an agent's draft).
+-- * score_before / score_after: the page's AEO score before and after the
+-- changes, once scoring runs (null until then).
+--
+-- Any member of the brand's organization reads and writes drafts, as with
+-- reports and site audits: writing content is the team's daily work, not a
+-- setting. No delete policy: nothing in the app deletes a draft yet.
+
+create table if not exists public.content_drafts (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ title text not null default '' check (char_length(title) <= 300),
+ page_type text check (page_type ~ '^[a-z_]{1,40}$'),
+ method text not null default 'create' check (method in ('create', 'optimize')),
+ status text not null default 'draft'
+ check (status in ('draft', 'in_review', 'ready', 'published')),
+ body_html text not null default '',
+ author text not null default 'user' check (author in ('user', 'agent')),
+ created_by uuid references public.profiles(id) on delete set null,
+ score_before smallint check (score_before between 0 and 100),
+ score_after smallint check (score_after between 0 and 100),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+comment on table public.content_drafts is
+ 'Content Editor (CE-002): pages written or changed in Ansvisor by a person or the Content Agent. The Content Library lists them.';
+
+create index if not exists content_drafts_brand_updated_idx
+ on public.content_drafts (brand_id, updated_at desc);
+
+create or replace trigger content_drafts_updated_at
+ before update on public.content_drafts
+ for each row execute function public.handle_updated_at();
+
+-- Who wrote a draft, its brand and its scores are the server's to set (the
+-- Content Agent, scoring), as with guard_organization_server_columns (00062):
+-- a member can't pass their draft off as the agent's, or score it.
+create or replace function public.guard_content_draft_server_columns()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ -- A role that bypasses RLS is server-side (service role, migrations).
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then
+ return new;
+ end if;
+
+ if tg_op = 'INSERT' then
+ if new.score_before is not null or new.score_after is not null then
+ raise exception 'content draft scores are set server-side'
+ using errcode = '42501';
+ end if;
+ elsif new.brand_id is distinct from old.brand_id
+ or new.author is distinct from old.author
+ or new.created_by is distinct from old.created_by
+ or new.created_at is distinct from old.created_at
+ or new.score_before is distinct from old.score_before
+ or new.score_after is distinct from old.score_after
+ then
+ raise exception 'content draft column is managed server-side'
+ using errcode = '42501';
+ end if;
+ return new;
+end;
+$$;
+
+create or replace trigger content_drafts_guard_server_columns
+ before insert or update on public.content_drafts
+ for each row execute function public.guard_content_draft_server_columns();
+
+alter table public.content_drafts enable row level security;
+
+create policy "content_drafts: member select"
+ on public.content_drafts
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+-- A person's own draft: the app writes created_by = the signed-in user, and
+-- an agent's draft comes through the service role, which RLS doesn't apply to.
+create policy "content_drafts: member insert"
+ on public.content_drafts
+ for insert
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ and author = 'user'
+ and created_by = auth.uid()
+ );
+
+-- The row being changed and the row it becomes both stay in the member's
+-- organization, so an update can't move a draft to another brand's.
+create policy "content_drafts: member update"
+ on public.content_drafts
+ for update
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ )
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 24bacb0b4..d59ac0150 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -28649,3 +28649,145 @@ comment on function public.citation_competitor_sources_daily(
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00204_content_drafts.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00204: content drafts, the Content Library's rows (Content Editor, CE-002)
+-- ============================================================================
+-- The Content area writes and improves pages in Ansvisor (Content Editor spec
+-- v2). Every page someone, or an agent, writes or changes there is a draft:
+-- the Library lists them, the editor opens one.
+--
+-- * method: create (a new page) or optimize (an existing page).
+-- * status: draft → in_review (an agent's draft waiting for a person) →
+-- ready (Mark ready) → published (the person gives the live URL).
+-- Ansvisor never publishes on its own.
+-- * page_type: a key from the web's page type list (feature_page,
+-- product_page, destination_page…). Not an enum: a new page type must not
+-- take a migration.
+-- * author: who wrote it, a person or the Content Agent. created_by is the
+-- person who started it (null for an agent's draft).
+-- * score_before / score_after: the page's AEO score before and after the
+-- changes, once scoring runs (null until then).
+--
+-- Any member of the brand's organization reads and writes drafts, as with
+-- reports and site audits: writing content is the team's daily work, not a
+-- setting. No delete policy: nothing in the app deletes a draft yet.
+
+create table if not exists public.content_drafts (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ title text not null default '' check (char_length(title) <= 300),
+ page_type text check (page_type ~ '^[a-z_]{1,40}$'),
+ method text not null default 'create' check (method in ('create', 'optimize')),
+ status text not null default 'draft'
+ check (status in ('draft', 'in_review', 'ready', 'published')),
+ body_html text not null default '',
+ author text not null default 'user' check (author in ('user', 'agent')),
+ created_by uuid references public.profiles(id) on delete set null,
+ score_before smallint check (score_before between 0 and 100),
+ score_after smallint check (score_after between 0 and 100),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+comment on table public.content_drafts is
+ 'Content Editor (CE-002): pages written or changed in Ansvisor by a person or the Content Agent. The Content Library lists them.';
+
+create index if not exists content_drafts_brand_updated_idx
+ on public.content_drafts (brand_id, updated_at desc);
+
+create or replace trigger content_drafts_updated_at
+ before update on public.content_drafts
+ for each row execute function public.handle_updated_at();
+
+-- Who wrote a draft, its brand and its scores are the server's to set (the
+-- Content Agent, scoring), as with guard_organization_server_columns (00062):
+-- a member can't pass their draft off as the agent's, or score it.
+create or replace function public.guard_content_draft_server_columns()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ -- A role that bypasses RLS is server-side (service role, migrations).
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then
+ return new;
+ end if;
+
+ if tg_op = 'INSERT' then
+ if new.score_before is not null or new.score_after is not null then
+ raise exception 'content draft scores are set server-side'
+ using errcode = '42501';
+ end if;
+ elsif new.brand_id is distinct from old.brand_id
+ or new.author is distinct from old.author
+ or new.created_by is distinct from old.created_by
+ or new.created_at is distinct from old.created_at
+ or new.score_before is distinct from old.score_before
+ or new.score_after is distinct from old.score_after
+ then
+ raise exception 'content draft column is managed server-side'
+ using errcode = '42501';
+ end if;
+ return new;
+end;
+$$;
+
+create or replace trigger content_drafts_guard_server_columns
+ before insert or update on public.content_drafts
+ for each row execute function public.guard_content_draft_server_columns();
+
+alter table public.content_drafts enable row level security;
+
+create policy "content_drafts: member select"
+ on public.content_drafts
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+-- A person's own draft: the app writes created_by = the signed-in user, and
+-- an agent's draft comes through the service role, which RLS doesn't apply to.
+create policy "content_drafts: member insert"
+ on public.content_drafts
+ for insert
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ and author = 'user'
+ and created_by = auth.uid()
+ );
+
+-- The row being changed and the row it becomes both stay in the member's
+-- organization, so an update can't move a draft to another brand's.
+create policy "content_drafts: member update"
+ on public.content_drafts
+ for update
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ )
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 801899285..acbf59e52 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -72,6 +72,8 @@
"topics": "Topics",
"queryFanouts": "Query Fan-outs",
"promptsInsights": "Insights",
+ "contentOpportunities": "Opportunities",
+ "contentLibrary": "Library",
"toggleSubmenu": "Show or hide {label}"
},
"actionCenter": {
@@ -3063,6 +3065,74 @@
"appearedIn": "Appeared in {visible} of {active, plural, one {# prompt} other {# prompts}}",
"openDetails": "Open topic details"
},
+ "contentEditor": {
+ "library": {
+ "title": "Library",
+ "description": "Everything you and the agents wrote or changed.",
+ "selectBrand": "Select a brand to see its content.",
+ "tabsLabel": "Library sections",
+ "tabs": {
+ "all": "All",
+ "draft": "Drafts",
+ "in_review": "In review",
+ "ready": "Ready",
+ "published": "Published"
+ },
+ "columns": {
+ "content": "Content",
+ "type": "Type",
+ "method": "Method",
+ "by": "By",
+ "status": "Status",
+ "score": "AEO score"
+ },
+ "scoreHint": "The page's AEO score, before → after the changes",
+ "untitled": "Untitled",
+ "you": "You",
+ "contentAgent": "Content Agent",
+ "formerMember": "Former member",
+ "empty": {
+ "title": "Nothing written yet",
+ "body": "Pages you and the Content Agent write or change in Ansvisor show up here."
+ },
+ "emptyTab": {
+ "draft": "No drafts.",
+ "in_review": "Nothing waiting for review.",
+ "ready": "Nothing marked ready.",
+ "published": "Nothing published yet."
+ },
+ "loadError": "Couldn't load the Library.",
+ "retry": "Try again"
+ },
+ "status": {
+ "draft": "Draft",
+ "in_review": "In review",
+ "ready": "Ready",
+ "published": "Published"
+ },
+ "method": {
+ "create": "Create",
+ "optimize": "Optimize"
+ },
+ "pageTypes": {
+ "feature_page": "Feature page",
+ "solution_page": "Solution page",
+ "comparison": "Comparison",
+ "integration": "Integration",
+ "pricing": "Pricing",
+ "guide": "Guide",
+ "blog_post": "Blog post",
+ "docs_faq": "Docs / FAQ",
+ "product_page": "Product page",
+ "category_page": "Category page",
+ "buying_guide": "Buying guide",
+ "best_of": "Best-of list",
+ "policy": "Policy",
+ "destination_page": "Destination page",
+ "itinerary": "Itinerary",
+ "help_faq": "Help & FAQ"
+ }
+ },
"content": {
"title": "Content Opportunities",
"description": "AI-powered content recommendations to improve your visibility in AI-generated answers.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx
new file mode 100644
index 000000000..7b1a09a09
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx
@@ -0,0 +1,132 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { Bot, FileText } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import { Badge } from '@/components/ui/badge';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';
+import { assigneeLabel, labelInitials } from '@/lib/action-center/display';
+import {
+ aeoScoreText,
+ contentEditorPath,
+ isPageType,
+ type ContentDraftListItem,
+ type LibraryTab,
+} from '@/lib/content/drafts';
+
+/**
+ * The Library's list (CE-002): one row per draft, the latest changed first.
+ * Columns as the spec's: Content · Type · Method (Create / Optimize) · By
+ * (a person or the Content Agent) · Status · AEO score (before → after).
+ * A row opens the draft in the editor.
+ */
+export function LibraryTable({ drafts, tab }: { drafts: ContentDraftListItem[]; tab: LibraryTab }) {
+ const t = useTranslations('contentEditor.library');
+ const tTypes = useTranslations('contentEditor.pageTypes');
+
+ if (drafts.length === 0) {
+ return tab === 'all' ? (
+ <div className="flex flex-col items-center gap-2 px-6 py-12 text-center">
+ <FileText className="h-8 w-8 text-muted-foreground/50" aria-hidden="true" />
+ <p className="text-sm font-medium">{t('empty.title')}</p>
+ <p className="max-w-sm text-sm text-muted-foreground">{t('empty.body')}</p>
+ </div>
+ ) : (
+ <p className="px-6 py-12 text-center text-sm text-muted-foreground">{t(`emptyTab.${tab}`)}</p>
+ );
+ }
+
+ return (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="pl-6">{t('columns.content')}</TableHead>
+ <TableHead>{t('columns.type')}</TableHead>
+ <TableHead>{t('columns.method')}</TableHead>
+ <TableHead>{t('columns.by')}</TableHead>
+ <TableHead>{t('columns.status')}</TableHead>
+ <TableHead className="pr-6 text-right" title={t('scoreHint')}>
+ {t('columns.score')}
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {drafts.map((draft) => {
+ const score = aeoScoreText(draft.scoreBefore, draft.scoreAfter);
+ return (
+ <TableRow key={draft.id}>
+ <TableCell className="max-w-[320px] pl-6">
+ <Link
+ href={contentEditorPath(draft.id)}
+ className="block truncate font-medium hover:underline"
+ >
+ {draft.title.trim() || t('untitled')}
+ </Link>
+ </TableCell>
+ <TableCell>
+ {isPageType(draft.pageType) ? (
+ <Badge variant="outline" className="font-normal">
+ {tTypes(draft.pageType)}
+ </Badge>
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </TableCell>
+ <TableCell>
+ <DraftMethodBadge method={draft.method} />
+ </TableCell>
+ <TableCell>
+ <DraftAuthorCell draft={draft} />
+ </TableCell>
+ <TableCell>
+ <DraftStatusBadge status={draft.status} />
+ </TableCell>
+ <TableCell className="pr-6 text-right tabular-nums">
+ {score ?? <span className="text-muted-foreground">—</span>}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ );
+}
+
+/** Who wrote it: the Content Agent, "You", or the member by name. */
+function DraftAuthorCell({ draft }: { draft: ContentDraftListItem }) {
+ const t = useTranslations('contentEditor.library');
+ if (draft.author === 'agent') {
+ return (
+ <span className="flex items-center gap-1.5 whitespace-nowrap text-xs text-muted-foreground">
+ <span className="flex h-5 w-5 items-center justify-center rounded-md bg-muted">
+ <Bot className="h-3.5 w-3.5" aria-hidden="true" />
+ </span>
+ {t('contentAgent')}
+ </span>
+ );
+ }
+ const label = draft.isMine
+ ? t('you')
+ : ((draft.createdBy && assigneeLabel(draft.createdBy)) ?? t('formerMember'));
+ const named = draft.createdBy && assigneeLabel(draft.createdBy);
+ return (
+ <span className="flex items-center gap-1.5 whitespace-nowrap text-xs text-muted-foreground">
+ <Avatar className="h-5 w-5">
+ {draft.createdBy?.avatarUrl && <AvatarImage src={draft.createdBy.avatarUrl} alt="" />}
+ <AvatarFallback className="text-[9px]">
+ {(named && labelInitials(named)) || '?'}
+ </AvatarFallback>
+ </Avatar>
+ {label}
+ </span>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
new file mode 100644
index 000000000..b90927a0f
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
@@ -0,0 +1,194 @@
+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 { ContentDraftListItem } from '@/lib/content/drafts';
+import ContentLibraryPage from './page';
+
+const getContentDrafts = vi.fn();
+vi.mock('@/lib/actions/content-drafts', () => ({
+ getContentDrafts: (...args: unknown[]) => getContentDrafts(...args),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+const brandState = vi.hoisted(() => ({ activeBrandId: 'brand-1' as string | null }));
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),
+}));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const row = (over: Partial<ContentDraftListItem>): ContentDraftListItem => ({
+ id: 'd1',
+ title: 'Pipeline forecasting',
+ pageType: 'feature_page',
+ method: 'optimize',
+ status: 'in_review',
+ author: 'user',
+ createdBy: { id: 'u1', fullName: 'Ada Lovelace', avatarUrl: null },
+ isMine: true,
+ scoreBefore: 62,
+ scoreAfter: 78,
+ updatedAt: '2026-10-20T10:00:00Z',
+ ...over,
+});
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function renderPage() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <ContentLibraryPage />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const tab = (name: string) =>
+ [...container.querySelectorAll<HTMLElement>('[role="tab"]')].find((el) =>
+ el.textContent?.startsWith(name),
+ )!;
+
+beforeEach(() => {
+ brandState.activeBrandId = 'brand-1';
+ window.history.replaceState(null, '', '/dashboard/content/library');
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ getContentDrafts.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('the Content Library', () => {
+ it('lists the brand’s drafts with who wrote them, and counts each tab', async () => {
+ getContentDrafts.mockResolvedValue([
+ row({}),
+ row({
+ id: 'd2',
+ title: 'Northwind vs HubSpot',
+ pageType: 'comparison',
+ method: 'create',
+ author: 'agent',
+ createdBy: null,
+ isMine: false,
+ scoreBefore: null,
+ scoreAfter: null,
+ }),
+ row({
+ id: 'd3',
+ title: '',
+ status: 'published',
+ isMine: false,
+ createdBy: { id: 'u2', fullName: null, avatarUrl: null, email: '[email protected]' },
+ scoreBefore: 81,
+ scoreAfter: null,
+ }),
+ ]);
+ await renderPage();
+
+ expect(getContentDrafts).toHaveBeenCalledWith('brand-1');
+ expect(tab('All').textContent).toBe('All3');
+ expect(tab('In review').textContent).toBe('In review2');
+ expect(tab('Ready').textContent).toBe('Ready0');
+
+ const rows = [...container.querySelectorAll('tbody tr')].map((tr) =>
+ [...tr.querySelectorAll('td')].map((td) => td.textContent),
+ );
+ expect(rows[0]).toEqual([
+ 'Pipeline forecasting',
+ 'Feature page',
+ 'Optimize',
+ 'AL' + 'You',
+ 'In review',
+ '62 → 78',
+ ]);
+ expect(rows[1]).toEqual([
+ 'Northwind vs HubSpot',
+ 'Comparison',
+ 'Create',
+ 'Content Agent',
+ 'In review',
+ '—',
+ ]);
+ // No title yet; a teammate with no name is named by e-mail.
+ expect(rows[2][0]).toBe('Untitled');
+ expect(rows[2][3]).toBe('[email protected]');
+ expect(rows[2][5]).toBe('81');
+
+ const link = container.querySelector('tbody a')!;
+ expect(link.getAttribute('href')).toBe('/dashboard/content/editor/d1');
+ });
+
+ it('shows a tab’s drafts only, and keeps the tab in the URL', async () => {
+ getContentDrafts.mockResolvedValue([row({}), row({ id: 'd2', status: 'published' })]);
+ await renderPage();
+
+ await act(async () => {
+ tab('Published').click();
+ });
+ expect(container.querySelectorAll('tbody tr')).toHaveLength(1);
+ expect(window.location.search).toBe('?tab=published');
+
+ await act(async () => {
+ tab('Ready').click();
+ });
+ expect(container.textContent).toContain('Nothing marked ready.');
+ });
+
+ it('opens the tab the URL names', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?tab=in_review');
+ getContentDrafts.mockResolvedValue([row({}), row({ id: 'd2', status: 'draft' })]);
+ await renderPage();
+ expect(tab('In review').getAttribute('aria-selected')).toBe('true');
+ expect(container.querySelectorAll('tbody tr')).toHaveLength(1);
+ });
+
+ it('says what the Library is for while it is empty', async () => {
+ getContentDrafts.mockResolvedValue([]);
+ await renderPage();
+ expect(container.textContent).toContain('Nothing written yet');
+ expect(container.textContent).toContain(
+ 'Pages you and the Content Agent write or change in Ansvisor show up here.',
+ );
+ });
+
+ it('offers a retry when the read fails', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ getContentDrafts.mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce([row({})]);
+ await renderPage();
+ expect(container.textContent).toContain("Couldn't load the Library.");
+
+ const retry = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Try again',
+ )!;
+ await act(async () => {
+ retry.click();
+ });
+ expect(getContentDrafts).toHaveBeenCalledTimes(2);
+ expect(container.querySelectorAll('tbody tr')).toHaveLength(1);
+ error.mockRestore();
+ });
+
+ it('asks for a brand when none is selected', async () => {
+ brandState.activeBrandId = null;
+ await renderPage();
+ expect(getContentDrafts).not.toHaveBeenCalled();
+ expect(container.textContent).toContain('Select a brand to see its content.');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
new file mode 100644
index 000000000..930ce1612
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Loader2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent } from '@/components/ui/card';
+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { getContentDrafts } from '@/lib/actions/content-drafts';
+import {
+ LIBRARY_TABS,
+ draftsInTab,
+ libraryTabCounts,
+ type ContentDraftListItem,
+ type LibraryTab,
+} from '@/lib/content/drafts';
+import { formatNumber } from '@/lib/format';
+import { readUrlChoice, writeUrlParams } from '@/lib/url-state';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { LibraryTable } from './_library-table';
+
+/** A read of the brand's drafts: null until it comes back. */
+interface LibraryRead {
+ brandId: string;
+ drafts: ContentDraftListItem[] | null;
+ failed: boolean;
+}
+
+/**
+ * The Content Library (Content Editor, CE-002): everything a person or the
+ * Content Agent wrote or changed in Ansvisor, by status. The tab lives in the
+ * URL (?tab=in_review), so a link can open "Library › In review".
+ */
+export default function ContentLibraryPage() {
+ const t = useTranslations('contentEditor.library');
+ const activeBrandId = useBrandStore((s) => s.activeBrandId);
+ const [tab, setTab] = useState<LibraryTab>('all');
+ const [read, setRead] = useState<LibraryRead | null>(null);
+ const [attempt, setAttempt] = useState(0);
+
+ useEffect(() => {
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount
+ setTab(readUrlChoice('tab', LIBRARY_TABS, 'all'));
+ }, []);
+
+ useEffect(() => {
+ if (!activeBrandId) return;
+ let cancelled = false;
+ getContentDrafts(activeBrandId)
+ .then((drafts) => {
+ if (!cancelled) setRead({ brandId: activeBrandId, drafts, failed: false });
+ })
+ .catch((err) => {
+ console.error('Failed to load the content library:', err);
+ if (!cancelled) setRead({ brandId: activeBrandId, drafts: null, failed: true });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [activeBrandId, attempt]);
+
+ const changeTab = (next: LibraryTab) => {
+ setTab(next);
+ writeUrlParams({ tab: next }, { tab: 'all' });
+ };
+
+ if (!activeBrandId) {
+ return (
+ <div className="flex min-h-[400px] items-center justify-center">
+ <p className="text-muted-foreground">{t('selectBrand')}</p>
+ </div>
+ );
+ }
+
+ // A read for another brand (just switched) counts as still loading.
+ const current = read?.brandId === activeBrandId ? read : null;
+ const drafts = current?.drafts ?? null;
+ const counts = drafts ? libraryTabCounts(drafts) : null;
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-sm text-muted-foreground">{t('description')}</p>
+ </div>
+
+ <Tabs value={tab} onValueChange={(v) => changeTab(v as LibraryTab)}>
+ <TabsList variant="line" aria-label={t('tabsLabel')}>
+ {LIBRARY_TABS.map((id) => (
+ <TabsTrigger key={id} value={id}>
+ {t(`tabs.${id}`)}
+ {counts && <TabCount count={counts[id]} />}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+
+ <Card className="py-0">
+ <CardContent className="px-0">
+ {current?.failed ? (
+ <div className="flex flex-col items-center gap-3 px-6 py-12 text-center">
+ <p className="text-sm text-muted-foreground">{t('loadError')}</p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ setRead(null);
+ setAttempt((n) => n + 1);
+ }}
+ >
+ {t('retry')}
+ </Button>
+ </div>
+ ) : drafts === null ? (
+ <div className="flex items-center justify-center py-12" aria-busy="true">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
+ </div>
+ ) : (
+ <LibraryTable drafts={draftsInTab(drafts, tab)} tab={tab} />
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
+
+function TabCount({ count }: { count: number }) {
+ return (
+ <span className="rounded-full bg-muted px-1.5 text-[11px] font-medium tabular-nums text-muted-foreground">
+ {formatNumber(count)}
+ </span>
+ );
+}
diff --git a/web/src/components/content/draft-badges.tsx b/web/src/components/content/draft-badges.tsx
new file mode 100644
index 000000000..4a40f5bd9
--- /dev/null
+++ b/web/src/components/content/draft-badges.tsx
@@ -0,0 +1,49 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { Badge } from '@/components/ui/badge';
+import { cn } from '@/lib/utils';
+import type { DraftMethod, DraftStatus } from '@/lib/content/drafts';
+
+/**
+ * A draft's status and method, as the Library and the editor show them
+ * (Content Editor spec: Draft grey, In review amber, Ready green, Published
+ * blue; Create blue, Optimize amber). Colors as Action Center's badges.
+ */
+
+export const DRAFT_STATUS_BADGE: Record<DraftStatus, string> = {
+ draft: 'border-border bg-muted/50 text-muted-foreground',
+ in_review: 'border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-400',
+ ready: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',
+ published: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',
+};
+
+export const DRAFT_METHOD_BADGE: Record<DraftMethod, string> = {
+ create: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',
+ optimize: 'border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-400',
+};
+
+export function DraftStatusBadge({ status }: { status: DraftStatus }) {
+ const t = useTranslations('contentEditor.status');
+ return (
+ <Badge variant="outline" className={DRAFT_STATUS_BADGE[status]}>
+ <span aria-hidden="true" className="h-1.5 w-1.5 rounded-full bg-current opacity-70" />
+ {t(status)}
+ </Badge>
+ );
+}
+
+export function DraftMethodBadge({
+ method,
+ className,
+}: {
+ method: DraftMethod;
+ className?: string;
+}) {
+ const t = useTranslations('contentEditor.method');
+ return (
+ <Badge variant="outline" className={cn(DRAFT_METHOD_BADGE[method], className)}>
+ {t(method)}
+ </Badge>
+ );
+}
diff --git a/web/src/components/layout/mobile-nav.tsx b/web/src/components/layout/mobile-nav.tsx
index 01a70d769..1283d18c8 100644
--- a/web/src/components/layout/mobile-nav.tsx
+++ b/web/src/components/layout/mobile-nav.tsx
@@ -4,7 +4,11 @@ import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { usePathname, Link } from '@/i18n/navigation';
import { dashboardNav } from '@/config/dashboard';
-import { getDashboardNavLabel, shouldShowDashboardNavItem } from '@/lib/dashboard-navigation';
+import {
+ activeChildHref,
+ getDashboardNavLabel,
+ shouldShowDashboardNavItem,
+} from '@/lib/dashboard-navigation';
import { useFeatureGate } from '@/hooks/use-feature-gate';
import { useAgentKeyStatus } from '@/hooks/use-agent-key-status';
import { siteConfig } from '@/config/site';
@@ -151,7 +155,8 @@ export function MobileNav() {
</Link>
);
if (!item.children?.length) return link;
- // The Prompts submenu (PROMPT-001), always shown on mobile.
+ // A submenu (Prompts, Content), always shown on mobile.
+ const currentChild = activeChildHref(item.children, pathname);
return (
<div key={item.href}>
{link}
@@ -161,7 +166,7 @@ export function MobileNav() {
<span
className={cn(
'block rounded-md px-3 py-1.5 text-sm transition-colors',
- pathname === child.href || pathname.startsWith(`${child.href}/`)
+ child.href === currentChild
? 'font-medium text-primary'
: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
)}
diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsx
index 99777fbb3..7e262f3e8 100644
--- a/web/src/components/layout/sidebar.tsx
+++ b/web/src/components/layout/sidebar.tsx
@@ -10,6 +10,7 @@ import { getTrackedPromptCount } from '@/lib/actions/prompt';
import { carriedParams, PROMPTS_BASE } from '@/lib/prompts-routes';
import { dashboardNav } from '@/config/dashboard';
import {
+ activeChildHref,
getDashboardNavLabel,
getDashboardNavGroupLabel,
shouldShowDashboardNavItem,
@@ -60,8 +61,19 @@ const NAV_VIEWPORT =
const NAV_SCROLLBAR =
'data-vertical:w-2 opacity-0 transition-opacity duration-300 data-hovering:opacity-100 data-scrolling:opacity-100 data-scrolling:duration-75 [&>[data-slot=scroll-area-thumb]]:bg-muted-foreground/25 [&>[data-slot=scroll-area-thumb]:hover]:bg-muted-foreground/45';
-/** Where the Prompts submenu's open/closed state is remembered (PROMPT-001). */
-const SUBMENU_KEY = 'ansvisor.sidebar.promptsOpen';
+/** The items that open a submenu (Prompts, Content). */
+const EXPANDABLE_HREFS = dashboardNav.flatMap((group) =>
+ group.items.filter((item) => item.children?.length).map((item) => item.href),
+);
+
+/**
+ * Where a submenu's open/closed state is remembered, per item: Prompts keeps
+ * its key from PROMPT-001 (ansvisor.sidebar.promptsOpen), Content gets
+ * ansvisor.sidebar.contentOpen.
+ */
+function submenuKey(href: string) {
+ return `ansvisor.sidebar.${href.split('/').pop()}Open`;
+}
/**
* Arrow keys in the sidebar's links (PROMPT-001): up and down move between
@@ -70,7 +82,7 @@ const SUBMENU_KEY = 'ansvisor.sidebar.promptsOpen';
*/
function handleNavKeys(
e: React.KeyboardEvent<HTMLElement>,
- setSubmenuOpen: (open: boolean) => void,
+ setSubmenuOpen: (href: string, open: boolean) => void,
) {
const items = [...e.currentTarget.querySelectorAll<HTMLElement>('[data-nav-item]')];
const current = document.activeElement as HTMLElement | null;
@@ -83,15 +95,16 @@ function handleNavKeys(
};
const isParent = current?.dataset.navItem === 'parent';
const isChild = current?.dataset.navItem === 'child';
+ const submenu = current?.dataset.submenu ?? '';
if (e.key === 'ArrowDown') focus(items[i + 1]);
else if (e.key === 'ArrowUp') focus(items[i - 1]);
else if (e.key === 'ArrowRight' && isParent) {
e.preventDefault();
if (current?.getAttribute('aria-expanded') === 'true') focus(items[i + 1]);
- else setSubmenuOpen(true);
+ else setSubmenuOpen(submenu, true);
} else if (e.key === 'ArrowLeft' && isParent) {
e.preventDefault();
- setSubmenuOpen(false);
+ setSubmenuOpen(submenu, false);
} else if (e.key === 'ArrowLeft' && isChild) {
focus(
items
@@ -114,9 +127,12 @@ export function Sidebar() {
const compact = isCollapsed && !peeking && !menuOpen;
const searchParams = useSearchParams();
const underPrompts = pathname.startsWith(PROMPTS_BASE);
- // The Prompts submenu: remembered per browser, and open whenever a Prompts
- // route is showing so the current view is always visible in it.
- const [submenuOpen, setSubmenuOpenState] = useState(true);
+ // Each submenu (Prompts, Content): remembered per browser, open until closed,
+ // and open whenever one of its routes is showing so the current view is
+ // always visible in it.
+ const [openMenus, setOpenMenus] = useState<Record<string, boolean>>({});
+ const isSubmenuOpen = (href: string) => openMenus[href] ?? true;
+ const underMenu = EXPANDABLE_HREFS.find((href) => pathname.startsWith(href)) ?? null;
const [trackedCount, setTrackedCount] = useState<number | null>(null);
const activeBrandId = useBrandStore((s) => s.activeBrandId);
const t = useTranslations('nav');
@@ -166,20 +182,23 @@ export function Sidebar() {
};
useEffect(() => {
- let stored: string | null = null;
- try {
- stored = localStorage.getItem(SUBMENU_KEY);
- } catch {
- // Storage can be unavailable (private mode); the default stands.
+ const stored: Record<string, boolean> = {};
+ for (const href of EXPANDABLE_HREFS) {
+ try {
+ const value = localStorage.getItem(submenuKey(href));
+ if (value !== null) stored[href] = value === '1';
+ } catch {
+ // Storage can be unavailable (private mode); the default stands.
+ }
}
// eslint-disable-next-line react-hooks/set-state-in-effect
- if (stored !== null) setSubmenuOpenState(stored === '1');
+ setOpenMenus((prev) => ({ ...stored, ...prev }));
}, []);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
- if (underPrompts) setSubmenuOpenState(true);
- }, [underPrompts]);
+ if (underMenu) setOpenMenus((prev) => ({ ...prev, [underMenu]: true }));
+ }, [underMenu]);
// The count beside Tracked Prompts, refreshed on brand switch and on every
// page change so adding or deleting prompts shows up.
@@ -194,10 +213,10 @@ export function Sidebar() {
};
}, [activeBrandId, pathname]);
- const setSubmenuOpen = (open: boolean) => {
- setSubmenuOpenState(open);
+ const setSubmenuOpen = (href: string, open: boolean) => {
+ setOpenMenus((prev) => ({ ...prev, [href]: open }));
try {
- localStorage.setItem(SUBMENU_KEY, open ? '1' : '0');
+ localStorage.setItem(submenuKey(href), open ? '1' : '0');
} catch {
// Not remembered this time; nothing else depends on it.
}
@@ -383,16 +402,22 @@ export function Sidebar() {
if (item.children?.length && !compact) {
// Expandable item (PROMPT-001): the row toggles the
// submenu, whose links are the item's views.
- const carry = underPrompts ? carriedParams(searchParams.toString()) : '';
+ const carry =
+ underPrompts && item.href === PROMPTS_BASE
+ ? carriedParams(searchParams.toString())
+ : '';
const submenuId = `submenu-${item.href.replace(/\W+/g, '-')}`;
+ const submenuOpen = isSubmenuOpen(item.href);
+ const currentChild = activeChildHref(item.children, pathname);
return (
<div key={item.href}>
<button
type="button"
data-nav-item="parent"
+ data-submenu={item.href}
aria-expanded={submenuOpen}
aria-controls={submenuId}
- onClick={() => setSubmenuOpen(!submenuOpen)}
+ onClick={() => setSubmenuOpen(item.href, !submenuOpen)}
className={cn(
'flex w-full items-center gap-3 rounded-md px-2 py-1.5 text-left text-[13px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',
isActive
@@ -412,10 +437,7 @@ export function Sidebar() {
{submenuOpen && (
<ul id={submenuId} className="mt-0.5 ml-[18px] space-y-0.5 border-l pl-2">
{item.children.map((child) => {
- // A view's own pages count too: a topic's page
- // sits under Topics.
- const childActive =
- pathname === child.href || pathname.startsWith(`${child.href}/`);
+ const childActive = child.href === currentChild;
return (
<li key={child.href}>
<Link
diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.ts
index 8199c77b8..360c5a78b 100644
--- a/web/src/config/dashboard.ts
+++ b/web/src/config/dashboard.ts
@@ -81,11 +81,18 @@ export const dashboardNav: NavGroup[] = [
icon: Sparkles,
requiredFeature: 'ai_agent',
},
+ // Content Editor (CE-001): a group, like Prompts. Opportunities is
+ // today's page and keeps /dashboard/content; the Library lists every
+ // page written or changed in Ansvisor.
{
- title: 'Content Optimization',
+ title: 'Content',
href: '/dashboard/content',
icon: FileText,
requiredFeature: 'content_optimization',
+ children: [
+ { title: 'Opportunities', href: '/dashboard/content' },
+ { title: 'Library', href: '/dashboard/content/library' },
+ ],
},
{
title: 'Site Audit',
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
new file mode 100644
index 000000000..5de8a83eb
--- /dev/null
+++ b/web/src/lib/actions/content-drafts.ts
@@ -0,0 +1,61 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+import { readAssignees } from '@/lib/action-center/assignees';
+import {
+ DRAFT_STATUSES,
+ type ContentDraftListItem,
+ type DraftMethod,
+ type DraftStatus,
+} from '@/lib/content/drafts';
+
+/**
+ * Content drafts (Content Editor, CE-002), read through the signed-in member's
+ * session: RLS (00204) keeps them to the brand's organization.
+ */
+
+/** How many drafts the Library lists, the latest changed first. */
+const LIBRARY_LIMIT = 500;
+
+/** The brand's drafts for the Library, with who started each. */
+export async function getContentDrafts(brandId: string): Promise<ContentDraftListItem[]> {
+ const supabase = await createClient();
+ const [userRes, draftsRes] = await Promise.all([
+ supabase.auth.getUser(),
+ supabase
+ .from('content_drafts')
+ .select(
+ 'id, title, page_type, method, status, author, created_by, score_before, score_after, updated_at',
+ )
+ .eq('brand_id', brandId)
+ .order('updated_at', { ascending: false })
+ .limit(LIBRARY_LIMIT),
+ ]);
+ if (draftsRes.error) throw new Error(draftsRes.error.message);
+ const rows = draftsRes.data ?? [];
+ const me = userRes.data.user?.id ?? null;
+
+ // A profile is readable only by its owner, so other members are named
+ // through the same reader as Action Center's assignees.
+ const people = await readAssignees(
+ supabase,
+ brandId,
+ rows.flatMap((row) => (row.created_by ? [row.created_by] : [])),
+ );
+
+ return rows.map((row) => ({
+ id: row.id,
+ title: row.title,
+ pageType: row.page_type,
+ method: row.method as DraftMethod,
+ status: (DRAFT_STATUSES as readonly string[]).includes(row.status)
+ ? (row.status as DraftStatus)
+ : 'draft',
+ author: row.author === 'agent' ? 'agent' : 'user',
+ createdBy: row.created_by ? (people.get(row.created_by) ?? null) : null,
+ isMine: me !== null && row.created_by === me,
+ scoreBefore: row.score_before,
+ scoreAfter: row.score_after,
+ updatedAt: row.updated_at,
+ }));
+}
diff --git a/web/src/lib/content/drafts.test.ts b/web/src/lib/content/drafts.test.ts
new file mode 100644
index 000000000..0b8be2f22
--- /dev/null
+++ b/web/src/lib/content/drafts.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest';
+import messages from '../../../messages/en.json';
+import {
+ DRAFT_STATUSES,
+ PAGE_TYPES,
+ aeoScoreText,
+ contentEditorPath,
+ draftsInTab,
+ isPageType,
+ libraryTabCounts,
+ type ContentDraftListItem,
+ type DraftStatus,
+} from './drafts';
+
+const draft = (id: string, status: DraftStatus): ContentDraftListItem => ({
+ id,
+ title: id,
+ pageType: 'feature_page',
+ method: 'create',
+ status,
+ author: 'user',
+ createdBy: null,
+ isMine: true,
+ scoreBefore: null,
+ scoreAfter: null,
+ updatedAt: '2026-10-20T10:00:00Z',
+});
+
+const drafts = [
+ draft('a', 'draft'),
+ draft('b', 'in_review'),
+ draft('c', 'in_review'),
+ draft('d', 'published'),
+];
+
+describe('the Library tabs', () => {
+ it('counts every draft under All and each under its status', () => {
+ expect(libraryTabCounts(drafts)).toEqual({
+ all: 4,
+ draft: 1,
+ in_review: 2,
+ ready: 0,
+ published: 1,
+ });
+ });
+
+ it('lists a tab’s drafts in their order, and every draft under All', () => {
+ expect(draftsInTab(drafts, 'in_review').map((d) => d.id)).toEqual(['b', 'c']);
+ expect(draftsInTab(drafts, 'ready')).toEqual([]);
+ expect(draftsInTab(drafts, 'all')).toBe(drafts);
+ });
+});
+
+describe('aeoScoreText', () => {
+ it('shows before → after once the changes are scored', () => {
+ expect(aeoScoreText(62, 78)).toBe('62 → 78');
+ });
+
+ it('shows the one score there is, or nothing', () => {
+ expect(aeoScoreText(54, null)).toBe('54');
+ expect(aeoScoreText(null, 81)).toBe('81');
+ expect(aeoScoreText(70, 70)).toBe('70');
+ expect(aeoScoreText(null, null)).toBeNull();
+ });
+});
+
+describe('page types and labels', () => {
+ it('names every page type, status and method', () => {
+ const editor = messages.contentEditor;
+ for (const type of PAGE_TYPES) expect(editor.pageTypes[type]).toBeTruthy();
+ for (const status of DRAFT_STATUSES) {
+ expect(editor.status[status]).toBeTruthy();
+ expect(editor.library.tabs[status]).toBeTruthy();
+ }
+ expect(editor.method.create).toBeTruthy();
+ expect(editor.method.optimize).toBeTruthy();
+ });
+
+ it('knows a stored key from anything else', () => {
+ expect(isPageType('product_page')).toBe(true);
+ expect(isPageType('landing')).toBe(false);
+ expect(isPageType(null)).toBe(false);
+ });
+
+ it('opens a draft in the editor', () => {
+ expect(contentEditorPath('d1')).toBe('/dashboard/content/editor/d1');
+ });
+});
diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.ts
new file mode 100644
index 000000000..72f351500
--- /dev/null
+++ b/web/src/lib/content/drafts.ts
@@ -0,0 +1,98 @@
+/**
+ * Content drafts (Content Editor, CE-002): the pages a person or the Content
+ * Agent writes or changes in Ansvisor, as the Library lists them. One row per
+ * content_drafts row (migration 00204).
+ */
+
+/** Draft → In review (an agent's draft waiting for a person) → Ready → Published. */
+export const DRAFT_STATUSES = ['draft', 'in_review', 'ready', 'published'] as const;
+export type DraftStatus = (typeof DRAFT_STATUSES)[number];
+
+/** A new page, or an existing one improved. */
+export type DraftMethod = 'create' | 'optimize';
+
+/**
+ * The page types a draft can be, across brand types (B2B, e-commerce, B2C).
+ * Stored as these keys (content_drafts.page_type); named in en.json under
+ * content.pageTypes.
+ */
+export const PAGE_TYPES = [
+ 'feature_page',
+ 'solution_page',
+ 'comparison',
+ 'integration',
+ 'pricing',
+ 'guide',
+ 'blog_post',
+ 'docs_faq',
+ 'product_page',
+ 'category_page',
+ 'buying_guide',
+ 'best_of',
+ 'policy',
+ 'destination_page',
+ 'itinerary',
+ 'help_faq',
+] as const;
+export type PageType = (typeof PAGE_TYPES)[number];
+
+export function isPageType(value: string | null): value is PageType {
+ return value !== null && (PAGE_TYPES as readonly string[]).includes(value);
+}
+
+/** The Library (CE-001 route). */
+export const CONTENT_LIBRARY_PATH = '/dashboard/content/library';
+
+/** Where a draft opens: the editor (CE-004). */
+export function contentEditorPath(draftId: string) {
+ return `/dashboard/content/editor/${draftId}`;
+}
+
+/** The Library's tabs: everything, then one per status. */
+export const LIBRARY_TABS = ['all', ...DRAFT_STATUSES] as const;
+export type LibraryTab = (typeof LIBRARY_TABS)[number];
+
+export interface DraftAuthor {
+ id: string;
+ fullName: string | null;
+ avatarUrl: string | null;
+ email?: string | null;
+}
+
+export interface ContentDraftListItem {
+ id: string;
+ title: string;
+ pageType: string | null;
+ method: DraftMethod;
+ status: DraftStatus;
+ /** A person or the Content Agent. */
+ author: 'user' | 'agent';
+ /** The person who started it: null for an agent's draft, or a member since removed. */
+ createdBy: DraftAuthor | null;
+ /** Whether the signed-in member started it ("You"). */
+ isMine: boolean;
+ scoreBefore: number | null;
+ scoreAfter: number | null;
+ updatedAt: string;
+}
+
+export function draftsInTab(drafts: ContentDraftListItem[], tab: LibraryTab) {
+ return tab === 'all' ? drafts : drafts.filter((d) => d.status === tab);
+}
+
+export function libraryTabCounts(drafts: ContentDraftListItem[]): Record<LibraryTab, number> {
+ const counts = Object.fromEntries(LIBRARY_TABS.map((tab) => [tab, 0])) as Record<
+ LibraryTab,
+ number
+ >;
+ counts.all = drafts.length;
+ for (const d of drafts) counts[d.status] += 1;
+ return counts;
+}
+
+/** "62 → 78" once the changes are scored, "54" before, null with no score yet. */
+export function aeoScoreText(before: number | null, after: number | null): string | null {
+ if (before !== null && after !== null && after !== before) return `${before} → ${after}`;
+ const score = after ?? before;
+ return score === null ? null : String(score);
+}
diff --git a/web/src/lib/dashboard-navigation.test.ts b/web/src/lib/dashboard-navigation.test.ts
index a1d8ac57d..6f8919061 100644
--- a/web/src/lib/dashboard-navigation.test.ts
+++ b/web/src/lib/dashboard-navigation.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import { dashboardNav } from '@/config/dashboard';
import {
+ activeChildHref,
dashboardNavLabelKeys,
getDashboardNavGroupLabel,
getDashboardNavLabel,
@@ -39,6 +40,18 @@ describe('getDashboardNavLabel', () => {
expect(items.some((item) => item.href === '/dashboard/topics')).toBe(false);
});
+ // Content Editor (CE-001): Content is a group; Opportunities keeps today's
+ // route.
+ it('lists Opportunities and the Library under Content', () => {
+ const items = dashboardNav.flatMap((group) => group.items);
+ const content = items.find((item) => item.title === 'Content')!;
+ expect(content.href).toBe('/dashboard/content');
+ expect(content.children).toEqual([
+ { title: 'Opportunities', href: '/dashboard/content' },
+ { title: 'Library', href: '/dashboard/content/library' },
+ ]);
+ });
+
it('uses the brands namespace only for Brands', () => {
expect(getDashboardNavLabel('Brands', translateNav, translateBrands)).toBe('brands.title');
expect(getDashboardNavLabel('Shopping', translateNav, translateBrands)).toBe('nav.shopping');
@@ -108,3 +121,30 @@ describe('the sidebar groups', () => {
}
});
});
+
+describe('activeChildHref', () => {
+ const content = [
+ { title: 'Opportunities', href: '/dashboard/content' },
+ { title: 'Library', href: '/dashboard/content/library' },
+ ];
+
+ it('marks only the Library on the Library, though its route starts with Opportunities’', () => {
+ expect(activeChildHref(content, '/dashboard/content/library')).toBe(
+ '/dashboard/content/library',
+ );
+ });
+
+ it('keeps an opportunity’s own page under Opportunities', () => {
+ expect(activeChildHref(content, '/dashboard/content')).toBe('/dashboard/content');
+ expect(activeChildHref(content, '/dashboard/content/3f2a')).toBe('/dashboard/content');
+ });
+
+ it('counts a view’s own pages, and nothing else', () => {
+ const prompts = [{ title: 'Topics', href: '/dashboard/prompts/topics' }];
+ expect(activeChildHref(prompts, '/dashboard/prompts/topics/t1')).toBe(
+ '/dashboard/prompts/topics',
+ );
+ expect(activeChildHref(prompts, '/dashboard/prompts/topicsx')).toBeNull();
+ expect(activeChildHref(content, '/dashboard/audit')).toBeNull();
+ });
+});
diff --git a/web/src/lib/dashboard-navigation.ts b/web/src/lib/dashboard-navigation.ts
index f36c3f4e3..b8fd23e3a 100644
--- a/web/src/lib/dashboard-navigation.ts
+++ b/web/src/lib/dashboard-navigation.ts
@@ -1,4 +1,4 @@
-import type { BrandPrefKey, NavItem } from '@/config/dashboard';
+import type { BrandPrefKey, NavChild, NavItem } from '@/config/dashboard';
type Translator = (key: string) => string;
@@ -19,7 +19,9 @@ export const dashboardNavLabelKeys: Record<string, NavLabelKey> = {
Topics: { namespace: 'nav', key: 'topics' },
'Query Fan-outs': { namespace: 'nav', key: 'queryFanouts' },
'Prompts Insights': { namespace: 'nav', key: 'promptsInsights' },
- 'Content Optimization': { namespace: 'nav', key: 'content' },
+ Content: { namespace: 'nav', key: 'content' },
+ Opportunities: { namespace: 'nav', key: 'contentOpportunities' },
+ Library: { namespace: 'nav', key: 'contentLibrary' },
'Site Audit': { namespace: 'nav', key: 'audit' },
Citations: { namespace: 'nav', key: 'citations' },
Mentions: { namespace: 'nav', key: 'mentions' },
@@ -47,6 +49,21 @@ export function getDashboardNavLabel(title: string, t: Translator, tBrands: Tran
return label.namespace === 'brands' ? tBrands(label.key) : t(label.key);
}
+/**
+ * The submenu entry the current page belongs to: its own route or a page
+ * under it (a topic's page sits under Topics). When one entry's route holds
+ * another's (Opportunities is /dashboard/content, the Library is
+ * /dashboard/content/library), the longer one wins, so only one is current.
+ */
+export function activeChildHref(children: NavChild[], pathname: string): string | null {
+ let best: string | null = null;
+ for (const child of children) {
+ const matches = pathname === child.href || pathname.startsWith(`${child.href}/`);
+ if (matches && (best === null || child.href.length > best.length)) best = child.href;
+ }
+ return best;
+}
+
/** Brand preferences hide a navigation item entirely; they are intentionally
* separate from plan gates, which render a visible but disabled item. */
export function shouldShowDashboardNavItem(
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 612cf52a6..f8eeb42ec 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -822,6 +822,69 @@ export type Database = {
},
]
}
+ content_drafts: {
+ Row: {
+ author: string
+ body_html: string
+ brand_id: string
+ created_at: string
+ created_by: string | null
+ id: string
+ method: string
+ page_type: string | null
+ score_after: number | null
+ score_before: number | null
+ status: string
+ title: string
+ updated_at: string
+ }
+ Insert: {
+ author?: string
+ body_html?: string
+ brand_id: string
+ created_at?: string
+ created_by?: string | null
+ id?: string
+ method?: string
+ page_type?: string | null
+ score_after?: number | null
+ score_before?: number | null
+ status?: string
+ title?: string
+ updated_at?: string
+ }
+ Update: {
+ author?: string
+ body_html?: string
+ brand_id?: string
+ created_at?: string
+ created_by?: string | null
+ id?: string
+ method?: string
+ page_type?: string | null
+ score_after?: number | null
+ score_before?: number | null
+ status?: string
+ title?: string
+ updated_at?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "content_drafts_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "content_drafts_created_by_fkey"
+ columns: ["created_by"]
+ isOneToOne: false
+ referencedRelation: "profiles"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
content_opportunities: {
Row: {
brand_id: string