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): list the sources a draft draws on in the editor's Sources tab (#1292)

Cihan6b2ed533954c
diff --git a/supabase/migrations/00211_content_draft_sources.sql b/supabase/migrations/00211_content_draft_sources.sql
new file mode 100644
index 000000000..ea8723617
--- /dev/null
+++ b/supabase/migrations/00211_content_draft_sources.sql
@@ -0,0 +1,281 @@
+-- ============================================================================
+-- 00211: the sources a draft is built from, for the editor's Sources tab
+-- ============================================================================
+-- The Sources tab (Content Editor spec v2 §10, CE-008) names every source a
+-- draft draws on, with where the draft uses it, and lets a person leave one
+-- out or add their own.
+--
+-- content_draft_sources(draft, days) reads the brand's data over the last N
+-- days (30 by default) and returns one jsonb:
+-- * prompts: the draft's prompts (content_drafts.prompt_ids) and, for a
+-- draft optimizing a live page, the prompts whose answers cited that
+-- page; each with its answers in the window and those naming the brand;
+-- * fanouts: the searches AI engines ran while answering those prompts
+-- (prompt_results.search_queries, 00021), one row per normalized query
+-- with its platforms and the answers that ran it, most searched first
+-- (at most 30);
+-- * citedPages: the pages those answers cited, with citations and answers
+-- (at most 20); ChatGPT Shopping cards left out, as the Citations page
+-- does;
+-- * gscQueries: the brand's Search Console queries over 28 days with
+-- clicks and impressions (at most 300). Search Console keeps no queries
+-- per page, so the caller keeps the ones sharing words with the draft,
+-- as page-prompt-suggestions.js does;
+-- * brandDomains and competitorDomains, to name each cited page's kind.
+-- Security definer with an organization check through the draft's brand:
+-- citation_urls has no member select policy. The page a draft optimizes is
+-- its source URL's path on that URL's host, which must be one of the brand's
+-- domains: /pricing on another site of the brand's, or on a site not the
+-- brand's, isn't it. Prompts are the brand's through their prompt set, as
+-- everywhere else (a prompt needs no topic). Bounded by the brand and the
+-- window on (brand_id, created_at), with citations grouped by address before
+-- any address is read, and planned for each call's own values
+-- (plan_cache_mode).
+--
+-- content_draft_sources (the table) keeps a person's choices: a source left
+-- out (included false), and a page address or Search Console query added by
+-- hand (added true). A prompt added by hand joins the draft's prompt_ids.
+
+create table if not exists public.content_draft_sources (
+ draft_id uuid not null references public.content_drafts(id) on delete cascade,
+ kind text not null check (kind in ('prompt', 'fanout', 'cited_page', 'gsc_query')),
+ ref text not null check (char_length(ref) between 1 and 2048),
+ included boolean not null default true,
+ added boolean not null default false,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ primary key (draft_id, kind, ref),
+ -- Only pages and queries are added by hand; a prompt joins prompt_ids.
+ check (not added or kind in ('cited_page', 'gsc_query'))
+);
+
+alter table public.content_draft_sources enable row level security;
+
+-- A draft the member can read is one in their organization (content_drafts'
+-- own member policies), so the choices follow it.
+create policy "content_draft_sources: member select"
+ on public.content_draft_sources
+ for select
+ using (draft_id in (select d.id from public.content_drafts d));
+
+create policy "content_draft_sources: member insert"
+ on public.content_draft_sources
+ for insert
+ with check (draft_id in (select d.id from public.content_drafts d));
+
+create policy "content_draft_sources: member update"
+ on public.content_draft_sources
+ for update
+ using (draft_id in (select d.id from public.content_drafts d))
+ with check (draft_id in (select d.id from public.content_drafts d));
+
+create policy "content_draft_sources: member delete"
+ on public.content_draft_sources
+ for delete
+ using (draft_id in (select d.id from public.content_drafts d));
+
+grant select, insert, update, delete on public.content_draft_sources to authenticated;
+
+create or replace trigger content_draft_sources_updated_at
+ before update on public.content_draft_sources
+ for each row execute function public.handle_updated_at();
+
+comment on table public.content_draft_sources is
+ 'Content Editor (CE-008): a person''s choices on a draft''s sources — one left out (included false), or a page address or Search Console query added by hand (added true).';
+
+create or replace function public.content_draft_sources(
+ p_draft_id uuid,
+ p_days integer default 30
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_brand_id uuid;
+ v_prompt_ids uuid[];
+ v_page_key text;
+ v_host text;
+ v_since timestamptz;
+ v_result jsonb;
+begin
+ select d.brand_id, d.prompt_ids, lower(public.normalize_page_path(d.source_url)),
+ -- Lower-cased first: a scheme may be written HTTPS://.
+ regexp_replace(substring(lower(d.source_url) from '^https?://([^/:?#]+)'), '^www\.', '')
+ into v_brand_id, v_prompt_ids, v_page_key, v_host
+ from public.content_drafts d
+ where d.id = p_draft_id;
+
+ if v_brand_id is null or (
+ not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = v_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 > 90 then
+ raise exception 'content_draft_sources: 1 to 90 days are needed' using errcode = '22023';
+ end if;
+
+ v_since := now() - make_interval(days => p_days);
+ -- A page on a site that isn't the brand's is no page of the brand's.
+ if v_host is null or not exists (
+ select 1 from public.brand_domains bd
+ where bd.brand_id = v_brand_id
+ and lower(regexp_replace(bd.domain, '^www\.', '')) = v_host
+ ) then
+ v_page_key := null;
+ end if;
+
+ with own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = v_brand_id
+ ),
+ -- The page's addresses: its path on its host.
+ page_urls as materialized (
+ select cu.id
+ from public.citation_urls cu
+ where v_page_key is not null
+ and cu.domain = v_host
+ and lower(public.normalize_page_path(cu.url)) = v_page_key
+ ),
+ -- The window's answers, from idx_prompt_results_brand_created_cover alone:
+ -- only for a draft with a page, to find the prompts citing it.
+ window_answers as materialized (
+ select pr.id, pr.prompt_id
+ from public.prompt_results pr
+ where v_page_key is not null
+ and pr.brand_id = v_brand_id
+ and pr.created_at >= v_since
+ and pr.platform is distinct from 'chatgpt-shopping'
+ ),
+ -- The prompts whose answers cited the page the draft optimizes.
+ page_prompts as (
+ select distinct wa.prompt_id
+ from public.prompt_result_citations prc
+ join window_answers wa on wa.id = prc.prompt_result_id
+ where prc.url_id in (select pu.id from page_urls pu)
+ and prc.brand_id = v_brand_id
+ and prc.created_at >= v_since
+ ),
+ source_prompts as (
+ select p.id, p.text, p.id = any(v_prompt_ids) as in_draft,
+ p.id in (select prompt_id from page_prompts) as cites_page
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = v_brand_id
+ and (p.id = any(v_prompt_ids) or p.id in (select prompt_id from page_prompts))
+ ),
+ answers as materialized (
+ select pr.id, pr.prompt_id, pr.platform, pr.mention_count, pr.search_queries
+ from public.prompt_results pr
+ where pr.brand_id = v_brand_id
+ and pr.created_at >= v_since
+ and pr.prompt_id in (select id from source_prompts)
+ and pr.platform is distinct from 'chatgpt-shopping'
+ ),
+ prompt_counts as (
+ select a.prompt_id, count(*) as answers, count(*) filter (where a.mention_count > 0) as mentioned
+ from answers a
+ group by a.prompt_id
+ ),
+ fanout_rows as (
+ select
+ a.id as answer_id,
+ lower(trim(regexp_replace(q.item->>'query', '\s+', ' ', 'g'))) as norm,
+ trim(regexp_replace(q.item->>'query', '\s+', ' ', 'g')) as query,
+ coalesce(nullif(q.item->>'source_platform', ''), a.platform) as platform
+ from answers a
+ cross join lateral jsonb_array_elements(
+ case when jsonb_typeof(a.search_queries) = 'array' then a.search_queries else '[]'::jsonb end
+ ) as q(item)
+ where coalesce(trim(q.item->>'query'), '') <> ''
+ ),
+ fanouts as (
+ select min(query) as query, array_agg(distinct platform order by platform) as platforms,
+ count(distinct answer_id) as searched
+ from fanout_rows
+ group by norm
+ order by count(distinct answer_id) desc, min(query)
+ limit 30
+ ),
+ -- Citations grouped by address first; only the top 20 addresses are read.
+ cited_ids as (
+ select prc.url_id, count(*) as citations, count(distinct a.id) as answers
+ from answers a
+ join public.prompt_result_citations prc
+ on prc.prompt_result_id = a.id
+ and prc.brand_id = v_brand_id
+ and prc.created_at >= v_since
+ group by prc.url_id
+ order by count(*) desc, count(distinct a.id) desc, prc.url_id
+ limit 20
+ ),
+ cited as (
+ select cu.url, cu.title, cu.domain, ci.citations, ci.answers
+ from cited_ids ci
+ join public.citation_urls cu on cu.id = ci.url_id
+ ),
+ queries as (
+ select g.query, sum(g.clicks)::bigint as clicks, sum(g.impressions)::bigint as impressions
+ from public.gsc_query_stats g
+ where g.brand_id = v_brand_id
+ and g.date >= (now() at time zone 'utc')::date - 28
+ group by g.query
+ order by sum(g.clicks) desc, sum(g.impressions) desc, g.query
+ limit 300
+ )
+ select jsonb_build_object(
+ 'prompts', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'id', sp.id,
+ 'text', sp.text,
+ 'inDraft', sp.in_draft,
+ 'citesPage', sp.cites_page,
+ 'answers', coalesce(pc.answers, 0),
+ 'mentioned', coalesce(pc.mentioned, 0)
+ ) order by sp.in_draft desc, sp.text)
+ from source_prompts sp
+ left join prompt_counts pc on pc.prompt_id = sp.id
+ ), '[]'::jsonb),
+ 'fanouts', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'query', f.query, 'platforms', to_jsonb(f.platforms), 'searched', f.searched
+ ) order by f.searched desc, f.query)
+ from fanouts f
+ ), '[]'::jsonb),
+ 'citedPages', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'url', c.url, 'title', c.title, 'domain', c.domain,
+ 'citations', c.citations, 'answers', c.answers
+ ) order by c.citations desc, c.answers desc, c.url)
+ from cited c
+ ), '[]'::jsonb),
+ 'gscQueries', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'query', q.query, 'clicks', q.clicks, 'impressions', q.impressions
+ ) order by q.clicks desc, q.impressions desc, q.query)
+ from queries q
+ ), '[]'::jsonb),
+ 'brandDomains', coalesce((select jsonb_agg(domain order by domain) from own_domains), '[]'::jsonb),
+ 'competitorDomains', coalesce((
+ select jsonb_agg(distinct lower(regexp_replace(c.domain, '^www\.', '')))
+ from public.competitors c
+ where c.brand_id = v_brand_id and coalesce(c.domain, '') <> ''
+ ), '[]'::jsonb)
+ ) into v_result;
+ return v_result;
+end;
+$$;
+
+revoke all on function public.content_draft_sources(uuid, integer) from public, anon;
+grant execute on function public.content_draft_sources(uuid, integer) to authenticated, service_role;
+
+comment on function public.content_draft_sources(uuid, integer) is
+ 'Content Editor (CE-008): a draft''s sources over the last N days — its prompts and those citing its page, their AI fan-out searches, the pages their answers cited, the brand''s Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft''s brand.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 8104cdbf5..3b0c39823 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -29542,3 +29542,288 @@ grant execute on function public.content_page_results(uuid, text, integer)
comment on function public.content_page_results(uuid, text, integer) is
'Content Editor (CE-016): one page''s AI visits per AI source over the last N whole UTC days (ending yesterday), with Google Analytics'' AI sessions landing on it, their key events, purchases and revenue. Security definer with an organization check.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00211_content_draft_sources.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00211: the sources a draft is built from, for the editor's Sources tab
+-- ============================================================================
+-- The Sources tab (Content Editor spec v2 §10, CE-008) names every source a
+-- draft draws on, with where the draft uses it, and lets a person leave one
+-- out or add their own.
+--
+-- content_draft_sources(draft, days) reads the brand's data over the last N
+-- days (30 by default) and returns one jsonb:
+-- * prompts: the draft's prompts (content_drafts.prompt_ids) and, for a
+-- draft optimizing a live page, the prompts whose answers cited that
+-- page; each with its answers in the window and those naming the brand;
+-- * fanouts: the searches AI engines ran while answering those prompts
+-- (prompt_results.search_queries, 00021), one row per normalized query
+-- with its platforms and the answers that ran it, most searched first
+-- (at most 30);
+-- * citedPages: the pages those answers cited, with citations and answers
+-- (at most 20); ChatGPT Shopping cards left out, as the Citations page
+-- does;
+-- * gscQueries: the brand's Search Console queries over 28 days with
+-- clicks and impressions (at most 300). Search Console keeps no queries
+-- per page, so the caller keeps the ones sharing words with the draft,
+-- as page-prompt-suggestions.js does;
+-- * brandDomains and competitorDomains, to name each cited page's kind.
+-- Security definer with an organization check through the draft's brand:
+-- citation_urls has no member select policy. The page a draft optimizes is
+-- its source URL's path on that URL's host, which must be one of the brand's
+-- domains: /pricing on another site of the brand's, or on a site not the
+-- brand's, isn't it. Prompts are the brand's through their prompt set, as
+-- everywhere else (a prompt needs no topic). Bounded by the brand and the
+-- window on (brand_id, created_at), with citations grouped by address before
+-- any address is read, and planned for each call's own values
+-- (plan_cache_mode).
+--
+-- content_draft_sources (the table) keeps a person's choices: a source left
+-- out (included false), and a page address or Search Console query added by
+-- hand (added true). A prompt added by hand joins the draft's prompt_ids.
+
+create table if not exists public.content_draft_sources (
+ draft_id uuid not null references public.content_drafts(id) on delete cascade,
+ kind text not null check (kind in ('prompt', 'fanout', 'cited_page', 'gsc_query')),
+ ref text not null check (char_length(ref) between 1 and 2048),
+ included boolean not null default true,
+ added boolean not null default false,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ primary key (draft_id, kind, ref),
+ -- Only pages and queries are added by hand; a prompt joins prompt_ids.
+ check (not added or kind in ('cited_page', 'gsc_query'))
+);
+
+alter table public.content_draft_sources enable row level security;
+
+-- A draft the member can read is one in their organization (content_drafts'
+-- own member policies), so the choices follow it.
+create policy "content_draft_sources: member select"
+ on public.content_draft_sources
+ for select
+ using (draft_id in (select d.id from public.content_drafts d));
+
+create policy "content_draft_sources: member insert"
+ on public.content_draft_sources
+ for insert
+ with check (draft_id in (select d.id from public.content_drafts d));
+
+create policy "content_draft_sources: member update"
+ on public.content_draft_sources
+ for update
+ using (draft_id in (select d.id from public.content_drafts d))
+ with check (draft_id in (select d.id from public.content_drafts d));
+
+create policy "content_draft_sources: member delete"
+ on public.content_draft_sources
+ for delete
+ using (draft_id in (select d.id from public.content_drafts d));
+
+grant select, insert, update, delete on public.content_draft_sources to authenticated;
+
+create or replace trigger content_draft_sources_updated_at
+ before update on public.content_draft_sources
+ for each row execute function public.handle_updated_at();
+
+comment on table public.content_draft_sources is
+ 'Content Editor (CE-008): a person''s choices on a draft''s sources — one left out (included false), or a page address or Search Console query added by hand (added true).';
+
+create or replace function public.content_draft_sources(
+ p_draft_id uuid,
+ p_days integer default 30
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_brand_id uuid;
+ v_prompt_ids uuid[];
+ v_page_key text;
+ v_host text;
+ v_since timestamptz;
+ v_result jsonb;
+begin
+ select d.brand_id, d.prompt_ids, lower(public.normalize_page_path(d.source_url)),
+ -- Lower-cased first: a scheme may be written HTTPS://.
+ regexp_replace(substring(lower(d.source_url) from '^https?://([^/:?#]+)'), '^www\.', '')
+ into v_brand_id, v_prompt_ids, v_page_key, v_host
+ from public.content_drafts d
+ where d.id = p_draft_id;
+
+ if v_brand_id is null or (
+ not exists (
+ select 1 from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = v_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 > 90 then
+ raise exception 'content_draft_sources: 1 to 90 days are needed' using errcode = '22023';
+ end if;
+
+ v_since := now() - make_interval(days => p_days);
+ -- A page on a site that isn't the brand's is no page of the brand's.
+ if v_host is null or not exists (
+ select 1 from public.brand_domains bd
+ where bd.brand_id = v_brand_id
+ and lower(regexp_replace(bd.domain, '^www\.', '')) = v_host
+ ) then
+ v_page_key := null;
+ end if;
+
+ with own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = v_brand_id
+ ),
+ -- The page's addresses: its path on its host.
+ page_urls as materialized (
+ select cu.id
+ from public.citation_urls cu
+ where v_page_key is not null
+ and cu.domain = v_host
+ and lower(public.normalize_page_path(cu.url)) = v_page_key
+ ),
+ -- The window's answers, from idx_prompt_results_brand_created_cover alone:
+ -- only for a draft with a page, to find the prompts citing it.
+ window_answers as materialized (
+ select pr.id, pr.prompt_id
+ from public.prompt_results pr
+ where v_page_key is not null
+ and pr.brand_id = v_brand_id
+ and pr.created_at >= v_since
+ and pr.platform is distinct from 'chatgpt-shopping'
+ ),
+ -- The prompts whose answers cited the page the draft optimizes.
+ page_prompts as (
+ select distinct wa.prompt_id
+ from public.prompt_result_citations prc
+ join window_answers wa on wa.id = prc.prompt_result_id
+ where prc.url_id in (select pu.id from page_urls pu)
+ and prc.brand_id = v_brand_id
+ and prc.created_at >= v_since
+ ),
+ source_prompts as (
+ select p.id, p.text, p.id = any(v_prompt_ids) as in_draft,
+ p.id in (select prompt_id from page_prompts) as cites_page
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = v_brand_id
+ and (p.id = any(v_prompt_ids) or p.id in (select prompt_id from page_prompts))
+ ),
+ answers as materialized (
+ select pr.id, pr.prompt_id, pr.platform, pr.mention_count, pr.search_queries
+ from public.prompt_results pr
+ where pr.brand_id = v_brand_id
+ and pr.created_at >= v_since
+ and pr.prompt_id in (select id from source_prompts)
+ and pr.platform is distinct from 'chatgpt-shopping'
+ ),
+ prompt_counts as (
+ select a.prompt_id, count(*) as answers, count(*) filter (where a.mention_count > 0) as mentioned
+ from answers a
+ group by a.prompt_id
+ ),
+ fanout_rows as (
+ select
+ a.id as answer_id,
+ lower(trim(regexp_replace(q.item->>'query', '\s+', ' ', 'g'))) as norm,
+ trim(regexp_replace(q.item->>'query', '\s+', ' ', 'g')) as query,
+ coalesce(nullif(q.item->>'source_platform', ''), a.platform) as platform
+ from answers a
+ cross join lateral jsonb_array_elements(
+ case when jsonb_typeof(a.search_queries) = 'array' then a.search_queries else '[]'::jsonb end
+ ) as q(item)
+ where coalesce(trim(q.item->>'query'), '') <> ''
+ ),
+ fanouts as (
+ select min(query) as query, array_agg(distinct platform order by platform) as platforms,
+ count(distinct answer_id) as searched
+ from fanout_rows
+ group by norm
+ order by count(distinct answer_id) desc, min(query)
+ limit 30
+ ),
+ -- Citations grouped by address first; only the top 20 addresses are read.
+ cited_ids as (
+ select prc.url_id, count(*) as citations, count(distinct a.id) as answers
+ from answers a
+ join public.prompt_result_citations prc
+ on prc.prompt_result_id = a.id
+ and prc.brand_id = v_brand_id
+ and prc.created_at >= v_since
+ group by prc.url_id
+ order by count(*) desc, count(distinct a.id) desc, prc.url_id
+ limit 20
+ ),
+ cited as (
+ select cu.url, cu.title, cu.domain, ci.citations, ci.answers
+ from cited_ids ci
+ join public.citation_urls cu on cu.id = ci.url_id
+ ),
+ queries as (
+ select g.query, sum(g.clicks)::bigint as clicks, sum(g.impressions)::bigint as impressions
+ from public.gsc_query_stats g
+ where g.brand_id = v_brand_id
+ and g.date >= (now() at time zone 'utc')::date - 28
+ group by g.query
+ order by sum(g.clicks) desc, sum(g.impressions) desc, g.query
+ limit 300
+ )
+ select jsonb_build_object(
+ 'prompts', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'id', sp.id,
+ 'text', sp.text,
+ 'inDraft', sp.in_draft,
+ 'citesPage', sp.cites_page,
+ 'answers', coalesce(pc.answers, 0),
+ 'mentioned', coalesce(pc.mentioned, 0)
+ ) order by sp.in_draft desc, sp.text)
+ from source_prompts sp
+ left join prompt_counts pc on pc.prompt_id = sp.id
+ ), '[]'::jsonb),
+ 'fanouts', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'query', f.query, 'platforms', to_jsonb(f.platforms), 'searched', f.searched
+ ) order by f.searched desc, f.query)
+ from fanouts f
+ ), '[]'::jsonb),
+ 'citedPages', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'url', c.url, 'title', c.title, 'domain', c.domain,
+ 'citations', c.citations, 'answers', c.answers
+ ) order by c.citations desc, c.answers desc, c.url)
+ from cited c
+ ), '[]'::jsonb),
+ 'gscQueries', coalesce((
+ select jsonb_agg(jsonb_build_object(
+ 'query', q.query, 'clicks', q.clicks, 'impressions', q.impressions
+ ) order by q.clicks desc, q.impressions desc, q.query)
+ from queries q
+ ), '[]'::jsonb),
+ 'brandDomains', coalesce((select jsonb_agg(domain order by domain) from own_domains), '[]'::jsonb),
+ 'competitorDomains', coalesce((
+ select jsonb_agg(distinct lower(regexp_replace(c.domain, '^www\.', '')))
+ from public.competitors c
+ where c.brand_id = v_brand_id and coalesce(c.domain, '') <> ''
+ ), '[]'::jsonb)
+ ) into v_result;
+ return v_result;
+end;
+$$;
+
+revoke all on function public.content_draft_sources(uuid, integer) from public, anon;
+grant execute on function public.content_draft_sources(uuid, integer) to authenticated, service_role;
+
+comment on function public.content_draft_sources(uuid, integer) is
+ 'Content Editor (CE-008): a draft''s sources over the last N days — its prompts and those citing its page, their AI fan-out searches, the pages their answers cited, the brand''s Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft''s brand.';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 83edaa8f4..2f59d8893 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3416,7 +3416,8 @@
"show": "Show side panel",
"hide": "Hide side panel",
"tabs": {
- "impact": "Impact"
+ "impact": "Impact",
+ "sources": "Sources"
}
},
"impact": {
@@ -3482,6 +3483,82 @@
},
"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."
+ },
+ "sources": {
+ "loadError": "Couldn't load the sources.",
+ "retry": "Retry",
+ "summary": "{count, plural, one {Built from # source} other {Built from # sources}}",
+ "summaryParts": "{prompts, plural, one {# prompt} other {# prompts}} · {fanouts, plural, one {# fan-out} other {# fan-outs}} · {pages, plural, one {# cited page} other {# cited pages}} · {queries, plural, one {# Search Console query} other {# Search Console queries}}",
+ "hint": "Each source shows where the draft uses it. Uncheck one to leave it out of the brief and the agent's work.",
+ "empty": "No sources yet. Add a prompt, a page or a Search Console query.",
+ "toggleFailed": "Couldn't change the source. Try again.",
+ "include": "Use {name}",
+ "usedInHint": "Where the draft uses this source, as written now",
+ "groups": {
+ "prompt": "Prompts",
+ "fanout": "Fan-outs",
+ "cited_page": "Cited pages (what AI quotes today)",
+ "gsc_query": "Search Console"
+ },
+ "detail": {
+ "answers": "{count, plural, one {# answer} other {# answers}}",
+ "named": "you're named in {count}",
+ "citesPage": "cites this page",
+ "searched": "searched {count}×",
+ "citations": "{count, plural, one {# citation} other {# citations}}",
+ "clicks": "{count, plural, one {# click} other {# clicks}}",
+ "impressions": "{count, plural, one {# impression} other {# impressions}}",
+ "added": "added by you",
+ "categories": {
+ "you": "yours",
+ "competitor": "competitor",
+ "editorial": "publication",
+ "forum": "forum",
+ "social": "social",
+ "review": "review site",
+ "institutional": "institution",
+ "other": "other"
+ }
+ },
+ "usedIn": {
+ "none": "Not used",
+ "h1": "H1",
+ "heading": "H{level} · {text}",
+ "paragraph": "Paragraph {index}",
+ "thisPage": "This page",
+ "internalLink": "Internal link",
+ "outboundLink": "Outbound link"
+ },
+ "add": {
+ "button": "Add source",
+ "title": "Add a source",
+ "description": "A prompt joins the draft's prompts, with its fan-outs and cited pages. A page or a Search Console query is kept as added by you.",
+ "kinds": {
+ "prompt": "Prompt",
+ "cited_page": "Page URL",
+ "gsc_query": "Search Console query"
+ },
+ "placeholders": {
+ "prompt": "Pick a prompt",
+ "cited_page": "Page address",
+ "gsc_query": "Pick a query"
+ },
+ "urlLabel": "Page address",
+ "search": "Search…",
+ "loading": "Loading…",
+ "empty": {
+ "prompt": "No other prompts.",
+ "cited_page": "No pages.",
+ "gsc_query": "No other Search Console queries."
+ },
+ "promptsFailed": "Couldn't load the prompts.",
+ "clicks": "{count, plural, one {# click} other {# clicks}}",
+ "gscHint": "{count, plural, one {The brand's Search Console query over the last 28 days.} other {The brand's # Search Console queries over the last 28 days, the most clicked first.}}",
+ "cancel": "Cancel",
+ "submit": "Add",
+ "added": "Source added",
+ "failed": "Couldn't add the source. Try again."
+ }
}
},
"status": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_add-source-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_add-source-dialog.tsx
new file mode 100644
index 000000000..01bb88892
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_add-source-dialog.tsx
@@ -0,0 +1,247 @@
+'use client';
+
+import { useEffect, useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Loader2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ Combobox,
+ ComboboxCollection,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxTrigger,
+ ComboboxValue,
+} from '@/components/ui/combobox';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import {
+ addDraftSource,
+ getContentStartOptions,
+ type AddedDraftSource,
+} from '@/lib/actions/content-drafts';
+import { normalizeQuery, type DraftSourcesData } from '@/lib/content/sources';
+
+const ADD_KINDS = ['prompt', 'cited_page', 'gsc_query'] as const;
+type AddKind = (typeof ADD_KINDS)[number];
+
+interface PickerItem {
+ value: string;
+ label: string;
+ meta?: string;
+}
+
+/**
+ * + Add source (CE-008): one of the brand's prompts (it joins the draft's
+ * prompts), a page's address, or one of the brand's Search Console queries.
+ * Files wait for workspace files (CHAT-06).
+ */
+export function AddSourceDialog({
+ open,
+ onOpenChange,
+ draftId,
+ brandId,
+ gscQueries,
+ listed,
+ onAdded,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ draftId: string;
+ brandId: string;
+ gscQueries: DraftSourcesData['gscQueries'];
+ /** `kind:ref` of the sources listed already, left out of the pickers. */
+ listed: string[];
+ onAdded: () => void;
+}) {
+ const t = useTranslations('contentEditor.editor.sources.add');
+ const [kind, setKind] = useState<AddKind>('prompt');
+ const [prompts, setPrompts] = useState<PickerItem[] | null>(null);
+ const [promptsFailed, setPromptsFailed] = useState(false);
+ const [picked, setPicked] = useState<PickerItem | null>(null);
+ const [url, setUrl] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ if (!open || prompts) return;
+ let cancelled = false;
+ getContentStartOptions(brandId)
+ .then((options) => {
+ if (!cancelled) setPrompts(options.prompts.map((p) => ({ value: p.id, label: p.text })));
+ })
+ .catch((err) => {
+ console.error('Failed to read the prompts:', err);
+ if (!cancelled) setPromptsFailed(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, prompts, brandId]);
+
+ const items = useMemo(() => {
+ const taken = new Set(listed);
+ if (kind === 'prompt') return (prompts ?? []).filter((p) => !taken.has(`prompt:${p.value}`));
+ if (kind === 'gsc_query') {
+ return gscQueries
+ .map((q) => ({
+ value: normalizeQuery(q.query),
+ label: q.query,
+ meta: t('clicks', { count: q.clicks }),
+ }))
+ .filter((q) => !taken.has(`gsc_query:${q.value}`));
+ }
+ return [];
+ }, [kind, prompts, gscQueries, listed, t]);
+
+ const validUrl = (() => {
+ try {
+ return /^https?:$/.test(new URL(url.trim()).protocol);
+ } catch {
+ return false;
+ }
+ })();
+
+ const close = (next: boolean) => {
+ onOpenChange(next);
+ if (!next) {
+ setPicked(null);
+ setUrl('');
+ }
+ };
+
+ const add = async () => {
+ let source: AddedDraftSource;
+ if (kind === 'cited_page') {
+ if (!validUrl) return;
+ source = { kind, url: url.trim() };
+ } else if (kind === 'prompt') {
+ if (!picked) return;
+ source = { kind, promptId: picked.value };
+ } else {
+ if (!picked) return;
+ source = { kind, query: picked.label };
+ }
+ setSaving(true);
+ try {
+ await addDraftSource(draftId, source);
+ toast.success(t('added'));
+ onAdded();
+ close(false);
+ } catch (err) {
+ console.error('Failed to add a draft source:', err);
+ toast.error(t('failed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const ready = kind === 'cited_page' ? validUrl : picked !== null;
+
+ return (
+ <Dialog open={open} onOpenChange={close}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{t('title')}</DialogTitle>
+ <DialogDescription>{t('description')}</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3">
+ <Tabs
+ value={kind}
+ onValueChange={(value) => {
+ setKind(value as AddKind);
+ setPicked(null);
+ }}
+ >
+ <TabsList>
+ {ADD_KINDS.map((value) => (
+ <TabsTrigger key={value} value={value}>
+ {t(`kinds.${value}`)}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+
+ {kind === 'cited_page' ? (
+ <Input
+ type="url"
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ placeholder="https://"
+ aria-label={t('urlLabel')}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && validUrl) void add();
+ }}
+ />
+ ) : kind === 'prompt' && promptsFailed ? (
+ <p className="text-xs text-destructive">{t('promptsFailed')}</p>
+ ) : (
+ <Combobox
+ items={items}
+ value={picked}
+ onValueChange={(item: PickerItem | null) => setPicked(item)}
+ disabled={kind === 'prompt' && !prompts}
+ >
+ <ComboboxTrigger
+ className="w-full"
+ aria-label={t(`placeholders.${kind}`)}
+ title={picked?.label}
+ >
+ {kind === 'prompt' && !prompts ? (
+ <span className="flex items-center gap-2 text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t('loading')}
+ </span>
+ ) : (
+ <ComboboxValue placeholder={t(`placeholders.${kind}`)} />
+ )}
+ </ComboboxTrigger>
+ <ComboboxContent>
+ <ComboboxInput placeholder={t('search')} />
+ <ComboboxList>
+ <ComboboxEmpty>{t(`empty.${kind}`)}</ComboboxEmpty>
+ <ComboboxCollection>
+ {(item: PickerItem) => (
+ <ComboboxItem key={item.value} value={item} title={item.label}>
+ <span className="min-w-0 flex-1 truncate">{item.label}</span>
+ {item.meta && (
+ <span className="shrink-0 text-xs text-muted-foreground">
+ {item.meta}
+ </span>
+ )}
+ </ComboboxItem>
+ )}
+ </ComboboxCollection>
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )}
+ {kind === 'gsc_query' && gscQueries.length > 0 && (
+ <p className="text-xs text-muted-foreground">
+ {t('gscHint', { count: gscQueries.length })}
+ </p>
+ )}
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => close(false)}>
+ {t('cancel')}
+ </Button>
+ <Button disabled={!ready || saving} onClick={() => void add()}>
+ {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {t('submit')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
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 f7454a5a2..7d7f43c74 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
@@ -22,7 +22,12 @@ import {
htmlFromSource,
publishableHtml,
} from '@/lib/content/clean-html';
-import { draftTitleFromDoc, lengthTarget, safeLinkHref } from '@/lib/content/editor';
+import {
+ PAGE_READ_DELAY_MS,
+ draftTitleFromDoc,
+ lengthTarget,
+ safeLinkHref,
+} from '@/lib/content/editor';
import { JsonLd } from '@/lib/content/json-ld-node';
import { detectPageType } from '@/lib/content/page-types';
import { cn } from '@/lib/utils';
@@ -63,12 +68,16 @@ const DOCUMENT_CLASS = cn(
* 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). The side panel, open
* beside the page or closed from the header, shows what the page earns
- * (Impact, CE-016).
+ * (Impact, CE-016) and the sources it draws on (Sources, CE-008).
*/
export function DraftEditor({ draft }: { draft: ContentDraft }) {
const t = useTranslations('contentEditor.editor');
const autosave = useDraftAutosave(draft.id, draft);
const [title, setTitle] = useState(draft.title);
+ // The page as written now, for the side panel's Sources.
+ const [pageHtml, setPageHtml] = useState(draft.bodyHtml);
+ const pageReadTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
+ useEffect(() => () => clearTimeout(pageReadTimer.current), []);
const [status, setStatus] = useState(draft.status);
const [marking, setMarking] = useState(false);
// A picked page type, or the one the page shows as it is written.
@@ -157,8 +166,13 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
const next = draftTitleFromDoc(e.getJSON());
const bodyHtml = e.getHTML();
setTitle(next);
- setDetectedType(detectPageType({ title: next, html: bodyHtml }, draft.siteType));
autosave.schedule({ title: next, bodyHtml });
+ // The panel and the type chip catch up once typing pauses.
+ clearTimeout(pageReadTimer.current);
+ pageReadTimer.current = setTimeout(() => {
+ setPageHtml(bodyHtml);
+ setDetectedType(detectPageType({ title: next, html: bodyHtml }, draft.siteType));
+ }, PAGE_READ_DELAY_MS);
},
});
@@ -395,7 +409,7 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
</div>
{attachments.ui}
</div>
- {panelOpen && <EditorSidePanel draft={draft} />}
+ {panelOpen && <EditorSidePanel draft={draft} title={title} bodyHtml={pageHtml} />}
</div>
</div>
);
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
index fe19647e3..1e37c8ec0 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 { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import type { ContentDraft } from '@/lib/content/drafts';
import { ImpactTab } from './_impact-tab';
+import { SourcesTab } from './_sources-tab';
/** Remembers whether the panel is open, across drafts and visits. */
const PANEL_OPEN_KEY = 'aeo:content-editor-panel';
@@ -38,22 +39,63 @@ export function useSidePanelOpen(): [boolean, () => void] {
return [open, toggle];
}
+const PANEL_TABS = ['impact', 'sources'] as const;
+type PanelTab = (typeof PANEL_TABS)[number];
+
/**
* 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).
+ * panel with the update that makes it work: Impact (CE-016), then Sources
+ * (CE-008). A tab opened once stays mounted, so switching back keeps it as
+ * it was.
*/
-export function EditorSidePanel({ draft }: { draft: ContentDraft }) {
+export function EditorSidePanel({
+ draft,
+ title,
+ bodyHtml,
+}: {
+ draft: ContentDraft;
+ /** The draft's title and page as written now: Sources says where each source is used. */
+ title: string;
+ bodyHtml: string;
+}) {
const t = useTranslations('contentEditor.editor.panel');
+ const [tab, setTab] = useState<PanelTab>('impact');
+ const [opened, setOpened] = useState<Set<PanelTab>>(() => new Set(['impact']));
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">
+ <Tabs
+ value={tab}
+ onValueChange={(value) => {
+ const next = value as PanelTab;
+ setTab(next);
+ setOpened((prev) => (prev.has(next) ? prev : new Set([...prev, next])));
+ }}
+ className="border-b px-3 pt-1.5"
+ >
<TabsList variant="line">
- <TabsTrigger value="impact">{t('tabs.impact')}</TabsTrigger>
+ {PANEL_TABS.map((value) => (
+ <TabsTrigger key={value} value={value}>
+ {t(`tabs.${value}`)}
+ </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 hidden={tab !== 'impact'}>
+ <ImpactTab brandId={draft.brandId} pageUrl={draft.sourceUrl} />
+ </div>
+ {opened.has('sources') && (
+ <div hidden={tab !== 'sources'}>
+ <SourcesTab
+ draftId={draft.id}
+ brandId={draft.brandId}
+ title={title}
+ sourceUrl={draft.sourceUrl}
+ bodyHtml={bodyHtml}
+ />
+ </div>
+ )}
</div>
</aside>
);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
new file mode 100644
index 000000000..1bf5944fc
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
@@ -0,0 +1,252 @@
+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 { DraftSourceChoice, DraftSourcesData } from '@/lib/content/sources';
+import { SourcesTab } from './_sources-tab';
+
+const getDraftSources = vi.fn();
+const setDraftSourceIncluded = vi.fn();
+const addDraftSource = vi.fn();
+const getContentStartOptions = vi.fn();
+vi.mock('@/lib/actions/content-drafts', () => ({
+ getDraftSources: (...args: unknown[]) => getDraftSources(...args),
+ setDraftSourceIncluded: (...args: unknown[]) => setDraftSourceIncluded(...args),
+ addDraftSource: (...args: unknown[]) => addDraftSource(...args),
+ getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),
+}));
+const toast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const PAGE = 'https://acme-coffee.example.com/guides/espresso';
+
+const data = (over: Partial<DraftSourcesData> = {}): DraftSourcesData => ({
+ prompts: [
+ {
+ id: 'p1',
+ text: 'Best espresso machines under $500?',
+ inDraft: true,
+ citesPage: false,
+ answers: 21,
+ mentioned: 4,
+ },
+ ],
+ fanouts: [{ query: 'home espresso grinder', platforms: ['perplexity-web'], searched: 3 }],
+ citedPages: [
+ {
+ url: 'https://www.reddit.com/r/espresso/x',
+ title: 'Thread',
+ domain: 'reddit.com',
+ citations: 12,
+ answers: 9,
+ },
+ ],
+ gscQueries: [
+ { query: 'espresso machine under 500', clicks: 40, impressions: 900 },
+ { query: 'coffee subscription', clicks: 12, impressions: 300 },
+ ],
+ brandDomains: ['acme-coffee.example.com'],
+ competitorDomains: [],
+ ...over,
+});
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render(
+ bodyHtml = '<h1>The home espresso guide</h1>',
+ choices: DraftSourceChoice[] = [],
+) {
+ getDraftSources.mockResolvedValue({ data: data(), choices });
+ await act(async () => {
+ root.render(<Tab bodyHtml={bodyHtml} />);
+ });
+}
+
+function Tab({ bodyHtml }: { bodyHtml: string }) {
+ return (
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <SourcesTab
+ draftId="d1"
+ brandId="b1"
+ title="The home espresso guide"
+ sourceUrl={PAGE}
+ bodyHtml={bodyHtml}
+ />
+ </NextIntlClientProvider>
+ );
+}
+
+const rows = () =>
+ [...container.querySelectorAll('li')].map((li) => ({
+ text: li.textContent,
+ checked: li.querySelector('[role="checkbox"]')?.getAttribute('aria-checked'),
+ }));
+const checkbox = (name: string) =>
+ container.querySelector<HTMLElement>(`[role="checkbox"][aria-label="Use ${name}"]`)!;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ getDraftSources.mockReset();
+ setDraftSourceIncluded.mockReset().mockResolvedValue(undefined);
+ addDraftSource.mockReset().mockResolvedValue(undefined);
+ getContentStartOptions
+ .mockReset()
+ .mockResolvedValue({ opportunities: [], prompts: [], topics: [] });
+ toast.mockReset();
+ toast.success.mockReset();
+ toast.error.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('the Sources tab', () => {
+ it('names every source with its numbers and where the draft uses it', async () => {
+ await render(
+ '<h1>The home espresso guide</h1><h2>Best espresso machines under $500</h2>' +
+ '<p>Read <a href="https://reddit.com/r/espresso/x">the thread</a>.</p>',
+ );
+
+ expect(getDraftSources).toHaveBeenCalledWith('d1');
+ expect(container.textContent).toContain('Built from 4 sources');
+ expect(container.textContent).toContain(
+ '1 prompt · 1 fan-out · 1 cited page · 1 Search Console query',
+ );
+ expect(rows()).toEqual([
+ {
+ text: "Best espresso machines under $500?21 answers · you're named in 4H2 · Best espresso machines under $500",
+ checked: 'true',
+ },
+ { text: 'home espresso grinderPerplexity · searched 3×Not used', checked: 'true' },
+ {
+ text: 'https://www.reddit.com/r/espresso/x12 citations · forumOutbound link',
+ checked: 'true',
+ },
+ {
+ text: 'espresso machine under 50040 clicks · 900 impressionsH2 · Best espresso machines under $500',
+ checked: 'true',
+ },
+ ]);
+ });
+
+ it('follows the page as it is written', async () => {
+ await render();
+ expect(rows()[1].text).toContain('Not used');
+ await act(async () => {
+ root.render(<Tab bodyHtml="<h1>Guide</h1><p>Buy a home espresso grinder first.</p>" />);
+ });
+ expect(rows()[1].text).toContain('Paragraph 1');
+ });
+
+ it('leaves a source out when it is unchecked, and keeps it in when that fails', async () => {
+ await render();
+ await act(async () => checkbox('home espresso grinder').click());
+ expect(setDraftSourceIncluded).toHaveBeenCalledWith('d1', {
+ kind: 'fanout',
+ ref: 'home espresso grinder',
+ included: false,
+ });
+ expect(rows()[1].checked).toBe('false');
+ expect(container.textContent).toContain('Built from 3 sources');
+
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ setDraftSourceIncluded.mockRejectedValueOnce(new Error('boom'));
+ await act(async () => checkbox('home espresso grinder').click());
+ expect(rows()[1].checked).toBe('false');
+ expect(toast.error).toHaveBeenCalledWith("Couldn't change the source. Try again.");
+ });
+
+ it('changes each row on its own, and puts back only the one that failed', async () => {
+ await render();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ let fail!: (err: Error) => void;
+ setDraftSourceIncluded
+ .mockImplementationOnce(() => new Promise((_, reject) => (fail = reject)))
+ .mockResolvedValueOnce(undefined);
+ // Two quick toggles: the second doesn't undo the first.
+ await act(async () => {
+ checkbox('home espresso grinder').click();
+ checkbox('Best espresso machines under $500?').click();
+ });
+ expect(rows()[1].checked).toBe('false');
+ expect(rows()[0].checked).toBe('false');
+
+ // The first one fails: only its row goes back.
+ await act(async () => fail(new Error('boom')));
+ expect(rows()[1].checked).toBe('true');
+ expect(rows()[0].checked).toBe('false');
+ });
+
+ it('lists a source left out unchecked', async () => {
+ await render(undefined, [{ kind: 'prompt', ref: 'p1', included: false, added: false }]);
+ expect(rows()[0].checked).toBe('false');
+ expect(container.textContent).toContain('Built from 3 sources');
+ });
+
+ it('adds a page by its address and reads the sources again', async () => {
+ await render();
+ const addButton = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Add source',
+ )!;
+ await act(async () => addButton.click());
+ const tab = [...document.querySelectorAll<HTMLElement>('[role="tab"]')].find(
+ (b) => b.textContent === 'Page URL',
+ )!;
+ await act(async () => {
+ tab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ tab.click();
+ });
+ const input = document.querySelector<HTMLInputElement>('input[aria-label="Page address"]')!;
+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setValue.call(input, 'https://example.org/espresso-study');
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ const submit = [...document.querySelectorAll('button')].find((b) => b.textContent === 'Add')!;
+ await act(async () => submit.click());
+
+ expect(addDraftSource).toHaveBeenCalledWith('d1', {
+ kind: 'cited_page',
+ url: 'https://example.org/espresso-study',
+ });
+ expect(toast.success).toHaveBeenCalledWith('Source added');
+ expect(getDraftSources).toHaveBeenCalledTimes(2);
+ });
+
+ it('offers to retry when the sources can’t be read', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ getDraftSources.mockRejectedValueOnce(new Error('boom'));
+ await act(async () => {
+ root.render(<Tab bodyHtml="" />);
+ });
+ expect(container.textContent).toContain("Couldn't load the sources.");
+
+ getDraftSources.mockResolvedValue({ data: data(), choices: [] });
+ const retry = [...container.querySelectorAll('button')].find((b) => b.textContent === 'Retry')!;
+ await act(async () => retry.click());
+ expect(container.textContent).toContain('Built from 4 sources');
+ });
+
+ it('says when there is nothing to list', async () => {
+ getDraftSources.mockResolvedValue({
+ data: data({ prompts: [], fanouts: [], citedPages: [], gscQueries: [] }),
+ choices: [],
+ });
+ await act(async () => {
+ root.render(<Tab bodyHtml="" />);
+ });
+ expect(container.textContent).toContain('No sources yet.');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
new file mode 100644
index 000000000..f4a2a9292
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
@@ -0,0 +1,282 @@
+'use client';
+
+import { useDeferredValue, useEffect, useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Loader2, Plus } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import { getDraftSources, setDraftSourceIncluded } from '@/lib/actions/content-drafts';
+import { platformNames } from '@/lib/content/impact';
+import {
+ buildSourceGroups,
+ includedCounts,
+ readDraftDoc,
+ usedIn,
+ type DraftSourceChoice,
+ type DraftSourceRow,
+ type DraftSourcesData,
+ type UsedIn,
+} from '@/lib/content/sources';
+import { formatNumber } from '@/lib/format';
+import { cn } from '@/lib/utils';
+import { AddSourceDialog } from './_add-source-dialog';
+
+type SourcesRead =
+ | { data: DraftSourcesData; choices: DraftSourceChoice[]; failed: false }
+ | { data: null; choices: []; failed: true };
+
+/**
+ * The Sources tab (Content Editor CE-008, spec §10): every source the draft
+ * draws on, by name, grouped — its prompts, the searches AI ran for them, the
+ * pages their answers cite, and the brand's Search Console queries — each
+ * with its numbers and where the draft uses it as written now. A person
+ * unchecks a source to leave it out, or adds a prompt, a page or a query.
+ */
+export function SourcesTab({
+ draftId,
+ brandId,
+ title,
+ sourceUrl,
+ bodyHtml,
+}: {
+ draftId: string;
+ brandId: string;
+ title: string;
+ sourceUrl: string | null;
+ bodyHtml: string;
+}) {
+ const t = useTranslations('contentEditor.editor.sources');
+ const [read, setRead] = useState<SourcesRead | null>(null);
+ const [attempt, setAttempt] = useState(0);
+ const [adding, setAdding] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ getDraftSources(draftId)
+ .then((result) => {
+ if (cancelled) return;
+ setRead(
+ result
+ ? { data: result.data, choices: result.choices, failed: false }
+ : { data: null, choices: [], failed: true },
+ );
+ })
+ .catch((err) => {
+ console.error('Failed to read the draft sources:', err);
+ if (!cancelled) setRead({ data: null, choices: [], failed: true });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [draftId, attempt]);
+
+ // Where each source is used follows the page as it is written, a beat behind typing.
+ const html = useDeferredValue(bodyHtml);
+ const doc = useMemo(() => readDraftDoc(html), [html]);
+ const groups = useMemo(
+ () => (read?.data ? buildSourceGroups(read.data, read.choices, { title, sourceUrl }) : []),
+ [read, title, sourceUrl],
+ );
+
+ if (!read) {
+ return (
+ <div className="flex justify-center py-8" aria-busy="true">
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
+ </div>
+ );
+ }
+ if (read.failed) {
+ return (
+ <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>
+ );
+ }
+
+ const counts = includedCounts(groups);
+ const total = Object.values(counts).reduce((a, b) => a + b, 0);
+ const listed = groups.reduce((n, g) => n + g.rows.length, 0);
+
+ // Each toggle changes its own row from the latest state, so quick toggles
+ // don't overwrite each other, and a failed one puts back only that row.
+ const toggle = async (row: DraftSourceRow, included: boolean) => {
+ const isRow = (c: DraftSourceChoice) => c.kind === row.kind && c.ref === row.ref;
+ const before = read.choices.find(isRow);
+ const withRow =
+ (choice: DraftSourceChoice | undefined) =>
+ (prev: SourcesRead | null): SourcesRead | null =>
+ prev && !prev.failed
+ ? {
+ ...prev,
+ choices: [...prev.choices.filter((c) => !isRow(c)), ...(choice ? [choice] : [])],
+ }
+ : prev;
+ setRead(withRow({ kind: row.kind, ref: row.ref, included, added: row.added }));
+ try {
+ await setDraftSourceIncluded(draftId, { kind: row.kind, ref: row.ref, included });
+ } catch (err) {
+ console.error('Failed to change a draft source:', err);
+ setRead(withRow(before));
+ toast.error(t('toggleFailed'));
+ }
+ };
+
+ return (
+ <div className="space-y-4 text-sm">
+ <div className="space-y-1 rounded-lg bg-muted/50 px-3 py-2">
+ <p className="font-medium">{t('summary', { count: total })}</p>
+ <p className="text-xs text-muted-foreground">
+ {t('summaryParts', {
+ prompts: counts.prompt,
+ fanouts: counts.fanout,
+ pages: counts.cited_page,
+ queries: counts.gsc_query,
+ })}
+ </p>
+ <p className="text-xs text-muted-foreground">{t('hint')}</p>
+ </div>
+
+ {listed === 0 ? (
+ <p className="text-xs text-muted-foreground">{t('empty')}</p>
+ ) : (
+ groups.map((group) =>
+ group.rows.length === 0 ? null : (
+ <section key={group.kind} className="space-y-1.5">
+ <h4 className="text-xs font-medium text-muted-foreground">
+ {t(`groups.${group.kind}`)}{' '}
+ <span className="font-normal">· {formatNumber(group.rows.length)}</span>
+ </h4>
+ <ul className="divide-y rounded-lg border">
+ {group.rows.map((row) => (
+ <SourceRow
+ key={`${row.kind}:${row.ref}`}
+ row={row}
+ used={usedIn(row, doc, { sourceUrl })}
+ onToggle={(included) => void toggle(row, included)}
+ />
+ ))}
+ </ul>
+ </section>
+ ),
+ )
+ )}
+
+ <Button variant="outline" size="sm" onClick={() => setAdding(true)}>
+ <Plus className="h-3.5 w-3.5" />
+ {t('add.button')}
+ </Button>
+ <AddSourceDialog
+ open={adding}
+ onOpenChange={setAdding}
+ draftId={draftId}
+ brandId={brandId}
+ gscQueries={read.data.gscQueries}
+ listed={groups.flatMap((g) => g.rows.map((r) => `${r.kind}:${r.ref}`))}
+ onAdded={() => setAttempt((n) => n + 1)}
+ />
+ </div>
+ );
+}
+
+function SourceRow({
+ row,
+ used,
+ onToggle,
+}: {
+ row: DraftSourceRow;
+ used: UsedIn | null;
+ onToggle: (included: boolean) => void;
+}) {
+ const t = useTranslations('contentEditor.editor.sources');
+ return (
+ <li className={cn('flex items-start gap-2.5 px-3 py-2', !row.included && 'opacity-60')}>
+ <Checkbox
+ className="mt-0.5"
+ checked={row.included}
+ onCheckedChange={(checked) => onToggle(checked === true)}
+ aria-label={t('include', { name: row.name })}
+ />
+ <div className="min-w-0 flex-1">
+ <p
+ className={cn(
+ 'line-clamp-2 text-xs font-medium',
+ row.kind === 'cited_page' ? 'break-all' : 'break-words',
+ )}
+ title={row.name}
+ >
+ {row.name}
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ <SourceDetail row={row} />
+ </p>
+ </div>
+ <span
+ className={cn(
+ 'max-w-[38%] shrink-0 truncate rounded-md px-1.5 py-0.5 text-[11px]',
+ used ? 'bg-muted text-foreground' : 'text-muted-foreground',
+ )}
+ title={t('usedInHint')}
+ >
+ <UsedInLabel used={used} />
+ </span>
+ </li>
+ );
+}
+
+function SourceDetail({ row }: { row: DraftSourceRow }) {
+ const t = useTranslations('contentEditor.editor.sources.detail');
+ const parts: string[] = [];
+ switch (row.kind) {
+ case 'prompt':
+ parts.push(t('answers', { count: row.answers }), t('named', { count: row.mentioned }));
+ if (row.citesPage) parts.push(t('citesPage'));
+ break;
+ case 'fanout':
+ parts.push(platformNames(row.platforms).join(', '), t('searched', { count: row.searched }));
+ break;
+ case 'cited_page':
+ if (row.citations !== null) parts.push(t('citations', { count: row.citations }));
+ parts.push(t(`categories.${row.category}`));
+ break;
+ case 'gsc_query':
+ if (row.clicks !== null && row.impressions !== null) {
+ parts.push(
+ t('clicks', { count: row.clicks }),
+ t('impressions', { count: row.impressions }),
+ );
+ }
+ break;
+ }
+ if (row.added) parts.push(t('added'));
+ return <>{parts.filter(Boolean).join(' · ')}</>;
+}
+
+function UsedInLabel({ used }: { used: UsedIn | null }) {
+ const t = useTranslations('contentEditor.editor.sources.usedIn');
+ if (!used) return <>{t('none')}</>;
+ switch (used.kind) {
+ case 'heading':
+ return (
+ <>{used.level === 1 ? t('h1') : t('heading', { level: used.level, text: used.text })}</>
+ );
+ case 'paragraph':
+ return <>{t('paragraph', { index: used.index })}</>;
+ case 'thisPage':
+ return <>{t('thisPage')}</>;
+ case 'internalLink':
+ return <>{t('internalLink')}</>;
+ case 'outboundLink':
+ return <>{t('outboundLink')}</>;
+ }
+}
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 ee63d7b51..087b663c7 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
@@ -12,7 +12,9 @@ const saveContentDraft = vi.fn();
const setContentDraftPageType = vi.fn();
const getContentImpact = vi.fn();
const getContentResults = vi.fn();
+const getDraftSources = vi.fn();
vi.mock('@/lib/actions/content-drafts', () => ({
+ getDraftSources: (...args: unknown[]) => getDraftSources(...args),
getContentImpact: (...args: unknown[]) => getContentImpact(...args),
getContentResults: (...args: unknown[]) => getContentResults(...args),
getContentDraft: (...args: unknown[]) => getContentDraft(...args),
@@ -142,6 +144,7 @@ beforeEach(() => {
saveContentDraft.mockReset().mockResolvedValue({ updatedAt: '2026-10-20T10:00:00Z' });
getContentImpact.mockReset().mockResolvedValue(null);
getContentResults.mockReset().mockResolvedValue(null);
+ getDraftSources.mockReset().mockResolvedValue(null);
localStorage.clear();
brandState.activeBrandId = 'b1';
brandState.setActiveBrand.mockReset();
@@ -240,6 +243,8 @@ describe('the content editor', () => {
expect(typeMenu().title).toBe('Detected from the page as you write. Pick a type to keep it.');
await rewrite('<h1>How to clean CRM data</h1>');
+ // It reads the page once typing pauses.
+ await act(() => new Promise((resolve) => setTimeout(resolve, 450)));
expect(typeMenu().textContent).toBe('Guide');
const types = await openTypes();
@@ -261,6 +266,7 @@ describe('the content editor', () => {
// Picked: the page no longer changes it.
await rewrite('<h1>Northwind vs HubSpot</h1>');
+ await act(() => new Promise((resolve) => setTimeout(resolve, 450)));
expect(typeMenu().textContent).toBe('Pricing');
});
@@ -586,6 +592,37 @@ describe('the side panel', () => {
expect(button('Hide side panel')!.getAttribute('aria-pressed')).toBe('true');
});
+ it('opens Sources only when its tab is picked, and keeps Impact as it was', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ getContentDraft.mockResolvedValue(draft({ sourceUrl: 'https://acme.example.com/pricing' }));
+ window.innerWidth = 1440;
+ await renderPage();
+ expect(getDraftSources).not.toHaveBeenCalled();
+
+ const tab = [...panel()!.querySelectorAll<HTMLElement>('[role="tab"]')].find(
+ (el) => el.textContent === 'Sources',
+ )!;
+ await act(async () => {
+ tab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ tab.click();
+ });
+ expect(getDraftSources).toHaveBeenCalledWith('d1');
+ // The draft's H1 carries the fan-out's words.
+ expect(panel()!.textContent).toContain('pipeline forecasting');
+ expect(panel()!.textContent).toContain('H1');
+ expect(getContentImpact).toHaveBeenCalledTimes(1);
+ });
+
it('starts open on a wide window, and remembers it closed', async () => {
getContentDraft.mockResolvedValue(draft({ method: 'create' }));
window.innerWidth = 1440;
diff --git a/web/src/lib/actions/content-drafts-sources.test.ts b/web/src/lib/actions/content-drafts-sources.test.ts
new file mode 100644
index 000000000..db49c46be
--- /dev/null
+++ b/web/src/lib/actions/content-drafts-sources.test.ts
@@ -0,0 +1,198 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** The Sources tab (CE-008): a draft's sources and a person's choices on them. */
+
+const DRAFT = '77777777-7777-7777-7777-777777777777';
+const PROMPT = '55555555-5555-5555-5555-555555555555';
+const OTHER_PROMPT = '66666666-6666-6666-6666-666666666666';
+
+interface Call {
+ table: string;
+ op: string;
+ value?: unknown;
+ options?: unknown;
+ filters: [string, unknown][];
+}
+let calls: Call[];
+let rpcCalls: { fn: string; args: unknown }[];
+let rpcResult: { data: unknown; error: { message: string } | null };
+let reads: Record<string, unknown>;
+
+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;
+ },
+ from: (table: string) => {
+ const call: Call = { table, op: 'select', filters: [] };
+ calls.push(call);
+ const result = () =>
+ call.op === 'select'
+ ? { data: reads[table] ?? null, error: null }
+ : { data: null, error: null };
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ eq: (col: string, v: unknown) => (call.filters.push([col, v]), chain),
+ update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),
+ upsert: (value: unknown, options: unknown) => (
+ (call.op = 'upsert'),
+ (call.value = value),
+ (call.options = options),
+ chain
+ ),
+ maybeSingle: async () => result(),
+ then: (resolve: (r: unknown) => void) => resolve(result()),
+ };
+ return chain;
+ },
+ })),
+}));
+
+const { addDraftSource, getDraftSources, setDraftSourceIncluded } =
+ await import('./content-drafts');
+
+const writes = () => calls.filter((c) => c.op !== 'select');
+
+beforeEach(() => {
+ calls = [];
+ rpcCalls = [];
+ rpcResult = { data: null, error: null };
+ reads = {};
+});
+
+describe('getDraftSources', () => {
+ it('reads the last 30 days of sources with the person’s choices', async () => {
+ const data = {
+ prompts: [],
+ fanouts: [],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ };
+ rpcResult = { data, error: null };
+ reads.content_draft_sources = [
+ { kind: 'fanout', ref: 'espresso', included: false, added: false },
+ { kind: 'file', ref: 'x', included: true, added: true },
+ ];
+ expect(await getDraftSources(DRAFT)).toEqual({
+ data,
+ choices: [{ kind: 'fanout', ref: 'espresso', included: false, added: false }],
+ });
+ expect(rpcCalls).toEqual([
+ { fn: 'content_draft_sources', args: { p_draft_id: DRAFT, p_days: 30 } },
+ ]);
+ expect(calls[0].filters).toEqual([['draft_id', DRAFT]]);
+ });
+
+ it('returns null for a draft the member can’t read, and throws on a failed read', async () => {
+ expect(await getDraftSources(DRAFT)).toBeNull();
+ rpcResult = { data: null, error: { message: 'boom' } };
+ await expect(getDraftSources(DRAFT)).rejects.toThrow('boom');
+ await expect(getDraftSources('d1')).rejects.toThrow('invalid');
+ });
+});
+
+describe('setDraftSourceIncluded', () => {
+ it('keeps the choice under the source’s kind and reference', async () => {
+ await setDraftSourceIncluded(DRAFT, {
+ kind: 'cited_page',
+ ref: 'https://x.example/a',
+ included: false,
+ });
+ expect(writes()).toEqual([
+ expect.objectContaining({
+ table: 'content_draft_sources',
+ op: 'upsert',
+ value: expect.objectContaining({
+ draft_id: DRAFT,
+ kind: 'cited_page',
+ ref: 'https://x.example/a',
+ included: false,
+ }),
+ options: { onConflict: 'draft_id,kind,ref' },
+ }),
+ ]);
+ expect((writes()[0].value as Record<string, unknown>).added).toBeUndefined();
+ });
+
+ it('writes nothing for an unknown kind or a malformed draft', async () => {
+ await expect(
+ setDraftSourceIncluded(DRAFT, { kind: 'file' as never, ref: 'x', included: true }),
+ ).rejects.toThrow('invalid');
+ await expect(
+ setDraftSourceIncluded('d1', { kind: 'fanout', ref: 'x', included: true }),
+ ).rejects.toThrow('invalid');
+ expect(writes()).toEqual([]);
+ });
+});
+
+describe('addDraftSource', () => {
+ it('adds a prompt to the draft’s prompts, and back in if it was left out', async () => {
+ reads.content_drafts = { prompt_ids: [OTHER_PROMPT] };
+ await addDraftSource(DRAFT, { kind: 'prompt', promptId: PROMPT });
+ expect(writes()).toEqual([
+ expect.objectContaining({
+ table: 'content_drafts',
+ op: 'update',
+ value: { prompt_ids: [OTHER_PROMPT, PROMPT] },
+ filters: [['id', DRAFT]],
+ }),
+ expect.objectContaining({
+ table: 'content_draft_sources',
+ op: 'update',
+ value: expect.objectContaining({ included: true }),
+ filters: [
+ ['draft_id', DRAFT],
+ ['kind', 'prompt'],
+ ['ref', PROMPT],
+ ],
+ }),
+ ]);
+ });
+
+ it('leaves the prompts as they are when the prompt is in them, and says when the draft isn’t found', async () => {
+ reads.content_drafts = { prompt_ids: [PROMPT] };
+ await addDraftSource(DRAFT, { kind: 'prompt', promptId: PROMPT });
+ expect(writes().map((w) => w.table)).toEqual(['content_draft_sources']);
+
+ reads.content_drafts = null;
+ await expect(addDraftSource(DRAFT, { kind: 'prompt', promptId: PROMPT })).rejects.toThrow(
+ 'not_found',
+ );
+ });
+
+ it('keeps a page or a query as added by the person', async () => {
+ await addDraftSource(DRAFT, { kind: 'cited_page', url: ' https://example.org/study ' });
+ await addDraftSource(DRAFT, { kind: 'gsc_query', query: ' Espresso Machine ' });
+ expect(writes().map((w) => w.value)).toEqual([
+ expect.objectContaining({
+ kind: 'cited_page',
+ ref: 'https://example.org/study',
+ added: true,
+ included: true,
+ }),
+ expect.objectContaining({
+ kind: 'gsc_query',
+ ref: 'espresso machine',
+ added: true,
+ included: true,
+ }),
+ ]);
+ });
+
+ it('refuses an address that isn’t a web page’s and a malformed prompt', async () => {
+ await expect(
+ addDraftSource(DRAFT, { kind: 'cited_page', url: 'javascript:alert(1)' }),
+ ).rejects.toThrow('invalid');
+ await expect(addDraftSource(DRAFT, { kind: 'cited_page', url: 'not a url' })).rejects.toThrow(
+ 'invalid',
+ );
+ await expect(addDraftSource(DRAFT, { kind: 'prompt', promptId: 'p1' })).rejects.toThrow(
+ 'invalid',
+ );
+ expect(calls).toEqual([]);
+ });
+});
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 12190b89d..1884b83e2 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -29,6 +29,14 @@ import {
} from '@/lib/content/editor';
import { detectPageType, siteTypeOf, type SiteType } from '@/lib/content/page-types';
import { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';
+import {
+ DRAFT_SOURCE_KINDS,
+ SOURCES_DAYS,
+ normalizeQuery,
+ type DraftSourceChoice,
+ type DraftSourceKind,
+ type DraftSourcesData,
+} from '@/lib/content/sources';
/**
* Content drafts (Content Editor, CE-002), read through the signed-in member's
@@ -625,3 +633,133 @@ export async function markContentDraftReady(id: string): Promise<DraftStatus> {
if (!current) throw new Error('not_found');
return current.status;
}
+
+/**
+ * The Sources tab (CE-008): the brand's data a draft draws on, over the last
+ * 30 days (content_draft_sources, 00211), with the person's choices on it.
+ * Null when the member can't read the draft.
+ */
+export async function getDraftSources(
+ id: string,
+): Promise<{ data: DraftSourcesData; choices: DraftSourceChoice[] } | null> {
+ if (!draftId.safeParse(id).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const [sourcesRes, choicesRes] = await Promise.all([
+ supabase.rpc('content_draft_sources', { p_draft_id: id, p_days: SOURCES_DAYS }),
+ supabase.from('content_draft_sources').select('kind, ref, included, added').eq('draft_id', id),
+ ]);
+ if (sourcesRes.error) throw new Error(sourcesRes.error.message);
+ if (choicesRes.error) throw new Error(choicesRes.error.message);
+ if (!sourcesRes.data) return null;
+ const kinds: readonly string[] = DRAFT_SOURCE_KINDS;
+ return {
+ data: sourcesRes.data as unknown as DraftSourcesData,
+ choices: (choicesRes.data ?? [])
+ .filter((row) => kinds.includes(row.kind))
+ .map((row) => ({
+ kind: row.kind as DraftSourceKind,
+ ref: row.ref,
+ included: row.included,
+ added: row.added,
+ })),
+ };
+}
+
+const sourceChoice = z.object({
+ kind: z.enum(DRAFT_SOURCE_KINDS),
+ ref: z.string().min(1).max(2048),
+ included: z.boolean(),
+});
+
+/** Keeps a source in the draft's sources, or leaves it out (CE-008). */
+export async function setDraftSourceIncluded(
+ id: string,
+ choice: { kind: DraftSourceKind; ref: string; included: boolean },
+): Promise<void> {
+ const parsed = sourceChoice.safeParse(choice);
+ if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { error } = await supabase.from('content_draft_sources').upsert(
+ {
+ draft_id: id,
+ kind: parsed.data.kind,
+ ref: parsed.data.ref,
+ included: parsed.data.included,
+ updated_at: new Date().toISOString(),
+ },
+ { onConflict: 'draft_id,kind,ref' },
+ );
+ if (error) throw new Error(error.message);
+}
+
+const addedSource = z.discriminatedUnion('kind', [
+ z.object({ kind: z.literal('prompt'), promptId: z.guid() }),
+ z.object({
+ kind: z.literal('cited_page'),
+ url: z
+ .string()
+ .trim()
+ .max(2048)
+ .refine((url) => {
+ try {
+ return /^https?:$/.test(new URL(url).protocol);
+ } catch {
+ return false;
+ }
+ }),
+ }),
+ z.object({ kind: z.literal('gsc_query'), query: z.string().trim().min(1).max(2048) }),
+]);
+
+export type AddedDraftSource = z.infer<typeof addedSource>;
+
+/**
+ * + Add source (CE-008): a prompt joins the draft's prompts (its fan-outs
+ * and cited pages follow); a page address or a Search Console query is kept
+ * as added by hand. Throws 'not_found' when the draft isn't the member's.
+ */
+export async function addDraftSource(id: string, source: AddedDraftSource): Promise<void> {
+ const parsed = addedSource.safeParse(source);
+ if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');
+ const supabase = await createClient();
+ const now = new Date().toISOString();
+
+ if (parsed.data.kind === 'prompt') {
+ const { promptId } = parsed.data;
+ const { data: draft, error } = await supabase
+ .from('content_drafts')
+ .select('prompt_ids')
+ .eq('id', id)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!draft) throw new Error('not_found');
+ const promptIds: string[] = draft.prompt_ids ?? [];
+ if (!promptIds.includes(promptId)) {
+ // check_content_draft_links (00206) refuses a prompt of another brand.
+ const { error: updateError } = await supabase
+ .from('content_drafts')
+ .update({ prompt_ids: [...promptIds, promptId] })
+ .eq('id', id);
+ if (updateError) throw new Error(updateError.message);
+ }
+ // A prompt left out before is back in.
+ const { error: choiceError } = await supabase
+ .from('content_draft_sources')
+ .update({ included: true, updated_at: now })
+ .eq('draft_id', id)
+ .eq('kind', 'prompt')
+ .eq('ref', promptId);
+ if (choiceError) throw new Error(choiceError.message);
+ return;
+ }
+
+ const ref =
+ parsed.data.kind === 'cited_page' ? parsed.data.url : normalizeQuery(parsed.data.query);
+ const { error } = await supabase
+ .from('content_draft_sources')
+ .upsert(
+ { draft_id: id, kind: parsed.data.kind, ref, included: true, added: true, updated_at: now },
+ { onConflict: 'draft_id,kind,ref' },
+ );
+ if (error) throw new Error(error.message);
+}
diff --git a/web/src/lib/content/editor.ts b/web/src/lib/content/editor.ts
index cedf3f9a3..fe21a9581 100644
--- a/web/src/lib/content/editor.ts
+++ b/web/src/lib/content/editor.ts
@@ -7,6 +7,13 @@
/** How long typing pauses before the draft saves itself. */
export const AUTOSAVE_DELAY_MS = 1500;
+/**
+ * How long typing pauses before the side panel and the type chip read the
+ * page again: reading it re-renders the editor and parses the page, too much
+ * for every keystroke.
+ */
+export const PAGE_READ_DELAY_MS = 400;
+
/** The largest body a draft saves, in characters of HTML (about 100 pages). */
export const MAX_BODY_HTML_LENGTH = 500_000;
diff --git a/web/src/lib/content/sources.test.ts b/web/src/lib/content/sources.test.ts
new file mode 100644
index 000000000..3f59f5654
--- /dev/null
+++ b/web/src/lib/content/sources.test.ts
@@ -0,0 +1,220 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildSourceGroups,
+ includedCounts,
+ normalizeQuery,
+ pageKey,
+ readDraftDoc,
+ relatedQueries,
+ usedIn,
+ wordsOf,
+ type DraftSourceRow,
+ type DraftSourcesData,
+} from './sources';
+
+const data = (over: Partial<DraftSourcesData> = {}): DraftSourcesData => ({
+ prompts: [
+ {
+ id: 'p1',
+ text: 'Best espresso machines under $500?',
+ inDraft: true,
+ citesPage: false,
+ answers: 21,
+ mentioned: 4,
+ },
+ {
+ id: 'p2',
+ text: 'Manual vs automatic espresso machine',
+ inDraft: false,
+ citesPage: true,
+ answers: 3,
+ mentioned: 0,
+ },
+ ],
+ fanouts: [
+ {
+ query: 'Best espresso machine under 500',
+ platforms: ['perplexity-web', 'copilot-web'],
+ searched: 5,
+ },
+ { query: 'home espresso grinder', platforms: ['copilot-web'], searched: 2 },
+ ],
+ citedPages: [
+ {
+ url: 'https://www.reddit.com/r/espresso/x',
+ title: 'Thread',
+ domain: 'reddit.com',
+ citations: 12,
+ answers: 9,
+ },
+ {
+ url: 'https://crema.example.com/guide',
+ title: 'Guide',
+ domain: 'crema.example.com',
+ citations: 4,
+ answers: 4,
+ },
+ {
+ url: 'https://acme-coffee.example.com/guides/espresso/',
+ title: 'Ours',
+ domain: 'acme-coffee.example.com',
+ citations: 2,
+ answers: 2,
+ },
+ ],
+ gscQueries: [
+ { query: 'espresso machine under 500', clicks: 40, impressions: 900 },
+ { query: 'coffee subscription', clicks: 12, impressions: 300 },
+ { query: 'acme coffee login', clicks: 8, impressions: 50 },
+ ],
+ brandDomains: ['acme-coffee.example.com'],
+ competitorDomains: ['crema.example.com'],
+ ...over,
+});
+
+const draft = {
+ title: 'The home espresso guide',
+ sourceUrl: 'https://acme-coffee.example.com/guides/espresso',
+};
+
+describe('words and keys', () => {
+ it('reads a text’s words for matching', () => {
+ expect(wordsOf('Best espresso machines under $500? The guide')).toEqual([
+ 'best',
+ 'espresso',
+ 'machine',
+ 'under',
+ '500',
+ 'guide',
+ ]);
+ expect(normalizeQuery(' Best Espresso ')).toBe('best espresso');
+ });
+
+ it('keys a page by host and path', () => {
+ expect(pageKey('https://www.Acme.com/Guides/Espresso/?utm_source=x#top')).toBe(
+ 'acme.com/guides/espresso',
+ );
+ expect(pageKey('/relative')).toBeNull();
+ expect(pageKey('mailto:[email protected]')).toBeNull();
+ });
+});
+
+describe('relatedQueries', () => {
+ it('keeps the brand’s queries sharing half their words with the draft', () => {
+ expect(
+ relatedQueries(data().gscQueries, ['espresso machine guide']).map((q) => q.query),
+ ).toEqual(['espresso machine under 500']);
+ expect(relatedQueries(data().gscQueries, ['espresso machine under'], 0)).toEqual([]);
+ });
+});
+
+describe('buildSourceGroups', () => {
+ it('lists the prompts, fan-outs, cited pages and related queries, each kind of page named', () => {
+ const groups = buildSourceGroups(data(), [], draft);
+ expect(groups.map((g) => [g.kind, g.rows.map((r) => r.name)])).toEqual([
+ ['prompt', ['Best espresso machines under $500?', 'Manual vs automatic espresso machine']],
+ ['fanout', ['Best espresso machine under 500', 'home espresso grinder']],
+ [
+ 'cited_page',
+ [
+ 'https://www.reddit.com/r/espresso/x',
+ 'https://crema.example.com/guide',
+ 'https://acme-coffee.example.com/guides/espresso/',
+ ],
+ ],
+ ['gsc_query', ['espresso machine under 500']],
+ ]);
+ const pages = groups[2].rows as Extract<DraftSourceRow, { kind: 'cited_page' }>[];
+ expect(pages.map((p) => p.category)).toEqual(['forum', 'competitor', 'you']);
+ const prompts = groups[0].rows as Extract<DraftSourceRow, { kind: 'prompt' }>[];
+ expect(prompts.map((p) => p.citesPage)).toEqual([false, true]);
+ });
+
+ it('keeps a source left out unchecked, and adds the pages and queries added by hand', () => {
+ const groups = buildSourceGroups(
+ data(),
+ [
+ { kind: 'fanout', ref: 'home espresso grinder', included: false, added: false },
+ { kind: 'cited_page', ref: 'https://example.org/study', included: true, added: true },
+ { kind: 'gsc_query', ref: 'coffee subscription', included: true, added: true },
+ { kind: 'gsc_query', ref: 'gone query', included: false, added: true },
+ ],
+ draft,
+ );
+ expect(groups[1].rows.map((r) => [r.name, r.included])).toEqual([
+ ['Best espresso machine under 500', true],
+ ['home espresso grinder', false],
+ ]);
+ expect(groups[2].rows.at(-1)).toMatchObject({
+ name: 'https://example.org/study',
+ added: true,
+ citations: null,
+ category: 'other',
+ });
+ expect(groups[3].rows.map((r) => [r.name, r.included, r.added])).toEqual([
+ ['espresso machine under 500', true, false],
+ ['coffee subscription', true, true],
+ ['gone query', false, true],
+ ]);
+ expect(includedCounts(groups)).toEqual({ prompt: 2, fanout: 1, cited_page: 4, gsc_query: 2 });
+ });
+});
+
+describe('usedIn', () => {
+ const doc = readDraftDoc(
+ '<h1>The home espresso guide</h1>' +
+ '<p>Pick a grinder before the machine.</p>' +
+ '<h2>Best espresso machines under $500</h2>' +
+ '<p>A home espresso grinder matters: see <a href="https://www.reddit.com/r/espresso/x?ref=1">this thread</a> ' +
+ 'and <a href="/guides/milk">our milk guide</a>.</p>',
+ );
+ const rows = Object.fromEntries(
+ buildSourceGroups(data(), [], draft).flatMap((g) => g.rows.map((r) => [r.name, r])),
+ );
+ const ctx = { sourceUrl: draft.sourceUrl };
+
+ it('finds a prompt or fan-out in a heading first, then a paragraph', () => {
+ expect(usedIn(rows['Best espresso machines under $500?'], doc, ctx)).toEqual({
+ kind: 'heading',
+ level: 2,
+ text: 'Best espresso machines under $500',
+ });
+ expect(usedIn(rows['home espresso grinder'], doc, ctx)).toEqual({
+ kind: 'paragraph',
+ index: 2,
+ });
+ expect(usedIn(rows['Manual vs automatic espresso machine'], doc, ctx)).toBeNull();
+ });
+
+ it('finds a page where the draft links to it, or the page itself', () => {
+ expect(usedIn(rows['https://www.reddit.com/r/espresso/x'], doc, ctx)).toEqual({
+ kind: 'outboundLink',
+ });
+ expect(usedIn(rows['https://crema.example.com/guide'], doc, ctx)).toBeNull();
+ expect(usedIn(rows['https://acme-coffee.example.com/guides/espresso/'], doc, ctx)).toEqual({
+ kind: 'thisPage',
+ });
+ });
+
+ it('calls a link to the brand’s own page internal', () => {
+ const own = readDraftDoc(
+ '<p><a href="https://acme-coffee.example.com/blog/beans">beans</a></p>',
+ );
+ const row = buildSourceGroups(
+ data({
+ citedPages: [
+ {
+ url: 'https://acme-coffee.example.com/blog/beans',
+ title: null,
+ domain: 'acme-coffee.example.com',
+ citations: 1,
+ answers: 1,
+ },
+ ],
+ }),
+ [],
+ draft,
+ )[2].rows[0];
+ expect(usedIn(row, own, ctx)).toEqual({ kind: 'internalLink' });
+ });
+});
diff --git a/web/src/lib/content/sources.ts b/web/src/lib/content/sources.ts
new file mode 100644
index 000000000..87003b79b
--- /dev/null
+++ b/web/src/lib/content/sources.ts
@@ -0,0 +1,307 @@
+import { classifyDomain, normalizeDomain, type SourceCategory } from '@/lib/citations/classify';
+
+/**
+ * The editor's Sources tab (Content Editor CE-008, spec §10): every source a
+ * draft draws on, by name, with where the draft uses it. The brand's data
+ * comes from content_draft_sources (00211); a person's choices — a source
+ * left out, a page or query added — from the table of the same name.
+ */
+
+export const DRAFT_SOURCE_KINDS = ['prompt', 'fanout', 'cited_page', 'gsc_query'] as const;
+export type DraftSourceKind = (typeof DRAFT_SOURCE_KINDS)[number];
+
+/** The sources of the last 30 days, as content_draft_sources reads them. */
+export const SOURCES_DAYS = 30;
+/** Search Console queries shown beside the draft, the most clicked first. */
+export const MAX_GSC_SOURCES = 10;
+
+export interface DraftSourcesData {
+ prompts: {
+ id: string;
+ text: string;
+ inDraft: boolean;
+ citesPage: boolean;
+ answers: number;
+ mentioned: number;
+ }[];
+ fanouts: { query: string; platforms: string[]; searched: number }[];
+ citedPages: {
+ url: string;
+ title: string | null;
+ domain: string;
+ citations: number;
+ answers: number;
+ }[];
+ gscQueries: { query: string; clicks: number; impressions: number }[];
+ brandDomains: string[];
+ competitorDomains: string[];
+}
+
+/** A person's choice on one source: left out, or added by hand. */
+export interface DraftSourceChoice {
+ kind: DraftSourceKind;
+ ref: string;
+ included: boolean;
+ added: boolean;
+}
+
+/** One row of the tab. */
+export type DraftSourceRow = {
+ kind: DraftSourceKind;
+ /** What a choice is stored under: a prompt id, a normalized query or an address. */
+ ref: string;
+ /** The full name or address. */
+ name: string;
+ included: boolean;
+ added: boolean;
+} & (
+ | { kind: 'prompt'; answers: number; mentioned: number; citesPage: boolean }
+ | { kind: 'fanout'; platforms: string[]; searched: number }
+ | { kind: 'cited_page'; category: SourceCategory; citations: number | null }
+ | { kind: 'gsc_query'; clicks: number | null; impressions: number | null }
+);
+
+export interface DraftSourceGroup {
+ kind: DraftSourceKind;
+ rows: DraftSourceRow[];
+}
+
+/** A query as one source: trimmed, spaces collapsed, lowercased (as 00211 groups fan-outs). */
+export function normalizeQuery(query: string): string {
+ return query.trim().replace(/\s+/g, ' ').toLowerCase();
+}
+
+const STOP_WORDS = new Set(
+ (
+ 'the and for with what which how are is was were you your our from that this does do did can ' +
+ 'vs not but has have had who why when where will would should could into about than then there ' +
+ 'their they them its it as at by of on in to or be an a'
+ ).split(' '),
+);
+
+/** A text's words for matching: lowercased, three letters or more, plurals as singulars. */
+export function wordsOf(text: string): string[] {
+ const words = text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
+ return words
+ .filter((w) => (w.length >= 3 || /^\d+$/.test(w)) && !STOP_WORDS.has(w))
+ .map((w) => (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') ? w.slice(0, -1) : w));
+}
+
+/** Whether `words` cover at least `share` of a source's words (and at least one). */
+function covers(sourceWords: string[], words: Set<string>, share: number): boolean {
+ const unique = [...new Set(sourceWords)];
+ if (!unique.length) return false;
+ const hits = unique.filter((w) => words.has(w)).length;
+ return hits > 0 && hits / unique.length >= share;
+}
+
+/**
+ * Search Console keeps no queries per page, so the draft's are the brand's
+ * queries sharing half their words with the draft's title, prompts and page
+ * address — as page-prompt-suggestions.js matches queries to a page.
+ */
+export function relatedQueries(
+ rows: DraftSourcesData['gscQueries'],
+ draftText: string[],
+ limit = MAX_GSC_SOURCES,
+): DraftSourcesData['gscQueries'] {
+ const words = new Set(draftText.flatMap(wordsOf));
+ return rows.filter((row) => covers(wordsOf(row.query), words, 0.5)).slice(0, limit);
+}
+
+/** A page address's path as words ("/guides/home-espresso" → "guides home espresso"): its host names the brand, not the page. */
+function pathWords(url: string | null): string {
+ if (!url) return '';
+ try {
+ return new URL(url).pathname.replace(/[/_.-]+/g, ' ');
+ } catch {
+ return '';
+ }
+}
+
+/** The parts of the draft a source can be used in. */
+export interface DraftDoc {
+ headings: { level: number; text: string; words: Set<string> }[];
+ paragraphs: Set<string>[];
+ links: string[];
+}
+
+/** Reads the draft's headings, paragraphs and links from its HTML. */
+export function readDraftDoc(html: string): DraftDoc {
+ const doc = new DOMParser().parseFromString(html, 'text/html');
+ const headings = [...doc.querySelectorAll('h1, h2, h3')].map((h) => {
+ const text = (h.textContent ?? '').trim();
+ return { level: Number(h.tagName.slice(1)), text, words: new Set(wordsOf(text)) };
+ });
+ const paragraphs = [...doc.querySelectorAll('p, li')].map(
+ (p) => new Set(wordsOf(p.textContent ?? '')),
+ );
+ const links = [...doc.querySelectorAll('a[href]')]
+ .map((a) => pageKey(a.getAttribute('href') ?? ''))
+ .filter((key): key is string => key !== null);
+ return { headings, paragraphs, links };
+}
+
+/** An address as one page: host without www, path without its trailing slash, lowercased. */
+export function pageKey(url: string): string | null {
+ try {
+ const parsed = new URL(url);
+ if (!/^https?:$/.test(parsed.protocol)) return null;
+ const host = parsed.hostname.toLowerCase().replace(/^www\./, '');
+ return `${host}${parsed.pathname.replace(/\/+$/, '').toLowerCase()}`;
+ } catch {
+ return null;
+ }
+}
+
+export type UsedIn =
+ | { kind: 'heading'; level: number; text: string }
+ | { kind: 'paragraph'; index: number }
+ | { kind: 'thisPage' }
+ | { kind: 'internalLink' }
+ | { kind: 'outboundLink' };
+
+/** The share of a source's words a heading or paragraph carries to count as using it. */
+const USED_SHARE = 0.75;
+
+/**
+ * Where the draft uses a source, as written now: a page is used where the
+ * draft links to it (or is the page itself); a prompt, fan-out or query in
+ * the first heading, then the first paragraph, carrying three quarters of
+ * its words.
+ */
+export function usedIn(
+ row: DraftSourceRow,
+ doc: DraftDoc,
+ ctx: { sourceUrl: string | null },
+): UsedIn | null {
+ if (row.kind === 'cited_page') {
+ const key = pageKey(row.name);
+ if (!key) return null;
+ if (ctx.sourceUrl && pageKey(ctx.sourceUrl) === key) return { kind: 'thisPage' };
+ if (!doc.links.includes(key)) return null;
+ return row.category === 'you' ? { kind: 'internalLink' } : { kind: 'outboundLink' };
+ }
+ const words = wordsOf(row.name);
+ const heading = doc.headings.find((h) => covers(words, h.words, USED_SHARE));
+ if (heading) return { kind: 'heading', level: heading.level, text: heading.text };
+ const index = doc.paragraphs.findIndex((p) => covers(words, p, USED_SHARE));
+ return index >= 0 ? { kind: 'paragraph', index: index + 1 } : null;
+}
+
+/**
+ * The tab's groups — Prompts · Fan-outs · Cited pages · Search Console — from
+ * the brand's data and a person's choices: a source left out stays listed,
+ * unchecked; a page or query added by hand joins its group.
+ */
+export function buildSourceGroups(
+ data: DraftSourcesData,
+ choices: DraftSourceChoice[],
+ draft: { title: string; sourceUrl: string | null },
+): DraftSourceGroup[] {
+ const choice = new Map(choices.map((c) => [`${c.kind}:${c.ref}`, c]));
+ const included = (kind: DraftSourceKind, ref: string) =>
+ choice.get(`${kind}:${ref}`)?.included ?? true;
+ const ctx = {
+ brandDomains: data.brandDomains.map(normalizeDomain),
+ competitorDomains: data.competitorDomains.map(normalizeDomain),
+ };
+ const categoryOf = (url: string): SourceCategory => {
+ const host = normalizeDomain(url);
+ return host ? classifyDomain(host, ctx) : 'other';
+ };
+
+ const prompts: DraftSourceRow[] = data.prompts.map((p) => ({
+ kind: 'prompt',
+ ref: p.id,
+ name: p.text,
+ included: included('prompt', p.id),
+ added: false,
+ answers: p.answers,
+ mentioned: p.mentioned,
+ citesPage: p.citesPage && !p.inDraft,
+ }));
+
+ const fanouts: DraftSourceRow[] = data.fanouts.map((f) => {
+ const ref = normalizeQuery(f.query);
+ return {
+ kind: 'fanout',
+ ref,
+ name: f.query,
+ included: included('fanout', ref),
+ added: false,
+ platforms: f.platforms,
+ searched: f.searched,
+ };
+ });
+
+ const pages: DraftSourceRow[] = data.citedPages.map((c) => ({
+ kind: 'cited_page',
+ ref: c.url,
+ name: c.url,
+ included: included('cited_page', c.url),
+ added: false,
+ category: categoryOf(c.url),
+ citations: c.citations,
+ }));
+ const listedPages = new Set(pages.map((p) => p.ref));
+ for (const c of choices) {
+ if (c.kind !== 'cited_page' || !c.added || listedPages.has(c.ref)) continue;
+ pages.push({
+ kind: 'cited_page',
+ ref: c.ref,
+ name: c.ref,
+ included: c.included,
+ added: true,
+ category: categoryOf(c.ref),
+ citations: null,
+ });
+ }
+
+ const byQuery = new Map(data.gscQueries.map((q) => [normalizeQuery(q.query), q]));
+ const related = relatedQueries(data.gscQueries, [
+ draft.title,
+ ...data.prompts.map((p) => p.text),
+ pathWords(draft.sourceUrl),
+ ]);
+ const queries: DraftSourceRow[] = related.map((q) => {
+ const ref = normalizeQuery(q.query);
+ return {
+ kind: 'gsc_query',
+ ref,
+ name: q.query,
+ included: included('gsc_query', ref),
+ added: false,
+ clicks: q.clicks,
+ impressions: q.impressions,
+ };
+ });
+ const listedQueries = new Set(queries.map((q) => q.ref));
+ for (const c of choices) {
+ if (c.kind !== 'gsc_query' || !c.added || listedQueries.has(c.ref)) continue;
+ const row = byQuery.get(c.ref);
+ queries.push({
+ kind: 'gsc_query',
+ ref: c.ref,
+ name: row?.query ?? c.ref,
+ included: c.included,
+ added: true,
+ clicks: row?.clicks ?? null,
+ impressions: row?.impressions ?? null,
+ });
+ }
+
+ return [
+ { kind: 'prompt', rows: prompts },
+ { kind: 'fanout', rows: fanouts },
+ { kind: 'cited_page', rows: pages },
+ { kind: 'gsc_query', rows: queries },
+ ];
+}
+
+/** The included sources per group, for the summary line. */
+export function includedCounts(groups: DraftSourceGroup[]): Record<DraftSourceKind, number> {
+ const counts = { prompt: 0, fanout: 0, cited_page: 0, gsc_query: 0 };
+ for (const group of groups) counts[group.kind] = group.rows.filter((r) => r.included).length;
+ return counts;
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index b9283aa4d..f416719e5 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -910,6 +910,44 @@ export type Database = {
},
]
}
+ content_draft_sources: {
+ Row: {
+ added: boolean
+ created_at: string
+ draft_id: string
+ included: boolean
+ kind: string
+ ref: string
+ updated_at: string
+ }
+ Insert: {
+ added?: boolean
+ created_at?: string
+ draft_id: string
+ included?: boolean
+ kind: string
+ ref: string
+ updated_at?: string
+ }
+ Update: {
+ added?: boolean
+ created_at?: string
+ draft_id?: string
+ included?: boolean
+ kind?: string
+ ref?: string
+ updated_at?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "content_draft_sources_draft_id_fkey"
+ columns: ["draft_id"]
+ isOneToOne: false
+ referencedRelation: "content_drafts"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
content_opportunities: {
Row: {
brand_id: string
@@ -3432,6 +3470,10 @@ export type Database = {
sent_count: number
}[]
}
+ content_draft_sources: {
+ Args: { p_days?: number; p_draft_id: string }
+ Returns: Json
+ }
content_page_impact: {
Args: { p_brand_id: string; p_days: number; p_page: string }
Returns: Json