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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content-editor): hand a brand's imported and agent-written pages off on their own, and list hand-offs in History (CE-051, part 4) (#1490)
Cihan17de88c4c6e8
diff --git a/web/messages/en.json b/web/messages/en.jsonindex d32eb9830..76c4e9f81 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3936,6 +3936,17 @@"publish": "kept on publish","restore": "kept when another version was restored"},+ "handOff": {+ "person": "Handed off to Content Agent",+ "auto": "Handed off automatically",+ "note": {+ "done": "{count, plural, one {# check} other {# checks}} · its changes were suggestions to review",+ "none": "{count, plural, one {# check} other {# checks}} · nothing it could change",+ "stopped": "{count, plural, one {# check} other {# checks}} · stopped",+ "failed": "{count, plural, one {# check} other {# checks}} · didn't finish",+ "running": "{count, plural, one {# check} other {# checks}} · under way"+ }+ },"restore": "Restore","restoreLabel": "Restore {version}, {when}","footer": "Restoring makes a new version. Nothing is lost.",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.tsxindex 9eea1649a..129b28c6f 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@@ -153,6 +153,7 @@ import { ReviewerMenu } from './_reviewer-menu';import { BeforePublish, TRUST_GATE, type ReadyAnyway, type ReadyToPaste } from './_before-publish';import { FlashBlock, findBlock, flashKey } from './_flash-block';import { useAgentRun } from './_use-agent-run';+import { useAutoHandOff } from './_use-auto-hand-off';import { useLinkChecks } from './_use-link-checks';import { WorkingDots } from './_working-dots';import { DropOverlay, useAttachments } from './_attach';@@ -1775,7 +1776,12 @@ export function DraftEditor({const runAgentFix = async (send: () => Promise<{ count: number } | { error: HandOffError }>,told: (count: number) => string = fixedMessage,+ // The editor's own run (the automatic hand-off): what the person didn't+ // start isn't said when it doesn't run or finds nothing, only logged.+ quiet = false,) => {+ const failed = (key: string, error: string) =>+ quiet ? console.warn('The automatic hand-off did not run:', error) : toast.error(t(key));setStoppingRun(null);stopSent.current = null;setFixing(true);@@ -1798,7 +1804,7 @@ export function DraftEditor({// No answer is not a failure: its batch shows if it lands in time.const landed = await agentBatch(draft.id, asked + FIX_WAIT_MS);if (!landed) {- toast.error(t('suggestions.fixErrors.failed'));+ failed('suggestions.fixErrors.failed', 'failed');return;}setSuggestions(landed);@@ -1814,7 +1820,7 @@ export function DraftEditor({return;}if ('error' in result) {- toast.error(t(`suggestions.fixErrors.${result.error}`));+ failed(`suggestions.fixErrors.${result.error}`, result.error);// Another tab (or the API) left them: show them here to decide.if (result.error === 'open_suggestions') {setSuggestions(await getDraftSuggestions(draft.id));@@ -1823,7 +1829,7 @@ export function DraftEditor({return;}if (result.count === 0) {- toast(t('suggestions.nothingToFix'));+ if (!quiet) toast(t('suggestions.nothingToFix'));return;}setSuggestions(await getDraftSuggestions(draft.id));@@ -1834,7 +1840,7 @@ export function DraftEditor({nudgeAt('agent');} catch (err) {console.error('Failed to run the Content Agent:', err);- toast.error(t('suggestions.fixErrors.failed'));+ failed('suggestions.fixErrors.failed', 'failed');} finally {setFixing(false);setStoppingRun(null);@@ -1879,6 +1885,7 @@ export function DraftEditor({await runAgentFix(() => handOffDraft(draft.id, draft.brandId, { items, origin, ...agentContext(editor) }),handedOff,+ origin === 'auto',);} finally {setHandingOff(false);@@ -2002,6 +2009,26 @@ export function DraftEditor({todos: quality.todos.filter((todo) => !todo.done).length,}: null;+ // Quality's automatic hand-off (CE-051): once a draft its brand hands off,+ // whose page came from elsewhere (imported to optimize, or the agent's).+ useAutoHandOff({+ draftId: draft.id,+ brandId: draft.brandId,+ due:+ sourcesOn &&+ draft.qualityHandoff &&+ status !== 'published' &&+ (draft.method === 'optimize' || draft.author === 'agent'),+ ready:+ qualitySettled &&+ !!handOffCard &&+ !handOffCard.blocked &&+ !handOffCard.running &&+ !agentWorking &&+ htmlSource === null,+ count: handOffList.length,+ run: () => handOff('auto'),+ });// The card's Run Agent says why it won't run, as the Rules card does: also// when the only rules left open are ones the agent doesn't fix (one H1).const agentRules = openRulesForAgent(rules.rules);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsxindex fff2a50de..2b4ae2f43 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_history-menu.tsx@@ -2,7 +2,7 @@import { useState } from 'react';import { useFormatter, useNow, useTranslations } from 'next-intl';-import { History, RotateCcw } from 'lucide-react';+import { Bot, History, RotateCcw } from 'lucide-react';import { Button } from '@/components/ui/button';import {DropdownMenu,@@ -14,13 +14,15 @@ import {DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';import { LoadingDots } from '@/components/ui/loading-dots';-import { getDraftVersions } from '@/lib/actions/content-drafts';-import { HISTORY_DAYS, type DraftVersion } from '@/lib/content/history';+import { getDraftHandoffs, getDraftVersions } from '@/lib/actions/content-drafts';+import { HISTORY_DAYS, type DraftHandOff, type DraftVersion } from '@/lib/content/history';/*** History in the editor's header (CE-018): the draft now, then its earlier* versions with their time and origin, read each time the menu opens. Picking- * one restores it; the page it replaces is kept as a version too.+ * one restores it; the page it replaces is kept as a version too. Its+ * hand-offs to the Content Agent (Quality CE-051) are listed among them by+ * time, with nothing to restore: their changes were suggestions.*/export function HistoryMenu({draftId,@@ -39,16 +41,30 @@ export function HistoryMenu({const format = useFormatter();const now = useNow();const [versions, setVersions] = useState<DraftVersion[] | 'loading' | 'failed'>('loading');+ const [handOffs, setHandOffs] = useState<DraftHandOff[]>([]);const load = () => {setVersions('loading');+ setHandOffs([]);getDraftVersions(draftId).then(setVersions).catch((err) => {console.error('Failed to read the draft history:', err);setVersions('failed');});+ // The versions are History; the hand-offs only add to it.+ getDraftHandoffs(draftId)+ .then(setHandOffs)+ .catch((err) => console.error('Failed to read the hand-offs:', err));};+ // Versions and hand-offs, the latest first.+ const rows =+ versions === 'loading' || versions === 'failed'+ ? []+ : [+ ...versions.map((version) => ({ at: version.createdAt, version, handOff: null })),+ ...handOffs.map((handOff) => ({ at: handOff.startedAt, version: null, handOff })),+ ].sort((a, b) => Date.parse(b.at) - Date.parse(a.at));/** "Today 10:42", or "Oct 12, 10:42". */const when = (iso: string) => {@@ -95,10 +111,30 @@ export function HistoryMenu({</p>) : versions === 'failed' ? (<p className="px-1.5 py-2 text-xs text-destructive">{t('failed')}</p>- ) : versions.length === 0 ? (+ ) : rows.length === 0 ? (<p className="px-1.5 py-2 text-xs text-muted-foreground">{t('empty')}</p>) : (- versions.map((version) => {+ rows.map(({ version, handOff }) => {+ if (handOff) {+ return (+ <div key={handOff.id} className="flex items-start gap-2 px-1.5 py-1.5">+ <span className="min-w-0 flex-1">+ <span className="block text-sm font-medium">+ {t(`handOff.${handOff.origin}`)}+ </span>+ <span className="block text-xs text-muted-foreground">+ {when(handOff.startedAt)} ·{' '}+ {t(+ `handOff.note.${handOff.changes === 0 ? 'none' : (handOff.outcome ?? 'running')}`,+ { count: handOff.checks ?? 0 },+ )}+ </span>+ </span>+ <Bot className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground" aria-hidden />+ </div>+ );+ }+ if (!version) return null;const label = t(`origin.${version.origin}`);return (<DropdownMenuItemdiff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-auto-hand-off.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-auto-hand-off.test.tsxnew file mode 100644index 000000000..e5f9c5752--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-auto-hand-off.test.tsx@@ -0,0 +1,86 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const readAutoHandOff = vi.fn();+vi.mock('@/lib/content/agent-runs-client', () => ({+ readAutoHandOff: (...args: unknown[]) => readAutoHandOff(...args),+}));++const { useAutoHandOff } = await import('./_use-auto-hand-off');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++/**+ * Quality's automatic hand-off (CE-051): once a draft its brand hands off,+ * when Quality is read and nothing holds Hand off; never again once the+ * draft had it, or when that can't be read.+ */++let container: HTMLDivElement;+let root: Root;+const run = vi.fn(async () => {});++function Probe({ due = true, ready = false, count = 3 }) {+ useAutoHandOff({ draftId: 'd1', brandId: 'b1', due, ready, count, run });+ return null;+}+const render = (props: { due?: boolean; ready?: boolean; count?: number } = {}) =>+ act(async () => root.render(<Probe {...props} />));++beforeEach(() => {+ readAutoHandOff.mockReset().mockResolvedValue(false);+ run.mockClear();+ container = document.createElement('div');+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+});++describe('useAutoHandOff', () => {+ it('hands off once, as soon as Quality is read and nothing holds it', async () => {+ await render();+ expect(readAutoHandOff).toHaveBeenCalledWith('d1', 'b1');+ // Not ready yet (the reads, an open suggestion, the budget): it waits.+ expect(run).not.toHaveBeenCalled();+ await render({ ready: true });+ expect(run).toHaveBeenCalledTimes(1);+ await render({ ready: false });+ await render({ ready: true });+ expect(run).toHaveBeenCalledTimes(1);+ });++ it('never runs on a draft that had it, when that can’t be read, or one the brand doesn’t hand off', async () => {+ readAutoHandOff.mockResolvedValue(true);+ await render({ ready: true });+ readAutoHandOff.mockResolvedValue(null);+ act(() => root.unmount());+ root = createRoot(container);+ await render({ ready: true });+ expect(run).not.toHaveBeenCalled();++ act(() => root.unmount());+ root = createRoot(container);+ readAutoHandOff.mockClear();+ await render({ due: false, ready: true });+ expect(readAutoHandOff).not.toHaveBeenCalled();+ expect(run).not.toHaveBeenCalled();+ });++ it('waits for the read of whether it had it when Quality is ready first', async () => {+ let read: (value: boolean) => void = () => {};+ readAutoHandOff.mockReturnValue(new Promise((resolve) => (read = resolve)));+ await render({ ready: true });+ expect(run).not.toHaveBeenCalled();+ await act(async () => read(false));+ expect(run).toHaveBeenCalledTimes(1);+ });++ it('runs none this session when there is nothing to fix the first time it may', async () => {+ await render({ ready: true, count: 0 });+ await render({ ready: true, count: 2 });+ expect(run).not.toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-auto-hand-off.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-auto-hand-off.tsnew file mode 100644index 000000000..8fe626366--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-auto-hand-off.ts@@ -0,0 +1,58 @@+'use client';++import { useEffect, useRef, useState } from 'react';+import { readAutoHandOff } from '@/lib/content/agent-runs-client';++/**+ * Quality's automatic hand-off (Content Editor Quality spec §5, CE-051): a+ * draft its brand hands off (Settings › Content, as it was when the draft+ * was made) goes to the Content Agent on its own, once, when its page came+ * from elsewhere (an imported page, or one the agent wrote) and the editor+ * has read it: Quality is in and nothing holds Hand off (open suggestions,+ * the agent at work, the month's AI usage spent: it waits for those). Only+ * the browser reads Quality, so the run starts here; the server's row is the+ * claim, so a reopen or a second tab doesn't run it again. Nothing to fix+ * the first time it may run: none this session.+ */+export function useAutoHandOff({+ draftId,+ brandId,+ due,+ ready,+ count,+ run,+}: {+ draftId: string;+ brandId: string;+ /** The brand hands off this draft, and its page didn't start empty here. */+ due: boolean;+ /** Quality is read and Hand off may run now. */+ ready: boolean;+ /** The suggestions it would hand off. */+ count: number;+ run: () => Promise<void>;+}): void {+ // Whether the draft's automatic run is behind it (it had it, or its brand+ // stopped handing off): read once. Unread counts as had, so it never runs twice.+ const [had, setHad] = useState<boolean | null>(null);+ useEffect(() => {+ if (!due) return;+ let live = true;+ void readAutoHandOff(draftId, brandId).then((read) => {+ if (live) setHad(read ?? true);+ });+ return () => {+ live = false;+ };+ }, [draftId, brandId, due]);+ const runRef = useRef(run);+ useEffect(() => {+ runRef.current = run;+ });+ const done = useRef(false);+ useEffect(() => {+ if (!due || had !== false || !ready || done.current) return;+ done.current = true;+ if (count > 0) void runRef.current();+ }, [due, had, ready, count]);+}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.tsxindex 0fe520858..63a01edc0 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@@ -48,9 +48,11 @@ const getDraftSources = vi.fn();const setDraftSourceIncluded = vi.fn();const readAgentRun = vi.fn();const stopAgentRun = vi.fn();+const readAutoHandOff = vi.fn();vi.mock('@/lib/content/agent-runs-client', () => ({readAgentRun: (...args: unknown[]) => readAgentRun(...args),stopAgentRun: (...args: unknown[]) => stopAgentRun(...args),+ readAutoHandOff: (...args: unknown[]) => readAutoHandOff(...args),}));const getDraftBrief = vi.fn();const rebuildDraftBrief = vi.fn();@@ -58,6 +60,7 @@ const saveDraftRules = vi.fn();const getMyRuleSets = vi.fn();const saveMyRuleSet = vi.fn();const getDraftVersions = vi.fn();+const getDraftHandoffs = vi.fn();const restoreDraftVersion = vi.fn();const getCitedPassages = vi.fn();const getDraftSuggestions = vi.fn();@@ -80,6 +83,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({keepAgentBeforeVersion: (...args: unknown[]) => keepAgentBeforeVersion(...args),getCitedPassages: (...args: unknown[]) => getCitedPassages(...args),getDraftVersions: (...args: unknown[]) => getDraftVersions(...args),+ getDraftHandoffs: (...args: unknown[]) => getDraftHandoffs(...args),restoreDraftVersion: (...args: unknown[]) => restoreDraftVersion(...args),getMyRuleSets: (...args: unknown[]) => getMyRuleSets(...args),saveMyRuleSet: (...args: unknown[]) => saveMyRuleSet(...args),@@ -234,6 +238,7 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({agentRun: null,updatedAt: '2026-10-20T10:00:00Z',archivedAt: null,+ qualityHandoff: false,...over,});@@ -338,6 +343,8 @@ beforeEach(() => {getMyRuleSets.mockReset().mockResolvedValue({});saveMyRuleSet.mockReset().mockResolvedValue(undefined);getDraftVersions.mockReset().mockResolvedValue([]);+ getDraftHandoffs.mockReset().mockResolvedValue([]);+ readAutoHandOff.mockReset().mockResolvedValue(false);restoreDraftVersion.mockReset();getCitedPassages.mockReset().mockResolvedValue([]);getDraftSuggestions.mockReset().mockResolvedValue([]);@@ -1052,6 +1059,31 @@ describe('the content editor', () => {);});+ it('lists the hand-offs among the versions by time, with nothing to restore (CE-051)', async () => {+ getContentDraft.mockResolvedValue(draft());+ getDraftVersions.mockResolvedValue(versions);+ getDraftHandoffs.mockResolvedValue([+ {+ id: 'r1',+ origin: 'auto',+ outcome: 'done',+ checks: 6,+ startedAt: '2026-10-15T09:00:00Z',+ },+ ]);+ await renderPage();+ const items = await openHistory();+ expect(getDraftHandoffs).toHaveBeenCalledWith('d1');+ // Only the versions restore; the hand-off sits between them.+ expect(items).toHaveLength(2);+ const body = document.body.textContent!;+ const text = body.slice(body.indexOf('Version history'));+ expect(text).toContain('Handed off automatically');+ expect(text).toContain('6 checks · its changes were suggestions to review');+ expect(text.indexOf('Marked ready')).toBeLessThan(text.indexOf('Handed off automatically'));+ expect(text.indexOf('Handed off automatically')).toBeLessThan(text.indexOf('Live page'));+ });+it('says when there is nothing to restore yet', async () => {getContentDraft.mockResolvedValue(draft());await renderPage();@@ -3141,6 +3173,76 @@ describe('the side panel', () => {await act(async () => void (await vi.advanceTimersByTimeAsync(0)));});+ it('hands an imported page off on its own once Quality is read, once a draft, when its brand does (CE-051)', async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ getContentAuthors.mockResolvedValue({+ authors: [],+ brands: [{ id: 'b1', name: 'Ledgerly' }],+ me: { id: 'u1', role: 'admin' },+ });+ const long = `Teams ${Array.from({ length: 39 }, () => 'plan').join(' ')}.`;+ const imported = {+ ...claimed,+ author: 'user' as const,+ method: 'optimize' as const,+ qualityHandoff: true,+ bodyHtml: `${claimed.bodyHtml}<p>${long}</p>`,+ };+ getContentDraft.mockResolvedValue(imported);+ handOffDraft.mockResolvedValue({ error: 'already' });+ window.innerWidth = 1440;+ await renderPage();+ // Not before Quality is read.+ expect(handOffDraft).not.toHaveBeenCalled();+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));+ await act(async () => void (await vi.advanceTimersByTimeAsync(0)));+ expect(readAutoHandOff).toHaveBeenCalledWith('d1', 'b1');+ expect(handOffDraft).toHaveBeenCalledTimes(1);+ expect(handOffDraft).toHaveBeenCalledWith(+ 'd1',+ 'b1',+ expect.objectContaining({+ origin: 'auto',+ items: expect.arrayContaining([+ expect.objectContaining({ key: 'readability:longSentences' }),+ ]),+ }),+ );+ // Another tab's run came first: nothing said.+ expect(toast.error).not.toHaveBeenCalled();+ // A brand that stopped handing off since: nothing said either.+ handOffDraft.mockClear().mockResolvedValue({ error: 'not_due' });+ act(() => root.unmount());+ root = createRoot(container);+ await renderPage();+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));+ await act(async () => void (await vi.advanceTimersByTimeAsync(0)));+ expect(handOffDraft).toHaveBeenCalledTimes(1);+ expect(toast.error).not.toHaveBeenCalled();++ // A draft that had it, or a brand that doesn't hand off: never.+ handOffDraft.mockClear();+ act(() => root.unmount());+ root = createRoot(container);+ readAutoHandOff.mockResolvedValue(true);+ await renderPage();+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));+ act(() => root.unmount());+ root = createRoot(container);+ readAutoHandOff.mockResolvedValue(false);+ getContentDraft.mockResolvedValue({ ...imported, qualityHandoff: false });+ await renderPage();+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));+ // Nor a published page.+ act(() => root.unmount());+ root = createRoot(container);+ getContentDraft.mockResolvedValue({ ...imported, status: 'published' as const });+ await renderPage();+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));+ expect(handOffDraft).not.toHaveBeenCalled();+ });+it('asks a page that puts the brand forward for its disclosure, and Add line puts it under the H1 (CE-050)', async () => {process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsindex 625895458..300b4cdd6 100644--- a/web/src/lib/actions/content-drafts.test.ts+++ b/web/src/lib/actions/content-drafts.test.ts@@ -97,6 +97,7 @@ const {getCitedPassages,getContentDraft,getDraftVersions,+ getDraftHandoffs,classifyDraftSources,keepDraftSource,markContentDraftReady,@@ -701,6 +702,75 @@ describe('History', () => {expect(calls[0].filters).toContainEqual(['eq', 'draft_id', DRAFT]);});+ it('lists the hand-offs of the last 90 days, with who, how they ended and their checks (CE-051)', async () => {+ list = [+ {+ id: 'r2',+ origin: 'auto',+ outcome: 'done',+ steps: [+ { key: 'read_checks', count: 6 },+ { key: 'write_changes', count: null },+ ],+ started_at: '2026-10-21T10:00:00Z',+ },+ {+ id: 'r1',+ origin: 'person',+ outcome: 'done',+ steps: [+ { key: 'read_checks', count: 2 },+ { key: 'write_changes', count: 0 },+ ],+ started_at: '2026-10-20T10:00:00Z',+ },+ // Stopped before its outcome was written; left by a stopped server; under way.+ {+ id: 'r0',+ origin: 'person',+ outcome: null,+ steps: [],+ started_at: '2026-10-19T10:00:00Z',+ stopped_at: '2026-10-19T10:00:30Z',+ },+ { id: 'rs', origin: 'auto', outcome: null, steps: [], started_at: '2026-10-18T10:00:00Z' },+ {+ id: 'rn',+ origin: 'person',+ outcome: null,+ steps: [],+ started_at: new Date().toISOString(),+ },+ ];+ await expect(getDraftHandoffs(DRAFT)).resolves.toEqual([+ {+ id: 'r2',+ origin: 'auto',+ outcome: 'done',+ checks: 6,+ changes: null,+ startedAt: '2026-10-21T10:00:00Z',+ },+ {+ id: 'r1',+ origin: 'person',+ outcome: 'done',+ checks: 2,+ changes: 0,+ startedAt: '2026-10-20T10:00:00Z',+ },+ expect.objectContaining({ id: 'r0', outcome: 'stopped', changes: null }),+ expect.objectContaining({ id: 'rs', outcome: 'failed' }),+ expect.objectContaining({ id: 'rn', outcome: null }),+ ]);+ expect(calls[0].filters).toContainEqual(['eq', 'draft_id', DRAFT]);+ expect(calls[0].filters).toContainEqual(['eq', 'kind', 'handoff']);+ const [, since] = calls[0].filters.find(([op]) => op === 'gte')!.slice(1);+ const days = (Date.now() - Date.parse(since as string)) / (24 * 60 * 60 * 1000);+ expect(Math.round(days)).toBe(90);+ await expect(getDraftHandoffs('d1')).rejects.toThrow('invalid');+ });+it('restores a version and returns the page the server has now', async () => {rpcResult = {data: { title: 'Old', bodyHtml: '<h1>Old</h1>', updatedAt: '2026-10-21T10:00:00Z' },diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex c4837dfc1..265cc5c1b 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -82,10 +82,12 @@ import {HISTORY_DAYS,HISTORY_LIMIT,isVersionOrigin,+ type DraftHandOff,type DraftVersion,type RestoredDraft,type VersionOrigin,} from '@/lib/content/history';+import { RUN_STALE_MS } from '@/lib/content/agent-runs';import type { AgentWriteRequest } from '@/lib/content/agent-write';import {actionPages,@@ -233,7 +235,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>const { data, error } = await supabase.from('content_drafts').select(- `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, author_id, reviewer_id, source_url, rules, kept_sources, author_real_at, author_profile_at, action_id, agent_state, agent_state_at, agent_run, updated_at, archived_at, ${BRAND_SITE}, actions(action_no)`,+ `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, author_id, reviewer_id, source_url, rules, kept_sources, author_real_at, author_profile_at, action_id, agent_state, agent_state_at, agent_run, updated_at, archived_at, quality_handoff, ${BRAND_SITE}, actions(action_no)`,).eq('id', id).maybeSingle();@@ -265,6 +267,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>agentRun: agentRunOf(data.agent_run),updatedAt: data.updated_at,archivedAt: data.archived_at,+ qualityHandoff: data.quality_handoff === true,};}@@ -1705,6 +1708,53 @@ export async function getDraftVersions(id: string): Promise<DraftVersion[]> {);}+/**+ * 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+ * with who started it, how it ended and how many checks it was given.+ */+export async function getDraftHandoffs(id: string): Promise<DraftHandOff[]> {+ if (!draftId.safeParse(id).success) throw new Error('invalid');+ const supabase = await createClient();+ const since = new Date(Date.now() - HISTORY_DAYS * 24 * 60 * 60 * 1000).toISOString();+ const { data, error } = await supabase+ .from('content_agent_runs')+ .select('id, origin, outcome, steps, started_at, stopped_at')+ .eq('draft_id', id)+ .eq('kind', 'handoff')+ .gte('started_at', since)+ .order('started_at', { ascending: false })+ .limit(HISTORY_LIMIT);+ if (error) throw new Error(error.message);+ return (data ?? []).map((row) => {+ const steps = Array.isArray(row.steps)+ ? (row.steps as { key?: unknown; count?: unknown }[])+ : [];+ const count = (key: string) => {+ const n = steps.find((step) => step?.key === key)?.count;+ return Number.isInteger(n) ? (n as number) : null;+ };+ // Stopped before its outcome was written; or left by a server that+ // stopped, past the longest run (RUN_STALE_MS): not under way.+ const outcome =+ row.outcome === 'done' || row.outcome === 'stopped' || row.outcome === 'failed'+ ? row.outcome+ : row.stopped_at+ ? 'stopped'+ : Date.now() - Date.parse(row.started_at) > RUN_STALE_MS+ ? 'failed'+ : null;+ return {+ id: row.id,+ origin: row.origin === 'auto' ? 'auto' : 'person',+ outcome,+ checks: count('read_checks'),+ changes: outcome === 'done' ? count('write_changes') : null,+ startedAt: row.started_at,+ };+ });+}+/*** Restores a version (CE-018): the draft as it is now is kept in History* first, so nothing is lost, then takes the version's title and bodydiff --git a/web/src/lib/content/agent-runs-client.test.ts b/web/src/lib/content/agent-runs-client.test.tsindex 97985ed6a..f510da828 100644--- a/web/src/lib/content/agent-runs-client.test.ts+++ b/web/src/lib/content/agent-runs-client.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { readAgentRun, stopAgentRun } from './agent-runs-client';+import { readAgentRun, readAutoHandOff, stopAgentRun } from './agent-runs-client';/*** The Content Agent's run, read and stopped from the browser (CE-027/035):@@ -7,19 +7,35 @@ import { readAgentRun, stopAgentRun } from './agent-runs-client';*/let row: { data: Record<string, unknown> | null; error: Error | null };+let rows: { data: Record<string, unknown>[] | null; error: Error | null };+let filters: [string, string][];+let brand: { data: Record<string, unknown> | null; error: Error | null };let session: { access_token: string } | null;const query = { draft: '', order: '', limit: 0 };vi.mock('@/lib/supabase/client', () => ({createClient: () => ({auth: { getSession: async () => ({ data: { session } }) },from: (table: string) => {+ if (table === 'brands') {+ const brandChain = {+ select: () => brandChain,+ eq: (col: string, value: string) => (filters.push([`brands.${col}`, value]), brandChain),+ maybeSingle: async () => brand,+ };+ return brandChain;+ }expect(table).toBe('content_agent_runs');const chain = {select: () => chain,- eq: (_col: string, value: string) => ((query.draft = value), chain),+ eq: (col: string, value: string) => (+ filters.push([col, value]),+ (query.draft = value),+ chain+ ),order: (col: string) => ((query.order = col), chain),limit: (n: number) => ((query.limit = n), chain),maybeSingle: async () => row,+ then: (resolve: (value: typeof rows) => void) => resolve(rows),};return chain;},@@ -30,11 +46,41 @@ const fetchMock = vi.fn();beforeEach(() => {row = { data: null, error: null };+ rows = { data: [], error: null };+ brand = { data: { content_quality_handoff: true }, error: null };+ filters = [];+ query.draft = '';session = { access_token: 'token-1' };fetchMock.mockReset();vi.stubGlobal('fetch', fetchMock);});+describe('readAutoHandOff (Quality CE-051)', () => {+ it('says whether the automatic hand-off is behind the draft, null when that can’t be read', async () => {+ expect(await readAutoHandOff('d1', 'b1')).toBe(false);+ expect(filters).toEqual([+ ['draft_id', 'd1'],+ ['kind', 'handoff'],+ ['origin', 'auto'],+ ['brands.id', 'b1'],+ ]);+ // It had it.+ rows = { data: [{ id: 'r1' }], error: null };+ expect(await readAutoHandOff('d1', 'b1')).toBe(true);+ // Its brand stopped handing off since the draft was made.+ rows = { data: [], error: null };+ brand = { data: { content_quality_handoff: false }, error: null };+ expect(await readAutoHandOff('d1', 'b1')).toBe(true);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ rows = { data: null, error: new Error('down') };+ expect(await readAutoHandOff('d1', 'b1')).toBeNull();+ rows = { data: [], error: null };+ brand = { data: null, error: new Error('down') };+ expect(await readAutoHandOff('d1', 'b1')).toBeNull();+ vi.mocked(console.error).mockRestore();+ });+});+describe('readAgentRun', () => {it('reads the draft’s latest run', async () => {row.data = {diff --git a/web/src/lib/content/agent-runs-client.ts b/web/src/lib/content/agent-runs-client.tsindex 8886e7e5f..118400228 100644--- a/web/src/lib/content/agent-runs-client.ts+++ b/web/src/lib/content/agent-runs-client.ts@@ -25,6 +25,31 @@ export async function readAgentRun(draftId: string): Promise<AgentRun | null> {return agentRunFrom(data);}+/**+ * Whether the draft's automatic hand-off is behind it (Quality CE-051,+ * 00275): it had it (once a draft, its row the claim), or its brand no+ * longer hands off (Settings › Content: the server would answer `not_due`).+ * Null when that can't be read.+ */+export async function readAutoHandOff(draftId: string, brandId: string): Promise<boolean | null> {+ const supabase = createClient();+ const [runs, brand] = await Promise.all([+ supabase+ .from('content_agent_runs')+ .select('id')+ .eq('draft_id', draftId)+ .eq('kind', 'handoff')+ .eq('origin', 'auto')+ .limit(1),+ supabase.from('brands').select('content_quality_handoff').eq('id', brandId).maybeSingle(),+ ]);+ if (runs.error || brand.error) {+ console.error('Failed to read the automatic hand-off:', runs.error ?? brand.error);+ return null;+ }+ return (runs.data ?? []).length > 0 || brand.data?.content_quality_handoff !== true;+}+/*** Stop (CE-027): ends the Content Agent's run on the draft — the one the* editor shows, so another tab's run goes on — through the API's same-origindiff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.tsindex e4050a846..69f9e16c3 100644--- a/web/src/lib/content/drafts.ts+++ b/web/src/lib/content/drafts.ts@@ -189,6 +189,11 @@ export interface ContentDraft {updatedAt: string;/** When an admin or manager archived it (00233): Content › Editor doesn't go back to it. */archivedAt: string | null;+ /**+ * Quality's automatic hand-off (CE-051, 00275): the brand handed off its+ * new and optimized pages when the draft was made. Its run is once a draft.+ */+ qualityHandoff: boolean;}/**diff --git a/web/src/lib/content/history.ts b/web/src/lib/content/history.tsindex 13bd3b0ea..20011026a 100644--- a/web/src/lib/content/history.ts+++ b/web/src/lib/content/history.ts@@ -25,6 +25,24 @@ export interface DraftVersion {createdAt: string;}+/**+ * A hand-off to the Content Agent (Quality CE-051, 00275): History lists it+ * beside the versions, without Restore (its changes were suggestions; the+ * page before the first one accepted is a version). Its checks are how many+ * it was given.+ */+export interface DraftHandOff {+ id: string;+ /** A person's Hand off, or the editor's on its own (Settings › Content). */+ origin: 'person' | 'auto';+ /** Null while it is under way; one a stopped server left reads as failed. */+ outcome: 'done' | 'stopped' | 'failed' | null;+ checks: number | null;+ /** The suggestions it left, once done (0: nothing it could change). */+ changes: number | null;+ startedAt: string;+}+/** The draft after a restore, as the server now has it. */export interface RestoredDraft {title: string;