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): show what the page earns in the editor's Impact tab (#1290)

Cihan6c3b183074ae
diff --git a/supabase/migrations/00209_content_page_impact.sql b/supabase/migrations/00209_content_page_impact.sql
new file mode 100644
index 000000000..3881d3e24
--- /dev/null
+++ b/supabase/migrations/00209_content_page_impact.sql
@@ -0,0 +1,239 @@
+-- ============================================================================
+-- 00209: what a page earns, for the editor's Impact tab (Content Editor, CE-016)
+-- ============================================================================
+-- The Impact tab (Content Editor spec v2 §7) shows, for the page a draft
+-- optimizes, the last N days against the N days before: citations, AI
+-- visits, Google clicks and the prompts that cite it, with the ones it lost.
+--
+-- content_page_impact(brand, page, days) returns one jsonb:
+-- * citations {cur, prev}: tracked answers citing the page, on the brand's
+-- own domains (citation_urls' domain index first, as ga_page_ai_visibility
+-- does); ChatGPT Shopping cards left out, as the Citations page does;
+-- * aiVisits {cur, prev}: AI-referred visits, by ai_traffic_merged's (00176)
+-- rule: the snippet on days it was active for the brand, Google Analytics
+-- on other days, never both;
+-- * gscClicks {cur, prev} and gscSince, the first day of Search Console page
+-- data the brand has (null without any): page stats are kept 190 days, so
+-- a window starting earlier is incomplete and the caller says so;
+-- * promptCounts {cur, prev, lost}: prompts citing the page in each window,
+-- and the ones it lost (cited before, not now), counted over all of them;
+-- * prompts: each prompt that cited the page in either window, with its
+-- citations and platforms in each, the most cited first (at most 100, to
+-- list: the counts don't come from it);
+-- * overlap: the brand's other pages cited in this window for the prompts
+-- citing this one, with how many of them (at most 3): pages competing
+-- with it for the same answers.
+-- A page is one lower(normalize_page_path) key, so /x/ and /x?utm_source=…
+-- are one page. Windows are whole UTC days ending yesterday: today's partial
+-- day would read as a drop against whole ones.
+--
+-- Both windows' answers come from idx_prompt_results_brand_created_cover
+-- alone (brand_id, created_at, with id, platform and prompt_id included),
+-- materialized and hash-joined, never from prompt_results' wide rows one
+-- citation at a time. The brand's other pages are found from the prompts
+-- citing this one outward. Planned for each call's own values
+-- (plan_cache_mode): after five calls plpgsql would switch to a generic plan,
+-- many times slower here.
+--
+-- Security definer with an organization check, as ai_traffic_page_citations
+-- (00176): citation_urls has no member select policy.
+
+create or replace function public.content_page_impact(
+ p_brand_id uuid,
+ p_page text,
+ p_days integer
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_key text := lower(public.normalize_page_path(p_page));
+ -- The last whole day.
+ v_last_day date := (now() at time zone 'utc')::date - 1;
+ v_cur_day date;
+ v_prev_day date;
+ v_cur timestamptz;
+ v_prev timestamptz;
+ v_until timestamptz;
+ v_result jsonb;
+begin
+ if not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ) and auth.role() is distinct from 'service_role' then
+ return null;
+ end if;
+ if p_days is null or p_days < 1 or p_days > 366 or p_page is null then
+ raise exception 'content_page_impact: a page and 1 to 366 days are needed'
+ using errcode = '22023';
+ end if;
+
+ v_cur_day := v_last_day - p_days + 1;
+ v_prev_day := v_cur_day - p_days;
+ v_cur := v_cur_day::timestamp at time zone 'utc';
+ v_prev := v_prev_day::timestamp at time zone 'utc';
+ v_until := (v_last_day + 1)::timestamp at time zone 'utc';
+
+ with own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = p_brand_id
+ ),
+ own_all as materialized (
+ select cu.id, cu.url, lower(public.normalize_page_path(cu.url)) as page_key
+ from public.citation_urls cu
+ where cu.domain in (select domain from own_domains)
+ ),
+ own_urls as (
+ select o.id from own_all o where o.page_key = v_key
+ ),
+ -- Both windows' answers, from the cover index alone.
+ answers as materialized (
+ select pr.id, pr.prompt_id, pr.platform, pr.created_at >= v_cur as is_cur
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.created_at >= v_prev
+ and pr.created_at < v_until
+ and pr.platform is distinct from 'chatgpt-shopping'
+ ),
+ cites as (
+ select a.prompt_id, a.platform, a.is_cur
+ from public.prompt_result_citations prc
+ join answers a on a.id = prc.prompt_result_id
+ where prc.url_id in (select u.id from own_urls u)
+ and prc.brand_id = p_brand_id
+ and prc.created_at >= v_prev
+ and prc.created_at < v_until
+ ),
+ per_prompt as (
+ select
+ c.prompt_id,
+ count(*) filter (where c.is_cur) as cur,
+ count(*) filter (where not c.is_cur) as prev,
+ coalesce(array_agg(distinct c.platform) filter (where c.is_cur), '{}') as cur_platforms,
+ coalesce(array_agg(distinct c.platform) filter (where not c.is_cur), '{}') as prev_platforms
+ from cites c
+ group by c.prompt_id
+ ),
+ -- This window's answers to the prompts citing the page, then their
+ -- citations, then the brand's other pages among them.
+ citing_answers as materialized (
+ select a.id, a.prompt_id
+ from answers a
+ where a.is_cur
+ and a.prompt_id in (select pp.prompt_id from per_prompt pp where pp.cur > 0)
+ ),
+ other_pages as (
+ select o.page_key, min(o.url) as page, count(distinct ca.prompt_id) as prompts
+ from citing_answers ca
+ join public.prompt_result_citations prc
+ on prc.prompt_result_id = ca.id
+ and prc.brand_id = p_brand_id
+ and prc.created_at >= v_cur
+ and prc.created_at < v_until
+ join own_all o on o.id = prc.url_id
+ where o.page_key <> v_key
+ group by o.page_key
+ ),
+ snippet_days as (
+ select distinct (l.created_at at time zone 'utc')::date as day
+ from public.ai_traffic_logs l
+ where l.brand_id = p_brand_id
+ and l.visit_of is null
+ and l.created_at >= v_prev
+ and l.created_at < v_until
+ ),
+ visits as (
+ select l.created_at >= v_cur as is_cur, 1::bigint as n
+ from public.ai_traffic_logs l
+ where l.brand_id = p_brand_id
+ and l.visit_of is null
+ and l.created_at >= v_prev
+ and l.created_at < v_until
+ and lower(public.normalize_page_path(l.url)) = v_key
+ union all
+ select g.date >= v_cur_day, g.sessions::bigint
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.sessions > 0
+ -- A session without a landing page would read as the home page.
+ and g.landing_page <> ''
+ and g.date >= v_prev_day
+ and g.date <= v_last_day
+ and lower(public.normalize_page_path(g.landing_page)) = v_key
+ and not exists (select 1 from snippet_days s where s.day = g.date)
+ ),
+ clicks as (
+ select g.date >= v_cur_day as is_cur, g.clicks::bigint as n
+ from public.gsc_page_stats g
+ where g.brand_id = p_brand_id
+ and g.page_key = v_key
+ and g.date >= v_prev_day
+ and g.date <= v_last_day
+ )
+ select jsonb_build_object(
+ 'citations', (
+ select jsonb_build_object('cur', coalesce(sum(cur), 0), 'prev', coalesce(sum(prev), 0))
+ from per_prompt
+ ),
+ 'promptCounts', (
+ select jsonb_build_object(
+ 'cur', count(*) filter (where cur > 0),
+ 'prev', count(*) filter (where prev > 0),
+ 'lost', count(*) filter (where cur = 0 and prev > 0)
+ )
+ from per_prompt
+ ),
+ 'aiVisits', (
+ select jsonb_build_object(
+ 'cur', coalesce(sum(n) filter (where is_cur), 0),
+ 'prev', coalesce(sum(n) filter (where not is_cur), 0)
+ )
+ from visits
+ ),
+ 'gscClicks', (
+ select jsonb_build_object(
+ 'cur', coalesce(sum(n) filter (where is_cur), 0),
+ 'prev', coalesce(sum(n) filter (where not is_cur), 0)
+ )
+ from clicks
+ ),
+ 'gscSince', (select min(g.date) from public.gsc_page_stats g where g.brand_id = p_brand_id),
+ 'overlap', coalesce((
+ select jsonb_agg(jsonb_build_object('page', op.page, 'prompts', op.prompts)
+ order by op.prompts desc, op.page)
+ from (select * from other_pages order by prompts desc, page limit 3) op
+ ), '[]'::jsonb),
+ 'prompts', coalesce((
+ select jsonb_agg(row order by (row->>'cur')::int desc, (row->>'prev')::int desc, row->>'text')
+ from (
+ select jsonb_build_object(
+ 'id', pp.prompt_id,
+ 'text', p.text,
+ 'cur', pp.cur,
+ 'prev', pp.prev,
+ 'curPlatforms', to_jsonb(pp.cur_platforms),
+ 'prevPlatforms', to_jsonb(pp.prev_platforms)
+ ) as row
+ from per_prompt pp
+ join public.prompts p on p.id = pp.prompt_id
+ order by pp.cur desc, pp.prev desc
+ limit 100
+ ) t
+ ), '[]'::jsonb)
+ ) into v_result;
+ return v_result;
+end;
+$$;
+
+revoke all on function public.content_page_impact(uuid, text, integer) from public, anon;
+grant execute on function public.content_page_impact(uuid, text, integer)
+ to authenticated, service_role;
+
+comment on function public.content_page_impact(uuid, text, integer) is
+ 'Content Editor (CE-016): one page''s citations, AI visits, Google clicks and citing prompts over the last N whole UTC days (ending yesterday) and the N before. Security definer with an organization check.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 54afd50ee..9025dc611 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -29131,3 +29131,246 @@ begin
end;
$$;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00209_content_page_impact.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00209: what a page earns, for the editor's Impact tab (Content Editor, CE-016)
+-- ============================================================================
+-- The Impact tab (Content Editor spec v2 §7) shows, for the page a draft
+-- optimizes, the last N days against the N days before: citations, AI
+-- visits, Google clicks and the prompts that cite it, with the ones it lost.
+--
+-- content_page_impact(brand, page, days) returns one jsonb:
+-- * citations {cur, prev}: tracked answers citing the page, on the brand's
+-- own domains (citation_urls' domain index first, as ga_page_ai_visibility
+-- does); ChatGPT Shopping cards left out, as the Citations page does;
+-- * aiVisits {cur, prev}: AI-referred visits, by ai_traffic_merged's (00176)
+-- rule: the snippet on days it was active for the brand, Google Analytics
+-- on other days, never both;
+-- * gscClicks {cur, prev} and gscSince, the first day of Search Console page
+-- data the brand has (null without any): page stats are kept 190 days, so
+-- a window starting earlier is incomplete and the caller says so;
+-- * promptCounts {cur, prev, lost}: prompts citing the page in each window,
+-- and the ones it lost (cited before, not now), counted over all of them;
+-- * prompts: each prompt that cited the page in either window, with its
+-- citations and platforms in each, the most cited first (at most 100, to
+-- list: the counts don't come from it);
+-- * overlap: the brand's other pages cited in this window for the prompts
+-- citing this one, with how many of them (at most 3): pages competing
+-- with it for the same answers.
+-- A page is one lower(normalize_page_path) key, so /x/ and /x?utm_source=…
+-- are one page. Windows are whole UTC days ending yesterday: today's partial
+-- day would read as a drop against whole ones.
+--
+-- Both windows' answers come from idx_prompt_results_brand_created_cover
+-- alone (brand_id, created_at, with id, platform and prompt_id included),
+-- materialized and hash-joined, never from prompt_results' wide rows one
+-- citation at a time. The brand's other pages are found from the prompts
+-- citing this one outward. Planned for each call's own values
+-- (plan_cache_mode): after five calls plpgsql would switch to a generic plan,
+-- many times slower here.
+--
+-- Security definer with an organization check, as ai_traffic_page_citations
+-- (00176): citation_urls has no member select policy.
+
+create or replace function public.content_page_impact(
+ p_brand_id uuid,
+ p_page text,
+ p_days integer
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_key text := lower(public.normalize_page_path(p_page));
+ -- The last whole day.
+ v_last_day date := (now() at time zone 'utc')::date - 1;
+ v_cur_day date;
+ v_prev_day date;
+ v_cur timestamptz;
+ v_prev timestamptz;
+ v_until timestamptz;
+ v_result jsonb;
+begin
+ if not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ) and auth.role() is distinct from 'service_role' then
+ return null;
+ end if;
+ if p_days is null or p_days < 1 or p_days > 366 or p_page is null then
+ raise exception 'content_page_impact: a page and 1 to 366 days are needed'
+ using errcode = '22023';
+ end if;
+
+ v_cur_day := v_last_day - p_days + 1;
+ v_prev_day := v_cur_day - p_days;
+ v_cur := v_cur_day::timestamp at time zone 'utc';
+ v_prev := v_prev_day::timestamp at time zone 'utc';
+ v_until := (v_last_day + 1)::timestamp at time zone 'utc';
+
+ with own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = p_brand_id
+ ),
+ own_all as materialized (
+ select cu.id, cu.url, lower(public.normalize_page_path(cu.url)) as page_key
+ from public.citation_urls cu
+ where cu.domain in (select domain from own_domains)
+ ),
+ own_urls as (
+ select o.id from own_all o where o.page_key = v_key
+ ),
+ -- Both windows' answers, from the cover index alone.
+ answers as materialized (
+ select pr.id, pr.prompt_id, pr.platform, pr.created_at >= v_cur as is_cur
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.created_at >= v_prev
+ and pr.created_at < v_until
+ and pr.platform is distinct from 'chatgpt-shopping'
+ ),
+ cites as (
+ select a.prompt_id, a.platform, a.is_cur
+ from public.prompt_result_citations prc
+ join answers a on a.id = prc.prompt_result_id
+ where prc.url_id in (select u.id from own_urls u)
+ and prc.brand_id = p_brand_id
+ and prc.created_at >= v_prev
+ and prc.created_at < v_until
+ ),
+ per_prompt as (
+ select
+ c.prompt_id,
+ count(*) filter (where c.is_cur) as cur,
+ count(*) filter (where not c.is_cur) as prev,
+ coalesce(array_agg(distinct c.platform) filter (where c.is_cur), '{}') as cur_platforms,
+ coalesce(array_agg(distinct c.platform) filter (where not c.is_cur), '{}') as prev_platforms
+ from cites c
+ group by c.prompt_id
+ ),
+ -- This window's answers to the prompts citing the page, then their
+ -- citations, then the brand's other pages among them.
+ citing_answers as materialized (
+ select a.id, a.prompt_id
+ from answers a
+ where a.is_cur
+ and a.prompt_id in (select pp.prompt_id from per_prompt pp where pp.cur > 0)
+ ),
+ other_pages as (
+ select o.page_key, min(o.url) as page, count(distinct ca.prompt_id) as prompts
+ from citing_answers ca
+ join public.prompt_result_citations prc
+ on prc.prompt_result_id = ca.id
+ and prc.brand_id = p_brand_id
+ and prc.created_at >= v_cur
+ and prc.created_at < v_until
+ join own_all o on o.id = prc.url_id
+ where o.page_key <> v_key
+ group by o.page_key
+ ),
+ snippet_days as (
+ select distinct (l.created_at at time zone 'utc')::date as day
+ from public.ai_traffic_logs l
+ where l.brand_id = p_brand_id
+ and l.visit_of is null
+ and l.created_at >= v_prev
+ and l.created_at < v_until
+ ),
+ visits as (
+ select l.created_at >= v_cur as is_cur, 1::bigint as n
+ from public.ai_traffic_logs l
+ where l.brand_id = p_brand_id
+ and l.visit_of is null
+ and l.created_at >= v_prev
+ and l.created_at < v_until
+ and lower(public.normalize_page_path(l.url)) = v_key
+ union all
+ select g.date >= v_cur_day, g.sessions::bigint
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.sessions > 0
+ -- A session without a landing page would read as the home page.
+ and g.landing_page <> ''
+ and g.date >= v_prev_day
+ and g.date <= v_last_day
+ and lower(public.normalize_page_path(g.landing_page)) = v_key
+ and not exists (select 1 from snippet_days s where s.day = g.date)
+ ),
+ clicks as (
+ select g.date >= v_cur_day as is_cur, g.clicks::bigint as n
+ from public.gsc_page_stats g
+ where g.brand_id = p_brand_id
+ and g.page_key = v_key
+ and g.date >= v_prev_day
+ and g.date <= v_last_day
+ )
+ select jsonb_build_object(
+ 'citations', (
+ select jsonb_build_object('cur', coalesce(sum(cur), 0), 'prev', coalesce(sum(prev), 0))
+ from per_prompt
+ ),
+ 'promptCounts', (
+ select jsonb_build_object(
+ 'cur', count(*) filter (where cur > 0),
+ 'prev', count(*) filter (where prev > 0),
+ 'lost', count(*) filter (where cur = 0 and prev > 0)
+ )
+ from per_prompt
+ ),
+ 'aiVisits', (
+ select jsonb_build_object(
+ 'cur', coalesce(sum(n) filter (where is_cur), 0),
+ 'prev', coalesce(sum(n) filter (where not is_cur), 0)
+ )
+ from visits
+ ),
+ 'gscClicks', (
+ select jsonb_build_object(
+ 'cur', coalesce(sum(n) filter (where is_cur), 0),
+ 'prev', coalesce(sum(n) filter (where not is_cur), 0)
+ )
+ from clicks
+ ),
+ 'gscSince', (select min(g.date) from public.gsc_page_stats g where g.brand_id = p_brand_id),
+ 'overlap', coalesce((
+ select jsonb_agg(jsonb_build_object('page', op.page, 'prompts', op.prompts)
+ order by op.prompts desc, op.page)
+ from (select * from other_pages order by prompts desc, page limit 3) op
+ ), '[]'::jsonb),
+ 'prompts', coalesce((
+ select jsonb_agg(row order by (row->>'cur')::int desc, (row->>'prev')::int desc, row->>'text')
+ from (
+ select jsonb_build_object(
+ 'id', pp.prompt_id,
+ 'text', p.text,
+ 'cur', pp.cur,
+ 'prev', pp.prev,
+ 'curPlatforms', to_jsonb(pp.cur_platforms),
+ 'prevPlatforms', to_jsonb(pp.prev_platforms)
+ ) as row
+ from per_prompt pp
+ join public.prompts p on p.id = pp.prompt_id
+ order by pp.cur desc, pp.prev desc
+ limit 100
+ ) t
+ ), '[]'::jsonb)
+ ) into v_result;
+ return v_result;
+end;
+$$;
+
+revoke all on function public.content_page_impact(uuid, text, integer) from public, anon;
+grant execute on function public.content_page_impact(uuid, text, integer)
+ to authenticated, service_role;
+
+comment on function public.content_page_impact(uuid, text, integer) is
+ 'Content Editor (CE-016): one page''s citations, AI visits, Google clicks and citing prompts over the last N whole UTC days (ending yesterday) and the N before. Security definer with an organization check.';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index b8262639d..9448e4986 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3410,6 +3410,55 @@
"invalid": "Enter the image's web address (https://…).",
"cancel": "Cancel",
"insert": "Insert"
+ },
+ "panel": {
+ "label": "Side panel",
+ "show": "Show side panel",
+ "hide": "Hide side panel",
+ "tabs": {
+ "impact": "Impact"
+ }
+ },
+ "impact": {
+ "newPage": "This draft is a new page, not live yet, so there's nothing to measure. Impact shows when a draft optimizes a live page.",
+ "thisPage": "This page",
+ "periodLabel": "Period",
+ "periods": {
+ "7": "7d",
+ "30": "30d",
+ "90": "90d",
+ "365": "1y"
+ },
+ "loadError": "Couldn't load the page's impact.",
+ "retry": "Retry",
+ "metrics": {
+ "citations": "Citations",
+ "aiVisits": "AI visits",
+ "gscClicks": "Google clicks",
+ "promptsCited": "Prompts cited"
+ },
+ "noSearchConsole": "No Search Console data",
+ "change": {
+ "new": "New",
+ "low": "Low sample",
+ "lowHint": "Fewer than 30 in this period or the one before, so a % change would mislead."
+ },
+ "prompts": {
+ "title": "Prompts cited · {count}",
+ "lost": "{count} lost",
+ "none": "No tracked prompt cited this page in this period or the one before.",
+ "cited": "Cited {count}×",
+ "lostBadge": "Lost",
+ "wasCitedOn": "Was cited on {platforms}",
+ "seeInCitations": "See in Citations"
+ },
+ "overlap": {
+ "title": "Your other pages for these prompts",
+ "only": "{count, plural, one {The only page cited for its prompt} other {The only page cited for its # prompts}} · no overlap",
+ "shared": "{count} of {total, plural, one {# prompt} other {# prompts}}"
+ },
+ "note": "The last {days} days against the {days} before, in whole UTC days. Citations come from tracked prompts, AI visits from the tracking snippet or Google Analytics, clicks from Search Console.",
+ "gscWindow": "Search Console keeps {days} days of page data, so older clicks aren't counted or compared."
}
},
"status": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
index d55f96808..f7454a5a2 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
@@ -9,7 +9,7 @@ import StarterKit from '@tiptap/starter-kit';
import { TableKit } from '@tiptap/extension-table';
import Image from '@tiptap/extension-image';
import { CharacterCount, Placeholder } from '@tiptap/extensions';
-import { ArrowLeft, Check, Copy, Loader2 } from 'lucide-react';
+import { ArrowLeft, Check, Copy, Loader2, PanelRight } from 'lucide-react';
import { Link } from '@/i18n/navigation';
import { Button } from '@/components/ui/button';
import { buttonVariants } from '@/components/ui/button-variants';
@@ -29,6 +29,7 @@ import { cn } from '@/lib/utils';
import { DropOverlay, useAttachments } from './_attach';
import { HtmlBlock, copyToClipboard } from './_html-block';
import { PageTypeMenu } from './_page-type-menu';
+import { EditorSidePanel, useSidePanelOpen } from './_side-panel';
import { EditorToolbar } from './_toolbar';
import { useDraftAutosave, type SaveState } from './_use-autosave';
@@ -60,7 +61,9 @@ const DOCUMENT_CLASS = cn(
* source, and cleans it the same way when it switches back. HTML blocks
* carry code as written, as many as the page needs, and Copy HTML puts the
* whole page, or one block, on the clipboard. The page type follows the page
- * as it is written until the person picks one (CE-023).
+ * as it is written until the person picks one (CE-023). The side panel, open
+ * beside the page or closed from the header, shows what the page earns
+ * (Impact, CE-016).
*/
export function DraftEditor({ draft }: { draft: ContentDraft }) {
const t = useTranslations('contentEditor.editor');
@@ -81,6 +84,7 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
const attachRef = useRef<(files: File[]) => void>(undefined);
const [dragging, setDragging] = useState(false);
const dragDepth = useRef(0);
+ const [panelOpen, togglePanel] = useSidePanelOpen();
const editor = useEditor({
extensions: [
@@ -326,54 +330,73 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
)}
{t('markReady')}
</Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-pressed={panelOpen}
+ aria-label={panelOpen ? t('panel.hide') : t('panel.show')}
+ title={panelOpen ? t('panel.hide') : t('panel.show')}
+ onClick={togglePanel}
+ className={cn(panelOpen && 'bg-muted')}
+ >
+ <PanelRight className="h-4 w-4" />
+ </Button>
</div>
</header>
- {editor && (
- <EditorToolbar
- editor={editor}
- target={lengthTarget(pageType)}
- htmlView={htmlSource !== null}
- onToggleHtml={htmlSource === null ? openHtmlView : applyHtmlView}
- onAttach={attachments.open}
- />
- )}
-
- {htmlSource !== null && (
- <div className="flex items-center gap-2 border-b bg-muted/40 px-4 py-1.5 text-xs text-muted-foreground">
- <span>
- <span className="font-medium text-foreground">{t('html.title')}</span> ·{' '}
- {t('html.hint', { marker: '<!-- html-block -->' })}
- </span>
- <Button size="sm" className="ml-auto h-7" onClick={applyHtmlView}>
- {t('html.back')}
- </Button>
- </div>
- )}
+ <div className="flex min-h-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col">
+ {editor && (
+ <EditorToolbar
+ editor={editor}
+ target={lengthTarget(pageType)}
+ htmlView={htmlSource !== null}
+ onToggleHtml={htmlSource === null ? openHtmlView : applyHtmlView}
+ onAttach={attachments.open}
+ />
+ )}
- <div className="relative min-h-0 flex-1" {...dropHandlers}>
- <div className="h-full overflow-y-auto">
{htmlSource !== null && (
- <textarea
- value={htmlSource}
- onChange={(e) => {
- setHtmlSource(e.target.value);
- setHtmlEdited(true);
- }}
- spellCheck={false}
- aria-label={t('html.label')}
- className="block h-full min-h-[600px] w-full resize-none bg-muted/20 px-7 py-5 font-mono text-[12.5px] leading-relaxed outline-none"
- />
+ <div className="flex items-center gap-2 border-b bg-muted/40 px-4 py-1.5 text-xs text-muted-foreground">
+ <span>
+ <span className="font-medium text-foreground">{t('html.title')}</span> ·{' '}
+ {t('html.hint', { marker: '<!-- html-block -->' })}
+ </span>
+ <Button size="sm" className="ml-auto h-7" onClick={applyHtmlView}>
+ {t('html.back')}
+ </Button>
+ </div>
)}
- <div
- className={cn('mx-auto max-w-[720px] px-7 pt-7 pb-20', htmlSource !== null && 'hidden')}
- >
- <EditorContent editor={editor} />
+
+ <div className="relative min-h-0 flex-1" {...dropHandlers}>
+ <div className="h-full overflow-y-auto">
+ {htmlSource !== null && (
+ <textarea
+ value={htmlSource}
+ onChange={(e) => {
+ setHtmlSource(e.target.value);
+ setHtmlEdited(true);
+ }}
+ spellCheck={false}
+ aria-label={t('html.label')}
+ className="block h-full min-h-[600px] w-full resize-none bg-muted/20 px-7 py-5 font-mono text-[12.5px] leading-relaxed outline-none"
+ />
+ )}
+ <div
+ className={cn(
+ 'mx-auto max-w-[720px] px-7 pt-7 pb-20',
+ htmlSource !== null && 'hidden',
+ )}
+ >
+ <EditorContent editor={editor} />
+ </div>
+ </div>
+ {dragging && <DropOverlay />}
</div>
+ {attachments.ui}
</div>
- {dragging && <DropOverlay />}
+ {panelOpen && <EditorSidePanel draft={draft} />}
</div>
- {attachments.ui}
</div>
);
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsx
new file mode 100644
index 000000000..6494ae57d
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsx
@@ -0,0 +1,193 @@
+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 { ContentImpact } from '@/lib/content/impact';
+import { ImpactTab } from './_impact-tab';
+
+const getContentImpact = vi.fn();
+vi.mock('@/lib/actions/content-drafts', () => ({
+ getContentImpact: (...args: unknown[]) => getContentImpact(...args),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const PAGE = 'https://acme.example.com/pricing';
+
+const impact = (over: Partial<ContentImpact> = {}): ContentImpact => ({
+ citations: { cur: 45, prev: 30 },
+ promptCounts: { cur: 1, prev: 2, lost: 1 },
+ aiVisits: { cur: 4, prev: 2 },
+ gscClicks: { cur: 12, prev: 0 },
+ gscSince: '2026-01-01',
+ prompts: [
+ {
+ id: 'p1',
+ text: 'best crm for realtors',
+ cur: 3,
+ prev: 1,
+ curPlatforms: ['chatgpt', 'perplexity'],
+ prevPlatforms: ['chatgpt'],
+ },
+ {
+ id: 'p2',
+ text: 'crm pricing',
+ cur: 0,
+ prev: 2,
+ curPlatforms: [],
+ prevPlatforms: ['google-ai-overviews'],
+ },
+ ],
+ overlap: [],
+ ...over,
+});
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render(pageUrl: string | null = PAGE) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <ImpactTab brandId="b1" pageUrl={pageUrl} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const metric = (label: string) =>
+ [...container.querySelectorAll('.grid > div')].find(
+ (cell) => cell.firstElementChild?.textContent === label,
+ )?.textContent;
+const periodButton = (name: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === name)!;
+
+beforeEach(() => {
+ vi.useFakeTimers({ now: new Date('2026-10-20T12:00:00Z'), toFake: ['Date'] });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ getContentImpact.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.useRealTimers();
+});
+
+describe('the Impact tab', () => {
+ it('shows what the page earns over the last 30 days against the 30 before', async () => {
+ getContentImpact.mockResolvedValue(impact());
+ await render();
+
+ expect(getContentImpact).toHaveBeenCalledWith('b1', PAGE, 30);
+ expect(periodButton('30d').getAttribute('aria-pressed')).toBe('true');
+ expect(metric('Citations')).toBe('Citations45+50%');
+ expect(metric('AI visits')).toBe('AI visits4Low sample');
+ expect(metric('Google clicks')).toBe('Google clicks12New');
+ // One prompt cites it now, as two did before.
+ expect(metric('Prompts cited')).toBe('Prompts cited1−1');
+ });
+
+ it('lists the prompts, the lost one with where it was cited', async () => {
+ getContentImpact.mockResolvedValue(impact());
+ await render();
+
+ expect(container.textContent).toContain('Prompts cited · 1 · 1 lost');
+ const rows = [...container.querySelectorAll('li')].map((li) => li.textContent);
+ expect(rows).toEqual([
+ 'best crm for realtorsChatGPT, PerplexityCited 3×',
+ 'crm pricingWas cited on Google AI OverviewLost',
+ ]);
+ expect(
+ container.querySelector('a[href^="/dashboard/citations/url"]')!.getAttribute('href'),
+ ).toBe(`/dashboard/citations/url?u=${encodeURIComponent(PAGE)}`);
+ });
+
+ it('counts the prompts over all of them, not the list it shows', async () => {
+ // The list is cut at 100 (lost prompts last); the counts come whole.
+ getContentImpact.mockResolvedValue(impact({ promptCounts: { cur: 140, prev: 150, lost: 12 } }));
+ await render();
+ expect(metric('Prompts cited')).toBe('Prompts cited140−10');
+ expect(container.textContent).toContain('Prompts cited · 140 · 12 lost');
+ });
+
+ it('names the brand’s other pages cited for the same prompts', async () => {
+ getContentImpact.mockResolvedValue(impact());
+ await render();
+ expect(container.textContent).toContain('The only page cited for its prompt · no overlap');
+
+ getContentImpact.mockResolvedValue(
+ impact({ overlap: [{ page: 'https://acme.example.com/blog/crm-guide', prompts: 1 }] }),
+ );
+ await act(async () => periodButton('7d').click());
+ expect(container.textContent).toContain('/blog/crm-guide1 of 1 prompt');
+ });
+
+ it('reads the period picked', async () => {
+ getContentImpact.mockResolvedValue(impact());
+ await render();
+ await act(async () => periodButton('90d').click());
+ expect(getContentImpact).toHaveBeenLastCalledWith('b1', PAGE, 90);
+ expect(periodButton('90d').getAttribute('aria-pressed')).toBe('true');
+ expect(container.textContent).toContain('The last 90 days against the 90 before');
+ });
+
+ it('says when Search Console has no data, or doesn’t reach back far enough', async () => {
+ getContentImpact.mockResolvedValue(impact({ gscSince: null }));
+ await render();
+ expect(metric('Google clicks')).toBe('Google clicks—No Search Console data');
+
+ // 190 days of page data: 1y starts before it, so no change is shown.
+ getContentImpact.mockResolvedValue(
+ impact({ gscSince: '2026-04-14', gscClicks: { cur: 300, prev: 0 } }),
+ );
+ await act(async () => periodButton('1y').click());
+ expect(metric('Google clicks')).toBe('Google clicks300—');
+ expect(container.textContent).toContain('Search Console keeps 190 days of page data');
+ });
+
+ it('says when no prompt cited the page', async () => {
+ getContentImpact.mockResolvedValue(
+ impact({
+ citations: { cur: 0, prev: 0 },
+ promptCounts: { cur: 0, prev: 0, lost: 0 },
+ prompts: [],
+ overlap: [],
+ }),
+ );
+ await render();
+ expect(container.textContent).toContain('No tracked prompt cited this page');
+ expect(container.textContent).not.toContain('no overlap');
+ });
+
+ it('offers to retry when the read fails', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ getContentImpact.mockRejectedValueOnce(new Error('boom')).mockResolvedValue(impact());
+ await render();
+ expect(container.textContent).toContain("Couldn't load the page's impact.");
+
+ await act(async () => periodButton('Retry').click());
+ expect(getContentImpact).toHaveBeenCalledTimes(2);
+ expect(metric('Citations')).toBe('Citations45+50%');
+ });
+
+ it('has nothing to measure for a new page', async () => {
+ await render(null);
+ expect(getContentImpact).not.toHaveBeenCalled();
+ expect(container.textContent).toContain('This draft is a new page, not live yet');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx
new file mode 100644
index 000000000..9a22e3cfc
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx
@@ -0,0 +1,320 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Check, ExternalLink, Loader2 } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { getContentImpact } from '@/lib/actions/content-drafts';
+import {
+ DEFAULT_IMPACT_PERIOD,
+ GSC_PAGE_DAYS,
+ IMPACT_PERIODS,
+ gscCoverage,
+ impactChange,
+ isLost,
+ platformNames,
+ type ContentImpact,
+ type ImpactPeriod,
+} from '@/lib/content/impact';
+import { pagePath } from '@/lib/content/overlap';
+import { formatNumber } from '@/lib/format';
+import { formatPctChange } from '@/lib/traffic-kpis';
+import type { VisitChange } from '@/lib/traffic-change';
+import { cn } from '@/lib/utils';
+
+/** One read of the tab, for one period: null while it runs. */
+interface ImpactRead {
+ period: ImpactPeriod;
+ impact: ContentImpact | null;
+ failed: boolean;
+}
+
+/**
+ * The Impact tab (Content Editor CE-016, spec §7): what the page a draft
+ * optimizes earns. Every number follows the period: citations, AI visits,
+ * Google clicks and prompts cited, each against the period before; the
+ * prompts themselves, always listed, the ones it lost marked; the brand's
+ * other pages cited for them; and where the numbers come from.
+ */
+export function ImpactTab({ brandId, pageUrl }: { brandId: string; pageUrl: string | null }) {
+ const t = useTranslations('contentEditor.editor.impact');
+ const [period, setPeriod] = useState<ImpactPeriod>(DEFAULT_IMPACT_PERIOD);
+ const [read, setRead] = useState<ImpactRead | null>(null);
+ const [attempt, setAttempt] = useState(0);
+
+ useEffect(() => {
+ if (!pageUrl) return;
+ let cancelled = false;
+ getContentImpact(brandId, pageUrl, period)
+ .then((impact) => {
+ if (!cancelled) setRead({ period, impact, failed: false });
+ })
+ .catch((err) => {
+ console.error('Failed to read the page impact:', err);
+ if (!cancelled) setRead({ period, impact: null, failed: true });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, pageUrl, period, attempt]);
+
+ // A new page has nothing to measure until it is live at an address.
+ if (!pageUrl) {
+ return <p className="text-sm text-muted-foreground">{t('newPage')}</p>;
+ }
+
+ const current = read?.period === period ? read : null;
+ const impact = current?.impact ?? null;
+
+ return (
+ <div className="space-y-5 text-sm">
+ <div className="flex items-center gap-2">
+ <h3 className="font-medium">{t('thisPage')}</h3>
+ <div
+ role="group"
+ aria-label={t('periodLabel')}
+ className="ml-auto flex rounded-lg border p-0.5"
+ >
+ {IMPACT_PERIODS.map((days) => (
+ <button
+ key={days}
+ type="button"
+ aria-pressed={period === days}
+ onClick={() => setPeriod(days)}
+ className={cn(
+ 'rounded-md px-2 py-0.5 text-xs text-muted-foreground transition-colors hover:text-foreground',
+ period === days && 'bg-muted font-medium text-foreground',
+ )}
+ >
+ {t(`periods.${days}`)}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {!current ? (
+ <div className="flex justify-center py-8" aria-busy="true">
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
+ </div>
+ ) : current.failed || !impact ? (
+ <p className="flex items-center gap-2 text-xs text-muted-foreground">
+ {t('loadError')}
+ <button
+ type="button"
+ className="font-medium underline"
+ onClick={() => {
+ setRead(null);
+ setAttempt((n) => n + 1);
+ }}
+ >
+ {t('retry')}
+ </button>
+ </p>
+ ) : (
+ <ImpactBody impact={impact} period={period} pageUrl={pageUrl} />
+ )}
+ </div>
+ );
+}
+
+function ImpactBody({
+ impact,
+ period,
+ pageUrl,
+}: {
+ impact: ContentImpact;
+ period: ImpactPeriod;
+ pageUrl: string;
+}) {
+ const t = useTranslations('contentEditor.editor.impact');
+ const coverage = gscCoverage(impact.gscSince, period);
+ const cited = impact.promptCounts;
+ const lost = impact.promptCounts.lost;
+ const promptDelta = cited.cur - cited.prev;
+
+ return (
+ <>
+ <div className="grid grid-cols-2 gap-2">
+ <Metric
+ label={t('metrics.citations')}
+ value={formatNumber(impact.citations.cur)}
+ change={<ChangeText change={impactChange(impact.citations)} />}
+ />
+ <Metric
+ label={t('metrics.aiVisits')}
+ value={formatNumber(impact.aiVisits.cur)}
+ change={<ChangeText change={impactChange(impact.aiVisits)} />}
+ />
+ <Metric
+ label={t('metrics.gscClicks')}
+ value={coverage === 'none' ? '—' : formatNumber(impact.gscClicks.cur)}
+ change={
+ coverage === 'none' ? (
+ <span className="text-muted-foreground">{t('noSearchConsole')}</span>
+ ) : (
+ <ChangeText change={impactChange(impact.gscClicks, coverage === 'both')} />
+ )
+ }
+ />
+ <Metric
+ label={t('metrics.promptsCited')}
+ value={formatNumber(cited.cur)}
+ change={
+ promptDelta === 0 ? (
+ <span className="text-muted-foreground">—</span>
+ ) : (
+ <span
+ className={
+ promptDelta > 0
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : 'text-red-600 dark:text-red-400'
+ }
+ >
+ {promptDelta > 0 ? `+${promptDelta}` : `−${Math.abs(promptDelta)}`}
+ </span>
+ )
+ }
+ />
+ </div>
+
+ <section className="space-y-2">
+ <h4 className="text-xs font-medium text-muted-foreground">
+ {t('prompts.title', { count: cited.cur })}
+ {lost > 0 && (
+ <span className="text-red-600 dark:text-red-400">
+ {' · '}
+ {t('prompts.lost', { count: lost })}
+ </span>
+ )}
+ </h4>
+ {impact.prompts.length === 0 ? (
+ <p className="text-xs text-muted-foreground">{t('prompts.none')}</p>
+ ) : (
+ <ul className="divide-y rounded-lg border">
+ {impact.prompts.map((prompt) => {
+ const gone = isLost(prompt);
+ const platforms = platformNames(gone ? prompt.prevPlatforms : prompt.curPlatforms);
+ return (
+ <li key={prompt.id} className="flex items-start gap-2.5 px-3 py-2">
+ <span
+ aria-hidden
+ className={cn(
+ 'mt-1.5 h-2 w-2 shrink-0 rounded-full',
+ gone ? 'bg-red-500' : 'bg-emerald-500',
+ )}
+ />
+ <div className="min-w-0 flex-1">
+ <p className="line-clamp-2 text-xs font-medium" title={prompt.text}>
+ {prompt.text}
+ </p>
+ {platforms.length > 0 && (
+ <p className="text-xs text-muted-foreground">
+ {gone
+ ? t('prompts.wasCitedOn', { platforms: platforms.join(', ') })
+ : platforms.join(', ')}
+ </p>
+ )}
+ </div>
+ <span
+ className={cn(
+ 'shrink-0 text-xs font-medium',
+ gone
+ ? 'text-red-600 dark:text-red-400'
+ : 'text-emerald-600 dark:text-emerald-400',
+ )}
+ >
+ {gone ? t('prompts.lostBadge') : t('prompts.cited', { count: prompt.cur })}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ <Link
+ href={`/dashboard/citations/url?u=${encodeURIComponent(pageUrl)}`}
+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
+ >
+ {t('prompts.seeInCitations')}
+ <ExternalLink className="h-3 w-3" />
+ </Link>
+ </section>
+
+ {cited.cur > 0 && (
+ <section className="space-y-1.5">
+ <h4 className="text-xs font-medium text-muted-foreground">{t('overlap.title')}</h4>
+ {impact.overlap.length === 0 ? (
+ <p className="flex items-center justify-between gap-2 rounded-lg border px-3 py-2 text-xs">
+ <span>{t('overlap.only', { count: cited.cur })}</span>
+ <Check className="h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400" />
+ </p>
+ ) : (
+ <ul className="space-y-1 rounded-lg border px-3 py-2 text-xs">
+ {impact.overlap.map((other) => (
+ <li key={other.page} className="flex items-center justify-between gap-2">
+ <span className="truncate" title={other.page}>
+ {pagePath(other.page)}
+ </span>
+ <span className="shrink-0 text-muted-foreground">
+ {t('overlap.shared', { count: other.prompts, total: cited.cur })}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ )}
+
+ <p className="rounded-lg bg-muted/50 px-3 py-2 text-xs text-muted-foreground">
+ {t('note', { days: period })}
+ {(coverage === 'partial' || coverage === 'current') &&
+ ` ${t('gscWindow', { days: GSC_PAGE_DAYS })}`}
+ </p>
+ </>
+ );
+}
+
+function Metric({
+ label,
+ value,
+ change,
+}: {
+ label: string;
+ value: string;
+ change: React.ReactNode;
+}) {
+ return (
+ <div className="rounded-lg border px-3 py-2">
+ <p className="text-xs text-muted-foreground">{label}</p>
+ <p className="text-lg font-semibold tabular-nums">{value}</p>
+ <p className="text-xs tabular-nums">{change}</p>
+ </div>
+ );
+}
+
+function ChangeText({ change }: { change: VisitChange }) {
+ const t = useTranslations('contentEditor.editor.impact.change');
+ switch (change.kind) {
+ case 'pct':
+ return (
+ <span
+ className={
+ change.pct > 0
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : 'text-red-600 dark:text-red-400'
+ }
+ >
+ {formatPctChange(change.pct)}
+ </span>
+ );
+ case 'new':
+ return <span className="text-emerald-600 dark:text-emerald-400">{t('new')}</span>;
+ case 'low':
+ return (
+ <span className="text-muted-foreground" title={t('lowHint')}>
+ {t('low')}
+ </span>
+ );
+ default:
+ return <span className="text-muted-foreground">—</span>;
+ }
+}
diff --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.tsx
new file mode 100644
index 000000000..fe19647e3
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import type { ContentDraft } from '@/lib/content/drafts';
+import { ImpactTab } from './_impact-tab';
+
+/** Remembers whether the panel is open, across drafts and visits. */
+const PANEL_OPEN_KEY = 'aeo:content-editor-panel';
+/** Wide enough for the page and the panel side by side: the panel starts open from here. */
+const PANEL_OPEN_FROM = 1280;
+
+/**
+ * Whether the side panel is open: as the person last left it, else open on a
+ * wide window. The editor renders on the client only (after its draft is
+ * read), so the first state can read the window.
+ */
+export function useSidePanelOpen(): [boolean, () => void] {
+ const [open, setOpen] = useState(() => {
+ try {
+ const stored = localStorage.getItem(PANEL_OPEN_KEY);
+ if (stored !== null) return stored === '1';
+ } catch {
+ // Storage unavailable (private mode): fall back to the window's width.
+ }
+ return window.innerWidth >= PANEL_OPEN_FROM;
+ });
+ const toggle = () => {
+ const next = !open;
+ setOpen(next);
+ try {
+ localStorage.setItem(PANEL_OPEN_KEY, next ? '1' : '0');
+ } catch {
+ // The choice just won't persist.
+ }
+ };
+ return [open, toggle];
+}
+
+/**
+ * The editor's right panel (Content Editor spec v2 §6), 400px beside the page.
+ * The spec's tabs are Impact · Chat · Brief · Sources · Rules; each joins the
+ * panel with the update that makes it work, Impact first (CE-016).
+ */
+export function EditorSidePanel({ draft }: { draft: ContentDraft }) {
+ const t = useTranslations('contentEditor.editor.panel');
+ return (
+ <aside aria-label={t('label')} className="flex w-[400px] shrink-0 flex-col border-l bg-card">
+ <Tabs value="impact" className="border-b px-3 pt-1.5">
+ <TabsList variant="line">
+ <TabsTrigger value="impact">{t('tabs.impact')}</TabsTrigger>
+ </TabsList>
+ </Tabs>
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
+ <ImpactTab brandId={draft.brandId} pageUrl={draft.sourceUrl} />
+ </div>
+ </aside>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
index e7a16a135..6a7e1de89 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
@@ -10,7 +10,9 @@ const getContentDraft = vi.fn();
const markContentDraftReady = vi.fn();
const saveContentDraft = vi.fn();
const setContentDraftPageType = vi.fn();
+const getContentImpact = vi.fn();
vi.mock('@/lib/actions/content-drafts', () => ({
+ getContentImpact: (...args: unknown[]) => getContentImpact(...args),
getContentDraft: (...args: unknown[]) => getContentDraft(...args),
markContentDraftReady: (...args: unknown[]) => markContentDraftReady(...args),
saveContentDraft: (...args: unknown[]) => saveContentDraft(...args),
@@ -80,6 +82,18 @@ if (!('getClientRects' in Range.prototype)) {
});
}
+// An in-memory localStorage: the test environment has none.
+const store = new Map<string, string>();
+Object.defineProperty(window, 'localStorage', {
+ configurable: true,
+ value: {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ removeItem: (key: string) => void store.delete(key),
+ clear: () => store.clear(),
+ },
+});
+
const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({
id: 'd1',
brandId: 'b1',
@@ -124,6 +138,8 @@ beforeEach(() => {
markContentDraftReady.mockReset();
setContentDraftPageType.mockReset().mockResolvedValue(undefined);
saveContentDraft.mockReset().mockResolvedValue({ updatedAt: '2026-10-20T10:00:00Z' });
+ getContentImpact.mockReset().mockResolvedValue(null);
+ localStorage.clear();
brandState.activeBrandId = 'b1';
brandState.setActiveBrand.mockReset();
toast.mockReset();
@@ -543,3 +559,44 @@ describe('the content editor', () => {
expect(container.querySelector('a[href="/dashboard/content/library"]')).not.toBeNull();
});
});
+
+describe('the side panel', () => {
+ const panel = () => container.querySelector('aside');
+ const innerWidth = window.innerWidth;
+ afterEach(() => {
+ window.innerWidth = innerWidth;
+ });
+
+ it('starts closed on a narrow window, and the header opens it', async () => {
+ getContentDraft.mockResolvedValue(draft({ sourceUrl: 'https://acme.example.com/pricing' }));
+ window.innerWidth = 1024;
+ await renderPage();
+ expect(panel()).toBeNull();
+ expect(getContentImpact).not.toHaveBeenCalled();
+
+ await act(async () => button('Show side panel')!.click());
+ expect(panel()!.getAttribute('aria-label')).toBe('Side panel');
+ expect(panel()!.textContent).toContain('Impact');
+ // The page the draft optimizes, over 30 days.
+ expect(getContentImpact).toHaveBeenCalledWith('b1', 'https://acme.example.com/pricing', 30);
+ expect(button('Hide side panel')!.getAttribute('aria-pressed')).toBe('true');
+ });
+
+ it('starts open on a wide window, and remembers it closed', async () => {
+ getContentDraft.mockResolvedValue(draft({ method: 'create' }));
+ window.innerWidth = 1440;
+ await renderPage();
+ // A new page: nothing to measure yet.
+ expect(panel()!.textContent).toContain('This draft is a new page, not live yet');
+ expect(getContentImpact).not.toHaveBeenCalled();
+
+ await act(async () => button('Hide side panel')!.click());
+ expect(panel()).toBeNull();
+ expect(localStorage.getItem('aeo:content-editor-panel')).toBe('0');
+
+ act(() => root.unmount());
+ root = createRoot(container);
+ await renderPage();
+ expect(panel()).toBeNull();
+ });
+});
diff --git a/web/src/lib/actions/content-drafts-impact.test.ts b/web/src/lib/actions/content-drafts-impact.test.ts
new file mode 100644
index 000000000..161b6d1e7
--- /dev/null
+++ b/web/src/lib/actions/content-drafts-impact.test.ts
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** The editor's Impact tab (CE-016): one page's numbers, as content_page_impact reads them. */
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const PAGE = 'https://acme.example.com/pricing';
+
+let rpcCalls: { fn: string; args: unknown }[];
+let rpcResult: { data: unknown; error: { message: string } | null };
+
+vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ rpc: async (fn: string, args: unknown) => {
+ rpcCalls.push({ fn, args });
+ return rpcResult;
+ },
+ })),
+}));
+
+const { getContentImpact } = await import('./content-drafts');
+
+beforeEach(() => {
+ rpcCalls = [];
+ rpcResult = { data: null, error: null };
+});
+
+describe('getContentImpact', () => {
+ it('reads the page over the period asked for', async () => {
+ const impact = {
+ citations: { cur: 4, prev: 2 },
+ aiVisits: { cur: 0, prev: 0 },
+ gscClicks: { cur: 12, prev: 20 },
+ gscSince: '2026-05-01',
+ prompts: [],
+ overlap: [],
+ };
+ rpcResult = { data: impact, error: null };
+ expect(await getContentImpact(BRAND, PAGE, 90)).toEqual(impact);
+ expect(rpcCalls).toEqual([
+ { fn: 'content_page_impact', args: { p_brand_id: BRAND, p_page: PAGE, p_days: 90 } },
+ ]);
+ });
+
+ it('returns null for a brand outside the member’s organization', async () => {
+ expect(await getContentImpact(BRAND, PAGE, 30)).toBeNull();
+ });
+
+ it('throws when the read fails', async () => {
+ rpcResult = { data: null, error: { message: 'boom' } };
+ await expect(getContentImpact(BRAND, PAGE, 30)).rejects.toThrow('boom');
+ });
+
+ it('reads nothing for a malformed brand, a period not offered, or a page without an address', async () => {
+ await expect(getContentImpact('b1', PAGE, 30)).rejects.toThrow('invalid');
+ await expect(getContentImpact(BRAND, PAGE, 14)).rejects.toThrow('invalid');
+ await expect(getContentImpact(BRAND, '/pricing', 30)).rejects.toThrow('invalid');
+ await expect(getContentImpact(BRAND, 'javascript:alert(1)', 30)).rejects.toThrow('invalid');
+ expect(rpcCalls).toEqual([]);
+ });
+});
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 520cb0b74..fdecb712f 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -20,6 +20,7 @@ import {
PAGE_IMPORT_ERRORS,
} from '@/lib/content/drafts';
import { escapeHtml } from '@/lib/content/attachments';
+import { IMPACT_PERIODS, type ContentImpact } from '@/lib/content/impact';
import {
MAX_BODY_HTML_LENGTH,
MAX_TITLE_LENGTH,
@@ -360,6 +361,33 @@ export async function sendContentDraftToActionCenter(
}
}
+/**
+ * The Impact tab (CE-016): what the page a draft optimizes earns over the
+ * last `days` against the `days` before (content_page_impact, 00209). Null
+ * when the member can't read the brand.
+ */
+export async function getContentImpact(
+ brandId: string,
+ page: string,
+ days: number,
+): Promise<ContentImpact | null> {
+ if (
+ !draftId.safeParse(brandId).success ||
+ !(IMPACT_PERIODS as readonly number[]).includes(days) ||
+ !/^https?:\/\//i.test(page)
+ ) {
+ throw new Error('invalid');
+ }
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc('content_page_impact', {
+ p_brand_id: brandId,
+ p_page: page,
+ p_days: days,
+ });
+ if (error) throw new Error(error.message);
+ return (data as ContentImpact | null) ?? null;
+}
+
const overlapSource = startInput.shape.source;
/**
diff --git a/web/src/lib/content/impact.test.ts b/web/src/lib/content/impact.test.ts
new file mode 100644
index 000000000..595765d90
--- /dev/null
+++ b/web/src/lib/content/impact.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+import {
+ gscCoverage,
+ impactChange,
+ impactWindows,
+ isLost,
+ platformNames,
+ type ImpactPrompt,
+} from './impact';
+
+const TODAY = new Date('2026-10-20T22:30:00Z');
+
+const prompt = (over: Partial<ImpactPrompt>): ImpactPrompt => ({
+ id: 'p',
+ text: 'best crm',
+ cur: 0,
+ prev: 0,
+ curPlatforms: [],
+ prevPlatforms: [],
+ ...over,
+});
+
+describe('impactWindows', () => {
+ it('counts whole UTC days, ending yesterday', () => {
+ expect(impactWindows(7, TODAY)).toEqual({ cur: '2026-10-13', prev: '2026-10-06' });
+ expect(impactWindows(1, TODAY)).toEqual({ cur: '2026-10-19', prev: '2026-10-18' });
+ expect(impactWindows(365, TODAY)).toEqual({ cur: '2025-10-20', prev: '2024-10-20' });
+ });
+});
+
+describe('gscCoverage', () => {
+ it('says how far Search Console covers both windows', () => {
+ expect(gscCoverage(null, 30, TODAY)).toBe('none');
+ // 190 days of page data: 30 and 90 days are whole, twice over.
+ expect(gscCoverage('2026-04-14', 30, TODAY)).toBe('both');
+ expect(gscCoverage('2026-04-14', 90, TODAY)).toBe('both');
+ // 1y: even this window starts before the first day.
+ expect(gscCoverage('2026-04-14', 365, TODAY)).toBe('partial');
+ // Data since last month: this window is whole, the one before isn't.
+ expect(gscCoverage('2026-09-01', 30, TODAY)).toBe('current');
+ expect(gscCoverage('2026-09-20', 30, TODAY)).toBe('current');
+ expect(gscCoverage('2026-09-21', 30, TODAY)).toBe('partial');
+ });
+});
+
+describe('impactChange', () => {
+ it('reads a change as the AI Traffic page does', () => {
+ expect(impactChange({ cur: 0, prev: 0 })).toEqual({ kind: 'none' });
+ expect(impactChange({ cur: 3, prev: 0 })).toEqual({ kind: 'new' });
+ expect(impactChange({ cur: 4, prev: 2 })).toEqual({ kind: 'low' });
+ expect(impactChange({ cur: 45, prev: 30 })).toEqual({ kind: 'pct', pct: 50 });
+ });
+
+ it('shows none when the previous window isn’t whole', () => {
+ expect(impactChange({ cur: 45, prev: 30 }, false)).toEqual({ kind: 'none' });
+ });
+});
+
+describe('prompts', () => {
+ const prompts = [
+ prompt({ id: 'a', cur: 3, prev: 1 }),
+ prompt({ id: 'b', cur: 1 }),
+ prompt({ id: 'c', prev: 2 }),
+ ];
+
+ it('marks a prompt cited before but not now as lost', () => {
+ expect(prompts.map(isLost)).toEqual([false, false, true]);
+ });
+
+ it('names the platforms once each', () => {
+ expect(platformNames(['chatgpt', 'chatgpt-web', 'perplexity', 'google-ai-overviews'])).toEqual([
+ 'ChatGPT',
+ 'Perplexity',
+ 'Google AI Overview',
+ ]);
+ expect(platformNames(['new-engine'])).toEqual(['new-engine']);
+ });
+});
diff --git a/web/src/lib/content/impact.ts b/web/src/lib/content/impact.ts
new file mode 100644
index 000000000..b5b8e2fd2
--- /dev/null
+++ b/web/src/lib/content/impact.ts
@@ -0,0 +1,82 @@
+import { PLATFORM_LABELS } from '@/config/platform-labels';
+import { visitChange, type VisitChange } from '@/lib/traffic-change';
+
+/**
+ * The editor's Impact tab (Content Editor CE-016, spec §7): what the page a
+ * draft optimizes earns, over the last N days against the N before, as
+ * content_page_impact (00209) reads it.
+ */
+
+/** The periods the tab offers, in days; 30 first. */
+export const IMPACT_PERIODS = [7, 30, 90, 365] as const;
+export type ImpactPeriod = (typeof IMPACT_PERIODS)[number];
+export const DEFAULT_IMPACT_PERIOD: ImpactPeriod = 30;
+
+/** Search Console page data is kept this long (gsc-sync.js PAGE_BACKFILL_DAYS). */
+export const GSC_PAGE_DAYS = 190;
+
+export interface ImpactCount {
+ cur: number;
+ prev: number;
+}
+
+export interface ImpactPrompt {
+ id: string;
+ text: string;
+ cur: number;
+ prev: number;
+ curPlatforms: string[];
+ prevPlatforms: string[];
+}
+
+export interface ContentImpact {
+ citations: ImpactCount;
+ /** Prompts citing the page in each window, and the ones it lost: counted over all of them. */
+ promptCounts: ImpactCount & { lost: number };
+ aiVisits: ImpactCount;
+ gscClicks: ImpactCount;
+ /** The first day of Search Console page data the brand has; null without any. */
+ gscSince: string | null;
+ /** The prompts to list, the most cited first: at most 100, so not to count from. */
+ prompts: ImpactPrompt[];
+ /** The brand's other pages cited now for this page's prompts. */
+ overlap: { page: string; prompts: number }[];
+}
+
+/** The first day of each window, as content_page_impact counts them: whole UTC days ending yesterday. */
+export function impactWindows(days: number, today = new Date()): { cur: string; prev: string } {
+ const utc = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
+ const day = (offset: number) => new Date(utc - offset * 86_400_000).toISOString().slice(0, 10);
+ return { cur: day(days), prev: day(2 * days) };
+}
+
+/**
+ * How far Search Console covers the windows: 'none' without data, 'partial'
+ * when even this window starts before its first day (1y, as pages are kept
+ * 190 days), 'current' when only the previous one does, else 'both'.
+ */
+export function gscCoverage(
+ gscSince: string | null,
+ days: number,
+ today = new Date(),
+): 'none' | 'partial' | 'current' | 'both' {
+ if (!gscSince) return 'none';
+ const { cur, prev } = impactWindows(days, today);
+ if (cur < gscSince) return 'partial';
+ return prev < gscSince ? 'current' : 'both';
+}
+
+/** A count's change, as the AI Traffic page reads one; none when the previous window isn't whole. */
+export function impactChange(count: ImpactCount, comparable = true): VisitChange {
+ return visitChange(count.cur, count.prev, { comparable });
+}
+
+/** A prompt the page lost: cited in the previous window, not in this one. */
+export function isLost(prompt: ImpactPrompt): boolean {
+ return prompt.cur === 0 && prompt.prev > 0;
+}
+
+/** Platform names for a prompt row: where it cites the page now, or did before it was lost. */
+export function platformNames(platforms: string[]): string[] {
+ return [...new Set(platforms.map((p) => PLATFORM_LABELS[p] ?? p))];
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index be5d34280..4e28b10d1 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3432,6 +3432,10 @@ export type Database = {
sent_count: number
}[]
}
+ content_page_impact: {
+ Args: { p_brand_id: string; p_days: number; p_page: string }
+ Returns: Json
+ }
content_page_overlap: {
Args: { p_brand_id: string; p_prompt_ids: string[]; p_since?: string }
Returns: {