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(settings): add Settings › Content with Hand off quality fixes automatically, per brand (CE-051, part 2) (#1482)

Cihan8d142a42ee94
diff --git a/web/messages/en.json b/web/messages/en.json
index a4466759d..076dcd381 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7096,6 +7096,17 @@
"general": "General",
"apiKeys": "API Keys",
"team": "Team",
+ "content": {
+ "title": "Content",
+ "description": "How the Content Editor works for each brand.",
+ "handOff": "Hand off quality fixes automatically",
+ "handOffHint": "Pages made while it's on get the Content Agent's quality fixes when they're first opened in the editor; turned off, the ones not handed off yet don't. Its changes wait for your review, each run is in the page's History, and each counts toward your AI usage.",
+ "managers": "Only admins and managers can change these.",
+ "noBrands": "Add a brand to choose how its pages work.",
+ "loading": "Loading the brands",
+ "loadFailed": "Couldn't load the brands.",
+ "saveFailed": "Couldn't save that. Try again."
+ },
"authors": {
"title": "Authors",
"description": "The people your pages are by. Each page names one as its author: your CMS shows the byline, and Person schema names them for search engines and AI answers.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.test.ts
index fc1426453..9c1047028 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.test.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.test.ts
@@ -39,6 +39,19 @@ describe('Authors (CE-037)', () => {
});
});
+describe('Content (CE-051)', () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ it("is there with Content Editor Quality's phase 2, as its hand-off is", () => {
+ vi.stubEnv('NEXT_PUBLIC_CONTENT_QUALITY_PHASE', '1');
+ expect(hasSettingsSection('content', selfHost)).toBe(false);
+ expect(resolveSettingsSection('content', cloud)).toBe('account');
+ vi.stubEnv('NEXT_PUBLIC_CONTENT_QUALITY_PHASE', '2');
+ expect(hasSettingsSection('content', selfHost)).toBe(true);
+ expect(resolveSettingsSection('content', selfHost)).toBe('content');
+ });
+});
+
describe('settingsSectionPath', () => {
it('keeps the locale prefix and replaces the section', () => {
expect(settingsSectionPath('/dashboard/settings', 'team')).toBe('/dashboard/settings/team');
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts b/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts
index 03f12deb2..7c6804c51 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts
@@ -10,6 +10,7 @@ export const SETTINGS_SECTIONS = [
'organization',
'team',
'authors',
+ 'content',
'notifications',
'integrations',
'api-keys',
@@ -24,6 +25,8 @@ const CLOUD_ONLY: readonly SettingsSection[] = ['ai-providers', 'billing'];
/** Content Editor Quality's Authors (CE-037): only while its phase is live. */
const hasAuthors = () => qualityPhase() >= 1;
+/** Content's settings (Quality's hand-off, CE-051): with Quality's phase 2. */
+const hasContent = () => qualityPhase() >= 2;
/** Older names an address may still carry: ?tab=project, ?tab=agent. */
const RENAMED: Record<string, SettingsSection> = {
@@ -48,6 +51,7 @@ export function resolveSettingsSection(
/** Whether this install shows the section. */
export function hasSettingsSection(section: SettingsSection, { isCloud }: { isCloud: boolean }) {
if (section === 'authors' && !hasAuthors()) return false;
+ if (section === 'content' && !hasContent()) return false;
return isCloud || !CLOUD_ONLY.includes(section);
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx
index 89abcffbd..4fa5d9a9d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx
@@ -14,6 +14,7 @@ import { usePlanContext } from '@/components/providers/plan-provider';
import { BillingSection } from '@/components/settings/billing-section';
import { TeamSection } from '@/components/settings/team-section';
import { AuthorsSection } from '@/components/settings/authors-section';
+import { ContentSection } from '@/components/settings/content-section';
import { ApiKeysSection } from '@/components/settings/api-keys-section';
import { AiProvidersSection } from '@/components/settings/ai-providers-section';
import { NotificationsSection } from '@/components/settings/notifications-section';
@@ -82,6 +83,7 @@ export function SettingsView({ section }: { section: SettingsSection }) {
organization: t('organization'),
team: t('team'),
authors: t('authors.title'),
+ content: t('content.title'),
notifications: t('notifications'),
integrations: t('integrations'),
'api-keys': t('apiKeys'),
@@ -178,6 +180,8 @@ export function SettingsView({ section }: { section: SettingsSection }) {
{active === 'authors' && hasSettingsSection('authors', { isCloud }) && <AuthorsSection />}
+ {active === 'content' && hasSettingsSection('content', { isCloud }) && <ContentSection />}
+
{active === 'notifications' && <NotificationsSection />}
{active === 'integrations' && <IntegrationsSection />}
diff --git a/web/src/components/settings/content-section.test.tsx b/web/src/components/settings/content-section.test.tsx
new file mode 100644
index 000000000..437971b35
--- /dev/null
+++ b/web/src/components/settings/content-section.test.tsx
@@ -0,0 +1,96 @@
+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';
+
+const getContentSettings = vi.fn();
+const setBrandQualityHandoff = vi.fn();
+vi.mock('@/lib/actions/content-settings', () => ({
+ getContentSettings: (...args: unknown[]) => getContentSettings(...args),
+ setBrandQualityHandoff: (...args: unknown[]) => setBrandQualityHandoff(...args),
+}));
+const toast = vi.hoisted(() => ({ error: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+const { ContentSection } = await import('./content-section');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** Settings › Content (CE-051): Hand off quality fixes automatically, per brand. */
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <ContentSection />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+const box = () => container.querySelector<HTMLButtonElement>('[role="checkbox"]')!;
+
+beforeEach(() => {
+ getContentSettings.mockReset().mockResolvedValue({
+ brands: [{ id: 'b1', name: 'Acme', qualityHandoff: false }],
+ canManage: true,
+ });
+ setBrandQualityHandoff.mockReset().mockResolvedValue(undefined);
+ toast.error.mockReset();
+ container = document.createElement('div');
+ root = createRoot(container);
+});
+afterEach(() => act(() => root.unmount()));
+
+describe('ContentSection', () => {
+ it('turns a brand’s hand-off on, and says what it does', async () => {
+ await render();
+ expect(container.textContent).toContain('AcmeHand off quality fixes automatically');
+ expect(container.textContent).toContain('Its changes wait for your review');
+ expect(box().getAttribute('aria-checked')).toBe('false');
+ await act(async () => box().click());
+ expect(setBrandQualityHandoff).toHaveBeenCalledWith('b1', true);
+ expect(box().getAttribute('aria-checked')).toBe('true');
+ // Saved: not read again.
+ expect(getContentSettings).toHaveBeenCalledTimes(1);
+ });
+
+ it('puts it back when the save fails', async () => {
+ setBrandQualityHandoff.mockRejectedValue(new Error('forbidden'));
+ await render();
+ await act(async () => box().click());
+ expect(toast.error).toHaveBeenCalledWith("Couldn't save that. Try again.");
+ expect(box().getAttribute('aria-checked')).toBe('false');
+ });
+
+ it('shows it, not to change, to members who aren’t admins or managers', async () => {
+ getContentSettings.mockResolvedValue({
+ brands: [{ id: 'b1', name: 'Acme', qualityHandoff: true }],
+ canManage: false,
+ });
+ await render();
+ expect(box().disabled).toBe(true);
+ expect(container.textContent).toContain('Only admins and managers can change these.');
+ });
+
+ it('says when there’s no brand, and when the read fails', async () => {
+ getContentSettings.mockResolvedValue({ brands: [], canManage: true });
+ await render();
+ expect(container.textContent).toContain('Add a brand to choose how its pages work.');
+ getContentSettings.mockRejectedValue(new Error('down'));
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(container.textContent).toContain("Couldn't load the brands.");
+ // No workspace to read: no endless wait.
+ getContentSettings.mockResolvedValue(null);
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(container.textContent).toContain("Couldn't load the brands.");
+ });
+});
diff --git a/web/src/components/settings/content-section.tsx b/web/src/components/settings/content-section.tsx
new file mode 100644
index 000000000..5d2b4ea55
--- /dev/null
+++ b/web/src/components/settings/content-section.tsx
@@ -0,0 +1,121 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Checkbox } from '@/components/ui/checkbox';
+import { LoadingDots } from '@/components/ui/loading-dots';
+import {
+ getContentSettings,
+ setBrandQualityHandoff,
+ type ContentSettings,
+} from '@/lib/actions/content-settings';
+
+/**
+ * Settings › Content (Quality spec §5, CE-051): per brand, Hand off quality
+ * fixes automatically — its new and optimized pages get the Content Agent's
+ * quality fixes, left for review. Admins and managers change it; anyone else
+ * sees it.
+ */
+export function ContentSection() {
+ const t = useTranslations('settings.content');
+ const tCommon = useTranslations('common');
+ const [read, setRead] = useState<ContentSettings | null>(null);
+ const [failed, setFailed] = useState(false);
+ // A brand's setting being saved: shown at once, put back if it fails.
+ const [saving, setSaving] = useState<Record<string, boolean>>({});
+
+ const load = useCallback(async () => {
+ setFailed(false);
+ try {
+ const next = await getContentSettings();
+ setRead(next);
+ // No workspace to read: nothing to wait for.
+ setFailed(!next);
+ } catch {
+ setFailed(true);
+ }
+ }, []);
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const toggle = async (brandId: string, on: boolean) => {
+ setSaving((prev) => ({ ...prev, [brandId]: on }));
+ try {
+ await setBrandQualityHandoff(brandId, on);
+ // Saved: shown as saved, with no read again to fail.
+ setRead(
+ (prev) =>
+ prev && {
+ ...prev,
+ brands: prev.brands.map((b) => (b.id === brandId ? { ...b, qualityHandoff: on } : b)),
+ },
+ );
+ } catch {
+ toast.error(t('saveFailed'));
+ } finally {
+ setSaving((prev) => {
+ const next = { ...prev };
+ delete next[brandId];
+ return next;
+ });
+ }
+ };
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('title')}</CardTitle>
+ <CardDescription>{t('description')}</CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-3">
+ {!read && !failed && (
+ <p className="text-sm text-muted-foreground" aria-busy="true">
+ <LoadingDots />
+ <span className="sr-only">{t('loading')}</span>
+ </p>
+ )}
+ {failed && (
+ <p className="text-sm text-destructive">
+ {t('loadFailed')}{' '}
+ <button type="button" className="underline" onClick={() => void load()}>
+ {tCommon('retry')}
+ </button>
+ </p>
+ )}
+ {read && read.brands.length === 0 && (
+ <p className="text-sm text-muted-foreground">{t('noBrands')}</p>
+ )}
+ {read && read.brands.length > 0 && (
+ <section className="space-y-2" aria-label={t('handOff')}>
+ <ul className="divide-y rounded-xl border">
+ {read.brands.map((brand) => (
+ <li key={brand.id} className="flex items-center gap-3 px-3 py-2.5">
+ <span
+ id={`content-${brand.id}`}
+ className="min-w-0 flex-1 text-sm [overflow-wrap:anywhere]"
+ >
+ {brand.name}
+ </span>
+ <label className="flex items-center gap-2 text-sm">
+ <Checkbox
+ checked={saving[brand.id] ?? brand.qualityHandoff}
+ aria-describedby={`content-${brand.id}`}
+ disabled={!read.canManage || brand.id in saving}
+ onCheckedChange={(checked) => void toggle(brand.id, checked === true)}
+ />
+ {t('handOff')}
+ </label>
+ </li>
+ ))}
+ </ul>
+ <p className="text-xs text-muted-foreground">{t('handOffHint')}</p>
+ {!read.canManage && <p className="text-xs text-muted-foreground">{t('managers')}</p>}
+ </section>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/lib/actions/content-settings.test.ts b/web/src/lib/actions/content-settings.test.ts
new file mode 100644
index 000000000..b59cfa46d
--- /dev/null
+++ b/web/src/lib/actions/content-settings.test.ts
@@ -0,0 +1,103 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Settings › Content (CE-051): a brand's Content settings, read and written.
+ * RLS decides who may change a brand; no row back is a refusal.
+ */
+
+const ME = '11111111-1111-4111-8111-111111111111';
+const ORG = '22222222-2222-4222-8222-222222222222';
+const ACME = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+
+interface Call {
+ table: string;
+ op: string;
+ row?: unknown;
+ filters: [string, unknown][];
+}
+let calls: Call[] = [];
+/** What a write or read of each table answers. */
+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: [] };
+ calls.push(call);
+ const answer = () => answers[`${table}.${call.op}`] ?? { data: null, error: null };
+ const chain = {
+ select: () => chain,
+ insert: (row: unknown) => Object.assign(call, { op: 'insert', row }) && chain,
+ update: (row: unknown) => Object.assign(call, { op: 'update', row }) && chain,
+ upsert: (row: unknown) => Object.assign(call, { op: 'upsert', row }) && chain,
+ delete: () => Object.assign(call, { op: 'delete' }) && chain,
+ eq: (column: string, value: unknown) => {
+ 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(),
+ then: (resolve: (value: unknown) => unknown) => Promise.resolve(answer()).then(resolve),
+ };
+ return chain;
+}
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ auth: { getUser: async () => ({ data: { user: { id: ME } } }) },
+ from: builder,
+ })),
+}));
+
+const { getContentSettings, setBrandQualityHandoff } = await import('./content-settings');
+
+const writes = () => calls.filter((c) => c.op !== 'select');
+
+beforeEach(() => {
+ calls = [];
+ answers = {
+ 'profiles.select': { data: { organization_id: ORG, role: 'manager' }, error: null },
+ 'brands.select': {
+ data: [{ id: ACME, name: 'Acme', content_quality_handoff: true }],
+ error: null,
+ },
+ };
+});
+
+describe('getContentSettings', () => {
+ it("reads the organization's brands with their hand-off, and whether the member may change it", async () => {
+ await expect(getContentSettings()).resolves.toEqual({
+ brands: [{ id: ACME, name: 'Acme', qualityHandoff: true }],
+ canManage: true,
+ });
+ expect(calls.find((c) => c.table === 'brands')!.filters).toEqual([['organization_id', ORG]]);
+ answers['profiles.select'] = { data: { organization_id: ORG, role: 'analyst' }, error: null };
+ await expect(getContentSettings()).resolves.toMatchObject({ canManage: false });
+ answers['profiles.select'] = { data: null, error: null };
+ await expect(getContentSettings()).resolves.toBeNull();
+ });
+});
+
+describe('setBrandQualityHandoff', () => {
+ it("turns a brand's hand-off on or off, and fails when RLS lets no row through", async () => {
+ answers['brands.update'] = { data: [{ id: ACME }], error: null };
+ await setBrandQualityHandoff(ACME, true);
+ expect(writes()).toEqual([
+ {
+ table: 'brands',
+ op: 'update',
+ row: { content_quality_handoff: true },
+ filters: [['id', ACME]],
+ },
+ ]);
+ answers['brands.update'] = { data: [], error: null };
+ await expect(setBrandQualityHandoff(ACME, false)).rejects.toThrow('forbidden');
+ await expect(setBrandQualityHandoff('acme', true)).rejects.toThrow('invalid');
+ });
+});
diff --git a/web/src/lib/actions/content-settings.ts b/web/src/lib/actions/content-settings.ts
new file mode 100644
index 000000000..d91bdaa73
--- /dev/null
+++ b/web/src/lib/actions/content-settings.ts
@@ -0,0 +1,57 @@
+'use server';
+
+import { z } from 'zod';
+import { createClient } from '@/lib/supabase/server';
+
+/** Settings › Content: a brand's Content Editor settings. */
+export interface ContentSettings {
+ brands: { id: string; name: string; qualityHandoff: boolean }[];
+ /** Admins and managers change them (brands: admin/manager update). */
+ canManage: boolean;
+}
+
+/** The organization's brands, each with its Content settings; null without a workspace. */
+export async function getContentSettings(): Promise<ContentSettings | null> {
+ const supabase = await createClient();
+ const { data: auth } = await supabase.auth.getUser();
+ if (!auth.user) return null;
+ const { data: profile, error: profileError } = await supabase
+ .from('profiles')
+ .select('organization_id, role')
+ .eq('id', auth.user.id)
+ .maybeSingle();
+ if (profileError) throw new Error(profileError.message);
+ if (!profile?.organization_id) return null;
+ const { data, error } = await supabase
+ .from('brands')
+ .select('id, name, content_quality_handoff')
+ .eq('organization_id', profile.organization_id)
+ .order('name');
+ if (error) throw new Error(error.message);
+ return {
+ brands: (data ?? []).map((b) => ({
+ id: b.id,
+ name: b.name,
+ qualityHandoff: b.content_quality_handoff,
+ })),
+ canManage: profile.role === 'admin' || profile.role === 'manager',
+ };
+}
+
+/**
+ * Hand off quality fixes automatically (Quality spec §5, CE-051): the
+ * brand's new and optimized pages get the Content Agent's hand-off run, its
+ * changes left for review. Admins and managers; a brand they can't change
+ * is refused.
+ */
+export async function setBrandQualityHandoff(brandId: string, on: boolean): Promise<void> {
+ if (!z.guid().safeParse(brandId).success || typeof on !== 'boolean') throw new Error('invalid');
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('brands')
+ .update({ content_quality_handoff: on })
+ .eq('id', brandId)
+ .select('id');
+ if (error) throw new Error(error.message);
+ if (!data?.length) throw new Error('forbidden');
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 7845a4fa7..f1180e40b 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -646,6 +646,7 @@ export type Database = {
brands: {
Row: {
content_byline: boolean
+ content_quality_handoff: boolean
created_at: string
description: string | null
ga_property_id: string | null
@@ -671,6 +672,7 @@ export type Database = {
}
Insert: {
content_byline?: boolean
+ content_quality_handoff?: boolean
created_at?: string
description?: string | null
ga_property_id?: string | null
@@ -696,6 +698,7 @@ export type Database = {
}
Update: {
content_byline?: boolean
+ content_quality_handoff?: boolean
created_at?: string
description?: string | null
ga_property_id?: string | null
@@ -979,6 +982,7 @@ export type Database = {
agent_run: string | null
agent_state: string | null
agent_state_at: string | null
+ quality_handoff: boolean
archived_at: string | null
archived_by: string | null
author: string
@@ -1018,6 +1022,7 @@ export type Database = {
agent_run?: string | null
agent_state?: string | null
agent_state_at?: string | null
+ quality_handoff?: boolean
archived_at?: string | null
archived_by?: string | null
author?: string
@@ -1057,6 +1062,7 @@ export type Database = {
agent_run?: string | null
agent_state?: string | null
agent_state_at?: string | null
+ quality_handoff?: boolean
archived_at?: string | null
archived_by?: string | null
author?: string
@@ -1229,6 +1235,7 @@ export type Database = {
finished_at: string | null
id: string
kind: string
+ origin: string
outcome: string | null
started_at: string
step: number
@@ -1241,6 +1248,7 @@ export type Database = {
finished_at?: string | null
id?: string
kind: string
+ origin?: string
outcome?: string | null
started_at?: string
step?: number
@@ -1253,6 +1261,7 @@ export type Database = {
finished_at?: string | null
id?: string
kind?: string
+ origin?: string
outcome?: string | null
started_at?: string
step?: number