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): keep a draft's earlier versions in History and restore any of them (#1301)

Cihan9307223ffe48
diff --git a/server/src/lib/content-history.js b/server/src/lib/content-history.js
new file mode 100644
index 000000000..479b0ffb2
--- /dev/null
+++ b/server/src/lib/content-history.js
@@ -0,0 +1,38 @@
+/**
+ * Content Editor version history (CE-018, 00215): a draft's earlier versions
+ * are kept 90 days. The daily run deletes older ones here; the editor's
+ * History leaves them out until then.
+ */
+import supabaseAdmin from '../config/supabase.js';
+import { logger } from './logger.js';
+
+/** How long a draft's version is kept. */
+export const VERSION_RETENTION_DAYS = 90;
+/** Versions deleted per call: each holds a whole page, up to 500 KB. */
+export const VERSION_PRUNE_BATCH = 200;
+/** Calls per daily run at most; the rest waits a day. */
+export const MAX_VERSION_PRUNE_CALLS = 100;
+
+/**
+ * The daily prune of versions past their 90 days, VERSION_PRUNE_BATCH a call
+ * (00215 content_draft_versions_prune), so no one DELETE runs into the
+ * statement timeout. Stops when a call deletes fewer than a batch.
+ */
+export async function pruneContentVersions(now = Date.now()) {
+ const before = new Date(now - VERSION_RETENTION_DAYS * 24 * 60 * 60 * 1000).toISOString();
+ for (let call = 0; call < MAX_VERSION_PRUNE_CALLS; call++) {
+ const { data, error } = await supabaseAdmin.rpc('content_draft_versions_prune', {
+ p_before: before,
+ p_limit: VERSION_PRUNE_BATCH,
+ });
+ if (error) {
+ logger.warn({ err: error }, '[content-history] prune failed');
+ return;
+ }
+ if ((data ?? 0) < VERSION_PRUNE_BATCH) return;
+ }
+ logger.warn(
+ { calls: MAX_VERSION_PRUNE_CALLS },
+ '[content-history] prune stopped early; the rest goes tomorrow',
+ );
+}
diff --git a/server/src/lib/content-history.test.js b/server/src/lib/content-history.test.js
new file mode 100644
index 000000000..28ffe2c91
--- /dev/null
+++ b/server/src/lib/content-history.test.js
@@ -0,0 +1,44 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const rpc = vi.fn();
+vi.mock('../config/supabase.js', () => ({ default: { rpc: (...a) => rpc(...a) } }));
+const warn = vi.fn();
+vi.mock('./logger.js', () => ({ logger: { warn: (...a) => warn(...a) } }));
+
+const { pruneContentVersions, MAX_VERSION_PRUNE_CALLS, VERSION_PRUNE_BATCH } =
+ await import('./content-history.js');
+
+const NOW = Date.parse('2026-10-21T10:00:00.000Z');
+
+beforeEach(() => {
+ rpc.mockReset();
+ warn.mockReset();
+});
+
+describe('pruneContentVersions', () => {
+ it('deletes versions older than 90 days in batches until a call deletes fewer', async () => {
+ rpc
+ .mockResolvedValueOnce({ data: VERSION_PRUNE_BATCH, error: null })
+ .mockResolvedValueOnce({ data: 12, error: null });
+ await pruneContentVersions(NOW);
+ expect(rpc).toHaveBeenCalledTimes(2);
+ expect(rpc).toHaveBeenCalledWith('content_draft_versions_prune', {
+ p_before: '2026-07-23T10:00:00.000Z',
+ p_limit: VERSION_PRUNE_BATCH,
+ });
+ });
+
+ it('stops after its call budget, and on an error', async () => {
+ rpc.mockResolvedValue({ data: VERSION_PRUNE_BATCH, error: null });
+ await pruneContentVersions(NOW);
+ expect(rpc).toHaveBeenCalledTimes(MAX_VERSION_PRUNE_CALLS);
+ expect(warn).toHaveBeenCalledWith(
+ { calls: MAX_VERSION_PRUNE_CALLS },
+ '[content-history] prune stopped early; the rest goes tomorrow',
+ );
+
+ rpc.mockReset().mockResolvedValue({ data: null, error: { message: 'timeout' } });
+ await pruneContentVersions(NOW);
+ expect(rpc).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/src/server.js b/server/src/server.js
index 02be3642d..0240aeedc 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -15,6 +15,7 @@ import routes from './routes/index.js';
import trafficRoutes from './routes/traffic.js';
import botIngestRoutes from './routes/bot-ingest.js';
import { pruneBotEvents } from './lib/bot-ingest.js';
+import { pruneContentVersions } from './lib/content-history.js';
import {
createJob,
cleanupStaleJobs,
@@ -268,6 +269,11 @@ async function runDailyTracking() {
logger.error({ err }, '[ai-bots] daily prune failed');
});
+ // Content Editor versions past their 90 days (CE-018).
+ pruneContentVersions().catch((err) => {
+ logger.error({ err }, '[content-history] daily prune failed');
+ });
+
// Google Analytics sync (#704) — same contract as the Search Console sync
// above: independent, never blocks or fails the tracking run, no-ops when
// Composio or the Analytics auth config isn't set.
diff --git a/supabase/migrations/00215_content_draft_versions.sql b/supabase/migrations/00215_content_draft_versions.sql
new file mode 100644
index 000000000..f53740f30
--- /dev/null
+++ b/supabase/migrations/00215_content_draft_versions.sql
@@ -0,0 +1,230 @@
+-- ============================================================================
+-- 00215: a draft's version history, for the editor's History menu
+-- ============================================================================
+-- History (Content Editor spec v2 §8, CE-018) lists a draft's earlier
+-- versions with their time and origin, and restores any of them:
+-- * import: the live page, as Start imported it from its address;
+-- * agent_before: the page before an agent's suggestions were accepted
+-- (CE-018 part C writes it);
+-- * ready: each Mark ready;
+-- * publish: each publish (CE-013 writes it);
+-- * restore: the page a restore replaced, so a restore loses nothing.
+-- "Now" is the draft itself. Versions are kept 90 days: the server's daily
+-- run prunes older ones (content_draft_versions_prune), and reads leave them
+-- out until then. A draft keeps its newest 50 (History lists 50), and a
+-- version that would repeat the draft's latest one (a restore after a
+-- restore, Mark ready on an unchanged page) isn't kept again. Members write
+-- import, agent_before and ready versions; publish is the server's.
+--
+-- A version is a copy of the draft's own title and body, which every save
+-- checks against the draft allow-list. So members only read versions; the two
+-- functions below write them from the draft row, and a hand-made version
+-- with unchecked HTML can't be restored into a draft.
+create table if not exists public.content_draft_versions (
+ id uuid primary key default gen_random_uuid(),
+ draft_id uuid not null references public.content_drafts(id) on delete cascade,
+ origin text not null
+ check (origin in ('import', 'agent_before', 'ready', 'publish', 'restore')),
+ title text not null default '',
+ body_html text not null default '',
+ created_by uuid references public.profiles(id) on delete set null,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists content_draft_versions_draft_idx
+ on public.content_draft_versions (draft_id, created_at desc);
+-- The daily prune walks the oldest first.
+create index if not exists content_draft_versions_created_idx
+ on public.content_draft_versions (created_at);
+
+alter table public.content_draft_versions enable row level security;
+
+-- A draft the member can read is one in their organization (content_drafts'
+-- own member policies), so its versions follow it.
+create policy "content_draft_versions: member select"
+ on public.content_draft_versions
+ for select
+ using (draft_id in (select d.id from public.content_drafts d));
+
+grant select on public.content_draft_versions to authenticated;
+
+comment on table public.content_draft_versions is
+ 'Content Editor (CE-018): a draft''s earlier versions — the imported live page, each Mark ready and publish, the page before agent changes or a restore. Written by content_draft_snapshot / content_draft_restore; kept 90 days.';
+
+-- Whether the caller may change the draft: a member of the organization that
+-- owns its brand, or the server.
+create or replace function public.content_draft_member(p_draft_id uuid)
+returns boolean
+language sql
+stable
+security definer
+set search_path to 'public'
+as $$
+ select auth.role() = 'service_role' or exists (
+ select 1
+ from public.content_drafts d
+ join public.brands b on b.id = d.brand_id
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where d.id = p_draft_id and pf.id = auth.uid()
+ );
+$$;
+
+revoke all on function public.content_draft_member(uuid) from public, anon;
+grant execute on function public.content_draft_member(uuid) to authenticated, service_role;
+
+-- Keeps the draft as it is now as a version of the given origin, unless its
+-- latest version is already this page (that one's id comes back), and keeps
+-- only the draft's newest 50. Called by the two functions below, not by
+-- members.
+create or replace function public.content_draft_keep_version(p_draft_id uuid, p_origin text)
+returns uuid
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_latest public.content_draft_versions%rowtype;
+ v_id uuid;
+begin
+ select * into v_latest
+ from public.content_draft_versions v
+ where v.draft_id = p_draft_id
+ order by v.created_at desc, v.id desc
+ limit 1;
+ if v_latest.id is not null and exists (
+ select 1 from public.content_drafts d
+ where d.id = p_draft_id and d.title = v_latest.title and d.body_html = v_latest.body_html
+ ) then
+ return v_latest.id;
+ end if;
+
+ insert into public.content_draft_versions (draft_id, origin, title, body_html, created_by)
+ select d.id, p_origin, d.title, d.body_html, auth.uid()
+ from public.content_drafts d
+ where d.id = p_draft_id
+ returning id into v_id;
+
+ delete from public.content_draft_versions v
+ where v.draft_id = p_draft_id
+ and v.id not in (
+ select o.id from public.content_draft_versions o
+ where o.draft_id = p_draft_id
+ order by o.created_at desc, o.id desc
+ limit 50
+ );
+ return v_id;
+end;
+$$;
+
+revoke all on function public.content_draft_keep_version(uuid, text)
+ from public, anon, authenticated;
+
+-- Keeps the draft as it is now as a version of the given origin. Returns the
+-- version's id, or null when the caller can't change the draft, or (a
+-- publish) isn't the server.
+create or replace function public.content_draft_snapshot(p_draft_id uuid, p_origin text)
+returns uuid
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_id uuid;
+begin
+ -- A restore keeps its own version (content_draft_restore).
+ if p_origin is null or p_origin not in ('import', 'agent_before', 'ready', 'publish') then
+ raise exception 'content_draft_snapshot: unknown origin %', p_origin using errcode = '22023';
+ end if;
+ if not public.content_draft_member(p_draft_id)
+ or (p_origin = 'publish' and auth.role() is distinct from 'service_role') then
+ return null;
+ end if;
+
+ v_id := public.content_draft_keep_version(p_draft_id, p_origin);
+ return v_id;
+end;
+$$;
+
+revoke all on function public.content_draft_snapshot(uuid, text) from public, anon;
+grant execute on function public.content_draft_snapshot(uuid, text) to authenticated, service_role;
+
+-- Restores a version: the draft as it is now is kept first (origin restore),
+-- then the draft takes the version's title and body; a draft that is already
+-- that page is left as it is. Only versions past the draft's newest 50 are
+-- ever deleted.
+-- Returns the draft's title, body and updated_at after, or null when the
+-- version is unknown, past its 90 days, or the caller can't change the draft.
+create or replace function public.content_draft_restore(p_version_id uuid)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_version public.content_draft_versions%rowtype;
+ v_draft public.content_drafts%rowtype;
+begin
+ select * into v_version
+ from public.content_draft_versions v
+ where v.id = p_version_id and v.created_at >= now() - interval '90 days';
+ if v_version.id is null or not public.content_draft_member(v_version.draft_id) then
+ return null;
+ end if;
+
+ select * into v_draft from public.content_drafts d where d.id = v_version.draft_id;
+ -- Already this page: nothing to keep or change.
+ if v_draft.title is distinct from v_version.title
+ or v_draft.body_html is distinct from v_version.body_html then
+ perform public.content_draft_keep_version(v_version.draft_id, 'restore');
+
+ update public.content_drafts d
+ set title = v_version.title, body_html = v_version.body_html
+ where d.id = v_version.draft_id
+ returning * into v_draft;
+ end if;
+
+ return jsonb_build_object(
+ 'title', v_draft.title,
+ 'bodyHtml', v_draft.body_html,
+ 'updatedAt', v_draft.updated_at
+ );
+end;
+$$;
+
+revoke all on function public.content_draft_restore(uuid) from public, anon;
+grant execute on function public.content_draft_restore(uuid) to authenticated, service_role;
+
+-- Deletes at most p_limit versions older than p_before, oldest first; the
+-- server's daily run calls it until fewer come back.
+create or replace function public.content_draft_versions_prune(
+ p_before timestamptz,
+ p_limit integer
+)
+returns integer
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_deleted integer;
+begin
+ delete from public.content_draft_versions v
+ where v.id in (
+ select o.id from public.content_draft_versions o
+ where o.created_at < p_before
+ order by o.created_at
+ limit p_limit
+ );
+ get diagnostics v_deleted = row_count;
+ return v_deleted;
+end;
+$$;
+
+revoke all on function public.content_draft_versions_prune(timestamptz, integer)
+ from public, anon, authenticated;
+grant execute on function public.content_draft_versions_prune(timestamptz, integer)
+ to service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 88ff64f7a..08912ed2a 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -29964,3 +29964,237 @@ grant select, insert, update on public.content_rule_sets to authenticated;
comment on table public.content_rule_sets is
'Content Editor (CE-009): a workspace''s "My rules" per page type — rule overrides and text rules a new draft of the type starts from.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00215_content_draft_versions.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00215: a draft's version history, for the editor's History menu
+-- ============================================================================
+-- History (Content Editor spec v2 §8, CE-018) lists a draft's earlier
+-- versions with their time and origin, and restores any of them:
+-- * import: the live page, as Start imported it from its address;
+-- * agent_before: the page before an agent's suggestions were accepted
+-- (CE-018 part C writes it);
+-- * ready: each Mark ready;
+-- * publish: each publish (CE-013 writes it);
+-- * restore: the page a restore replaced, so a restore loses nothing.
+-- "Now" is the draft itself. Versions are kept 90 days: the server's daily
+-- run prunes older ones (content_draft_versions_prune), and reads leave them
+-- out until then. A draft keeps its newest 50 (History lists 50), and a
+-- version that would repeat the draft's latest one (a restore after a
+-- restore, Mark ready on an unchanged page) isn't kept again. Members write
+-- import, agent_before and ready versions; publish is the server's.
+--
+-- A version is a copy of the draft's own title and body, which every save
+-- checks against the draft allow-list. So members only read versions; the two
+-- functions below write them from the draft row, and a hand-made version
+-- with unchecked HTML can't be restored into a draft.
+create table if not exists public.content_draft_versions (
+ id uuid primary key default gen_random_uuid(),
+ draft_id uuid not null references public.content_drafts(id) on delete cascade,
+ origin text not null
+ check (origin in ('import', 'agent_before', 'ready', 'publish', 'restore')),
+ title text not null default '',
+ body_html text not null default '',
+ created_by uuid references public.profiles(id) on delete set null,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists content_draft_versions_draft_idx
+ on public.content_draft_versions (draft_id, created_at desc);
+-- The daily prune walks the oldest first.
+create index if not exists content_draft_versions_created_idx
+ on public.content_draft_versions (created_at);
+
+alter table public.content_draft_versions enable row level security;
+
+-- A draft the member can read is one in their organization (content_drafts'
+-- own member policies), so its versions follow it.
+create policy "content_draft_versions: member select"
+ on public.content_draft_versions
+ for select
+ using (draft_id in (select d.id from public.content_drafts d));
+
+grant select on public.content_draft_versions to authenticated;
+
+comment on table public.content_draft_versions is
+ 'Content Editor (CE-018): a draft''s earlier versions — the imported live page, each Mark ready and publish, the page before agent changes or a restore. Written by content_draft_snapshot / content_draft_restore; kept 90 days.';
+
+-- Whether the caller may change the draft: a member of the organization that
+-- owns its brand, or the server.
+create or replace function public.content_draft_member(p_draft_id uuid)
+returns boolean
+language sql
+stable
+security definer
+set search_path to 'public'
+as $$
+ select auth.role() = 'service_role' or exists (
+ select 1
+ from public.content_drafts d
+ join public.brands b on b.id = d.brand_id
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where d.id = p_draft_id and pf.id = auth.uid()
+ );
+$$;
+
+revoke all on function public.content_draft_member(uuid) from public, anon;
+grant execute on function public.content_draft_member(uuid) to authenticated, service_role;
+
+-- Keeps the draft as it is now as a version of the given origin, unless its
+-- latest version is already this page (that one's id comes back), and keeps
+-- only the draft's newest 50. Called by the two functions below, not by
+-- members.
+create or replace function public.content_draft_keep_version(p_draft_id uuid, p_origin text)
+returns uuid
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_latest public.content_draft_versions%rowtype;
+ v_id uuid;
+begin
+ select * into v_latest
+ from public.content_draft_versions v
+ where v.draft_id = p_draft_id
+ order by v.created_at desc, v.id desc
+ limit 1;
+ if v_latest.id is not null and exists (
+ select 1 from public.content_drafts d
+ where d.id = p_draft_id and d.title = v_latest.title and d.body_html = v_latest.body_html
+ ) then
+ return v_latest.id;
+ end if;
+
+ insert into public.content_draft_versions (draft_id, origin, title, body_html, created_by)
+ select d.id, p_origin, d.title, d.body_html, auth.uid()
+ from public.content_drafts d
+ where d.id = p_draft_id
+ returning id into v_id;
+
+ delete from public.content_draft_versions v
+ where v.draft_id = p_draft_id
+ and v.id not in (
+ select o.id from public.content_draft_versions o
+ where o.draft_id = p_draft_id
+ order by o.created_at desc, o.id desc
+ limit 50
+ );
+ return v_id;
+end;
+$$;
+
+revoke all on function public.content_draft_keep_version(uuid, text)
+ from public, anon, authenticated;
+
+-- Keeps the draft as it is now as a version of the given origin. Returns the
+-- version's id, or null when the caller can't change the draft, or (a
+-- publish) isn't the server.
+create or replace function public.content_draft_snapshot(p_draft_id uuid, p_origin text)
+returns uuid
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_id uuid;
+begin
+ -- A restore keeps its own version (content_draft_restore).
+ if p_origin is null or p_origin not in ('import', 'agent_before', 'ready', 'publish') then
+ raise exception 'content_draft_snapshot: unknown origin %', p_origin using errcode = '22023';
+ end if;
+ if not public.content_draft_member(p_draft_id)
+ or (p_origin = 'publish' and auth.role() is distinct from 'service_role') then
+ return null;
+ end if;
+
+ v_id := public.content_draft_keep_version(p_draft_id, p_origin);
+ return v_id;
+end;
+$$;
+
+revoke all on function public.content_draft_snapshot(uuid, text) from public, anon;
+grant execute on function public.content_draft_snapshot(uuid, text) to authenticated, service_role;
+
+-- Restores a version: the draft as it is now is kept first (origin restore),
+-- then the draft takes the version's title and body; a draft that is already
+-- that page is left as it is. Only versions past the draft's newest 50 are
+-- ever deleted.
+-- Returns the draft's title, body and updated_at after, or null when the
+-- version is unknown, past its 90 days, or the caller can't change the draft.
+create or replace function public.content_draft_restore(p_version_id uuid)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_version public.content_draft_versions%rowtype;
+ v_draft public.content_drafts%rowtype;
+begin
+ select * into v_version
+ from public.content_draft_versions v
+ where v.id = p_version_id and v.created_at >= now() - interval '90 days';
+ if v_version.id is null or not public.content_draft_member(v_version.draft_id) then
+ return null;
+ end if;
+
+ select * into v_draft from public.content_drafts d where d.id = v_version.draft_id;
+ -- Already this page: nothing to keep or change.
+ if v_draft.title is distinct from v_version.title
+ or v_draft.body_html is distinct from v_version.body_html then
+ perform public.content_draft_keep_version(v_version.draft_id, 'restore');
+
+ update public.content_drafts d
+ set title = v_version.title, body_html = v_version.body_html
+ where d.id = v_version.draft_id
+ returning * into v_draft;
+ end if;
+
+ return jsonb_build_object(
+ 'title', v_draft.title,
+ 'bodyHtml', v_draft.body_html,
+ 'updatedAt', v_draft.updated_at
+ );
+end;
+$$;
+
+revoke all on function public.content_draft_restore(uuid) from public, anon;
+grant execute on function public.content_draft_restore(uuid) to authenticated, service_role;
+
+-- Deletes at most p_limit versions older than p_before, oldest first; the
+-- server's daily run calls it until fewer come back.
+create or replace function public.content_draft_versions_prune(
+ p_before timestamptz,
+ p_limit integer
+)
+returns integer
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_deleted integer;
+begin
+ delete from public.content_draft_versions v
+ where v.id in (
+ select o.id from public.content_draft_versions o
+ where o.created_at < p_before
+ order by o.created_at
+ limit p_limit
+ );
+ get diagnostics v_deleted = row_count;
+ return v_deleted;
+end;
+$$;
+
+revoke all on function public.content_draft_versions_prune(timestamptz, integer)
+ from public, anon, authenticated;
+grant execute on function public.content_draft_versions_prune(timestamptz, integer)
+ to service_role;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index baf4b8704..288920dde 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3352,6 +3352,39 @@
"insert": "Add block"
},
"markedReady": "Marked ready. Publish it on your site when you're ready.",
+ "history": {
+ "button": "History",
+ "hint": "Earlier versions of this page, to restore any of them",
+ "title": "Version history",
+ "kept": "kept {days} days",
+ "now": "Now",
+ "nowNote": "This draft, as you see it",
+ "loading": "Reading the history…",
+ "failed": "Couldn't read the history. Try again.",
+ "empty": "No earlier versions yet. Mark ready keeps one.",
+ "today": "Today {time}",
+ "origin": {
+ "import": "Live page",
+ "agent_before": "Before agent changes",
+ "ready": "Marked ready",
+ "publish": "Published",
+ "restore": "Before a restore"
+ },
+ "note": {
+ "import": "imported from the URL",
+ "agent_before": "auto-saved",
+ "ready": "kept on Mark ready",
+ "publish": "kept on publish",
+ "restore": "kept when another version was restored"
+ },
+ "restore": "Restore",
+ "restoreLabel": "Restore {version}, {when}",
+ "footer": "Restoring makes a new version. Nothing is lost.",
+ "restored": "Restored “{version}”. The page before it is in History.",
+ "restoreFailed": "Couldn't restore it. Try again.",
+ "htmlOpen": "Go back to the page to use History",
+ "restoring": "Restoring…"
+ },
"markReadyFailed": "Couldn't mark it ready. Try again.",
"markReadyUnsaved": "The page has changes that aren't saved, so it wasn't marked ready.",
"loadError": "Couldn't open this draft.",
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 e9f908b99..8d0849a11 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
@@ -14,8 +14,13 @@ import { Link } from '@/i18n/navigation';
import { Button } from '@/components/ui/button';
import { buttonVariants } from '@/components/ui/button-variants';
import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';
-import { markContentDraftReady, setContentDraftPageType } from '@/lib/actions/content-drafts';
+import {
+ markContentDraftReady,
+ restoreDraftVersion,
+ setContentDraftPageType,
+} from '@/lib/actions/content-drafts';
import { CONTENT_LIBRARY_PATH, type ContentDraft, type PageType } from '@/lib/content/drafts';
+import type { DraftVersion } from '@/lib/content/history';
import {
cleanHtml,
formatHtmlSource,
@@ -27,6 +32,7 @@ import { JsonLd } from '@/lib/content/json-ld-node';
import { detectPageType } from '@/lib/content/page-types';
import { cn } from '@/lib/utils';
import { DropOverlay, useAttachments } from './_attach';
+import { HistoryMenu } from './_history-menu';
import { HtmlBlock, copyToClipboard } from './_html-block';
import { PageTypeMenu } from './_page-type-menu';
import { EditorSidePanel, useSidePanelOpen } from './_side-panel';
@@ -67,7 +73,8 @@ const DOCUMENT_CLASS = cn(
* beside the page or closed from the header, shows what the page earns
* (Impact, CE-016), its brief and the sources it draws on (CE-007, CE-008)
* and the rules it is written to (CE-009); the header's chip says how many
- * of those rules the page meets now.
+ * of those rules the page meets now. History keeps earlier versions (the
+ * imported live page, each Mark ready) and restores any of them (CE-018).
*/
export function DraftEditor({ draft }: { draft: ContentDraft }) {
const t = useTranslations('contentEditor.editor');
@@ -79,6 +86,7 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
useEffect(() => () => clearTimeout(pageReadTimer.current), []);
const [status, setStatus] = useState(draft.status);
const [marking, setMarking] = useState(false);
+ const [restoring, setRestoring] = useState(false);
// A picked page type, or the one the page shows as it is written.
const [picked, setPicked] = useState(draft.pageTypeSource === 'user' ? draft.pageType : null);
const [detectedType, setDetectedType] = useState(() =>
@@ -268,8 +276,9 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
const markReady = async () => {
setMarking(true);
try {
- // What's waiting goes out first, so the ready draft is the one on screen;
- // a page that can't be saved isn't marked ready.
+ // What's waiting goes out first, so the ready draft (and the version
+ // History keeps of it) is the one on screen; a page that can't be saved
+ // isn't marked ready.
try {
await autosave.settle();
} catch {
@@ -287,6 +296,34 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
}
};
+ // A version from History replaces the page: what's waiting is saved first,
+ // as the server keeps the page it replaces, and the page can't change
+ // while the restore runs.
+ const restoreVersion = async (version: DraftVersion, label: string) => {
+ if (!editor || restoring) return;
+ setRestoring(true);
+ editor.setEditable(false, false);
+ try {
+ await autosave.settle();
+ const restored = await restoreDraftVersion(version.id);
+ editor.commands.setContent(restored.bodyHtml, { emitUpdate: false });
+ // The server has this page now: nothing from before it is still to
+ // save, and saves go on from the restored version.
+ autosave.discard(restored);
+ const html = editor.getHTML();
+ setTitle(restored.title);
+ setPageHtml(html);
+ setDetectedType(detectPageType({ title: restored.title, html }, draft.siteType));
+ toast.success(t('history.restored', { version: label }));
+ } catch (err) {
+ console.error('Failed to restore the version:', err);
+ toast.error(t('history.restoreFailed'));
+ } finally {
+ editor.setEditable(true, false);
+ setRestoring(false);
+ }
+ };
+
const pickPageType = async (type: PageType) => {
if (type === picked) return;
const before = picked;
@@ -357,6 +394,17 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
</button>
<div className="ml-auto flex shrink-0 items-center gap-3">
<SaveIndicator state={autosave.state} onRetry={() => void autosave.retry()} />
+ <HistoryMenu
+ draftId={draft.id}
+ disabled={
+ htmlSource !== null
+ ? t('history.htmlOpen')
+ : restoring
+ ? t('history.restoring')
+ : null
+ }
+ onRestore={(version, label) => void restoreVersion(version, label)}
+ />
<Button
variant="outline"
size="sm"
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsx
new file mode 100644
index 000000000..cd8fef428
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsx
@@ -0,0 +1,125 @@
+'use client';
+
+import { useState } from 'react';
+import { useFormatter, useNow, useTranslations } from 'next-intl';
+import { History, Loader2, RotateCcw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { getDraftVersions } from '@/lib/actions/content-drafts';
+import { HISTORY_DAYS, type DraftVersion } from '@/lib/content/history';
+
+/**
+ * History in the editor's header (CE-018): the draft now, then its earlier
+ * versions with their time and origin, read each time the menu opens. Picking
+ * one restores it; the page it replaces is kept as a version too.
+ */
+export function HistoryMenu({
+ draftId,
+ disabled,
+ onRestore,
+}: {
+ draftId: string;
+ /** Why it can't open now (the HTML view is open), or null. */
+ disabled: string | null;
+ onRestore: (version: DraftVersion, label: string) => void;
+}) {
+ const t = useTranslations('contentEditor.editor.history');
+ const format = useFormatter();
+ const now = useNow();
+ const [versions, setVersions] = useState<DraftVersion[] | 'loading' | 'failed'>('loading');
+
+ const load = () => {
+ setVersions('loading');
+ getDraftVersions(draftId)
+ .then(setVersions)
+ .catch((err) => {
+ console.error('Failed to read the draft history:', err);
+ setVersions('failed');
+ });
+ };
+
+ /** "Today 10:42", or "Oct 12, 10:42". */
+ const when = (iso: string) => {
+ const date = new Date(iso);
+ const time = format.dateTime(date, { hour: 'numeric', minute: '2-digit' });
+ return date.toDateString() === now.toDateString()
+ ? t('today', { time })
+ : format.dateTime(date, {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ });
+ };
+
+ return (
+ <DropdownMenu onOpenChange={(open) => open && load()}>
+ <DropdownMenuTrigger
+ render={<Button variant="outline" size="sm" />}
+ disabled={disabled !== null}
+ title={disabled ?? t('hint')}
+ aria-label={t('button')}
+ >
+ <History className="h-3.5 w-3.5" />
+ <span className="hidden xl:inline">{t('button')}</span>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-80">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>
+ {t('title')}{' '}
+ <span className="font-normal text-muted-foreground">
+ · {t('kept', { days: HISTORY_DAYS })}
+ </span>
+ </DropdownMenuLabel>
+ <div className="rounded-md bg-muted/60 px-1.5 py-1.5">
+ <p className="text-sm font-medium">{t('now')}</p>
+ <p className="text-xs text-muted-foreground">{t('nowNote')}</p>
+ </div>
+ {versions === 'loading' ? (
+ <p className="flex items-center gap-2 px-1.5 py-2 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t('loading')}
+ </p>
+ ) : versions === 'failed' ? (
+ <p className="px-1.5 py-2 text-xs text-destructive">{t('failed')}</p>
+ ) : versions.length === 0 ? (
+ <p className="px-1.5 py-2 text-xs text-muted-foreground">{t('empty')}</p>
+ ) : (
+ versions.map((version) => {
+ const label = t(`origin.${version.origin}`);
+ return (
+ <DropdownMenuItem
+ key={version.id}
+ onClick={() => onRestore(version, label)}
+ aria-label={t('restoreLabel', { version: label, when: when(version.createdAt) })}
+ className="items-start"
+ >
+ <span className="min-w-0 flex-1">
+ <span className="block text-sm font-medium">{label}</span>
+ <span className="block text-xs text-muted-foreground">
+ {when(version.createdAt)} · {t(`note.${version.origin}`)}
+ </span>
+ </span>
+ <span className="flex shrink-0 items-center gap-1 text-xs text-muted-foreground">
+ <RotateCcw className="h-3 w-3" />
+ {t('restore')}
+ </span>
+ </DropdownMenuItem>
+ );
+ })
+ )}
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <p className="px-1.5 py-1 text-xs text-muted-foreground">{t('footer')}</p>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsx
index 9ce10e1d0..a6b6d2a25 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsx
@@ -36,6 +36,10 @@ function Harness() {
))}
<button data-big onClick={() => autosave.schedule(content(BIG))} />
<button data-retry onClick={() => void autosave.retry()} />
+ <button
+ data-discard
+ onClick={() => autosave.discard({ updatedAt: 't9', bodyHtml: '<p>restored</p>' })}
+ />
<button
data-settle
onClick={() =>
@@ -172,6 +176,44 @@ describe('the editor’s autosave', () => {
expect(settled()).toBe('unsaved');
});
+ it('settles after a save under way, then sends what is waiting', async () => {
+ let finish!: () => void;
+ saveContentDraft.mockImplementationOnce(
+ () => new Promise((resolve) => (finish = () => resolve(saved('t1', 'h1')))),
+ );
+ edit('<p>1</p>');
+ await act(async () => vi.advanceTimersByTime(1500));
+ edit('<p>12</p>');
+
+ await settle();
+ expect(settled()).toBe('');
+ await act(async () => finish());
+ await act(async () => vi.advanceTimersByTime(200));
+
+ expect(saveContentDraft).toHaveBeenCalledTimes(2);
+ expect(saveContentDraft).toHaveBeenLastCalledWith('d1', {
+ ...content('<p>12</p>'),
+ base: { updatedAt: 't1', bodyHash: 'h1' },
+ });
+ expect(settled()).toBe('saved');
+ expect(state()).toBe('saved');
+ });
+
+ it('discards what is waiting once the server has the page, and saves go on from it', async () => {
+ edit('<p>x</p>');
+ await act(async () => container.querySelector<HTMLButtonElement>('[data-discard]')!.click());
+ await act(async () => vi.advanceTimersByTime(1500));
+ expect(saveContentDraft).not.toHaveBeenCalled();
+ expect(state()).toBe('saved');
+
+ edit('<p>last</p>');
+ await act(async () => vi.advanceTimersByTime(1500));
+ expect(saveContentDraft).toHaveBeenCalledWith('d1', {
+ ...content('<p>last</p>'),
+ base: { updatedAt: 't9', bodyHash: 'hash:<p>restored</p>' },
+ });
+ });
+
it('asks before leaving the page while something is unsaved', async () => {
const leave = () => {
const event = new Event('beforeunload', { cancelable: true });
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts
index 44d07b164..1f8699320 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts
@@ -31,9 +31,11 @@ interface DraftContent {
* so and stops saving until it's reloaded. A page over the size limit isn't
* sent at all.
*
- * Before a step that reads the saved page (Mark ready), settle() saves what
- * is waiting and waits for a save under way, and throws when the page isn't
- * saved.
+ * Before a step that reads the saved page (Mark ready keeps it in History) or
+ * replaces it (a restore), settle() saves what is waiting and waits for a
+ * save under way, and throws when the page isn't saved; discard() drops what
+ * is waiting once the server's page has replaced it, and saves go on from
+ * that version.
*/
export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; bodyHtml: string }) {
const [state, setState] = useState<SaveState>('saved');
@@ -133,6 +135,17 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; b
}
}, [flush]);
+ /** Drops what is waiting to save: the server's page replaced it, and saves go on from it. */
+ const discard = useCallback((version: { updatedAt: string; bodyHtml: string }) => {
+ clearTimeout(timer.current);
+ pending.current = null;
+ failed.current = false;
+ stopped.current = false;
+ base.current = { updatedAt: version.updatedAt, bodyHash: null };
+ loadedBody.current = version.bodyHtml;
+ if (!saving.current) setState('saved');
+ }, []);
+
const unsaved = state !== 'saved';
useEffect(() => {
if (!unsaved) return;
@@ -161,5 +174,5 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; b
[draftId, baseVersion],
);
- return { state, schedule, retry: flush, settle };
+ return { state, schedule, retry: flush, settle, discard };
}
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 5e1b24148..6079bc25b 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
@@ -19,7 +19,11 @@ const rebuildDraftBrief = vi.fn();
const saveDraftRules = vi.fn();
const getMyRuleSets = vi.fn();
const saveMyRuleSet = vi.fn();
+const getDraftVersions = vi.fn();
+const restoreDraftVersion = vi.fn();
vi.mock('@/lib/actions/content-drafts', () => ({
+ getDraftVersions: (...args: unknown[]) => getDraftVersions(...args),
+ restoreDraftVersion: (...args: unknown[]) => restoreDraftVersion(...args),
getMyRuleSets: (...args: unknown[]) => getMyRuleSets(...args),
saveMyRuleSet: (...args: unknown[]) => saveMyRuleSet(...args),
saveDraftRules: (...args: unknown[]) => saveDraftRules(...args),
@@ -155,7 +159,9 @@ beforeEach(() => {
getContentDraft.mockReset();
markContentDraftReady.mockReset();
setContentDraftPageType.mockReset().mockResolvedValue(undefined);
- saveContentDraft.mockReset().mockResolvedValue({ updatedAt: '2026-10-20T10:00:00Z' });
+ saveContentDraft
+ .mockReset()
+ .mockResolvedValue({ ok: true, updatedAt: '2026-10-20T10:00:00Z', bodyHash: 'h0' });
getContentImpact.mockReset().mockResolvedValue(null);
getContentResults.mockReset().mockResolvedValue(null);
getDraftSources.mockReset().mockResolvedValue(null);
@@ -164,6 +170,8 @@ beforeEach(() => {
saveDraftRules.mockReset().mockResolvedValue(undefined);
getMyRuleSets.mockReset().mockResolvedValue({});
saveMyRuleSet.mockReset().mockResolvedValue(undefined);
+ getDraftVersions.mockReset().mockResolvedValue([]);
+ restoreDraftVersion.mockReset();
localStorage.clear();
brandState.activeBrandId = 'b1';
brandState.setActiveBrand.mockReset();
@@ -348,6 +356,130 @@ describe('the content editor', () => {
expect(button('Mark ready')!.disabled).toBe(true);
});
+ describe('history', () => {
+ const versions = [
+ {
+ id: 'v2',
+ origin: 'ready',
+ title: 'Pipeline forecasting',
+ createdAt: '2026-10-19T09:00:00Z',
+ },
+ { id: 'v1', origin: 'import', title: 'Old title', createdAt: '2026-10-12T09:42:00Z' },
+ ];
+ /** Opens History and returns its versions. */
+ async function openHistory() {
+ const trigger = button('History')!;
+ await act(async () => {
+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ trigger.click();
+ });
+ await act(async () => {});
+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ }
+
+ it('lists earlier versions with their origin', async () => {
+ getContentDraft.mockResolvedValue(draft());
+ getDraftVersions.mockResolvedValue(versions);
+ await renderPage();
+
+ const items = await openHistory();
+ expect(getDraftVersions).toHaveBeenCalledWith('d1');
+ expect(document.body.textContent).toContain('Version history · kept 90 days');
+ expect(document.body.textContent).toContain('NowThis draft, as you see it');
+ expect(items.map((item) => item.textContent)).toEqual([
+ expect.stringMatching(/^Marked ready.* · kept on Mark readyRestore$/),
+ expect.stringMatching(/^Live page.* · imported from the URLRestore$/),
+ ]);
+ expect(document.body.textContent).toContain(
+ 'Restoring makes a new version. Nothing is lost.',
+ );
+ });
+
+ it('says when there is nothing to restore yet', async () => {
+ getContentDraft.mockResolvedValue(draft());
+ await renderPage();
+ expect(await openHistory()).toHaveLength(0);
+ expect(document.body.textContent).toContain('No earlier versions yet. Mark ready keeps one.');
+ });
+
+ it('restores a version in place, after saving what was waiting', async () => {
+ getContentDraft.mockResolvedValue(draft());
+ getDraftVersions.mockResolvedValue(versions);
+ restoreDraftVersion.mockResolvedValue({
+ title: 'Old title',
+ bodyHtml: '<h1>Old title</h1><p>As the live page had it.</p>',
+ updatedAt: '2026-10-21T10:00:00Z',
+ });
+ await renderPage();
+ // An edit still waiting for its save.
+ await act(async () => button('Edit as HTML')!.click());
+ const source = container.querySelector('textarea')!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(
+ source,
+ '<h1>Pipeline forecasting</h1><p>Edited.</p>',
+ );
+ source.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () => button('Back to visual')!.click());
+ expect(saveContentDraft).not.toHaveBeenCalled();
+
+ const items = await openHistory();
+ await act(async () => items[1].click());
+ await act(async () => {});
+
+ expect(saveContentDraft).toHaveBeenCalledWith('d1', {
+ title: 'Pipeline forecasting',
+ bodyHtml: '<h1>Pipeline forecasting</h1><p>Edited.</p>',
+ base: {
+ updatedAt: '2026-10-20T10:00:00Z',
+ bodyHash: expect.stringMatching(/^[0-9a-f]{64}$/),
+ },
+ });
+ expect(restoreDraftVersion).toHaveBeenCalledWith('v1');
+ expect(saveContentDraft.mock.invocationCallOrder[0]).toBeLessThan(
+ restoreDraftVersion.mock.invocationCallOrder[0],
+ );
+ expect(container.querySelector('.ProseMirror')!.textContent).toBe(
+ 'Old titleAs the live page had it.',
+ );
+ expect(container.querySelector('header h1')!.textContent).toBe('Old title');
+ expect(toast.success).toHaveBeenCalledWith(
+ 'Restored “Live page”. The page before it is in History.',
+ );
+ // Nothing from before the restore is sent after it.
+ expect(saveContentDraft).toHaveBeenCalledTimes(1);
+ expect(container.querySelector('header')!.textContent).toContain('Saved');
+ });
+
+ it('keeps the page when the restore fails', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ getContentDraft.mockResolvedValue(draft());
+ getDraftVersions.mockResolvedValue(versions);
+ restoreDraftVersion.mockRejectedValue(new Error('not_found'));
+ await renderPage();
+
+ const items = await openHistory();
+ await act(async () => items[0].click());
+ await act(async () => {});
+
+ expect(toast.error).toHaveBeenCalledWith("Couldn't restore it. Try again.");
+ expect(container.querySelector('.ProseMirror')!.textContent).toBe(
+ 'Pipeline forecastingTeams trust it.',
+ );
+ });
+
+ it('waits while the HTML view is open', async () => {
+ getContentDraft.mockResolvedValue(draft());
+ await renderPage();
+ await act(async () => button('Edit as HTML')!.click());
+ expect(button('History')!.title).toBe('Go back to the page to use History');
+ expect(button('History')!.disabled || button('History')!.hasAttribute('data-disabled')).toBe(
+ true,
+ );
+ });
+ });
+
it('shows the page as HTML, and cleans it when it switches back', async () => {
getContentDraft.mockResolvedValue(
draft({
diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.ts
index c9691bf28..24339cade 100644
--- a/web/src/lib/actions/content-drafts.test.ts
+++ b/web/src/lib/actions/content-drafts.test.ts
@@ -18,11 +18,17 @@ let updated: Record<string, unknown> | null;
// Or, update by update, when a test needs more than one.
let updates: (Record<string, unknown> | null)[];
let row: Record<string, unknown> | null;
+// What a list read returns (History's versions).
+let list: Record<string, unknown>[];
+// Database functions called, and what the next one returns.
+let rpcCalls: [string, unknown][];
+let rpcResult: { data: unknown; error: { message: string } | null };
vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },
+ rpc: async (name: string, args: unknown) => (rpcCalls.push([name, args]), rpcResult),
from: () => {
const call: Call = { op: 'select', filters: [] };
calls.push(call);
@@ -36,6 +42,9 @@ vi.mock('@/lib/supabase/server', () => ({
select: () => chain,
eq: (col: string, v: unknown) => (call.filters.push(['eq', col, v]), chain),
in: (col: string, v: unknown) => (call.filters.push(['in', col, v]), chain),
+ gte: (col: string, v: unknown) => (call.filters.push(['gte', col, v]), chain),
+ order: () => chain,
+ limit: async () => ({ data: list, error: null }),
update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),
insert: (value: unknown) => ((call.op = 'insert'), (call.value = value), chain),
maybeSingle: async () => result(),
@@ -46,8 +55,15 @@ vi.mock('@/lib/supabase/server', () => ({
})),
}));
-const { getContentDraft, markContentDraftReady, saveContentDraft, setContentDraftPageType } =
- await import('./content-drafts');
+const {
+ createContentDraft,
+ getContentDraft,
+ getDraftVersions,
+ markContentDraftReady,
+ restoreDraftVersion,
+ saveContentDraft,
+ setContentDraftPageType,
+} = await import('./content-drafts');
const { bodyHash } = await import('@/lib/content/editor');
beforeEach(() => {
@@ -55,6 +71,9 @@ beforeEach(() => {
updated = null;
updates = [];
row = null;
+ list = [];
+ rpcCalls = [];
+ rpcResult = { data: 'v-new', error: null };
});
describe('saveContentDraft', () => {
@@ -264,6 +283,88 @@ describe('markContentDraftReady', () => {
it('says so when the draft isn’t the member’s', async () => {
await expect(markContentDraftReady(DRAFT)).rejects.toThrow('not_found');
});
+
+ it('keeps the ready page in History, and only when it became ready', async () => {
+ updated = { status: 'ready' };
+ await markContentDraftReady(DRAFT);
+ expect(rpcCalls).toEqual([
+ ['content_draft_snapshot', { p_draft_id: DRAFT, p_origin: 'ready' }],
+ ]);
+
+ rpcCalls = [];
+ updated = null;
+ row = { id: DRAFT, brand_id: 'b1', status: 'ready', author: 'user' };
+ await markContentDraftReady(DRAFT);
+ expect(rpcCalls).toEqual([]);
+ });
+
+ it('is ready even when History couldn’t keep the version', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ updated = { status: 'ready' };
+ rpcResult = { data: null, error: { message: 'timeout' } };
+ await expect(markContentDraftReady(DRAFT)).resolves.toBe('ready');
+ expect(error).toHaveBeenCalled();
+ error.mockRestore();
+ });
+});
+
+describe('History', () => {
+ const BRAND = '9a1b2c3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d';
+ const start = {
+ method: 'optimize' as const,
+ title: 'Pricing',
+ pageType: 'pricing' as const,
+ source: { kind: 'content' as const },
+ };
+
+ it('starts a page brought in from its address with the live page', async () => {
+ await createContentDraft(BRAND, {
+ ...start,
+ bodyHtml: '<h1>Pricing</h1>',
+ sourceUrl: 'https://acme.example/pricing',
+ });
+ expect(rpcCalls).toEqual([
+ ['content_draft_snapshot', { p_draft_id: 'new-draft', p_origin: 'import' }],
+ ]);
+
+ rpcCalls = [];
+ await createContentDraft(BRAND, { ...start, bodyHtml: '<h1>Pasted</h1>' });
+ await createContentDraft(BRAND, { ...start, sourceUrl: 'https://acme.example/pricing' });
+ expect(rpcCalls).toEqual([]);
+ });
+
+ it('lists the versions of the last 90 days, the known origins only', async () => {
+ list = [
+ { id: 'v2', origin: 'ready', title: 'A', created_at: '2026-10-20T10:00:00Z' },
+ { id: 'v3', origin: 'something_new', title: 'B', created_at: '2026-10-19T10:00:00Z' },
+ { id: 'v1', origin: 'import', title: 'C', created_at: '2026-10-12T10:00:00Z' },
+ ];
+ await expect(getDraftVersions(DRAFT)).resolves.toEqual([
+ { id: 'v2', origin: 'ready', title: 'A', createdAt: '2026-10-20T10:00:00Z' },
+ { id: 'v1', origin: 'import', title: 'C', createdAt: '2026-10-12T10:00:00Z' },
+ ]);
+ const [, since] = calls[0].filters.find(([op]) => op === 'gte')!.slice(1);
+ const days = (Date.now() - Date.parse(since as string)) / (24 * 60 * 60 * 1000);
+ expect(Math.round(days)).toBe(90);
+ expect(calls[0].filters).toContainEqual(['eq', 'draft_id', DRAFT]);
+ });
+
+ it('restores a version and returns the page the server has now', async () => {
+ rpcResult = {
+ data: { title: 'Old', bodyHtml: '<h1>Old</h1>', updatedAt: '2026-10-21T10:00:00Z' },
+ error: null,
+ };
+ await expect(restoreDraftVersion(DRAFT)).resolves.toEqual({
+ title: 'Old',
+ bodyHtml: '<h1>Old</h1>',
+ updatedAt: '2026-10-21T10:00:00Z',
+ });
+ expect(rpcCalls).toEqual([['content_draft_restore', { p_version_id: DRAFT }]]);
+
+ rpcResult = { data: null, error: null };
+ await expect(restoreDraftVersion(DRAFT)).rejects.toThrow('not_found');
+ await expect(restoreDraftVersion('../etc')).rejects.toThrow('invalid');
+ });
});
describe('getContentDraft', () => {
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 68ab9a83b..304488a14 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -43,6 +43,14 @@ import {
type RebuildSources,
} from '@/lib/content/brief';
import type { ContentBrief } from '@/types';
+import {
+ HISTORY_DAYS,
+ HISTORY_LIMIT,
+ isVersionOrigin,
+ type DraftVersion,
+ type RestoredDraft,
+ type VersionOrigin,
+} from '@/lib/content/history';
import {
DRAFT_SOURCE_KINDS,
SOURCES_DAYS,
@@ -514,6 +522,8 @@ export async function createContentDraft(brandId: string, start: DraftStart): Pr
.select('id')
.single();
if (error) throw new Error(error.message);
+ // A page brought in from its address starts History as the live page.
+ if (sourceUrl && bodyHtml !== undefined) await keepVersion(supabase, data.id, 'import');
return data.id;
}
@@ -643,12 +653,74 @@ export async function markContentDraftReady(id: string): Promise<DraftStatus> {
.select('status')
.maybeSingle();
if (error) throw new Error(error.message);
- if (data) return draftStatus(data.status);
+ if (data) {
+ await keepVersion(supabase, id, 'ready');
+ return draftStatus(data.status);
+ }
const current = await getContentDraft(id);
if (!current) throw new Error('not_found');
return current.status;
}
+/**
+ * Keeps the draft as it is now in its History (CE-018, 00215
+ * content_draft_snapshot). A failure is logged, not thrown: the step it
+ * records has already happened.
+ */
+async function keepVersion(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ id: string,
+ origin: Exclude<VersionOrigin, 'restore'>,
+): Promise<void> {
+ const { error } = await supabase.rpc('content_draft_snapshot', {
+ p_draft_id: id,
+ p_origin: origin,
+ });
+ if (error) console.error(`Failed to keep the draft's ${origin} version:`, error.message);
+}
+
+/** History (CE-018): the draft's versions of the last 90 days, the latest first. */
+export async function getDraftVersions(id: string): Promise<DraftVersion[]> {
+ if (!draftId.safeParse(id).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const since = new Date(Date.now() - HISTORY_DAYS * 24 * 60 * 60 * 1000).toISOString();
+ const { data, error } = await supabase
+ .from('content_draft_versions')
+ .select('id, origin, title, created_at')
+ .eq('draft_id', id)
+ .gte('created_at', since)
+ .order('created_at', { ascending: false })
+ .limit(HISTORY_LIMIT);
+ if (error) throw new Error(error.message);
+ return (data ?? []).flatMap((row) =>
+ isVersionOrigin(row.origin)
+ ? [{ id: row.id, origin: row.origin, title: row.title, createdAt: row.created_at }]
+ : [],
+ );
+}
+
+/**
+ * Restores a version (CE-018): the draft as it is now is kept in History
+ * first, so nothing is lost, then takes the version's title and body
+ * (00215 content_draft_restore). Throws 'not_found' when the version is
+ * unknown, past its 90 days, or another organization's.
+ */
+export async function restoreDraftVersion(versionId: string): Promise<RestoredDraft> {
+ if (!draftId.safeParse(versionId).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc('content_draft_restore', {
+ p_version_id: versionId,
+ });
+ if (error) throw new Error(error.message);
+ if (!data) throw new Error('not_found');
+ const restored = data as unknown as RestoredDraft;
+ return {
+ title: restored.title,
+ bodyHtml: restored.bodyHtml,
+ updatedAt: restored.updatedAt,
+ };
+}
+
/**
* 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.
diff --git a/web/src/lib/content/history.ts b/web/src/lib/content/history.ts
new file mode 100644
index 000000000..13bd3b0ea
--- /dev/null
+++ b/web/src/lib/content/history.ts
@@ -0,0 +1,33 @@
+/**
+ * A draft's version history (Content Editor spec v2 §8, CE-018, 00215): the
+ * live page it was imported from, each Mark ready and publish, and the page
+ * before agent changes or a restore. "Now" is the draft itself.
+ */
+
+/** Where a version came from. */
+export const VERSION_ORIGINS = ['import', 'agent_before', 'ready', 'publish', 'restore'] as const;
+export type VersionOrigin = (typeof VERSION_ORIGINS)[number];
+
+export function isVersionOrigin(value: unknown): value is VersionOrigin {
+ return (VERSION_ORIGINS as readonly unknown[]).includes(value);
+}
+
+/** How long History keeps a version (the server prunes older ones daily). */
+export const HISTORY_DAYS = 90;
+
+/** The most versions History lists. */
+export const HISTORY_LIMIT = 50;
+
+export interface DraftVersion {
+ id: string;
+ origin: VersionOrigin;
+ title: string;
+ createdAt: string;
+}
+
+/** The draft after a restore, as the server now has it. */
+export interface RestoredDraft {
+ title: string;
+ bodyHtml: string;
+ updatedAt: string;
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index bdb8a84ea..30992b058 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -981,6 +981,51 @@ export type Database = {
},
]
}
+ content_draft_versions: {
+ Row: {
+ body_html: string
+ created_at: string
+ created_by: string | null
+ draft_id: string
+ id: string
+ origin: string
+ title: string
+ }
+ Insert: {
+ body_html?: string
+ created_at?: string
+ created_by?: string | null
+ draft_id: string
+ id?: string
+ origin: string
+ title?: string
+ }
+ Update: {
+ body_html?: string
+ created_at?: string
+ created_by?: string | null
+ draft_id?: string
+ id?: string
+ origin?: string
+ title?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "content_draft_versions_created_by_fkey"
+ columns: ["created_by"]
+ isOneToOne: false
+ referencedRelation: "profiles"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "content_draft_versions_draft_id_fkey"
+ columns: ["draft_id"]
+ isOneToOne: false
+ referencedRelation: "content_drafts"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
content_opportunities: {
Row: {
brand_id: string
@@ -3507,6 +3552,16 @@ export type Database = {
Args: { p_days?: number; p_draft_id: string }
Returns: Json
}
+ content_draft_member: { Args: { p_draft_id: string }; Returns: boolean }
+ content_draft_restore: { Args: { p_version_id: string }; Returns: Json }
+ content_draft_snapshot: {
+ Args: { p_draft_id: string; p_origin: string }
+ Returns: string
+ }
+ content_draft_versions_prune: {
+ Args: { p_before: string; p_limit: number }
+ Returns: number
+ }
content_page_impact: {
Args: { p_brand_id: string; p_days: number; p_page: string }
Returns: Json