Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): set the site type from the editor and tell the Content Agent (CE-056) (#1449)
Cihan404c7ccaa01b
diff --git a/server/.env.example b/server/.env.exampleindex 8a7bfef9d..2a737a82b 100644--- a/server/.env.example+++ b/server/.env.example@@ -62,6 +62,11 @@ COMPETITOR_SUGGESTION_MODEL=google/gemini-3-flash-preview# ACTION_TASKS_AI=# The model that writes them. Falls back to IMPROVE_SUGGESTION_MODEL.# ACTION_TASKS_MODEL=+# Content Editor Quality (Drive quality spec): which phase is live on the+# server, 0 (unset) for none, as the web's NEXT_PUBLIC_CONTENT_QUALITY_PHASE.+# 2 tells the Content Agent the brand's site type (CE-056); set it with the+# web's NEXT_PUBLIC_CONTENT_QUALITY_PHASE.+# CONTENT_QUALITY_PHASE=# How alike two content opportunities' prompt and fan-out baskets must be to# count as one (0-1, default 0.6). A new suggestion above it is skipped and# uses no quota (CONTENT-004). Raise it if distinct work is being dropped.diff --git a/server/src/lib/content-agent.js b/server/src/lib/content-agent.jsindex 0366682c1..5892f01a7 100644--- a/server/src/lib/content-agent.js+++ b/server/src/lib/content-agent.js@@ -6,7 +6,7 @@ import supabaseAdmin from '../config/supabase.js';import { resolveModel } from './ai-provider.js';import { contentBriefModelId, rebuildSources } from './content-brief.js';import { linkAllowList, linkKey, linkTargetsPrompt, readLinkTargets } from './content-links.js';-import { pageTypeFormat } from './content-page-types.js';+import { siteTypeLine, pageTypeFormat } from './content-page-types.js';import { authorWords, guardPeopleInHtml, knownPeople } from './content-people.js';import {RunStoppedError,@@ -526,7 +526,7 @@ export function buildFixPrompt({const own = input.textRules.map((text) => `- ${text}`);return `Brand: ${brand?.name || 'Unknown'}Industry: ${brand?.industry || 'Not specified'}-Description: ${brand?.description || 'N/A'}+${siteTypeLine(brand)}Description: ${brand?.description || 'N/A'}Page: ${draft.title || 'Untitled'}Page type: ${pageTypeFormat(draft.page_type)}@@ -628,7 +628,9 @@ export async function fixDraftRules({ draftId, brandId, input }) {const { data: brand, error: brandError } = await supabaseAdmin.from('brands')- .select('name, industry, description, organization_id, language')+ .select(+ 'name, industry, description, organization_id, language, site_type, shopping_mode_enabled',+ ).eq('id', brandId).single();if (brandError) throw brandError;diff --git a/server/src/lib/content-agent.test.js b/server/src/lib/content-agent.test.jsindex 729a20019..c4d7a27b4 100644--- a/server/src/lib/content-agent.test.js+++ b/server/src/lib/content-agent.test.js@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/*** Fix open rules with agent (Content Editor CE-018): the Content Agent's@@ -171,6 +171,24 @@ describe('the page as the agent reads it', () => {expect(prompt).not.toContain('The page goes on');});+ describe('with Quality’s phase 2 live', () => {+ afterEach(() => vi.unstubAllEnvs());++ it('names the brand’s site type after its industry (CE-056)', () => {+ vi.stubEnv('CONTENT_QUALITY_PHASE', '2');+ const prompt = buildFixPrompt({+ brand: { name: 'Acme Coffee', industry: 'Food & Beverage', language: 'en' },+ draft: rows.content_drafts,+ passages: draftPassages(BODY),+ lockedKeys: new Set(),+ input: input(),+ });+ expect(prompt).toContain(+ 'Industry: Food & Beverage\nSite type: E-commerce (an online shop selling products)\nDescription:',+ );+ });+ });+it('sends a long page only up to its cap, and no passage too long to change', () => {const long = { tag: 'p', text: 'x'.repeat(5_001) };const passage = { tag: 'p', text: 'y'.repeat(4_000) };diff --git a/server/src/lib/content-brief.js b/server/src/lib/content-brief.jsindex 88eb8f4c5..64f203ed0 100644--- a/server/src/lib/content-brief.js+++ b/server/src/lib/content-brief.js@@ -2,7 +2,7 @@ import { NoObjectGeneratedError, generateObject } from 'ai';import { z } from 'zod';import supabaseAdmin from '../config/supabase.js';import { resolveModel } from './ai-provider.js';-import { pageTypeFormat } from './content-page-types.js';+import { siteTypeLine, pageTypeFormat } from './content-page-types.js';import { getLanguageName } from './languages.js';import {RunStoppedError,@@ -151,7 +151,9 @@ export async function rebuildDraftBrief({ draftId, brandId, sources }) {const [brandRes, promptsRes] = await Promise.all([supabaseAdmin.from('brands')- .select('name, industry, description, organization_id, language')+ .select(+ 'name, industry, description, organization_id, language, site_type, shopping_mode_enabled',+ ).eq('id', brandId).single(),sources.promptIds.length@@ -303,7 +305,7 @@ export function buildBriefPrompt({ brand, draft, prompts, sources }) {const list = (items) => (items.length ? items.map((item) => `- ${item}`).join('\n') : '- none');return `Brand: ${brand?.name || 'Unknown'}Industry: ${brand?.industry || 'Not specified'}-Description: ${brand?.description || 'N/A'}+${siteTypeLine(brand)}Description: ${brand?.description || 'N/A'}Page: ${draft.title || 'Untitled'}Page type: ${pageTypeFormat(draft.page_type)}diff --git a/server/src/lib/content-brief.test.js b/server/src/lib/content-brief.test.jsindex a5c2e9e69..e1bd7dee5 100644--- a/server/src/lib/content-brief.test.js+++ b/server/src/lib/content-brief.test.js@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/*** Rebuild outline (Content Editor CE-007): the brief written from the@@ -352,6 +352,8 @@ describe('rebuildSources', () => {});describe('the brief prompt', () => {+ afterEach(() => vi.unstubAllEnvs());+it('says a new page is new, and lists none where a source is empty', () => {const prompt = buildBriefPrompt({brand: { name: 'Acme', language: 'en' },@@ -367,6 +369,23 @@ describe('the brief prompt', () => {expect(prompt).toContain('Write the brief in English.');});+ it('names the brand’s site type once Quality’s phase 2 is live (CE-056)', () => {+ const draft = { title: 'Rain jackets', page_type: null, method: 'create', source_url: null };+ const read = (phase) => {+ vi.stubEnv('CONTENT_QUALITY_PHASE', phase);+ return buildBriefPrompt({+ brand: { name: 'Acme', industry: 'Fashion & Apparel', language: 'en' },+ draft,+ prompts: [],+ sources: sources({ fanouts: [], pages: [], queries: [], headings: [] }),+ });+ };+ expect(read('2')).toContain(+ 'Industry: Fashion & Apparel\nSite type: E-commerce (an online shop selling products)\nDescription:',+ );+ expect(read('1')).toContain('Industry: Fashion & Apparel\nDescription:');+ });+it('maps an outline with no fan-outs kept to none', () => {expect(mapOutline(outline.slice(0, 1), [])).toEqual([{diff --git a/server/src/lib/content-page-types.js b/server/src/lib/content-page-types.jsindex b1038916f..9faa4dd91 100644--- a/server/src/lib/content-page-types.js+++ b/server/src/lib/content-page-types.js@@ -1,3 +1,5 @@+import { qualityPhase } from './content-quality.js';+/*** The Content Editor's page types (web/src/lib/content/drafts.ts, PAGE_TYPES)* as the person picks them (web/messages/en.json, contentEditor.pageTypes),@@ -5,6 +7,7 @@* Agent write the page the person chose rather than read a key such as* "solution_page".*/+export const PAGE_TYPE_FORMATS = {feature_page: 'Feature page: one capability, what it does and who it is for',solution_page: 'Use case page: how the product serves one use case, industry or team',@@ -106,6 +109,30 @@ export function siteTypeOf({ siteType, industry, shoppingModeEnabled } = {}) {return Object.hasOwn(INDUSTRY_SITE_TYPES, industry ?? '') ? INDUSTRY_SITE_TYPES[industry] : 'b2b';}+/** What each kind of site is, for a model prompt: the proof a page asks for follows it. */+const SITE_TYPE_MEANINGS = {+ b2b: 'software or services sold to businesses',+ ecommerce: 'an online shop selling products',+ b2c: 'a service for consumers',+};++/**+ * The brand's kind of site as a prompt's line (Quality CE-056, the spec's+ * business type), with a line break, once Quality's phase 2 is live; else+ * nothing.+ *+ * @param {{ site_type?: string|null, industry?: string|null, shopping_mode_enabled?: boolean|null }|null} brand+ */+export function siteTypeLine(brand) {+ if (qualityPhase() < 2) return '';+ const type = siteTypeOf({+ siteType: brand?.site_type,+ industry: brand?.industry,+ shoppingModeEnabled: brand?.shopping_mode_enabled,+ });+ return `Site type: ${SITE_TYPE_NAMES[type]} (${SITE_TYPE_MEANINGS[type]})\n`;+}+/** The page types this kind of site writes, one a line with its format, for a model prompt. */export function sitePageTypeLines(siteType) {return SITE_PAGE_TYPES[siteType].map((type) => `- ${type}: ${pageTypeFormat(type)}`).join('\n');diff --git a/server/src/lib/content-page-types.test.js b/server/src/lib/content-page-types.test.jsindex 71e4cc106..e9cbadeff 100644--- a/server/src/lib/content-page-types.test.js+++ b/server/src/lib/content-page-types.test.js@@ -1,9 +1,10 @@import { readFileSync } from 'node:fs';-import { describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {PAGE_TYPE_FORMATS,SITE_PAGE_TYPES,SITE_TYPES,+ siteTypeLine,pageTypeFormat,sitePageTypeLines,siteTypeOf,@@ -80,3 +81,27 @@ describe('sitePageTypeLines', () => {);});});++describe('siteTypeLine (Quality CE-056)', () => {+ afterEach(() => vi.unstubAllEnvs());++ it('says nothing until Quality’s phase 2 is live', () => {+ vi.stubEnv('CONTENT_QUALITY_PHASE', '1');+ expect(siteTypeLine({ site_type: 'ecommerce' })).toBe('');+ vi.stubEnv('CONTENT_QUALITY_PHASE', '');+ expect(siteTypeLine({ site_type: 'ecommerce' })).toBe('');+ });++ it('names the kind of site picked, else the guess, on a line of its own', () => {+ vi.stubEnv('CONTENT_QUALITY_PHASE', '2');+ expect(siteTypeLine({ site_type: 'ecommerce' })).toBe(+ 'Site type: E-commerce (an online shop selling products)\n',+ );+ expect(siteTypeLine({ industry: 'Travel & Hospitality' })).toBe(+ 'Site type: B2C (a service for consumers)\n',+ );+ expect(siteTypeLine(null)).toBe(+ 'Site type: B2B SaaS (software or services sold to businesses)\n',+ );+ });+});diff --git a/server/src/lib/content-quality.js b/server/src/lib/content-quality.jsnew file mode 100644index 000000000..aa8702956--- /dev/null+++ b/server/src/lib/content-quality.js@@ -0,0 +1,9 @@+/**+ * The Content Editor's Quality (Drive quality spec) on the server: which of+ * its three phases is live (CONTENT_QUALITY_PHASE, as the web's+ * NEXT_PUBLIC_CONTENT_QUALITY_PHASE), 0 for none.+ */+export function qualityPhase() {+ const phase = Number(process.env.CONTENT_QUALITY_PHASE ?? 0);+ return Number.isInteger(phase) && phase > 0 ? Math.min(phase, 3) : 0;+}diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.jsindex ac19f398c..8893755e8 100644--- a/server/src/lib/content-writer.js+++ b/server/src/lib/content-writer.js@@ -19,7 +19,7 @@ import {} from './content-agent.js';import { contentBriefModelId, rebuildSources } from './content-brief.js';import { linkAllowList, linkTargetsPrompt, readLinkTargets } from './content-links.js';-import { pageTypeFormat } from './content-page-types.js';+import { siteTypeLine, pageTypeFormat } from './content-page-types.js';import { authorWords, guardPeople, guardPeopleInHtml, knownPeople } from './content-people.js';import {SOURCES_RULE,@@ -267,7 +267,7 @@ export function buildWritePrompt({: `Write a new page titled about: ${draft.title || 'the questions below'}.`;return `Brand: ${brand?.name || 'Unknown'}Industry: ${brand?.industry || 'Not specified'}-Description: ${brand?.description || 'N/A'}+${siteTypeLine(brand)}Description: ${brand?.description || 'N/A'}Page type: ${pageTypeFormat(draft.page_type)}Length: about ${sources.length} characters.@@ -399,7 +399,9 @@ export async function startDraftWriting({ draftId, brandId, input, rewrite = falconst { data: brand, error: brandError } = await supabaseAdmin.from('brands')- .select('name, industry, description, organization_id, language')+ .select(+ 'name, industry, description, organization_id, language, site_type, shopping_mode_enabled',+ ).eq('id', brandId).single();if (brandError) throw brandError;diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.jsindex 3cd6a1bec..669896197 100644--- a/server/src/lib/content-writer.test.js+++ b/server/src/lib/content-writer.test.js@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/*** Start's Agent (Content Editor CE-015): the Content Agent writes a new page@@ -88,7 +88,7 @@ vi.mock('./content-agent.js', async (importOriginal) => ({hasOpenSuggestions: (...args) => hasOpenSuggestions(...args),}));-const { briefText, renderPage, runDraftWriting, sourcedPage, startDraftWriting } =+const { buildWritePrompt, briefText, renderPage, runDraftWriting, sourcedPage, startDraftWriting } =await import('./content-writer.js');const { NAME_PLACEHOLDER, QUOTE_PLACEHOLDER, knownPeople } = await import('./content-people.js');const { textLength } = await import('./content-rewrite.js');@@ -764,3 +764,23 @@ describe('Rewrite the page to these rules', () => {expect(writes.find((w) => w.table === 'content_draft_suggestions')).toBeUndefined();});});++describe('the write prompt', () => {+ afterEach(() => vi.unstubAllEnvs());++ it('names the brand’s site type once Quality’s phase 2 is live (CE-056)', () => {+ const write = (phase) => {+ vi.stubEnv('CONTENT_QUALITY_PHASE', phase);+ return buildWritePrompt({+ brand,+ draft: draftRow(),+ brief: 'No brief.',+ input: { sources: { length: 3000 }, rules: [], textRules: [] },+ });+ };+ expect(write('2')).toContain(+ 'Industry: Coffee\nSite type: B2B SaaS (software or services sold to businesses)\nDescription:',+ );+ expect(write('')).toContain('Industry: Coffee\nDescription:');+ });+});diff --git a/web/.env.example b/web/.env.exampleindex 6e88e399d..933c764a3 100644--- a/web/.env.example+++ b/web/.env.example@@ -62,6 +62,9 @@ NEXT_PUBLIC_ACTION_TASKS_AI=# -----------------------------------------------------------------------------# Content Editor Quality (Drive quality spec): which phase is live, 0 (unset)# for none. 1 shows Instructions › Quality and the header's Quality chip.+# 2 adds the AI checks, starting with the site type picked in the editor+# (CE-056); set the server's CONTENT_QUALITY_PHASE to the same value, so the+# Content Agent is told it too.# -----------------------------------------------------------------------------NEXT_PUBLIC_CONTENT_QUALITY_PHASE=diff --git a/web/messages/en.json b/web/messages/en.jsonindex 9b008ed6f..cd0036a21 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3630,7 +3630,12 @@"detectedHint": "Detected from the page as you write. Pick a type to keep it.","pickedHint": "You picked this type, so changes to the page don't change it.","siteSettings": "Change the site type in brand settings",- "failed": "Couldn't change the page type. Try again."+ "failed": "Couldn't change the page type. Try again.",+ "siteTitle": "Site type · for the whole brand",+ "siteHint": "Sets the page types offered, My rules and what the Content Agent writes, for every page of this brand.",+ "siteChanged": "Site type set to {site} for the whole brand.",+ "siteFailed": "Couldn't change the site type. Try again.",+ "siteGuessed": "Guessed until someone picks one."},"placeholder": "Start with the page's H1, then write…","documentLabel": "Page content",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 860e4d9c8..0e8a78070 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@@ -30,6 +30,7 @@ import { useUserRole } from '@/hooks/use-user-role';import { PLATFORM_LABELS } from '@/config/platform-labels';import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';import { SendDialog } from '@/components/content/send-to-cms-dialog';+import { updateBrand } from '@/lib/actions/brand';import {decideDraftSuggestions,fixDraftRules,@@ -92,7 +93,7 @@ import {titlePlaceholders,withByline,} from '@/lib/content/ready-to-publish';-import { detectPageType } from '@/lib/content/page-types';+import { detectPageType, isSiteType, type SiteType } from '@/lib/content/page-types';import { BAND_CLASSES, qualityAverage, qualityBand, qualityPhase } from '@/lib/content/quality';import { eeat, linksToCheck, trust, trustBlocks } from '@/lib/content/quality-checks';import { qualityTodos } from '@/lib/content/quality-todos';@@ -313,8 +314,15 @@ export function DraftEditor({detectPageType({ title: draft.title, html: draft.bodyHtml }, draft.siteType) ??(isPageType(draft.pageType) ? draft.pageType : null),);- const detectType = (title: string, html: string) =>- setDetectedType((had) => detectPageType({ title, html }, draft.siteType) ?? had);+ // The brand's site type (Quality CE-056, the spec's business type), changed+ // here for the whole brand; a ref too, as the editor's update handler is+ // made once.+ const [siteType, setSiteType] = useState<SiteType>(draft.siteType);+ const siteTypeRef = useRef(draft.siteType);+ const detectType = (title: string, html: string) => {+ const site = siteTypeRef.current;+ setDetectedType((had) => detectPageType({ title, html }, site) ?? had);+ };const pageType = picked ?? detectedType;// The HTML view's text while it is open; null in the visual editor.const [htmlSource, setHtmlSource] = useState<string | null>(null);@@ -448,6 +456,7 @@ export function DraftEditor({const reads = useDraftReads(draft.id);const rules = useDraftRules({draft,+ siteType,html: pageHtml,characters: (editor?.storage.characterCount.characters() as number | undefined) ?? 0,pageType,@@ -1917,6 +1926,38 @@ export function DraftEditor({}};+ // The site type, for the whole brand as in Brand settings: admins and+ // managers (as the brands table lets them), once Quality's phase 2 is live.+ // The page types offered, My rules and the agent follow it.+ const updateBrandStore = useBrandStore((s) => s.updateBrand);+ const storedSite = useBrandStore((s) => s.brands.find((b) => b.id === draft.brandId)?.siteType);+ const siteGuessed = !isSiteType(storedSite);+ const tSites = useTranslations('brands.siteTypes');+ const [siteSaving, setSiteSaving] = useState(false);+ const pickSite = async (next: SiteType) => {+ if (next === siteType || siteSaving) return;+ // Taken once saved: My rules are read again for it, and one pick at a time.+ setSiteSaving(true);+ const saved = await updateBrand(draft.brandId, { siteType: next }).catch((err) => {+ console.error('Failed to change the site type:', err);+ return null;+ });+ setSiteSaving(false);+ if (!saved) {+ toast.error(t('pageType.siteFailed'));+ return;+ }+ updateBrandStore(draft.brandId, saved);+ setSiteType(next);+ siteTypeRef.current = next;+ const html = editor?.getHTML() ?? pageHtml;+ detectType(title, html);+ // A detected type is the server's too: a save reads it again for the new+ // site type, so the Library and the agent agree with the header.+ if (picked === null && editor) autosave.schedule({ title, bodyHtml: html });+ toast(t('pageType.siteChanged', { site: tSites(next) }));+ };+// Why History waits (the HTML view holds the page, a restore runs), or null.const historyWaits =htmlSource !== null ? t('history.htmlOpen') : restoring ? t('history.restoring') : null;@@ -2119,7 +2160,12 @@ export function DraftEditor({<div className="mt-1.5 flex flex-wrap items-center gap-2 pl-[38px]"><PageTypeMenubrandId={draft.brandId}- siteType={draft.siteType}+ siteType={siteType}+ onPickSite={+ canManage && qualityPhase() >= 2 ? (next) => void pickSite(next) : undefined+ }+ sitePending={siteSaving}+ siteGuessed={siteGuessed}pageType={pageType}detected={picked === null}isNew={draft.method === 'create'}@@ -2361,6 +2407,7 @@ export function DraftEditor({{panelOpen ? (<EditorSidePaneldraft={draft}+ siteType={siteType}title={title}bodyHtml={pageHtml}pageType={pageType}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-type-menu.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-type-menu.tsxindex bce27b66c..81300563f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-type-menu.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-type-menu.tsx@@ -17,14 +17,16 @@ import {} from '@/components/ui/dropdown-menu';import { isPageType, type PageType } from '@/lib/content/drafts';import { pagePath } from '@/lib/content/overlap';-import { SITE_PAGE_TYPES, type SiteType } from '@/lib/content/page-types';+import { SITE_PAGE_TYPES, SITE_TYPES, isSiteType, type SiteType } from '@/lib/content/page-types';import { cn } from '@/lib/utils';/*** The draft's page type in the editor's header (CE-023): detected from the* page until the person picks one from the types their kind of site writes.* A type from another kind of site, picked before the site type changed,- * stays on the list so the menu still shows it.+ * stays on the list so the menu still shows it. With `onPickSite` (Quality+ * CE-056: admins and managers once phase 2 is live), the brand's business+ * type is picked here too, for the whole brand as in Brand settings.*/export function PageTypeMenu({brandId,@@ -34,6 +36,9 @@ export function PageTypeMenu({isNew,sourceUrl,onPick,+ onPickSite,+ sitePending = false,+ siteGuessed = false,}: {brandId: string;siteType: SiteType;@@ -45,6 +50,11 @@ export function PageTypeMenu({/** The existing page an optimize draft is for: the tag shows its path. */sourceUrl: string | null;onPick: (type: PageType) => void;+ onPickSite?: (site: SiteType) => void;+ /** A site type pick is being saved: one at a time. */+ sitePending?: boolean;+ /** The brand has no site type picked yet: the one shown is guessed, as Brand settings says. */+ siteGuessed?: boolean;}) {const t = useTranslations('contentEditor.editor');const tTypes = useTranslations('contentEditor.pageTypes');@@ -71,6 +81,35 @@ export function PageTypeMenu({<ChevronDown className="h-3 w-3 opacity-60" /></DropdownMenuTrigger><DropdownMenuContent align="start" className="w-60">+ {onPickSite && (+ <>+ <DropdownMenuGroup>+ <DropdownMenuLabel>{t('pageType.siteTitle')}</DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={siteType}+ onValueChange={(value) => {+ if (isSiteType(value)) onPickSite(value);+ }}+ >+ {SITE_TYPES.map((site) => (+ <DropdownMenuRadioItem+ key={site}+ value={site}+ disabled={sitePending}+ closeOnClick+ >+ {tSites(site)}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ <p className="px-1.5 pb-1 text-xs text-muted-foreground">+ {t('pageType.siteHint')}+ {siteGuessed && ` ${t('pageType.siteGuessed')}`}+ </p>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ </>+ )}<DropdownMenuGroup><DropdownMenuLabel>{t('pageType.title', { site: tSites(siteType) })}</DropdownMenuLabel><DropdownMenuRadioGroupdiff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsxindex a3dc2e015..095a55c50 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx@@ -5,6 +5,7 @@ import { useTranslations } from 'next-intl';import { toast } from 'sonner';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { isPageType, type ContentDraft } from '@/lib/content/drafts';+import type { SiteType } from '@/lib/content/page-types';import { buildSourceGroups, includedCounts, type DraftSourceKind } from '@/lib/content/sources';import { formatNumber } from '@/lib/format';import { BAND_CLASSES, qualityBand, qualityPhase } from '@/lib/content/quality';@@ -106,6 +107,7 @@ export function EditorPanelRail({ onOpen }: { onOpen: (tab: PanelTab) => void })*/export function EditorSidePanel({draft,+ siteType,title,bodyHtml,pageType,@@ -127,6 +129,8 @@ export function EditorSidePanel({onPickAuthor,}: {draft: ContentDraft;+ /** The brand's business type as the editor holds it (Quality CE-056). */+ siteType: SiteType;/** The draft's title, page and type as written now: Sources and Brief read them. */title: string;bodyHtml: string;@@ -405,7 +409,7 @@ export function EditorSidePanel({: undefined}state={rules}- siteType={draft.siteType}+ siteType={siteType}draftPageType={isPageType(pageType) ? pageType : null}/></div>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.tsindex c4e334f93..304e6029a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts@@ -5,6 +5,7 @@ import { useTranslations } from 'next-intl';import { toast } from 'sonner';import { getMyRuleSets, saveDraftRules, saveMyRuleSet } from '@/lib/actions/content-drafts';import { isPageType, type ContentDraft, type PageType } from '@/lib/content/drafts';+import type { SiteType } from '@/lib/content/page-types';import {MAX_TEXT_RULES,activeRules,@@ -68,6 +69,10 @@ const newId = () =>? crypto.randomUUID(): `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;+type RuleSets = Partial<Record<PageType, SavedRuleSet>>;+/** No sets while My rules are unread: one object, so what reads them doesn't change. */+const NO_RULE_SETS: RuleSets = {};+/*** The draft's rules (CE-009) as the editor reads them: the set for its page* type with the person's changes, each checked against the page as written —@@ -80,12 +85,15 @@ const newId = () =>*/export function useDraftRules({draft,+ siteType,html,characters,pageType,reads,}: {draft: ContentDraft;+ /** The brand's business type as the editor holds it: My rules are kept per type (00227). */+ siteType: SiteType;html: string;characters: number;pageType: string | null;@@ -94,28 +102,32 @@ export function useDraftRules({const t = useTranslations('contentEditor.editor.rules');const tTypes = useTranslations('contentEditor.pageTypes');const [choices, setChoices] = useState<DraftRules>(draft.rules);- const [mine, setMine] = useState<Partial<Record<PageType, SavedRuleSet>>>({});- const [mineRead, setMineRead] = useState(false);+ // My rules as read, and for which site type: they are kept per type+ // (00227), so after a switch they count as unread until read again.+ const [mineState, setMineState] = useState<{ site: SiteType; sets: RuleSets } | null>(null);+ const mineRead = mineState?.site === siteType;+ const mine = mineRead ? mineState.sets : NO_RULE_SETS;const language = useBrandStore((s) => s.brands.find((b) => b.id === draft.brandId)?.language);// One save at a time, the latest waiting; what the database holds, to go back to.const saving = useRef(false);const waiting = useRef<{ rules: DraftRules; message: string } | null>(null);const saved = useRef<DraftRules>(draft.rules);+ // Read again once the brand's site type is saved (the editor passes it then).useEffect(() => {let cancelled = false;getMyRuleSets(draft.brandId).then((sets) => {- if (!cancelled) setMine(sets);+ if (!cancelled) setMineState({ site: siteType, sets });})- .catch((err) => console.error('Failed to read My rules:', err))- .finally(() => {- if (!cancelled) setMineRead(true);+ .catch((err) => {+ console.error('Failed to read My rules:', err);+ if (!cancelled) setMineState({ site: siteType, sets: {} });});return () => {cancelled = true;};- }, [draft.brandId]);+ }, [draft.brandId, siteType]);const sources = reads.sources;const ctx = useMemo<RuleContext>(() => {@@ -287,7 +299,7 @@ export function useDraftRules({}saveMyRuleSet(draft.brandId, setType, set).then(() => {- setMine((prev) => ({ ...prev, [setType]: set }));+ setMineState((prev) => prev && { ...prev, sets: { ...prev.sets, [setType]: set } });save({ ...effective, source: 'mine' }, t('savedMine', { type: typeName(setType) }));}).catch((err) => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex eda68d2c5..6c7a7a6a6 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@@ -111,7 +111,10 @@ const brandState = vi.hoisted(() => ({activeBrandId: 'b1' as string | null,brands: [{ id: 'b1' }, { id: 'b2' }],setActiveBrand: vi.fn(),+ updateBrand: vi.fn(),}));+const updateBrand = vi.hoisted(() => vi.fn());+vi.mock('@/lib/actions/brand', () => ({ updateBrand }));vi.mock('@/stores/use-brand-store', () => ({useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),}));@@ -295,6 +298,8 @@ beforeEach(() => {localStorage.clear();brandState.activeBrandId = 'b1';brandState.setActiveBrand.mockReset();+ brandState.updateBrand.mockReset();+ updateBrand.mockReset();toast.mockReset();toast.success.mockReset();toast.error.mockReset();@@ -489,6 +494,79 @@ describe('the content editor', () => {]);});+ describe('its site type (Quality CE-056)', () => {+ afterEach(() => {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ });++ it('is set for the whole brand from the menu once phase 2 is live', async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';+ updateBrand.mockResolvedValue({ id: 'b1', siteType: 'ecommerce' });+ getContentDraft.mockResolvedValue(+ draft({ siteType: 'b2b', pageType: 'feature_page', pageTypeSource: 'user' }),+ );+ await renderPage();+ expect(getMyRuleSets).toHaveBeenCalledTimes(1);+ const items = await openTypes();+ expect(items.slice(0, 4).map((item) => item.textContent)).toEqual([+ 'B2B SaaS',+ 'E-commerce',+ 'B2C',+ 'Feature page',+ ]);+ // No site type picked yet: the one shown is guessed.+ expect(document.body.textContent).toContain('Guessed until someone picks one.');+ await act(async () => items[1].click());+ expect(updateBrand).toHaveBeenCalledWith('b1', { siteType: 'ecommerce' });+ expect(brandState.updateBrand).toHaveBeenCalledWith('b1', {+ id: 'b1',+ siteType: 'ecommerce',+ });+ expect(toast).toHaveBeenCalledWith('Site type set to E-commerce for the whole brand.');+ // My rules are kept per site type: read again once it is saved.+ expect(getMyRuleSets).toHaveBeenCalledTimes(2);+ // A shop's page types now, the type picked kept on the list.+ const types = (await openTypes()).map((item) => item.textContent);+ expect(types.slice(3, 5)).toEqual(['Product page', 'Category page']);+ expect(types.at(-1)).toBe('Feature page');++ // Kept as it was when it can't be saved.+ vi.spyOn(console, 'error').mockImplementation(() => {});+ updateBrand.mockRejectedValueOnce(new Error('rls'));+ await act(async () =>+ document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')[2].click(),+ );+ expect(toast.error).toHaveBeenCalledWith("Couldn't change the site type. Try again.");+ expect((await openTypes())[3].textContent).toBe('Product page');+ });++ it('saves a detected page type again for the new site type', async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';+ updateBrand.mockResolvedValue({ id: 'b1', siteType: 'ecommerce' });+ getContentDraft.mockResolvedValue(draft({ siteType: 'b2b', pageTypeSource: 'detected' }));+ await renderPage();+ await act(async () => (await openTypes())[1].click());+ // The server reads the type again on a save (after the autosave's pause).+ await vi.waitFor(() => expect(saveContentDraft).toHaveBeenCalledTimes(1), {+ timeout: 3_000,+ });+ });++ it('stays in Brand settings for members, and before phase 2', async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';+ getContentDraft.mockResolvedValue(draft({ siteType: 'b2b', pageType: 'feature_page' }));+ await renderPage('analyst');+ expect((await openTypes())[0].textContent).toBe('Feature page');+ await act(async () => root.unmount());+ root = createRoot(container);++ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';+ await renderPage();+ expect((await openTypes())[0].textContent).toBe('Feature page');+ expect(updateBrand).not.toHaveBeenCalled();+ });+ });+it('puts the type back when picking it fails', async () => {vi.spyOn(console, 'error').mockImplementation(() => {});setContentDraftPageType.mockRejectedValue(new Error('not_found'));