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.

fix(content): hold the agent card while a restore runs, say what the restore set aside, and open a pre-restore batch's card closed (#1522 follow-ups) (#1536)

Cihana443462b2d1e
diff --git a/supabase/migrations/00289_content_draft_restored_at.sql b/supabase/migrations/00289_content_draft_restored_at.sql
new file mode 100644
index 000000000..4882dae67
--- /dev/null
+++ b/supabase/migrations/00289_content_draft_restored_at.sql
@@ -0,0 +1,128 @@
+-- ============================================================================
+-- 00289: when a draft's page was last restored from History
+-- ============================================================================
+-- The editor opens the agent's card closed when its latest batch is from
+-- before the page was last restored: that batch was for the page before
+-- (#1522's follow-up, #1536). The "restore" version can't say when: it is
+-- kept only when the page differs from the draft's latest version (00215,
+-- content_draft_keep_version), so a restore right after Mark ready, or after
+-- an Undo all, leaves none.
+--
+-- content_drafts.restored_at is set by content_draft_restore (00215) each
+-- time it changes the page; a restore of the page the draft already is
+-- leaves it as it was, and says so ('restored': false), so the editor sets
+-- nothing aside for it. Null for a draft never restored, and for one
+-- restored before this: no backfill, as an update to content_drafts moves
+-- its updated_at (the Library's order, an open editor's save base), and
+-- #1522 hasn't shipped. It is the server's to write:
+-- guard_content_draft_server_columns (00262) refuses a member's.
+
+alter table public.content_drafts
+ add column if not exists restored_at timestamptz;
+
+comment on column public.content_drafts.restored_at is
+ 'When content_draft_restore last changed the page to a History version (00289): the agent''s batch from before it was for the page before. Null when never restored.';
+
+-- As 00215's, with restored_at set when the page changes, and whether it did.
+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;
+ v_changed boolean;
+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.
+ v_changed := v_draft.title is distinct from v_version.title
+ or v_draft.body_html is distinct from v_version.body_html;
+ if v_changed 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, restored_at = now()
+ 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,
+ 'restored', v_changed
+ );
+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;
+
+-- ----------------------------------------------------------------------------
+-- When the page was restored is the server's: as 00262's, with restored_at.
+-- ----------------------------------------------------------------------------
+create or replace function public.guard_content_draft_server_columns()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ -- A role that bypasses RLS is server-side (service role, migrations).
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then
+ return new;
+ end if;
+
+ if tg_op = 'INSERT' then
+ if new.score_before is not null or new.score_after is not null then
+ raise exception 'content draft scores are set server-side'
+ using errcode = '42501';
+ end if;
+ if new.action_id is not null then
+ raise exception 'content draft action is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.agent_state is not null or new.agent_state_at is not null
+ or new.agent_run is not null then
+ raise exception 'content draft agent state is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.published_url is not null or new.published_at is not null then
+ raise exception 'content draft live address is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.restored_at is not null then
+ raise exception 'content draft restore time is set server-side'
+ using errcode = '42501';
+ end if;
+ elsif new.brand_id is distinct from old.brand_id
+ or new.author is distinct from old.author
+ or new.created_by is distinct from old.created_by
+ or new.created_at is distinct from old.created_at
+ or new.score_before is distinct from old.score_before
+ or new.score_after is distinct from old.score_after
+ or new.action_id is distinct from old.action_id
+ or new.agent_state is distinct from old.agent_state
+ or new.agent_state_at is distinct from old.agent_state_at
+ or new.agent_run is distinct from old.agent_run
+ or new.published_url is distinct from old.published_url
+ or new.published_at is distinct from old.published_at
+ or new.restored_at is distinct from old.restored_at
+ then
+ raise exception 'content draft column is managed server-side'
+ using errcode = '42501';
+ end if;
+ return new;
+end;
+$$;
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 476fe39d7..61a61c3f3 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -40216,3 +40216,135 @@ comment on column public.content_draft_suggestions.kept_chars is
comment on column public.content_draft_suggestions.after_chars is
'The characters a page rewrite came to (00285).';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00289_content_draft_restored_at.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00289: when a draft's page was last restored from History
+-- ============================================================================
+-- The editor opens the agent's card closed when its latest batch is from
+-- before the page was last restored: that batch was for the page before
+-- (#1522's follow-up, #1536). The "restore" version can't say when: it is
+-- kept only when the page differs from the draft's latest version (00215,
+-- content_draft_keep_version), so a restore right after Mark ready, or after
+-- an Undo all, leaves none.
+--
+-- content_drafts.restored_at is set by content_draft_restore (00215) each
+-- time it changes the page; a restore of the page the draft already is
+-- leaves it as it was, and says so ('restored': false), so the editor sets
+-- nothing aside for it. Null for a draft never restored, and for one
+-- restored before this: no backfill, as an update to content_drafts moves
+-- its updated_at (the Library's order, an open editor's save base), and
+-- #1522 hasn't shipped. It is the server's to write:
+-- guard_content_draft_server_columns (00262) refuses a member's.
+
+alter table public.content_drafts
+ add column if not exists restored_at timestamptz;
+
+comment on column public.content_drafts.restored_at is
+ 'When content_draft_restore last changed the page to a History version (00289): the agent''s batch from before it was for the page before. Null when never restored.';
+
+-- As 00215's, with restored_at set when the page changes, and whether it did.
+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;
+ v_changed boolean;
+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.
+ v_changed := v_draft.title is distinct from v_version.title
+ or v_draft.body_html is distinct from v_version.body_html;
+ if v_changed 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, restored_at = now()
+ 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,
+ 'restored', v_changed
+ );
+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;
+
+-- ----------------------------------------------------------------------------
+-- When the page was restored is the server's: as 00262's, with restored_at.
+-- ----------------------------------------------------------------------------
+create or replace function public.guard_content_draft_server_columns()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ -- A role that bypasses RLS is server-side (service role, migrations).
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then
+ return new;
+ end if;
+
+ if tg_op = 'INSERT' then
+ if new.score_before is not null or new.score_after is not null then
+ raise exception 'content draft scores are set server-side'
+ using errcode = '42501';
+ end if;
+ if new.action_id is not null then
+ raise exception 'content draft action is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.agent_state is not null or new.agent_state_at is not null
+ or new.agent_run is not null then
+ raise exception 'content draft agent state is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.published_url is not null or new.published_at is not null then
+ raise exception 'content draft live address is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.restored_at is not null then
+ raise exception 'content draft restore time is set server-side'
+ using errcode = '42501';
+ end if;
+ elsif new.brand_id is distinct from old.brand_id
+ or new.author is distinct from old.author
+ or new.created_by is distinct from old.created_by
+ or new.created_at is distinct from old.created_at
+ or new.score_before is distinct from old.score_before
+ or new.score_after is distinct from old.score_after
+ or new.action_id is distinct from old.action_id
+ or new.agent_state is distinct from old.agent_state
+ or new.agent_state_at is distinct from old.agent_state_at
+ or new.agent_run is distinct from old.agent_run
+ or new.published_url is distinct from old.published_url
+ or new.published_at is distinct from old.published_at
+ or new.restored_at is distinct from old.restored_at
+ then
+ raise exception 'content draft column is managed server-side'
+ using errcode = '42501';
+ end if;
+ return new;
+end;
+$$;
+
+notify pgrst, 'reload schema';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 524006bc0..a98a04a9a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -4000,7 +4000,8 @@
"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.",
+ "restoredSame": "“{version}” is the page as it is: nothing changed.",
+ "restored": "Restored “{version}”. {count, plural, =0 {The page before it is in History.} one {The agent’s open change was for the page before, so it was set aside.} other {The agent’s # open changes were for the page before, so they were set aside.}}",
"restoreFailed": "Couldn't restore it. Try again.",
"htmlOpen": "Go back to the page to use History",
"restoring": "Restoring…",
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 723e76bf9..29f98debe 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
@@ -41,6 +41,7 @@ import {
type HandOffError,
getCitedPassages,
getDraftSuggestions,
+ getLastRestoreAt,
getLastPageRewrite,
type AgentEmptyWhy,
keepAgentBeforeVersion,
@@ -1710,11 +1711,17 @@ export function DraftEditor({
[t, tDetail, sourceRows],
);
- // The latest batch, read when the editor opens.
+ // The latest batch, read when the editor opens. One from before the page
+ // was last restored was for the page before: its card opens closed, as it
+ // closed in the tab that restored it (open ones it still has show).
useEffect(() => {
if (!editor) return;
- getDraftSuggestions(draft.id)
- .then(setSuggestions)
+ Promise.all([getDraftSuggestions(draft.id), getLastRestoreAt(draft.id).catch(() => null)])
+ .then(([read, restoredAt]) => {
+ setSuggestions(read);
+ const ranAt = read[0]?.createdAt;
+ if (restoredAt && ranAt && Date.parse(ranAt) < Date.parse(restoredAt)) setBarClosed(true);
+ })
.catch((err) => console.error('Failed to read the agent suggestions:', err));
}, [editor, draft.id]);
@@ -1840,7 +1847,8 @@ export function DraftEditor({
* as it was in History before the first agent change.
*/
const decide = async (ids: string[], decision: SuggestionDecision | 'undo_all') => {
- if (!editor || deciding) return;
+ // Never under a restore: it sets the open ones aside on the page it puts in.
+ if (!editor || deciding || restoringNow.current) return;
const all = suggestionsNow.current;
const next = all.map((s) => ({ ...s }));
const picked = next.filter((s) => ids.includes(s.id));
@@ -2228,7 +2236,7 @@ export function DraftEditor({
* isn't written over: the person runs the rewrite again.
*/
const decidePage = async (s: DraftSuggestion, to: SuggestionStatus) => {
- if (!editor || deciding) return;
+ if (!editor || deciding || restoringNow.current) return;
const undo = to === 'open' && s.status === 'accepted';
// What the page must still read as for the change to go in.
const expected = to === 'accepted' ? (s.beforeHtml ?? '') : undo ? s.afterText : null;
@@ -2292,8 +2300,9 @@ export function DraftEditor({
* batch of suggestions for review.
*/
const fixRules = async (only?: string[]) => {
- // One agent run at a time, and never before the locked passages are read.
- if (!editor || fixing || starting || rewriting || !citedRead) return;
+ // One agent run at a time, never before the locked passages are read,
+ // nor while a restore replaces the page it would read.
+ if (!editor || fixing || starting || rewriting || !citedRead || restoringNow.current) return;
if (openSuggestions > 0) {
toast(t('suggestions.decideFirst', { count: openSuggestions }));
return;
@@ -2494,7 +2503,7 @@ export function DraftEditor({
* workspace's AI usage).
*/
const handOff = async (origin: 'person' | 'auto' = 'person') => {
- if (!editor || fixing || starting || rewriting || !citedRead) return;
+ if (!editor || fixing || starting || rewriting || !citedRead || restoringNow.current) return;
if (openSuggestions > 0) {
toast(t('suggestions.decideFirst', { count: openSuggestions }));
return;
@@ -2620,13 +2629,15 @@ export function DraftEditor({
const agentFixBlocked = (running: boolean) =>
aiUsedUp && !running
? aiUsedUp
- : openSuggestions > 0
- ? t('suggestions.decideFirst', { count: openSuggestions })
- : !citedRead
- ? t('suggestions.citedLoading')
- : agentBusy && !running
- ? t('suggestions.agentBusy')
- : null;
+ : restoring
+ ? t('history.restoring')
+ : openSuggestions > 0
+ ? t('suggestions.decideFirst', { count: openSuggestions })
+ : !citedRead
+ ? t('suggestions.citedLoading')
+ : agentBusy && !running
+ ? t('suggestions.agentBusy')
+ : null;
const agentFix: AgentFix = {
run: (only) => void fixRules(only),
running: fixRunning,
@@ -2819,7 +2830,7 @@ export function DraftEditor({
* here, and the page waits for it.
*/
const startAgent = async () => {
- if (!editor) return;
+ if (!editor || restoringNow.current) return;
setStarting(true);
try {
await autosave.settle();
@@ -2868,11 +2879,13 @@ export function DraftEditor({
blocked:
aiUsedUp && !starting
? aiUsedUp
- : openSuggestions > 0
- ? t('suggestions.decideFirst', { count: openSuggestions })
- : agentBusy && !starting
- ? t('suggestions.agentBusy')
- : null,
+ : restoring
+ ? t('history.restoring')
+ : openSuggestions > 0
+ ? t('suggestions.decideFirst', { count: openSuggestions })
+ : agentBusy && !starting
+ ? t('suggestions.agentBusy')
+ : null,
}
: undefined;
@@ -2890,7 +2903,7 @@ export function DraftEditor({
*/
const rewritePage = async ({ citedToo = false }: { citedToo?: boolean } = {}) => {
// Never before the locked passages are read: the rewrite would be told none are.
- if (!editor || agentBusy || !citedRead) return;
+ if (!editor || agentBusy || !citedRead || restoringNow.current) return;
setRewriting(true);
try {
await autosave.settle();
@@ -2949,13 +2962,15 @@ export function DraftEditor({
blocked:
aiUsedUp && !rewriting
? aiUsedUp
- : openSuggestions > 0
- ? t('suggestions.decideFirst', { count: openSuggestions })
- : !citedRead
- ? t('suggestions.citedLoading')
- : agentBusy && !rewriting
- ? t('suggestions.agentBusy')
- : null,
+ : restoring
+ ? t('history.restoring')
+ : openSuggestions > 0
+ ? t('suggestions.decideFirst', { count: openSuggestions })
+ : !citedRead
+ ? t('suggestions.citedLoading')
+ : agentBusy && !rewriting
+ ? t('suggestions.agentBusy')
+ : null,
}
: undefined;
// Before you publish (CE-041) opens on Mark ready once Quality is live,
@@ -3300,6 +3315,7 @@ export function DraftEditor({
try {
await autosave.settle();
const restored = await restoreDraftVersion(draft.id, version.id);
+ const pageBefore = editor.getHTML();
editor
.chain()
.setMeta(CITED_EDIT_ALLOWED, true)
@@ -3314,12 +3330,18 @@ export function DraftEditor({
setTitle(restored.title);
setPageHtml(html);
detectType(restored.title, html);
- toast.success(t('history.restored', { version: label }));
void loadCited();
// The agent's open suggestions were for the page before it: they go,
// so they hold no later run (open_suggestions). Left open when that
- // fails, for the person to decide on the card.
- const stale = suggestionsNow.current.filter((s) => s.status === 'open').map((s) => s.id);
+ // fails, for the person to decide on the card; and kept when the
+ // version is the page it was (nothing was restored).
+ // As the server says (00289), or, from a database before it, as the page reads.
+ const samePage =
+ restored.restored === false ||
+ (restored.restored === undefined && html === pageBefore && restored.title === title);
+ const stale = samePage
+ ? []
+ : suggestionsNow.current.filter((s) => s.status === 'open').map((s) => s.id);
const setAside =
stale.length === 0 ||
(await decideDraftSuggestions(stale, 'rejected').then(
@@ -3334,9 +3356,15 @@ export function DraftEditor({
now.map((s) => (stale.includes(s.id) ? { ...s, status: 'rejected' as const } : s)),
);
}
+ // It says what went: they counted toward AI usage, and many may still apply.
+ toast.success(
+ samePage
+ ? t('history.restoredSame', { version: label })
+ : t('history.restored', { version: label, count: setAside ? stale.length : 0 }),
+ );
// Its card goes as if closed, with its Undo all and last run: they were
// for the page before (editor test 2026-10-25). A new batch opens it.
- setBarClosed(true);
+ if (!samePage) setBarClosed(true);
} catch (err) {
console.error('Failed to restore the version:', err);
toast.error(t('history.restoreFailed'));
@@ -3746,7 +3774,9 @@ export function DraftEditor({
size="sm"
className="h-7"
// Used up, as the red strip above says: it would only fail again.
- disabled={!!aiUsedUp || agentBusy || !editor || (failedRewrite && !citedRead)}
+ disabled={
+ !!aiUsedUp || agentBusy || restoring || !editor || (failedRewrite && !citedRead)
+ }
title={aiUsedUp ?? undefined}
onClick={() => void (failedRewrite ? rewritePage() : startAgent())}
>
@@ -3792,7 +3822,7 @@ export function DraftEditor({
sourceCount={batchSources(suggestions).length}
onSeeSources={() => openPanelTab('sources')}
// Not while the HTML view holds the page: it would write over it.
- busy={deciding || htmlSource !== null}
+ busy={deciding || restoring || htmlSource !== null}
working={agentWorking}
run={agentRun}
lastRunFailed={lastRunFailed}
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 83c1ee0b3..541d57eaf 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
@@ -72,6 +72,7 @@ const getDraftHandoffs = vi.fn();
const restoreDraftVersion = vi.fn();
const getCitedPassages = vi.fn();
const getDraftSuggestions = vi.fn();
+const getLastRestoreAt = vi.fn();
// What the page's last rewrite came to (Length's reach): none unless a test gives one.
const getLastPageRewrite = vi.fn();
const decideDraftSuggestions = vi.fn();
@@ -89,6 +90,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({
startAgentWriting: (...args: unknown[]) => startAgentWriting(...args),
startPageRewrite: (...args: unknown[]) => startPageRewrite(...args),
getDraftSuggestions: (...args: unknown[]) => getDraftSuggestions(...args),
+ getLastRestoreAt: (...args: unknown[]) => getLastRestoreAt(...args),
getLastPageRewrite: (...args: unknown[]) => getLastPageRewrite(...args),
decideDraftSuggestions: (...args: unknown[]) => decideDraftSuggestions(...args),
keepAgentBeforeVersion: (...args: unknown[]) => keepAgentBeforeVersion(...args),
@@ -372,6 +374,7 @@ beforeEach(() => {
restoreDraftVersion.mockReset();
getCitedPassages.mockReset().mockResolvedValue([]);
getDraftSuggestions.mockReset().mockResolvedValue([]);
+ getLastRestoreAt.mockReset().mockResolvedValue(null);
getLastPageRewrite.mockReset().mockResolvedValue(null);
decideDraftSuggestions.mockReset().mockResolvedValue(1);
keepAgentBeforeVersion.mockReset().mockResolvedValue(undefined);
@@ -1548,6 +1551,231 @@ describe('the content editor', () => {
expect(decideDraftSuggestions).toHaveBeenCalledWith(['n1'], 'rejected');
// Its Undo all would undo nothing on the page restored.
expect(card()).toBeNull();
+ // Said, as they counted toward AI usage.
+ expect(toast.success).toHaveBeenCalledWith(
+ expect.stringMatching(
+ /^Restored “.+”\. The agent’s open change was for the page before, so it was set aside\.$/,
+ ),
+ );
+ });
+
+ it('waits while a restore runs: the card’s buttons and the agent’s runs', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ bodyHtml: '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>',
+ }),
+ );
+ getDraftVersions.mockResolvedValue(versions);
+ getDraftSuggestions.mockResolvedValue([
+ {
+ id: 'n1',
+ batchId: 'b2',
+ actionId: null,
+ actionNo: null,
+ kind: 'replace' as const,
+ blockText: 'We delve into how teams forecast.',
+ beforeText: 'delve into',
+ afterText: 'look at',
+ reason: 'remove an AI trace (rule)',
+ ruleKeys: ['aiTraces'],
+ status: 'open' as const,
+ },
+ ]);
+ let restored: (value: unknown) => void = () => {};
+ restoreDraftVersion.mockReturnValue(new Promise((r) => (restored = r)));
+ await renderPage();
+ const accept = () =>
+ [
+ ...container
+ .querySelector('[role="region"][aria-label="Agent suggestions"]')!
+ .querySelectorAll('button'),
+ ].find((b) => b.textContent === 'Accept all')!;
+ const items = await openHistory();
+ await act(async () => items[1].click());
+ // The decision would land under the restore setting the same ones aside.
+ expect(accept().disabled || accept().hasAttribute('data-disabled')).toBe(true);
+ // The card on the page too.
+ const inPage = [
+ ...container
+ .querySelector('.ProseMirror [data-suggestion="n1"]')!
+ .querySelectorAll('button'),
+ ].find((b) => b.textContent === 'Accept')!;
+ await act(async () => inPage.click());
+ await act(async () =>
+ restored({
+ title: 'Old title',
+ bodyHtml: '<h1>Old title</h1><p>We delve into how teams forecast.</p>',
+ updatedAt: '2026-10-21T10:00:00Z',
+ }),
+ );
+ await act(async () => {});
+ expect(decideDraftSuggestions).toHaveBeenCalledTimes(1);
+ expect(decideDraftSuggestions).toHaveBeenCalledWith(['n1'], 'rejected');
+ });
+
+ // A batch, decided or open, the agent left on 21 October.
+ const ranBefore = (status: 'accepted' | 'open') => [
+ {
+ id: 'a1',
+ batchId: 'b2',
+ actionId: null,
+ actionNo: null,
+ kind: 'replace' as const,
+ blockText: 'Teams delve into how they forecast.',
+ beforeText: 'delve into',
+ afterText: 'look at',
+ reason: 'remove an AI trace (rule)',
+ ruleKeys: ['aiTraces'],
+ status,
+ createdAt: '2026-10-21T10:00:00Z',
+ },
+ ];
+ const agentCard = () =>
+ container.querySelector('[role="region"][aria-label="Agent suggestions"]');
+
+ it('holds Try again while a restore runs', async () => {
+ getContentDraft.mockResolvedValue(draft({ status: 'draft', agentState: 'failed' }));
+ getDraftVersions.mockResolvedValue(versions);
+ restoreDraftVersion.mockReturnValue(new Promise(() => {}));
+ await renderPage();
+ const items = await openHistory();
+ await act(async () => items[1].click());
+ expect(button('Try again')!.disabled).toBe(true);
+ await act(async () => button('Try again')!.click());
+ expect(startAgentWriting).not.toHaveBeenCalled();
+ });
+
+ it('says how many open changes it set aside', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ bodyHtml:
+ '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p><p>Teams trust it.</p>',
+ }),
+ );
+ getDraftVersions.mockResolvedValue(versions);
+ const open = {
+ batchId: 'b2',
+ actionId: null,
+ actionNo: null,
+ kind: 'replace' as const,
+ reason: 'remove an AI trace (rule)',
+ ruleKeys: ['aiTraces'],
+ status: 'open' as const,
+ };
+ getDraftSuggestions.mockResolvedValue([
+ {
+ ...open,
+ id: 'n1',
+ blockText: 'We delve into how teams forecast.',
+ beforeText: 'delve into',
+ afterText: 'look at',
+ },
+ {
+ ...open,
+ id: 'n2',
+ blockText: 'Teams trust it.',
+ beforeText: 'trust',
+ afterText: 'rely on',
+ },
+ ]);
+ 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();
+ const items = await openHistory();
+ await act(async () => items[1].click());
+ await act(async () => {});
+ expect(decideDraftSuggestions).toHaveBeenCalledWith(['n1', 'n2'], 'rejected');
+ expect(toast.success).toHaveBeenCalledWith(
+ expect.stringMatching(
+ /^Restored “.+”\. The agent’s 2 open changes were for the page before, so they were set aside\.$/,
+ ),
+ );
+ });
+
+ it('sets nothing aside when the version is the page as it is', async () => {
+ const body = '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>';
+ getContentDraft.mockResolvedValue(draft({ bodyHtml: body }));
+ getDraftVersions.mockResolvedValue(versions);
+ getDraftSuggestions.mockResolvedValue([
+ {
+ id: 'n1',
+ batchId: 'b2',
+ actionId: null,
+ actionNo: null,
+ kind: 'replace' as const,
+ blockText: 'We delve into how teams forecast.',
+ beforeText: 'delve into',
+ afterText: 'look at',
+ reason: 'remove an AI trace (rule)',
+ ruleKeys: ['aiTraces'],
+ status: 'open' as const,
+ },
+ ]);
+ // The server left the draft as it was, and says so (00289).
+ restoreDraftVersion.mockResolvedValue({
+ title: 'Pipeline forecasting',
+ bodyHtml: body,
+ updatedAt: '2026-10-20T10:00:00Z',
+ restored: false,
+ });
+ await renderPage();
+ const items = await openHistory();
+ await act(async () => items[1].click());
+ await act(async () => {});
+ expect(decideDraftSuggestions).not.toHaveBeenCalled();
+ expect(
+ container.querySelector('[role="region"][aria-label="Agent suggestions"]'),
+ ).not.toBeNull();
+ expect(toast.success).toHaveBeenCalledWith(
+ expect.stringMatching(/^“.+” is the page as it is: nothing changed\.$/),
+ );
+ });
+
+ it('opens the card closed for a batch from before the page was last restored', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({ bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams look at how they forecast.</p>' }),
+ );
+ getLastRestoreAt.mockResolvedValue('2026-10-22T09:00:00Z');
+ getDraftSuggestions.mockResolvedValue(ranBefore('accepted'));
+ await renderPage();
+ // After a reload, or in another tab: its Undo all was for the page before.
+ expect(getLastRestoreAt).toHaveBeenCalledWith('d1');
+ expect(agentCard()).toBeNull();
+ });
+
+ it('still shows a batch from before the restore with open changes to decide', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams delve into how they forecast.</p>',
+ }),
+ );
+ getLastRestoreAt.mockResolvedValue('2026-10-22T09:00:00Z');
+ getDraftSuggestions.mockResolvedValue(ranBefore('open'));
+ await renderPage();
+ expect(agentCard()).not.toBeNull();
+ });
+
+ it('shows a batch left after the last restore as ever', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({ bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams look at how they forecast.</p>' }),
+ );
+ getLastRestoreAt.mockResolvedValue('2026-10-20T09:00:00Z');
+ getDraftSuggestions.mockResolvedValue(ranBefore('accepted'));
+ await renderPage();
+ expect(agentCard()).not.toBeNull();
+ });
+
+ it('shows the batch as ever when the last restore can’t be read', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({ bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams look at how they forecast.</p>' }),
+ );
+ getLastRestoreAt.mockRejectedValue(new Error('offline'));
+ getDraftSuggestions.mockResolvedValue(ranBefore('accepted'));
+ await renderPage();
+ expect(agentCard()).not.toBeNull();
});
it('closes the card of a batch already decided: its Undo all and last run were for the page before', async () => {
@@ -1636,6 +1864,9 @@ describe('the content editor', () => {
await act(async () => items[1].click());
await act(async () => {});
// Still open on the server: on the card to decide, never shown as set aside.
+ expect(toast.success).toHaveBeenCalledWith(
+ expect.stringMatching(/^Restored “.+”\. The page before it is in History\.$/),
+ );
const card = container.querySelector('[role="region"][aria-label="Agent suggestions"]');
expect(card).not.toBeNull();
expect(
diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.ts
index b96b5682c..9e4f4ae0a 100644
--- a/web/src/lib/actions/content-drafts.test.ts
+++ b/web/src/lib/actions/content-drafts.test.ts
@@ -106,6 +106,7 @@ const {
fixDraftRules,
decideDraftSuggestions,
getDraftSuggestions,
+ getLastRestoreAt,
keepAgentBeforeVersion,
getCitedPassages,
getContentDraft,
@@ -828,6 +829,18 @@ describe('History', () => {
});
expect(rpcCalls).toEqual([['content_draft_restore', { p_version_id: VERSION }]]);
+ // Whether the page changed, as the server says it (00289).
+ rpcResult = {
+ data: {
+ title: 'Old',
+ bodyHtml: '<h1>Old</h1>',
+ updatedAt: '2026-10-21T10:00:00Z',
+ restored: false,
+ },
+ error: null,
+ };
+ await expect(restoreDraftVersion(DRAFT, VERSION)).resolves.toMatchObject({ restored: false });
+
rpcResult = { data: null, error: null };
await expect(restoreDraftVersion(DRAFT, VERSION)).rejects.toThrow('not_found');
await expect(restoreDraftVersion(DRAFT, '../etc')).rejects.toThrow('invalid');
@@ -975,6 +988,17 @@ describe('agent suggestions', () => {
expect(calls[1].filters).toContainEqual(['eq', 'batch_id', 'new']);
});
+ it('reads when the page was last restored, or none (00289)', async () => {
+ queue = [[{ restored_at: '2026-10-22T09:00:00Z' }]];
+ await expect(getLastRestoreAt(DRAFT)).resolves.toBe('2026-10-22T09:00:00Z');
+ expect(calls[0].filters).toEqual([['eq', 'id', DRAFT]]);
+ queue = [[{ restored_at: null }]];
+ await expect(getLastRestoreAt(DRAFT)).resolves.toBeNull();
+ queue = [[]];
+ await expect(getLastRestoreAt(DRAFT)).resolves.toBeNull();
+ await expect(getLastRestoreAt('../etc')).rejects.toThrow('invalid');
+ });
+
it('reads none for a draft the agent never suggested on', async () => {
list = [];
await expect(getDraftSuggestions(DRAFT)).resolves.toEqual([]);
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 6a27124d7..bf101966e 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -1745,6 +1745,23 @@ export async function getDraftVersions(id: string): Promise<DraftVersion[]> {
);
}
+/**
+ * When the draft's page was last restored from History (00289: set each time
+ * a restore changes the page), or null. The agent's batch from before it was
+ * for the page before: the editor opens its card closed.
+ */
+export async function getLastRestoreAt(id: string): Promise<string | null> {
+ if (!draftId.safeParse(id).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_drafts')
+ .select('restored_at')
+ .eq('id', id)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ return data?.restored_at ?? null;
+}
+
/**
* History's hand-offs (Quality CE-051): the draft's runs of Hand off (00275,
* its members may read them) in the last 90 days, the latest first, each
@@ -1842,7 +1859,12 @@ export async function restoreDraftVersion(id: string, versionId: string): Promis
else if (typed) updatedAt = typed.updated_at;
}
}
- return { title: restored.title, bodyHtml: restored.bodyHtml, updatedAt };
+ return {
+ title: restored.title,
+ bodyHtml: restored.bodyHtml,
+ updatedAt,
+ ...(typeof restored.restored === 'boolean' ? { restored: restored.restored } : {}),
+ };
}
/**
diff --git a/web/src/lib/content/history.ts b/web/src/lib/content/history.ts
index 20011026a..af4ef890a 100644
--- a/web/src/lib/content/history.ts
+++ b/web/src/lib/content/history.ts
@@ -48,4 +48,6 @@ export interface RestoredDraft {
title: string;
bodyHtml: string;
updatedAt: string;
+ /** Whether the page changed (00289); false for the version the page already was, unsaid before 00289. */
+ restored?: boolean;
}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 3a2992ae4..8e16bc277 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1252,6 +1252,7 @@ export type Database = {
prompt_ids: string[]
published_at: string | null
published_url: string | null
+ restored_at: string | null
reviewer_id: string | null
rules: Json | null
source_url: string | null
@@ -1292,6 +1293,7 @@ export type Database = {
prompt_ids?: string[]
published_at?: string | null
published_url?: string | null
+ restored_at?: string | null
reviewer_id?: string | null
rules?: Json | null
source_url?: string | null
@@ -1332,6 +1334,7 @@ export type Database = {
prompt_ids?: string[]
published_at?: string | null
published_url?: string | null
+ restored_at?: string | null
reviewer_id?: string | null
rules?: Json | null
source_url?: string | null