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): review an agent's suggestions in the page, accept or reject each (#1303)

Cihanb10d04be4396
diff --git a/supabase/migrations/00217_content_draft_suggestions.sql b/supabase/migrations/00217_content_draft_suggestions.sql
new file mode 100644
index 000000000..4e46d46c9
--- /dev/null
+++ b/supabase/migrations/00217_content_draft_suggestions.sql
@@ -0,0 +1,99 @@
+-- ============================================================================
+-- 00217: an agent's suggestions on a draft, for review in the editor
+-- ============================================================================
+-- Agent suggestions (Content Editor spec v2 §8, CE-018): an agent leaves
+-- changes on a draft for a person to accept or reject, each with who made it
+-- and why. They sit in the page as cards; accepting one changes the page,
+-- and Undo, Restore and Undo all bring it back to review.
+--
+-- A suggestion is one of two kinds:
+-- * replace: in the passage whose text is block_text, before_text becomes
+-- after_text (plain text);
+-- * insert: after the passage whose text is block_text, the blocks in
+-- after_text (HTML, checked against the draft allow-list where it is
+-- inserted) are added.
+-- One agent run is a batch; the editor shows the latest. action_id names the
+-- Action Center action the run came from ("from Action AC-214").
+--
+-- Agents write suggestions through the server (service role, CE-018 part D
+-- and CE-022). Members read them, and decide them only through
+-- content_draft_decide_suggestions, which records who decided and when.
+create table if not exists public.content_draft_suggestions (
+ id uuid primary key default gen_random_uuid(),
+ draft_id uuid not null references public.content_drafts(id) on delete cascade,
+ batch_id uuid not null,
+ action_id uuid references public.actions(id) on delete set null,
+ agent text not null default 'content_agent' check (agent in ('content_agent')),
+ kind text not null check (kind in ('replace', 'insert')),
+ block_text text not null check (char_length(block_text) between 1 and 5000),
+ before_text text not null default '' check (char_length(before_text) <= 5000),
+ after_text text not null check (char_length(after_text) between 1 and 20000),
+ reason text not null check (char_length(reason) between 1 and 300),
+ rule_keys text[] not null default '{}',
+ position integer not null default 0,
+ status text not null default 'open' check (status in ('open', 'accepted', 'rejected')),
+ decided_by uuid references public.profiles(id) on delete set null,
+ decided_at timestamptz,
+ created_at timestamptz not null default now(),
+ -- A replacement names the words it replaces.
+ check (kind = 'insert' or before_text <> '')
+);
+
+create index if not exists content_draft_suggestions_draft_idx
+ on public.content_draft_suggestions (draft_id, created_at desc);
+
+alter table public.content_draft_suggestions enable row level security;
+
+-- A draft the member can read is one in their organization (content_drafts'
+-- own member policies), so its suggestions follow it.
+create policy "content_draft_suggestions: member select"
+ on public.content_draft_suggestions
+ for select
+ using (draft_id in (select d.id from public.content_drafts d));
+
+grant select on public.content_draft_suggestions to authenticated;
+
+comment on table public.content_draft_suggestions is
+ 'Content Editor (CE-018): an agent''s suggested changes on a draft — replace words in a passage, or insert blocks after one — open, accepted or rejected. Written by the server; decided through content_draft_decide_suggestions.';
+
+-- Accepts, rejects, or sends back to review (open) the given suggestions of
+-- drafts the caller may change, recording who decided and when. Returns how
+-- many changed.
+create or replace function public.content_draft_decide_suggestions(
+ p_ids uuid[],
+ p_status text
+)
+returns integer
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_count integer;
+begin
+ if p_status is null or p_status not in ('open', 'accepted', 'rejected') then
+ raise exception 'content_draft_decide_suggestions: unknown status %', p_status
+ using errcode = '22023';
+ end if;
+ if p_ids is null or cardinality(p_ids) = 0 then
+ return 0;
+ end if;
+ if cardinality(p_ids) > 200 then
+ raise exception 'content_draft_decide_suggestions: at most 200 at once' using errcode = '22023';
+ end if;
+
+ update public.content_draft_suggestions s
+ set status = p_status,
+ decided_by = case when p_status = 'open' then null else auth.uid() end,
+ decided_at = case when p_status = 'open' then null else now() end
+ where s.id = any(p_ids)
+ and public.content_draft_member(s.draft_id);
+ get diagnostics v_count = row_count;
+ return v_count;
+end;
+$$;
+
+revoke all on function public.content_draft_decide_suggestions(uuid[], text) from public, anon;
+grant execute on function public.content_draft_decide_suggestions(uuid[], text)
+ to authenticated, service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 216d43a33..27e04939d 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -30311,3 +30311,106 @@ revoke all on function public.content_draft_cited_answers(uuid, integer) from pu
grant execute on function public.content_draft_cited_answers(uuid, integer)
to authenticated, service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00217_content_draft_suggestions.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00217: an agent's suggestions on a draft, for review in the editor
+-- ============================================================================
+-- Agent suggestions (Content Editor spec v2 §8, CE-018): an agent leaves
+-- changes on a draft for a person to accept or reject, each with who made it
+-- and why. They sit in the page as cards; accepting one changes the page,
+-- and Undo, Restore and Undo all bring it back to review.
+--
+-- A suggestion is one of two kinds:
+-- * replace: in the passage whose text is block_text, before_text becomes
+-- after_text (plain text);
+-- * insert: after the passage whose text is block_text, the blocks in
+-- after_text (HTML, checked against the draft allow-list where it is
+-- inserted) are added.
+-- One agent run is a batch; the editor shows the latest. action_id names the
+-- Action Center action the run came from ("from Action AC-214").
+--
+-- Agents write suggestions through the server (service role, CE-018 part D
+-- and CE-022). Members read them, and decide them only through
+-- content_draft_decide_suggestions, which records who decided and when.
+create table if not exists public.content_draft_suggestions (
+ id uuid primary key default gen_random_uuid(),
+ draft_id uuid not null references public.content_drafts(id) on delete cascade,
+ batch_id uuid not null,
+ action_id uuid references public.actions(id) on delete set null,
+ agent text not null default 'content_agent' check (agent in ('content_agent')),
+ kind text not null check (kind in ('replace', 'insert')),
+ block_text text not null check (char_length(block_text) between 1 and 5000),
+ before_text text not null default '' check (char_length(before_text) <= 5000),
+ after_text text not null check (char_length(after_text) between 1 and 20000),
+ reason text not null check (char_length(reason) between 1 and 300),
+ rule_keys text[] not null default '{}',
+ position integer not null default 0,
+ status text not null default 'open' check (status in ('open', 'accepted', 'rejected')),
+ decided_by uuid references public.profiles(id) on delete set null,
+ decided_at timestamptz,
+ created_at timestamptz not null default now(),
+ -- A replacement names the words it replaces.
+ check (kind = 'insert' or before_text <> '')
+);
+
+create index if not exists content_draft_suggestions_draft_idx
+ on public.content_draft_suggestions (draft_id, created_at desc);
+
+alter table public.content_draft_suggestions enable row level security;
+
+-- A draft the member can read is one in their organization (content_drafts'
+-- own member policies), so its suggestions follow it.
+create policy "content_draft_suggestions: member select"
+ on public.content_draft_suggestions
+ for select
+ using (draft_id in (select d.id from public.content_drafts d));
+
+grant select on public.content_draft_suggestions to authenticated;
+
+comment on table public.content_draft_suggestions is
+ 'Content Editor (CE-018): an agent''s suggested changes on a draft — replace words in a passage, or insert blocks after one — open, accepted or rejected. Written by the server; decided through content_draft_decide_suggestions.';
+
+-- Accepts, rejects, or sends back to review (open) the given suggestions of
+-- drafts the caller may change, recording who decided and when. Returns how
+-- many changed.
+create or replace function public.content_draft_decide_suggestions(
+ p_ids uuid[],
+ p_status text
+)
+returns integer
+language plpgsql
+volatile
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_count integer;
+begin
+ if p_status is null or p_status not in ('open', 'accepted', 'rejected') then
+ raise exception 'content_draft_decide_suggestions: unknown status %', p_status
+ using errcode = '22023';
+ end if;
+ if p_ids is null or cardinality(p_ids) = 0 then
+ return 0;
+ end if;
+ if cardinality(p_ids) > 200 then
+ raise exception 'content_draft_decide_suggestions: at most 200 at once' using errcode = '22023';
+ end if;
+
+ update public.content_draft_suggestions s
+ set status = p_status,
+ decided_by = case when p_status = 'open' then null else auth.uid() end,
+ decided_at = case when p_status = 'open' then null else now() end
+ where s.id = any(p_ids)
+ and public.content_draft_member(s.draft_id);
+ get diagnostics v_count = row_count;
+ return v_count;
+end;
+$$;
+
+revoke all on function public.content_draft_decide_suggestions(uuid[], text) from public, anon;
+grant execute on function public.content_draft_decide_suggestions(uuid[], text)
+ to authenticated, service_role;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 6aa63325a..efbb35b5c 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3352,6 +3352,32 @@
"insert": "Add block"
},
"markedReady": "Marked ready. Publish it on your site when you're ready.",
+ "suggestions": {
+ "bar": "Agent suggestions",
+ "agent": "Content Agent",
+ "suggested": "suggested {count, plural, one {# change} other {# changes}}",
+ "fromAction": "from Action AC-{no}",
+ "decided": "{accepted} accepted · {rejected} rejected",
+ "rulesOpen": "{count, plural, one {# rule still open} other {# rules still open}}",
+ "acceptAll": "Accept all",
+ "rejectAll": "Reject all",
+ "undoAll": "Undo all",
+ "close": "Close",
+ "accept": "Accept",
+ "reject": "Reject",
+ "accepted": "Accepted",
+ "rejected": "Rejected",
+ "undo": "Undo",
+ "restore": "Restore",
+ "locked": "AI quotes this passage, so agents don't change it.",
+ "stale": "The page changed here since the agent read it.",
+ "acceptedToast": "{count, plural, one {Accepted} other {# changes accepted}} · undo any time",
+ "rejectedToast": "{count, plural, one {Rejected} other {# changes rejected}} · restore any time",
+ "undoneToast": "{count, plural, one {Undone · back to the suggestion} other {# undone · the suggestions are back}}",
+ "notApplied": "{count, plural, one {# suggestion couldn't be applied} other {# suggestions couldn't be applied}}: the page changed there, or AI quotes the passage.",
+ "saveFailed": "Couldn't keep the decision. Try again.",
+ "htmlBlocked": "Accept or reject the {count, plural, one {# agent suggestion} other {# agent suggestions}} first, then edit as HTML."
+ },
"cited": {
"platform": "{name} {count}×",
"label": "✓ Cited by {platforms} in {days} days · keep wording",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-bar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-bar.tsx
new file mode 100644
index 000000000..9e83da4be
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-bar.tsx
@@ -0,0 +1,111 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { Bot, X } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { Button } from '@/components/ui/button';
+import { suggestionCounts, type DraftSuggestion } from '@/lib/content/suggestions';
+
+/**
+ * The agent bar over the page (CE-018): while an agent's suggestions are
+ * open, who left how many and from which action, with Reject all and Accept
+ * all (open ones only); once all are decided, how many were accepted and
+ * rejected and how many rules are still open. Undo all brings every decided
+ * one back to review.
+ */
+export function AgentBar({
+ suggestions,
+ rulesOpen,
+ busy,
+ onAcceptAll,
+ onRejectAll,
+ onUndoAll,
+ onClose,
+}: {
+ suggestions: DraftSuggestion[];
+ rulesOpen: number;
+ busy: boolean;
+ onAcceptAll: () => void;
+ onRejectAll: () => void;
+ onUndoAll: () => void;
+ onClose: () => void;
+}) {
+ const t = useTranslations('contentEditor.editor.suggestions');
+ const { open, accepted, rejected } = suggestionCounts(suggestions);
+ const action = suggestions.find((s) => s.actionId && s.actionNo !== null);
+
+ return (
+ <div
+ role="region"
+ aria-label={t('bar')}
+ className="flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b bg-muted/40 px-4 py-1.5 text-[13px]"
+ >
+ <Bot aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />
+ {open > 0 ? (
+ <span className="min-w-0">
+ <span className="font-medium">{t('agent')}</span> {t('suggested', { count: open })}
+ {action && (
+ <>
+ {' · '}
+ <Link
+ href={`/dashboard/action-center/actions?action=${action.actionId}`}
+ className="underline underline-offset-2 hover:no-underline"
+ >
+ {t('fromAction', { no: action.actionNo! })}
+ </Link>
+ </>
+ )}
+ </span>
+ ) : (
+ <span className="min-w-0">
+ <span className="font-medium">{t('decided', { accepted, rejected })}</span>
+ {rulesOpen > 0 && (
+ <span className="text-muted-foreground">
+ {' · '}
+ {t('rulesOpen', { count: rulesOpen })}
+ </span>
+ )}
+ </span>
+ )}
+ <span className="ml-auto flex shrink-0 items-center gap-1.5">
+ {accepted + rejected > 0 && (
+ <Button variant="ghost" size="sm" className="h-7" disabled={busy} onClick={onUndoAll}>
+ {t('undoAll')}
+ </Button>
+ )}
+ {open > 0 ? (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7"
+ disabled={busy}
+ onClick={onRejectAll}
+ >
+ {t('rejectAll')}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7"
+ disabled={busy}
+ onClick={onAcceptAll}
+ >
+ {t('acceptAll')}
+ </Button>
+ </>
+ ) : (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('close')}
+ title={t('close')}
+ onClick={onClose}
+ >
+ <X className="h-3.5 w-3.5" />
+ </Button>
+ )}
+ </span>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts
index adec49a4b..9216486b9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts
@@ -53,7 +53,7 @@ export function citedLocks(state: EditorState): CitedLocks {
* worked out once, not on every keystroke.
*/
const passageKeys = new WeakMap<PmNode, string>();
-function keyOf(node: PmNode): string {
+export function blockKey(node: PmNode): string {
let key = passageKeys.get(node);
if (key === undefined) {
key = passageKey(node.textContent);
@@ -103,7 +103,7 @@ function changedRanges(tr: Transaction): { before: [number, number][]; after: [n
function lockedCounts(blocks: { node: PmNode }[], locks: CitedLocks): Map<string, number> {
const counts = new Map<string, number>();
for (const { node } of blocks) {
- const key = keyOf(node);
+ const key = blockKey(node);
if (isLocked(key, locks)) counts.set(key, (counts.get(key) ?? 0) + 1);
}
return counts;
@@ -111,7 +111,7 @@ function lockedCounts(blocks: { node: PmNode }[], locks: CitedLocks): Map<string
/** The mark of a quoted passage, if this block is one. */
function markOf(node: PmNode, pos: number, locks: CitedLocks): Decoration | null {
- const label = locks.labels.get(keyOf(node));
+ const label = locks.labels.get(blockKey(node));
return label
? Decoration.node(pos, pos + node.nodeSize, {
class: 'cited-passage',
@@ -140,7 +140,7 @@ function lockedAtSelection(state: EditorState, locks: CitedLocks): string | null
state.doc.nodesBetween(from, to, (node) => {
if (found) return false;
if (!node.isTextblock) return true;
- const key = keyOf(node);
+ const key = blockKey(node);
if (isLocked(key, locks)) found = key;
return false;
});
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 36bd7dccc..4b11eff62 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
@@ -1,10 +1,10 @@
'use client';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useFormatter, useTranslations } from 'next-intl';
import { toast } from 'sonner';
import { EditorContent, useEditor } from '@tiptap/react';
-import { TextSelection } from '@tiptap/pm/state';
+import { TextSelection, type Transaction } from '@tiptap/pm/state';
import StarterKit from '@tiptap/starter-kit';
import { TableKit } from '@tiptap/extension-table';
import Image from '@tiptap/extension-image';
@@ -24,7 +24,10 @@ import {
import { PLATFORM_LABELS } from '@/config/platform-labels';
import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';
import {
+ decideDraftSuggestions,
getCitedPassages,
+ getDraftSuggestions,
+ keepAgentBeforeVersion,
markContentDraftReady,
restoreDraftVersion,
setContentDraftPageType,
@@ -32,6 +35,7 @@ import {
import { CONTENT_LIBRARY_PATH, type ContentDraft, type PageType } from '@/lib/content/drafts';
import { CITED_DAYS, MAX_PASSAGES, type CitedPassage } from '@/lib/content/cited-passages';
import type { DraftVersion } from '@/lib/content/history';
+import type { DraftSuggestion, SuggestionStatus } from '@/lib/content/suggestions';
import {
cleanHtml,
formatHtmlSource,
@@ -42,6 +46,7 @@ import { PAGE_READ_DELAY_MS, draftTitleFromDoc, safeLinkHref } from '@/lib/conte
import { JsonLd } from '@/lib/content/json-ld-node';
import { detectPageType } from '@/lib/content/page-types';
import { cn } from '@/lib/utils';
+import { AgentBar } from './_agent-bar';
import { DropOverlay, useAttachments } from './_attach';
import {
CITED_EDIT_ALLOWED,
@@ -55,6 +60,14 @@ import { HistoryMenu } from './_history-menu';
import { HtmlBlock, copyToClipboard } from './_html-block';
import { PageTypeMenu } from './_page-type-menu';
import { EditorSidePanel, useSidePanelOpen } from './_side-panel';
+import {
+ AgentSuggestions,
+ acceptInto,
+ suggestionsKey,
+ undoInto,
+ type SuggestionDecision,
+ type SuggestionLabels,
+} from './_suggestions';
import { useDraftReads } from './_use-draft-reads';
import { useDraftRules } from './_use-draft-rules';
import { EditorToolbar } from './_toolbar';
@@ -76,6 +89,9 @@ const DOCUMENT_CLASS = cn(
// Locked passages (CE-018): a green line, and what quotes them above.
'[&_.cited-passage]:rounded-r-md [&_.cited-passage]:border-l-[3px] [&_.cited-passage]:border-emerald-300 [&_.cited-passage]:bg-emerald-50/70 [&_.cited-passage]:py-1 [&_.cited-passage]:pr-2 [&_.cited-passage]:pl-3 dark:[&_.cited-passage]:border-emerald-700 dark:[&_.cited-passage]:bg-emerald-950/30',
'[&_.cited-passage]:before:mb-0.5 [&_.cited-passage]:before:block [&_.cited-passage]:before:text-[11.5px] [&_.cited-passage]:before:leading-snug [&_.cited-passage]:before:font-medium [&_.cited-passage]:before:tracking-normal [&_.cited-passage]:before:text-emerald-700 [&_.cited-passage]:before:content-[attr(data-cited-label)] dark:[&_.cited-passage]:before:text-emerald-400',
+ // An accepted agent suggestion (CE-018): a thin green line, the words it put in underlined.
+ '[&_.agent-accepted]:border-l-2 [&_.agent-accepted]:border-emerald-300 [&_.agent-accepted]:pl-2.5 dark:[&_.agent-accepted]:border-emerald-700',
+ '[&_.agent-accepted-text]:underline [&_.agent-accepted-text]:decoration-emerald-300 [&_.agent-accepted-text]:decoration-2 [&_.agent-accepted-text]:underline-offset-4 dark:[&_.agent-accepted-text]:decoration-emerald-700',
'[&_.is-editor-empty:first-child]:before:pointer-events-none [&_.is-editor-empty:first-child]:before:float-left [&_.is-editor-empty:first-child]:before:h-0 [&_.is-editor-empty:first-child]:before:text-muted-foreground [&_.is-editor-empty:first-child]:before:content-[attr(data-placeholder)]',
);
@@ -98,7 +114,8 @@ const DOCUMENT_CLASS = cn(
* of those rules the page meets now. History keeps earlier versions (the
* imported live page, each Mark ready) and restores any of them; passages
* AI answers quote today are locked: marked, and changed only after a
- * warning (CE-018).
+ * warning; an agent's suggestions sit in the page as cards to accept or
+ * reject, with the agent bar over it (CE-018).
*/
export function DraftEditor({ draft }: { draft: ContentDraft }) {
const t = useTranslations('contentEditor.editor');
@@ -117,6 +134,14 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
// What quotes each locked passage, for the warning: "ChatGPT 14× and …".
const citedBy = useRef(new Map<string, string>());
const [citedCount, setCitedCount] = useState(0);
+ // An agent's suggestions (CE-018): its latest batch, with what was decided.
+ const [suggestions, setSuggestions] = useState<DraftSuggestion[]>([]);
+ const suggestionsNow = useRef(suggestions);
+ const [deciding, setDeciding] = useState(false);
+ const [barClosed, setBarClosed] = useState(false);
+ // History keeps the page before the first suggestion accepted here.
+ const agentBeforeKept = useRef(false);
+ const onDecide = useRef<(id: string, decision: SuggestionDecision) => void>(() => {});
// 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(() =>
@@ -162,6 +187,7 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
// person can't type while the question is open.
onHeld: (edit) => setHeld((current) => current ?? edit),
}),
+ AgentSuggestions.configure({ onDecide: (id, decision) => onDecide.current(id, decision) }),
],
content: draft.bodyHtml,
// Rendered on the client only, so the server's HTML can't disagree with it.
@@ -234,6 +260,7 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
});
useEffect(() => {
attachRef.current = (files) => void attachments.attach(files);
+ onDecide.current = (id, decision) => void decide([id], decision);
});
/** "ChatGPT 14× and Perplexity 6×": the platforms quoting a passage, the most first. */
@@ -316,6 +343,117 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
editor.commands.focus();
};
+ const suggestionLabels = useMemo<SuggestionLabels>(
+ () => ({
+ agent: t('suggestions.agent'),
+ accept: t('suggestions.accept'),
+ reject: t('suggestions.reject'),
+ accepted: t('suggestions.accepted'),
+ rejected: t('suggestions.rejected'),
+ undo: t('suggestions.undo'),
+ restore: t('suggestions.restore'),
+ locked: t('suggestions.locked'),
+ stale: t('suggestions.stale'),
+ }),
+ [t],
+ );
+
+ // The latest batch, read when the editor opens.
+ useEffect(() => {
+ if (!editor) return;
+ getDraftSuggestions(draft.id)
+ .then(setSuggestions)
+ .catch((err) => console.error('Failed to read the agent suggestions:', err));
+ }, [editor, draft.id]);
+
+ // The page shows them as they are now.
+ useEffect(() => {
+ suggestionsNow.current = suggestions;
+ if (!editor || editor.isDestroyed) return;
+ editor.view.dispatch(
+ editor.state.tr.setMeta(suggestionsKey, { suggestions, labels: suggestionLabels }),
+ );
+ }, [editor, suggestions, suggestionLabels]);
+
+ /**
+ * Accept, reject, undo (an accepted one) or restore (a rejected one): the
+ * page changes first, then the decision is kept. Accepting keeps the page
+ * as it was in History before the first agent change.
+ */
+ const decide = async (ids: string[], decision: SuggestionDecision | 'undo_all') => {
+ if (!editor || deciding) return;
+ const all = suggestionsNow.current;
+ const next = all.map((s) => ({ ...s }));
+ const picked = next.filter((s) => ids.includes(s.id));
+ const changed: string[] = [];
+ let status: SuggestionStatus = 'open';
+ // The page's change, applied only once the decision is saved.
+ let tr: Transaction | null = null;
+ setDeciding(true);
+ try {
+ if (decision === 'accept') {
+ const open = picked.filter((s) => s.status === 'open');
+ if (open.length > 0 && !agentBeforeKept.current) {
+ await autosave.settle();
+ await keepAgentBeforeVersion(draft.id);
+ agentBeforeKept.current = true;
+ }
+ tr = editor.state.tr;
+ for (const s of open) {
+ if (acceptInto(tr, editor.state, s, next)) {
+ s.status = 'accepted';
+ changed.push(s.id);
+ }
+ }
+ status = 'accepted';
+ if (open.length > changed.length) {
+ toast(t('suggestions.notApplied', { count: open.length - changed.length }));
+ }
+ } else if (decision === 'reject') {
+ for (const s of picked.filter((s) => s.status === 'open')) {
+ s.status = 'rejected';
+ changed.push(s.id);
+ }
+ status = 'rejected';
+ } else {
+ // Undo, Restore and Undo all send suggestions back to review.
+ tr = editor.state.tr;
+ for (const s of [...picked].reverse()) {
+ if (s.status === 'accepted' && decision !== 'restore') {
+ if (!undoInto(tr, editor.state, s, next)) continue;
+ } else if (s.status !== 'rejected' || decision === 'undo') {
+ continue;
+ }
+ s.status = 'open';
+ changed.push(s.id);
+ }
+ }
+ if (changed.length === 0) return;
+ // The decision is saved first, with the page held still: when it fails,
+ // neither the page nor the cards change, so they stay in step.
+ const editable = editor.isEditable;
+ editor.setEditable(false, false);
+ try {
+ await decideDraftSuggestions(changed, status);
+ } finally {
+ if (editable) editor.setEditable(true, false);
+ }
+ if (tr?.docChanged && tr.before.eq(editor.state.doc)) editor.view.dispatch(tr);
+ setSuggestions(next);
+ if (decision === 'accept')
+ toast.success(t('suggestions.acceptedToast', { count: changed.length }));
+ else if (decision === 'reject')
+ toast(t('suggestions.rejectedToast', { count: changed.length }));
+ else toast(t('suggestions.undoneToast', { count: changed.length }));
+ } catch (err) {
+ console.error('Failed to decide the suggestions:', err);
+ toast.error(t('suggestions.saveFailed'));
+ } finally {
+ setDeciding(false);
+ }
+ };
+ const openSuggestions = suggestions.filter((s) => s.status === 'open').length;
+
// A drag with files over the page shows where they go; one dropped beside
// the page (not on its text) goes in at the cursor.
const withFiles = (e: React.DragEvent) =>
@@ -345,6 +483,11 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
const openHtmlView = () => {
if (!editor) return;
+ // The cards aren't in the HTML: decide them first.
+ if (openSuggestions > 0) {
+ toast(t('suggestions.htmlBlocked', { count: openSuggestions }));
+ return;
+ }
setHtmlSource(formatHtmlSource(editor.getHTML()));
setHtmlEdited(false);
};
@@ -582,6 +725,32 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
<div className="flex min-h-0 flex-1">
<div className="flex min-w-0 flex-1 flex-col">
+ {suggestions.length > 0 && !(barClosed && openSuggestions === 0) && (
+ <AgentBar
+ suggestions={suggestions}
+ rulesOpen={Math.max(0, rules.total - rules.met)}
+ busy={deciding}
+ onAcceptAll={() =>
+ void decide(
+ suggestions.filter((s) => s.status === 'open').map((s) => s.id),
+ 'accept',
+ )
+ }
+ onRejectAll={() =>
+ void decide(
+ suggestions.filter((s) => s.status === 'open').map((s) => s.id),
+ 'reject',
+ )
+ }
+ onUndoAll={() =>
+ void decide(
+ suggestions.filter((s) => s.status !== 'open').map((s) => s.id),
+ 'undo_all',
+ )
+ }
+ onClose={() => setBarClosed(true)}
+ />
+ )}
{editor && (
<EditorToolbar
editor={editor}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts
new file mode 100644
index 000000000..e9adbea32
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts
@@ -0,0 +1,496 @@
+import { Extension } from '@tiptap/core';
+import {
+ DOMParser as PmDOMParser,
+ type Fragment,
+ type Node as PmNode,
+ type Schema,
+} from '@tiptap/pm/model';
+import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import { cleanHtml } from '@/lib/content/clean-html';
+import { passageKey } from '@/lib/content/cited-passages';
+import type { DraftSuggestion } from '@/lib/content/suggestions';
+import { blockKey, citedLocks, citedPassagesKey, type CitedLocks } from './_cited-passages';
+
+/**
+ * An agent's suggestions in the page (CE-018): each open one is a card where
+ * it applies, with who made it and why, the words it removes in red and adds
+ * in green, and Reject / Accept. An accepted one keeps a thin green line and
+ * Undo; a rejected one a dashed card and Restore. A suggestion finds its
+ * passage by the text the agent read, so one the page changed since can only
+ * be rejected, and one on a locked passage (AI quotes it) is never applied.
+ */
+
+export type SuggestionDecision = 'accept' | 'reject' | 'undo' | 'restore';
+
+/** The words on the cards, from the editor's messages. */
+export interface SuggestionLabels {
+ agent: string;
+ accept: string;
+ reject: string;
+ accepted: string;
+ rejected: string;
+ undo: string;
+ restore: string;
+ locked: string;
+ stale: string;
+}
+
+interface SuggestionView {
+ suggestions: DraftSuggestion[];
+ labels: SuggestionLabels | null;
+}
+
+/** The plugin's state: the suggestions, and their cards and marks where the page has them. */
+interface SuggestionState extends SuggestionView {
+ marks: DecorationSet;
+}
+
+export const suggestionsKey = new PluginKey<SuggestionState>('agentSuggestions');
+
+const NO_SUGGESTIONS: SuggestionView = { suggestions: [], labels: null };
+
+// ─── Finding a suggestion in the page ─────────────────────────────────────────
+
+/** The passage's text after the accepted replaces on it (other than one), as the page has it. */
+function currentKey(s: DraftSuggestion, all: DraftSuggestion[]): string {
+ let text = s.blockText;
+ for (const other of all) {
+ if (
+ other.id !== s.id &&
+ other.kind === 'replace' &&
+ other.status === 'accepted' &&
+ other.blockText === s.blockText
+ ) {
+ // A function, so $ in the agent's text is taken as written.
+ text = text.replace(other.beforeText, () => other.afterText);
+ }
+ }
+ return passageKey(text);
+}
+
+/** The document position of a character offset in a textblock's text. */
+function textPos(block: PmNode, blockPos: number, offset: number): number {
+ let left = offset;
+ let found = -1;
+ block.forEach((child, childOffset) => {
+ if (found >= 0) return;
+ const length = child.isText ? child.text!.length : 0;
+ if (child.isText && left <= length) {
+ found = blockPos + 1 + childOffset + left;
+ return;
+ }
+ left -= length;
+ });
+ return found >= 0 ? found : blockPos + 1 + block.content.size;
+}
+
+interface Block {
+ node: PmNode;
+ pos: number;
+}
+
+function findBlock(doc: PmNode, test: (node: PmNode) => boolean): Block | null {
+ let found: Block | null = null;
+ doc.descendants((node, pos) => {
+ if (found) return false;
+ if (!node.isTextblock) return true;
+ if (test(node)) found = { node, pos };
+ return false;
+ });
+ return found;
+}
+
+/** The top-level block holding a position, with where it starts and ends. */
+function topBlock(doc: PmNode, pos: number): { index: number; from: number; to: number } | null {
+ let found: { index: number; from: number; to: number } | null = null;
+ doc.forEach((child, offset, index) => {
+ if (!found && pos >= offset && pos < offset + child.nodeSize) {
+ found = { index, from: offset, to: offset + child.nodeSize };
+ }
+ });
+ return found;
+}
+
+/** Inserts' blocks already read, by schema and HTML: cleaning and parsing is the slow part. */
+const insertCache = new WeakMap<Schema, Map<string, Fragment>>();
+
+/** An insert's blocks, as the page's schema reads its HTML (checked like a paste). */
+export function insertBlocks(state: EditorState, html: string): Fragment {
+ let bySchema = insertCache.get(state.schema);
+ if (!bySchema) {
+ bySchema = new Map();
+ insertCache.set(state.schema, bySchema);
+ }
+ const known = bySchema.get(html);
+ if (known) return known;
+ const holder = document.createElement('div');
+ holder.innerHTML = cleanHtml(html, { keepImages: false }).html;
+ const blocks = PmDOMParser.fromSchema(state.schema).parse(holder).content;
+ bySchema.set(html, blocks);
+ return blocks;
+}
+
+type Placed =
+ /** An open or rejected replace: the words it replaces. */
+ | { at: 'words'; from: number; to: number; block: Block }
+ /** An open or rejected insert: where its blocks go. */
+ | { at: 'gap'; pos: number; anchor: Block }
+ /** An accepted replace: the words it put in. */
+ | { at: 'added'; from: number; to: number; block: Block }
+ /** An accepted insert: the blocks it added. */
+ | { at: 'blocks'; from: number; to: number };
+
+/**
+ * Where a suggestion is in the page now (or in doc, a page a transaction is
+ * building), as its status has it; null when the page changed.
+ */
+export function placeSuggestion(
+ state: EditorState,
+ s: DraftSuggestion,
+ all: DraftSuggestion[],
+ doc: PmNode = state.doc,
+): Placed | null {
+ const key = currentKey(s, all);
+ if (s.kind === 'replace') {
+ if (s.status === 'accepted') {
+ const block = findBlock(doc, (node) => {
+ const text = node.textContent;
+ return (
+ text.includes(s.afterText) &&
+ passageKey(text.replace(s.afterText, () => s.beforeText)) === key
+ );
+ });
+ if (!block) return null;
+ const offset = block.node.textContent.indexOf(s.afterText);
+ return {
+ at: 'added',
+ block,
+ from: textPos(block.node, block.pos, offset),
+ to: textPos(block.node, block.pos, offset + s.afterText.length),
+ };
+ }
+ const block = findBlock(
+ doc,
+ (node) => blockKey(node) === key && node.textContent.includes(s.beforeText),
+ );
+ if (!block) return null;
+ const offset = block.node.textContent.indexOf(s.beforeText);
+ return {
+ at: 'words',
+ block,
+ from: textPos(block.node, block.pos, offset),
+ to: textPos(block.node, block.pos, offset + s.beforeText.length),
+ };
+ }
+
+ const anchor = findBlock(doc, (node) => blockKey(node) === key);
+ if (!anchor) return null;
+ const top = topBlock(doc, anchor.pos);
+ if (!top) return null;
+ if (s.status !== 'accepted') return { at: 'gap', pos: top.to, anchor };
+ const blocks = insertBlocks(state, s.afterText);
+ let to = top.to;
+ for (let i = 0; i < blocks.childCount; i++) {
+ const next = doc.maybeChild(top.index + 1 + i);
+ if (!next || next.textContent !== blocks.child(i).textContent) return null;
+ to += next.nodeSize;
+ }
+ return { at: 'blocks', from: top.to, to };
+}
+
+/** Whether a passage is locked (AI quotes it) and not opened for editing. */
+function lockedBlock(block: Block, locks: CitedLocks): boolean {
+ const key = blockKey(block.node);
+ return locks.labels.has(key) && !locks.unlocked.has(key);
+}
+
+/** Why an open suggestion can't be accepted now, or null. */
+export function blockedReason(
+ state: EditorState,
+ s: DraftSuggestion,
+ all: DraftSuggestion[],
+ doc: PmNode = state.doc,
+ locks: CitedLocks = citedLocks(state),
+): 'stale' | 'locked' | null {
+ const placed = placeSuggestion(state, { ...s, status: 'open' }, all, doc);
+ if (!placed) return 'stale';
+ if (placed.at === 'words' && lockedBlock(placed.block, locks)) return 'locked';
+ return null;
+}
+
+// ─── Accepting and undoing ────────────────────────────────────────────────────
+
+/**
+ * Accepts a suggestion into a transaction: the words replaced, or the blocks
+ * added. False when the page changed there or the passage is locked.
+ */
+export function acceptInto(
+ tr: Transaction,
+ state: EditorState,
+ s: DraftSuggestion,
+ all: DraftSuggestion[],
+): boolean {
+ if (blockedReason(state, s, all, tr.doc)) return false;
+ const placed = placeSuggestion(state, { ...s, status: 'open' }, all, tr.doc);
+ if (!placed) return false;
+ if (placed.at === 'words') {
+ tr.insertText(s.afterText, placed.from, placed.to);
+ return true;
+ }
+ if (placed.at === 'gap') {
+ tr.insert(placed.pos, insertBlocks(state, s.afterText));
+ return true;
+ }
+ return false;
+}
+
+/** Undoes an accepted suggestion into a transaction. False when the page changed there since. */
+export function undoInto(
+ tr: Transaction,
+ state: EditorState,
+ s: DraftSuggestion,
+ all: DraftSuggestion[],
+): boolean {
+ const placed = placeSuggestion(state, { ...s, status: 'accepted' }, all, tr.doc);
+ if (!placed) return false;
+ if (placed.at === 'added') {
+ tr.insertText(s.beforeText, placed.from, placed.to);
+ return true;
+ }
+ if (placed.at === 'blocks') {
+ tr.delete(placed.from, placed.to);
+ return true;
+ }
+ return false;
+}
+
+// ─── The cards ────────────────────────────────────────────────────────────────
+
+const BUTTON =
+ 'rounded-md border bg-background px-2 py-0.5 text-xs font-medium text-foreground hover:bg-muted disabled:pointer-events-none disabled:opacity-50';
+const PRIMARY =
+ 'rounded-md bg-primary px-2 py-0.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50';
+const LINK = 'text-xs font-medium text-foreground underline underline-offset-2 hover:no-underline';
+
+function el<K extends keyof HTMLElementTagNameMap>(
+ tag: K,
+ className: string,
+ text?: string,
+): HTMLElementTagNameMap[K] {
+ const node = document.createElement(tag);
+ node.className = className;
+ if (text !== undefined) node.textContent = text;
+ return node;
+}
+
+function button(
+ className: string,
+ text: string,
+ onClick: () => void,
+ disabled = false,
+): HTMLButtonElement {
+ const node = el('button', className, text);
+ node.type = 'button';
+ node.disabled = disabled;
+ // Keeps the page's selection where it was.
+ node.addEventListener('mousedown', (event) => event.preventDefault());
+ node.addEventListener('click', onClick);
+ return node;
+}
+
+/** The card's top line: the agent and why, then its buttons or what was decided. */
+function head(s: DraftSuggestion, labels: SuggestionLabels, controls: HTMLElement[]): HTMLElement {
+ const line = el('div', 'flex items-center gap-2 text-xs text-muted-foreground');
+ line.append(el('span', 'min-w-0 truncate', `${labels.agent} · ${s.reason}`));
+ const right = el('span', 'ml-auto flex shrink-0 items-center gap-1.5');
+ right.append(...controls);
+ line.append(right);
+ return line;
+}
+
+function badge(text: string, tone: 'ok' | 'no'): HTMLElement {
+ return el(
+ 'span',
+ tone === 'ok'
+ ? 'rounded-md bg-emerald-50 px-1.5 text-[11px] leading-[18px] font-medium text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300'
+ : 'rounded-md bg-muted px-1.5 text-[11px] leading-[18px] font-medium text-muted-foreground',
+ text,
+ );
+}
+
+function card(
+ s: DraftSuggestion,
+ labels: SuggestionLabels,
+ blocked: 'stale' | 'locked' | null,
+ decide: (id: string, decision: SuggestionDecision) => void,
+): HTMLElement {
+ if (s.status === 'rejected') {
+ const box = el('div', 'not-prose my-3 rounded-xl border border-dashed px-3 py-1.5');
+ box.append(
+ head(s, labels, [
+ badge(labels.rejected, 'no'),
+ button(LINK, labels.restore, () => decide(s.id, 'restore')),
+ ]),
+ );
+ box.dataset.suggestion = s.id;
+ return box;
+ }
+ if (s.status === 'accepted') {
+ const line = head(s, labels, [
+ badge(labels.accepted, 'ok'),
+ button(LINK, labels.undo, () => decide(s.id, 'undo')),
+ ]);
+ line.className += ' not-prose mb-1';
+ line.dataset.suggestion = s.id;
+ return line;
+ }
+
+ const box = el(
+ 'div',
+ 'not-prose my-3 rounded-xl border bg-card px-3 py-2.5 text-[14.5px] leading-relaxed shadow-sm',
+ );
+ box.dataset.suggestion = s.id;
+ box.append(
+ head(s, labels, [
+ button(BUTTON, labels.reject, () => decide(s.id, 'reject')),
+ button(PRIMARY, labels.accept, () => decide(s.id, 'accept'), blocked !== null),
+ ]),
+ );
+ const change = el('div', 'mt-1.5');
+ if (s.kind === 'replace') {
+ change.append(
+ el(
+ 'del',
+ 'rounded-sm bg-red-50 text-red-700 dark:bg-red-950/40 dark:text-red-300',
+ s.beforeText,
+ ),
+ document.createTextNode(' '),
+ el(
+ 'ins',
+ 'rounded-sm bg-emerald-50 text-emerald-800 no-underline dark:bg-emerald-950/40 dark:text-emerald-300',
+ s.afterText,
+ ),
+ );
+ } else {
+ const added = el(
+ 'div',
+ 'rounded-md bg-emerald-50 px-2 py-1 text-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-200 [&_li]:ml-4 [&_li]:list-disc [&_p]:my-1',
+ );
+ added.innerHTML = cleanHtml(s.afterText, { keepImages: false }).html;
+ change.append(added);
+ }
+ box.append(change);
+ if (blocked) {
+ box.append(el('p', 'mt-1.5 text-xs text-amber-700 dark:text-amber-400', labels[blocked]));
+ }
+ return box;
+}
+
+export const AgentSuggestions = Extension.create<{
+ onDecide: (id: string, decision: SuggestionDecision) => void;
+}>({
+ name: 'agentSuggestions',
+
+ addOptions() {
+ return { onDecide: () => {} };
+ },
+
+ addProseMirrorPlugins() {
+ const decide = (id: string, decision: SuggestionDecision) =>
+ this.options.onDecide(id, decision);
+ /** The cards and marks for the suggestions where the page has them now. */
+ const placeMarks = (
+ state: EditorState,
+ view: SuggestionView,
+ locks: CitedLocks,
+ ): DecorationSet => {
+ const { suggestions, labels } = view;
+ if (!labels || suggestions.length === 0) return DecorationSet.empty;
+ const marks: Decoration[] = [];
+ // Cards for suggestions the page no longer has a place for go first.
+ const unplaced: DraftSuggestion[] = [];
+ for (const s of suggestions) {
+ const placed = placeSuggestion(state, s, suggestions);
+ const blocked =
+ s.status === 'open' ? blockedReason(state, s, suggestions, state.doc, locks) : null;
+ const widget = (pos: number) =>
+ Decoration.widget(pos, () => card(s, labels, blocked, decide), {
+ key: `${s.id}:${s.status}:${blocked ?? ''}:${s.reason}`,
+ side: -1,
+ ignoreSelection: true,
+ stopEvent: () => true,
+ });
+ if (!placed) {
+ if (s.status !== 'accepted') unplaced.push(s);
+ continue;
+ }
+ if (placed.at === 'words') {
+ marks.push(widget(placed.block.pos));
+ if (s.status === 'open') {
+ marks.push(
+ Decoration.inline(placed.from, placed.to, {
+ class: 'rounded-sm bg-amber-100 dark:bg-amber-900/40',
+ }),
+ );
+ }
+ } else if (placed.at === 'gap') {
+ marks.push(widget(placed.pos));
+ } else if (placed.at === 'added') {
+ marks.push(widget(placed.block.pos));
+ marks.push(
+ Decoration.node(placed.block.pos, placed.block.pos + placed.block.node.nodeSize, {
+ class: 'agent-accepted',
+ }),
+ Decoration.inline(placed.from, placed.to, { class: 'agent-accepted-text' }),
+ );
+ } else {
+ marks.push(widget(placed.from));
+ state.doc.nodesBetween(placed.from, placed.to, (node, pos) => {
+ if (pos >= placed.from && pos + node.nodeSize <= placed.to) {
+ marks.push(Decoration.node(pos, pos + node.nodeSize, { class: 'agent-accepted' }));
+ }
+ return false;
+ });
+ }
+ }
+ for (const s of unplaced) {
+ const blocked = s.status === 'open' ? 'stale' : null;
+ marks.push(
+ Decoration.widget(0, () => card(s, labels, blocked, decide), {
+ key: `${s.id}:${s.status}:unplaced`,
+ side: -1,
+ ignoreSelection: true,
+ stopEvent: () => true,
+ }),
+ );
+ }
+ return DecorationSet.create(state.doc, marks);
+ };
+ return [
+ new Plugin<SuggestionState>({
+ key: suggestionsKey,
+ state: {
+ init: () => ({ ...NO_SUGGESTIONS, marks: DecorationSet.empty }),
+ // The cards and marks are placed again only when the page, the
+ // suggestions or the locks change, not on every selection move.
+ apply: (tr, value, old, state) => {
+ const view = tr.getMeta(suggestionsKey) as SuggestionView | undefined;
+ const newLocks = tr.getMeta(citedPassagesKey) as CitedLocks | undefined;
+ if (!view && !tr.docChanged && !newLocks) return value;
+ const next = view ?? { suggestions: value.suggestions, labels: value.labels };
+ if (!next.labels || next.suggestions.length === 0) {
+ return { ...next, marks: DecorationSet.empty };
+ }
+ // The locks plugin may not have taken this transaction yet: its
+ // locks come from the transaction when it changes them, else as they were.
+ return { ...next, marks: placeMarks(state, next, newLocks ?? citedLocks(old)) };
+ },
+ },
+ props: {
+ decorations: (state) => suggestionsKey.getState(state)?.marks ?? null,
+ },
+ }),
+ ];
+ },
+});
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 1d2f4b7f8..7141d9e6f 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
@@ -6,6 +6,7 @@ import messages from '../../../../../../../../messages/en.json';
import type { Editor } from '@tiptap/core';
import { RoleProvider } from '@/components/providers/role-provider';
import type { ContentDraft } from '@/lib/content/drafts';
+import type { DraftSuggestion } from '@/lib/content/suggestions';
import { passageKey } from '@/lib/content/cited-passages';
import ContentEditorPage from './page';
@@ -24,7 +25,13 @@ const saveMyRuleSet = vi.fn();
const getDraftVersions = vi.fn();
const restoreDraftVersion = vi.fn();
const getCitedPassages = vi.fn();
+const getDraftSuggestions = vi.fn();
+const decideDraftSuggestions = vi.fn();
+const keepAgentBeforeVersion = vi.fn();
vi.mock('@/lib/actions/content-drafts', () => ({
+ getDraftSuggestions: (...args: unknown[]) => getDraftSuggestions(...args),
+ decideDraftSuggestions: (...args: unknown[]) => decideDraftSuggestions(...args),
+ keepAgentBeforeVersion: (...args: unknown[]) => keepAgentBeforeVersion(...args),
getCitedPassages: (...args: unknown[]) => getCitedPassages(...args),
getDraftVersions: (...args: unknown[]) => getDraftVersions(...args),
restoreDraftVersion: (...args: unknown[]) => restoreDraftVersion(...args),
@@ -177,6 +184,9 @@ beforeEach(() => {
getDraftVersions.mockReset().mockResolvedValue([]);
restoreDraftVersion.mockReset();
getCitedPassages.mockReset().mockResolvedValue([]);
+ getDraftSuggestions.mockReset().mockResolvedValue([]);
+ decideDraftSuggestions.mockReset().mockResolvedValue(1);
+ keepAgentBeforeVersion.mockReset().mockResolvedValue(undefined);
localStorage.clear();
brandState.activeBrandId = 'b1';
brandState.setActiveBrand.mockReset();
@@ -625,6 +635,217 @@ describe('the content editor', () => {
});
});
+ describe('agent suggestions', () => {
+ const VAGUE = 'Our forecasting is very accurate.';
+ const page = draft({
+ bodyHtml: `<h1>Pipeline forecasting</h1><p>${VAGUE}</p><p>Teams trust it.</p>`,
+ });
+ const suggestion = (over: Partial<DraftSuggestion>): DraftSuggestion => ({
+ id: 's1',
+ batchId: 'b1',
+ actionId: 'a1',
+ actionNo: 214,
+ kind: 'replace',
+ blockText: VAGUE,
+ beforeText: VAGUE,
+ afterText: 'Accuracy is shown per team, each week, against closed revenue.',
+ reason: 'answer fan-out “how accurate is CRM forecasting”',
+ ruleKeys: [],
+ status: 'open',
+ ...over,
+ });
+ const batch = [
+ suggestion({}),
+ suggestion({
+ id: 's2',
+ kind: 'insert',
+ blockText: 'Teams trust it.',
+ beforeText: '',
+ afterText: '<h2>FAQ</h2><p>Does it work with custom stages? Yes, any stage.</p>',
+ reason: 'add FAQ block (rule: 5 questions)',
+ }),
+ ];
+ const cardOf = (id: string) =>
+ container.querySelector<HTMLElement>(`.ProseMirror [data-suggestion="${id}"]`);
+ const press = async (id: string, label: string) => {
+ const target = [...cardOf(id)!.querySelectorAll('button')].find(
+ (b) => b.textContent === label,
+ )!;
+ await act(async () => target.click());
+ await act(async () => {});
+ };
+ const bar = () => container.querySelector('[role="region"][aria-label="Agent suggestions"]');
+ const barButton = (label: string) =>
+ [...bar()!.querySelectorAll('button')].find((b) => b.textContent === label)!;
+ /** The page's own text: the cards are drawn over it, not part of it. */
+ const pageText = () =>
+ (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor }).editor.state.doc
+ .textContent;
+
+ it('shows each open suggestion where it applies, with the agent bar', async () => {
+ getContentDraft.mockResolvedValue(page);
+ getDraftSuggestions.mockResolvedValue(batch);
+ await renderPage();
+
+ expect(getDraftSuggestions).toHaveBeenCalledWith('d1');
+ expect(bar()!.textContent).toContain(
+ 'Content Agent suggested 2 changes · from Action AC-214',
+ );
+ expect(bar()!.querySelector('a')!.getAttribute('href')).toBe(
+ '/dashboard/action-center/actions?action=a1',
+ );
+ const replace = cardOf('s1')!;
+ expect(replace.textContent).toContain(
+ 'Content Agent · answer fan-out “how accurate is CRM forecasting”',
+ );
+ expect(replace.querySelector('del')!.textContent).toBe(VAGUE);
+ expect(replace.querySelector('ins')!.textContent).toBe(
+ 'Accuracy is shown per team, each week, against closed revenue.',
+ );
+ expect(cardOf('s2')!.textContent).toContain('Does it work with custom stages?');
+ // The page itself is unchanged until one is accepted.
+ expect(pageText()).not.toContain('Accuracy is shown');
+ });
+
+ it('accepts one into the page, keeping the page before it in History, and undoes it', async () => {
+ getContentDraft.mockResolvedValue(page);
+ getDraftSuggestions.mockResolvedValue(batch);
+ await renderPage();
+
+ await press('s1', 'Accept');
+ expect(keepAgentBeforeVersion).toHaveBeenCalledWith('d1');
+ expect(decideDraftSuggestions).toHaveBeenCalledWith(['s1'], 'accepted');
+ expect(pageText()).toContain(
+ 'Accuracy is shown per team, each week, against closed revenue.',
+ );
+ expect(pageText()).not.toContain(VAGUE);
+ expect(cardOf('s1')!.textContent).toContain('Accepted');
+ expect(container.querySelector('.ProseMirror .agent-accepted-text')!.textContent).toBe(
+ 'Accuracy is shown per team, each week, against closed revenue.',
+ );
+ expect(bar()!.textContent).toContain('suggested 1 change');
+
+ await press('s1', 'Undo');
+ expect(decideDraftSuggestions).toHaveBeenLastCalledWith(['s1'], 'open');
+ expect(pageText()).toContain(VAGUE);
+ expect(cardOf('s1')!.querySelector('del')).not.toBeNull();
+ // History kept the page once, before the first change.
+ await press('s1', 'Accept');
+ expect(keepAgentBeforeVersion).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects one, and restores it to review', async () => {
+ getContentDraft.mockResolvedValue(page);
+ getDraftSuggestions.mockResolvedValue(batch);
+ await renderPage();
+
+ await press('s2', 'Reject');
+ expect(decideDraftSuggestions).toHaveBeenCalledWith(['s2'], 'rejected');
+ expect(cardOf('s2')!.textContent).toContain('Rejected');
+ expect(pageText()).not.toContain('FAQ');
+
+ await press('s2', 'Restore');
+ expect(decideDraftSuggestions).toHaveBeenLastCalledWith(['s2'], 'open');
+ expect(cardOf('s2')!.textContent).toContain('Accept');
+ });
+
+ it('accepts all, says what is left, and undoes all', async () => {
+ getContentDraft.mockResolvedValue(page);
+ getDraftSuggestions.mockResolvedValue(batch);
+ await renderPage();
+
+ await act(async () => barButton('Accept all').click());
+ await act(async () => {});
+ expect(decideDraftSuggestions).toHaveBeenCalledWith(['s1', 's2'], 'accepted');
+ expect(pageText()).toContain(
+ 'Accuracy is shown per team, each week, against closed revenue.Teams trust it.FAQDoes it work with custom stages? Yes, any stage.',
+ );
+ expect(bar()!.textContent).toMatch(/^2 accepted · 0 rejected · \d+ rules? still open/);
+
+ await act(async () => barButton('Undo all').click());
+ await act(async () => {});
+ expect(decideDraftSuggestions).toHaveBeenLastCalledWith(['s2', 's1'], 'open');
+ expect(pageText()).toBe(`Pipeline forecasting${VAGUE}Teams trust it.`);
+ expect(bar()!.textContent).toContain('suggested 2 changes');
+ });
+
+ it('never applies one to a passage AI quotes, or to one the page changed', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ sourceUrl: 'https://acme.example/forecasting',
+ bodyHtml: `<h1>Pipeline forecasting</h1><p>${VAGUE}</p><p>Teams trust it.</p>`,
+ }),
+ );
+ getCitedPassages.mockResolvedValue([
+ { key: passageKey(VAGUE), platforms: [{ platform: 'chatgpt-web', answers: 3 }] },
+ ]);
+ getDraftSuggestions.mockResolvedValue([
+ suggestion({}),
+ suggestion({ id: 's3', blockText: 'Gone since.', beforeText: 'Gone since.' }),
+ ]);
+ await renderPage();
+
+ const locked = cardOf('s1')!;
+ expect(locked.textContent).toContain("AI quotes this passage, so agents don't change it.");
+ expect(
+ [...locked.querySelectorAll('button')].find((b) => b.textContent === 'Accept')!.disabled,
+ ).toBe(true);
+ const stale = cardOf('s3')!;
+ expect(stale.textContent).toContain('The page changed here since the agent read it.');
+
+ await act(async () => barButton('Accept all').click());
+ await act(async () => {});
+ expect(pageText()).toContain(VAGUE);
+ expect(decideDraftSuggestions).not.toHaveBeenCalled();
+ expect(toast).toHaveBeenCalledWith(
+ "2 suggestions couldn't be applied: the page changed there, or AI quotes the passage.",
+ );
+ });
+
+ it('leaves the page and the card as they were when the decision can’t be saved', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ getContentDraft.mockResolvedValue(page);
+ getDraftSuggestions.mockResolvedValue([suggestion({})]);
+ decideDraftSuggestions.mockRejectedValueOnce(new Error('offline'));
+ await renderPage();
+
+ await press('s1', 'Accept');
+ expect(pageText()).toContain(VAGUE);
+ expect(cardOf('s1')!.textContent).toContain('Accept');
+ expect(toast.error).toHaveBeenCalled();
+ });
+
+ it('takes text with $ in it as written, so an accepted one can be undone', async () => {
+ // String.replace would read "$$" in the page's words as "$".
+ const before = 'Plans start at $$49, or $& with add-ons.';
+ getContentDraft.mockResolvedValue(
+ draft({ bodyHtml: `<h1>Pipeline forecasting</h1><p>${before}</p>` }),
+ );
+ getDraftSuggestions.mockResolvedValue([
+ suggestion({ blockText: before, beforeText: before, afterText: 'Plans start at $49.' }),
+ ]);
+ decideDraftSuggestions.mockResolvedValue(undefined);
+ await renderPage();
+
+ await press('s1', 'Accept');
+ expect(pageText()).toContain('Plans start at $49.');
+ await press('s1', 'Undo');
+ expect(pageText()).toContain(before);
+ });
+
+ it('waits with the HTML view until they are decided', async () => {
+ getContentDraft.mockResolvedValue(page);
+ getDraftSuggestions.mockResolvedValue(batch);
+ await renderPage();
+
+ await act(async () => button('Edit as HTML')!.click());
+ expect(container.querySelector('textarea')).toBeNull();
+ expect(toast).toHaveBeenCalledWith(
+ 'Accept or reject the 2 agent suggestions first, then edit as HTML.',
+ );
+ });
+ });
+
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 7898881b9..f917d6758 100644
--- a/web/src/lib/actions/content-drafts.test.ts
+++ b/web/src/lib/actions/content-drafts.test.ts
@@ -57,6 +57,9 @@ vi.mock('@/lib/supabase/server', () => ({
const {
createContentDraft,
+ decideDraftSuggestions,
+ getDraftSuggestions,
+ keepAgentBeforeVersion,
getCitedPassages,
getContentDraft,
getDraftVersions,
@@ -431,3 +434,68 @@ describe('getCitedPassages', () => {
await expect(getCitedPassages(DRAFT, ['x'.repeat(5_001)])).rejects.toThrow('invalid');
});
});
+
+describe('agent suggestions', () => {
+ const row = (over: Record<string, unknown>) => ({
+ id: 's1',
+ batch_id: 'new',
+ action_id: 'a1',
+ kind: 'replace',
+ block_text: 'Our forecasting is very accurate.',
+ before_text: 'very accurate',
+ after_text: 'shown per team',
+ reason: 'answer a fan-out',
+ rule_keys: ['dated'],
+ position: 0,
+ status: 'open',
+ created_at: '2026-10-21T10:00:00Z',
+ actions: { action_no: 214 },
+ ...over,
+ });
+
+ it('reads the latest batch, in the agent’s order, with its action', async () => {
+ list = [
+ row({ id: 's2', position: 1, kind: 'insert', before_text: '' }),
+ row({ id: 's1', position: 0 }),
+ row({ id: 'old', batch_id: 'older', created_at: '2026-10-01T10:00:00Z' }),
+ ];
+ const read = await getDraftSuggestions(DRAFT);
+ expect(read.map((s) => s.id)).toEqual(['s1', 's2']);
+ expect(read[0]).toEqual({
+ id: 's1',
+ batchId: 'new',
+ actionId: 'a1',
+ actionNo: 214,
+ kind: 'replace',
+ blockText: 'Our forecasting is very accurate.',
+ beforeText: 'very accurate',
+ afterText: 'shown per team',
+ reason: 'answer a fan-out',
+ ruleKeys: ['dated'],
+ status: 'open',
+ });
+ expect(calls[0].filters).toContainEqual(['eq', 'draft_id', DRAFT]);
+ });
+
+ it('keeps who decided through the database function', async () => {
+ rpcResult = { data: 2, error: null };
+ await expect(decideDraftSuggestions([DRAFT, DRAFT], 'accepted')).resolves.toBe(2);
+ expect(rpcCalls).toEqual([
+ ['content_draft_decide_suggestions', { p_ids: [DRAFT, DRAFT], p_status: 'accepted' }],
+ ]);
+
+ rpcResult = { data: 0, error: null };
+ await expect(decideDraftSuggestions([DRAFT], 'open')).rejects.toThrow('not_found');
+ await expect(decideDraftSuggestions([], 'open')).rejects.toThrow('invalid');
+ await expect(decideDraftSuggestions([DRAFT], 'maybe' as unknown as 'open')).rejects.toThrow(
+ 'invalid',
+ );
+ });
+
+ it('keeps the page before agent changes in History', async () => {
+ await keepAgentBeforeVersion(DRAFT);
+ expect(rpcCalls).toEqual([
+ ['content_draft_snapshot', { p_draft_id: DRAFT, p_origin: 'agent_before' }],
+ ]);
+ });
+});
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 47dab91b9..94ca00e56 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -50,6 +50,12 @@ import {
type CitedAnswer,
type CitedPassage,
} from '@/lib/content/cited-passages';
+import {
+ MAX_DECIDE,
+ SUGGESTION_STATUSES,
+ type DraftSuggestion,
+ type SuggestionStatus,
+} from '@/lib/content/suggestions';
import {
HISTORY_DAYS,
HISTORY_LIMIT,
@@ -728,6 +734,85 @@ export async function restoreDraftVersion(versionId: string): Promise<RestoredDr
};
}
+/**
+ * History keeps the page before an agent's suggestions change it (CE-018):
+ * the editor saves what is waiting, then calls this before the first one it
+ * accepts. A failure is logged, not thrown: the suggestion can be undone.
+ */
+export async function keepAgentBeforeVersion(id: string): Promise<void> {
+ if (!draftId.safeParse(id).success) throw new Error('invalid');
+ const supabase = await createClient();
+ await keepVersion(supabase, id, 'agent_before');
+}
+
+/**
+ * An agent's suggestions on the draft (CE-018, 00217): its latest batch, in
+ * the order the agent left them, with the Action Center action it came from.
+ */
+export async function getDraftSuggestions(id: string): Promise<DraftSuggestion[]> {
+ if (!draftId.safeParse(id).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_draft_suggestions')
+ .select(
+ 'id, batch_id, action_id, kind, block_text, before_text, after_text, reason, rule_keys, position, status, created_at, actions(action_no)',
+ )
+ .eq('draft_id', id)
+ .order('created_at', { ascending: false })
+ .limit(MAX_DECIDE);
+ if (error) throw new Error(error.message);
+ const rows = data ?? [];
+ const batch = rows[0]?.batch_id;
+ const statuses: readonly string[] = SUGGESTION_STATUSES;
+ return rows
+ .filter((row) => row.batch_id === batch && statuses.includes(row.status))
+ .sort((a, b) => a.position - b.position)
+ .map((row) => {
+ const action = (Array.isArray(row.actions) ? row.actions[0] : row.actions) as {
+ action_no: number;
+ } | null;
+ return {
+ id: row.id,
+ batchId: row.batch_id,
+ actionId: row.action_id,
+ actionNo: action?.action_no ?? null,
+ kind: row.kind === 'insert' ? 'insert' : 'replace',
+ blockText: row.block_text,
+ beforeText: row.before_text,
+ afterText: row.after_text,
+ reason: row.reason,
+ ruleKeys: row.rule_keys ?? [],
+ status: row.status as SuggestionStatus,
+ };
+ });
+}
+
+const decideInput = z.object({
+ ids: z.array(z.guid()).min(1).max(MAX_DECIDE),
+ status: z.enum(SUGGESTION_STATUSES),
+});
+
+/**
+ * Accepts, rejects or sends back to review (open) a draft's suggestions,
+ * recording who decided (00217 content_draft_decide_suggestions). Throws
+ * 'not_found' when none changed.
+ */
+export async function decideDraftSuggestions(
+ ids: string[],
+ status: SuggestionStatus,
+): Promise<number> {
+ const parsed = decideInput.safeParse({ ids, status });
+ if (!parsed.success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc('content_draft_decide_suggestions', {
+ p_ids: parsed.data.ids,
+ p_status: parsed.data.status,
+ });
+ if (error) throw new Error(error.message);
+ if (!data) throw new Error('not_found');
+ return data;
+}
+
const citedInput = z.array(z.string().max(5_000)).max(MAX_PASSAGES);
/**
diff --git a/web/src/lib/content/suggestions.ts b/web/src/lib/content/suggestions.ts
new file mode 100644
index 000000000..8118719a1
--- /dev/null
+++ b/web/src/lib/content/suggestions.ts
@@ -0,0 +1,42 @@
+/**
+ * An agent's suggestions on a draft (Content Editor spec v2 §8, CE-018,
+ * 00217): changes left for a person to accept or reject, one batch per agent
+ * run. The editor shows the latest batch.
+ *
+ * A replace changes words in a passage (before → after, plain text); an
+ * insert adds blocks (HTML) after a passage. Both find their passage by its
+ * text, as the agent read it.
+ */
+
+export const SUGGESTION_STATUSES = ['open', 'accepted', 'rejected'] as const;
+export type SuggestionStatus = (typeof SUGGESTION_STATUSES)[number];
+
+export interface DraftSuggestion {
+ id: string;
+ batchId: string;
+ /** The Action Center action the run came from, with its number ("AC-214"). */
+ actionId: string | null;
+ actionNo: number | null;
+ kind: 'replace' | 'insert';
+ /** The passage's text when the agent read it. */
+ blockText: string;
+ /** replace: the words replaced; insert: empty. */
+ beforeText: string;
+ /** replace: the new words; insert: the blocks added, as HTML. */
+ afterText: string;
+ /** Why, as the agent says it: "add a dated data point (rule)". */
+ reason: string;
+ /** The rules it is meant to fix. */
+ ruleKeys: string[];
+ status: SuggestionStatus;
+}
+
+/** The most suggestions decided at once (00217). */
+export const MAX_DECIDE = 200;
+
+/** How many are still open, accepted and rejected. */
+export function suggestionCounts(suggestions: DraftSuggestion[]) {
+ const counts = { open: 0, accepted: 0, rejected: 0 };
+ for (const s of suggestions) counts[s.status] += 1;
+ return counts;
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index b7c3da3bb..2ca10a504 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -981,6 +981,85 @@ export type Database = {
},
]
}
+ content_draft_suggestions: {
+ Row: {
+ action_id: string | null
+ after_text: string
+ agent: string
+ batch_id: string
+ before_text: string
+ block_text: string
+ created_at: string
+ decided_at: string | null
+ decided_by: string | null
+ draft_id: string
+ id: string
+ kind: string
+ position: number
+ reason: string
+ rule_keys: string[]
+ status: string
+ }
+ Insert: {
+ action_id?: string | null
+ after_text: string
+ agent?: string
+ batch_id: string
+ before_text?: string
+ block_text: string
+ created_at?: string
+ decided_at?: string | null
+ decided_by?: string | null
+ draft_id: string
+ id?: string
+ kind: string
+ position?: number
+ reason: string
+ rule_keys?: string[]
+ status?: string
+ }
+ Update: {
+ action_id?: string | null
+ after_text?: string
+ agent?: string
+ batch_id?: string
+ before_text?: string
+ block_text?: string
+ created_at?: string
+ decided_at?: string | null
+ decided_by?: string | null
+ draft_id?: string
+ id?: string
+ kind?: string
+ position?: number
+ reason?: string
+ rule_keys?: string[]
+ status?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "content_draft_suggestions_action_id_fkey"
+ columns: ["action_id"]
+ isOneToOne: false
+ referencedRelation: "actions"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "content_draft_suggestions_decided_by_fkey"
+ columns: ["decided_by"]
+ isOneToOne: false
+ referencedRelation: "profiles"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "content_draft_suggestions_draft_id_fkey"
+ columns: ["draft_id"]
+ isOneToOne: false
+ referencedRelation: "content_drafts"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
content_draft_versions: {
Row: {
body_html: string
@@ -3556,6 +3635,10 @@ export type Database = {
Args: { p_days?: number; p_draft_id: string }
Returns: Json
}
+ content_draft_decide_suggestions: {
+ Args: { p_ids: string[]; p_status: string }
+ Returns: number
+ }
content_draft_member: { Args: { p_draft_id: string }; Returns: boolean }
content_draft_restore: { Args: { p_version_id: string }; Returns: Json }
content_draft_snapshot: {