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): rewrite the page from its brief with the Content Agent (#1351)
Cihan4e14ae52d960
diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.jsindex ff94d1bb4..36208b125 100644--- a/server/src/lib/content-writer.js+++ b/server/src/lib/content-writer.js@@ -40,6 +40,13 @@ const CALL_TIMEOUT_MS = 180_000;/** A 'writing' this old was left by a server that stopped: it can start again. */export const WRITING_STALE_MS = 10 * 60_000;+/**+ * The drafts the agent writes in: still being worked on, a draft or one in+ * review (Rewrite from brief, after its first run), never one marked ready+ * or published.+ */+const OPEN_STATUSES = ['draft', 'in_review'];+/** What the person's dashboard sends: the sources kept, the page's rules, its locked passages. */export const writeDraftInput = z.object({sources: rebuildSources,@@ -234,7 +241,7 @@ async function organizationWriting(organizationId, draftId, staleBefore) {}/**- * Starts the agent on a draft: checks it is the brand's and still a draft,+ * Starts the agent on a draft: checks it is the brand's and still open to it,* that the agent isn't already on it or on another of the organization's* drafts, the AI usage budget and the model; marks it 'writing' and runs the* model in the background. Throws with `.status` 404 for a draft outside the@@ -254,8 +261,8 @@ export async function startDraftWriting({ draftId, brandId, input }) {if (!draft || draft.brand_id !== brandId) {throw Object.assign(new Error('Draft not found'), { status: 404 });}- if (draft.status !== 'draft') {- throw Object.assign(new Error('Only a draft can be written'), {+ if (!OPEN_STATUSES.includes(draft.status)) {+ throw Object.assign(new Error('Only a draft or one in review can be written'), {status: 409,code: 'not_draft',});@@ -301,7 +308,7 @@ export async function startDraftWriting({ draftId, brandId, input }) {.from('content_drafts').update({ agent_state: 'writing', agent_state_at: new Date().toISOString() }).eq('id', draftId)- .eq('status', 'draft')+ .in('status', OPEN_STATUSES).or(`agent_state.is.null,agent_state.eq.failed,agent_state_at.lt."${staleBefore}"`).select('id').maybeSingle();@@ -321,25 +328,25 @@ export async function startDraftWriting({ draftId, brandId, input }) {/*** The agent's state as it ends, only while it is still the run's to end;- * with `draftOnly`, only while the draft is still a draft (not marked ready+ * with `openOnly`, only while the draft is still open to it (not marked ready* meanwhile). Answers whether it ended it.*/-async function finish(draftId, values, { draftOnly = false } = {}) {+async function finish(draftId, values, { openOnly = false } = {}) {let query = supabaseAdmin.from('content_drafts').update({ ...values, agent_state_at: new Date().toISOString() }).eq('id', draftId).eq('agent_state', 'writing');- if (draftOnly) query = query.eq('status', 'draft');+ if (openOnly) query = query.in('status', OPEN_STATUSES);const { data, error } = await query.select('id').maybeSingle();if (error) throw error;return !!data;}-/** A draft that left Draft during the run keeps its page; the agent lets go of it. */+/** A draft marked ready or published during the run keeps its page; the agent lets go of it. */async function letGo(draftId) {await finish(draftId, { agent_state: null });- logger.info({ draftId }, '[content-writer] the draft left Draft during the run');+ logger.info({ draftId }, '[content-writer] the draft was closed during the run');return { skipped: true };}@@ -405,7 +412,7 @@ export async function runDraftWriting({ draft, brand, model, modelId, input }) {author: 'agent',agent_state: null,},- { draftOnly: true },+ { openOnly: true },);// Awaited here, so a failure to let go is caught below.return written ? { written: true } : await letGo(draft.id);@@ -449,9 +456,7 @@ export async function runDraftWriting({ draft, brand, model, modelId, input }) {})),);if (insertError) throw insertError;- if (- !(await finish(draft.id, { status: 'in_review', agent_state: null }, { draftOnly: true }))- ) {+ if (!(await finish(draft.id, { status: 'in_review', agent_state: null }, { openOnly: true }))) {// Nobody reviews suggestions on a page already marked ready.const { error: dropError } = await supabaseAdmin.from('content_draft_suggestions')diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.jsindex d2588a055..9502650c3 100644--- a/server/src/lib/content-writer.test.js+++ b/server/src/lib/content-writer.test.js@@ -202,8 +202,8 @@ describe('startDraftWriting', () => {);const finish = writes.filter((w) => w.table === 'content_drafts')[1];expect(finish.filters).toContainEqual(['agent_state', 'writing']);- // Only while it is still a draft: one marked ready meanwhile keeps its page.- expect(finish.filters).toContainEqual(['status', 'draft']);+ // Only while it is still open to it: one marked ready meanwhile keeps its page.+ expect(finish.filters).toContainEqual(['status', ['draft', 'in_review']]);// A new page holds only its H1: nothing of the person's to keep first.expect(rpcCalls).toEqual([]);expect(writes.some((w) => w.table === 'prompt_improve_usage')).toBe(true);@@ -214,12 +214,34 @@ describe('startDraftWriting', () => {expect(prompt).toContain('Page type: How-to guide: numbered steps to get one thing done');});- it('refuses another brand’s draft, one past Draft, or one the agent is on — before charging', async () => {+ // Rewrite from brief: a draft the agent wrote is in review, and is written again.+ it('writes a draft in review again, keeping its page in History first', async () => {+ rows.content_drafts = draftRow({+ status: 'in_review',+ author: 'agent',+ body_html: '<h1>How to brew pour-over coffee</h1><p>The first run.</p>',+ });+ await expect(+ startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() }),+ ).resolves.toEqual({ started: true });+ const claim = writes.find((w) => w.table === 'content_drafts');+ expect(claim.filters).toContainEqual(['status', ['draft', 'in_review']]);++ await vi.waitFor(() => expect(draftUpdates()).toHaveLength(2));+ expect(rpcCalls).toEqual([+ ['content_draft_snapshot', { p_draft_id: DRAFT, p_origin: 'agent_before' }],+ ]);+ expect(draftUpdates()[1]).toMatchObject({ status: 'in_review', agent_state: null });+ });++ it('refuses another brand’s draft, one marked ready or published, or one the agent is on — before charging', async () => {const start = () => startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() });rows.content_drafts = draftRow({ brand_id: 'other' });await expect(start()).rejects.toMatchObject({ status: 404 });- rows.content_drafts = draftRow({ status: 'in_review' });- await expect(start()).rejects.toMatchObject({ status: 409, code: 'not_draft' });+ for (const status of ['ready', 'published']) {+ rows.content_drafts = draftRow({ status });+ await expect(start()).rejects.toMatchObject({ status: 409, code: 'not_draft' });+ }rows.content_drafts = draftRow({agent_state: 'writing',agent_state_at: new Date().toISOString(),diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.jsindex 555b26976..4a6cf5d8e 100644--- a/server/src/routes/content-drafts.js+++ b/server/src/routes/content-drafts.js@@ -97,8 +97,8 @@ const writeBody = writeDraftInput.extend({ brandId: z.guid() });* POST /api/content-drafts/:draftId/write* Body: { brandId, sources, rules, textRules, locked }* Answers 202 { started: true } at once: the agent runs in the background- * and the draft shows where it is (agent_state). 409 when the draft isn't a- * draft any more (code not_draft), the agent is on it (code writing) or on+ * and the draft shows where it is (agent_state). 409 when the draft is marked+ * ready or published (code not_draft), the agent is on it (code writing) or on* another of the organization's drafts (code org_writing), or an existing* page's suggestions are still open (code open_suggestions).*/diff --git a/web/messages/en.json b/web/messages/en.jsonindex e1d127218..519f58416 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3835,6 +3835,18 @@"edited": "Edited by you.","builtFrom": "{count, plural, one {Built from # source} other {Built from # sources}} · {date}","rebuild": "Rebuild outline",+ "rewrite": {+ "button": {+ "create": "Rewrite from brief",+ "optimize": "Suggest changes from brief"+ },+ "confirm": {+ "create": "Content Agent writes the page again from this brief, the sources you keep and the rules. The page you have now stays in History. It uses this month's AI usage.",+ "optimize": "Content Agent suggests changes to the page from this brief, the sources you keep and the rules, for you to accept or reject. Passages AI answers quote stay as they are. It uses this month's AI usage."+ },+ "start": "Start the agent",+ "cancel": "Cancel"+ },"rebuildEdited": "Rebuild outline writes a new brief over the one you edited.","rebuildAnyway": "Rebuild anyway","keepEdited": "Keep my brief",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsxindex 2d94033d7..bd582b4d2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx@@ -4,7 +4,8 @@ import { NextIntlClientProvider } from 'next-intl';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../../../messages/en.json';import type { DraftBrief } from '@/lib/content/brief';-import { BriefTab, type BriefState } from './_brief-tab';+import type { DraftMethod } from '@/lib/content/drafts';+import { BriefTab, type AgentRewrite, type BriefState } from './_brief-tab';const saveDraftBrief = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({@@ -46,7 +47,13 @@ let root: Root;async function render(state: BriefState,- extra: { pageType?: string | null; sourceUrl?: string | null; length?: number } = {},+ extra: {+ pageType?: string | null;+ sourceUrl?: string | null;+ length?: number;+ method?: DraftMethod;+ rewrite?: AgentRewrite;+ } = {},) {await act(async () => {root.render(@@ -59,10 +66,12 @@ async function render(sourceUrl={extra.sourceUrl === undefined ? 'https://acme.example/guides/espresso' : extra.sourceUrl}+ method={extra.method ?? 'optimize'}rebuilding={false}onRebuild={onRebuild}onRetry={onRetry}onSaved={onSaved}+ rewrite={extra.rewrite}/></NextIntlClientProvider>,);@@ -216,6 +225,51 @@ describe('the Brief tab', () => {expect(onSaved).not.toHaveBeenCalled();});+ it('rewrites a new page from the brief, once the person says so', async () => {+ const run = vi.fn();+ await render(+ { status: 'ready', brief },+ { method: 'create', sourceUrl: null, rewrite: { run, running: false, blocked: null } },+ );+ await act(async () => button('Rewrite from brief').click());+ expect(run).not.toHaveBeenCalled();+ expect(container.querySelector('[role="alert"]')!.textContent).toContain(+ 'The page you have now stays in History.',+ );+ await act(async () => button('Start the agent').click());+ expect(run).toHaveBeenCalledTimes(1);+ });++ it('suggests changes to a live page from the brief, and waits for open suggestions', async () => {+ const run = vi.fn();+ await render(+ { status: 'ready', brief },+ { rewrite: { run, running: false, blocked: 'Accept or reject the open suggestions first.' } },+ );+ const suggest = button('Suggest changes from brief');+ expect(suggest.disabled).toBe(true);+ expect(suggest.title).toBe('Accept or reject the open suggestions first.');++ await render({ status: 'ready', brief }, { rewrite: { run, running: false, blocked: null } });+ await act(async () => button('Suggest changes from brief').click());+ expect(container.querySelector('[role="alert"]')!.textContent).toContain(+ 'Passages AI answers quote stay as they are.',+ );+ await act(async () => button('Cancel').click());+ expect(run).not.toHaveBeenCalled();+ });++ it('offers no rewrite without an outline, or once the page is ready', async () => {+ const run = vi.fn();+ await render(+ { status: 'ready', brief: { ...brief, outline: [] } },+ { rewrite: { run, running: false, blocked: null } },+ );+ expect(button('Suggest changes from brief')).toBeUndefined();+ await render({ status: 'ready', brief });+ expect(button('Suggest changes from brief')).toBeUndefined();+ });+it('offers to retry when the brief can’t be read', async () => {await render({ status: 'failed' });await act(async () => button('Retry').click());diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsxindex f2687ce47..2f24ed4d5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx@@ -3,16 +3,29 @@import { useState } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';-import { Loader2, Pencil, Plus, RefreshCw, Trash2 } from 'lucide-react';+import { Bot, Loader2, Pencil, Plus, RefreshCw, Trash2 } from 'lucide-react';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Textarea } from '@/components/ui/textarea';import { saveDraftBrief } from '@/lib/actions/content-drafts';import { MAX_BRIEF_SECTIONS, builtFromCount, type DraftBrief } from '@/lib/content/brief';+import type { DraftMethod } from '@/lib/content/drafts';import { platformNames } from '@/lib/content/impact';import { pagePath } from '@/lib/content/overlap';import { formatDateTime, formatNumber } from '@/lib/format';+/**+ * Rewrite from brief: the Content Agent writes the page again from the brief+ * (a new page), or suggests changes from it (a live page), as Start's agent+ * does (content-writer.js).+ */+export interface AgentRewrite {+ run: () => void;+ running: boolean;+ /** Why it can't run now (open suggestions to decide first), or null. */+ blocked: string | null;+}+/** The brief as the panel holds it: read once the tab opens. */export type BriefState =| { status: 'loading' }@@ -24,7 +37,8 @@ export type BriefState =* address at the top, then the goal, audience and length, and the outline* with each H2's fan-out and platform. Rebuild outline writes it from the* sources kept; Edit brief changes it by hand. Until the draft has a brief,- * the opportunity's brief it started from is shown.+ * the opportunity's brief it started from is shown. Rewrite from brief hands+ * the page to the Content Agent with it.*/export function BriefTab({draftId,@@ -32,10 +46,12 @@ export function BriefTab({pageType,length,sourceUrl,+ method,rebuilding,onRebuild,onRetry,onSaved,+ rewrite,}: {draftId: string;state: BriefState;@@ -43,16 +59,21 @@ export function BriefTab({/** The length the rules ask for (CE-009). */length: number;sourceUrl: string | null;+ method: DraftMethod;rebuilding: boolean;onRebuild: () => void;onRetry: () => void;onSaved: (brief: DraftBrief) => void;+ /** Absent once the page is ready or published. */+ rewrite?: AgentRewrite;}) {const t = useTranslations('contentEditor.editor.brief');const tTypes = useTranslations('contentEditor.pageTypes');const [editing, setEditing] = useState(false);// A brief edited by hand is rebuilt only once the person says so.const [confirming, setConfirming] = useState(false);+ // The agent writes over the page (or suggests changes) only once the person says so.+ const [confirmingRewrite, setConfirmingRewrite] = useState(false);if (state.status === 'loading') {return (@@ -174,6 +195,44 @@ export function BriefTab({</p>)}+ {rewrite &&+ brief &&+ brief.outline.length > 0 &&+ (confirmingRewrite ? (+ <div role="alert" className="space-y-2 rounded-md border px-3 py-2 text-xs">+ <p>{t(`rewrite.confirm.${method}`)}</p>+ <div className="flex flex-wrap gap-2">+ <Button+ size="sm"+ onClick={() => {+ setConfirmingRewrite(false);+ rewrite.run();+ }}+ >+ {t('rewrite.start')}+ </Button>+ <Button size="sm" variant="ghost" onClick={() => setConfirmingRewrite(false)}>+ {t('rewrite.cancel')}+ </Button>+ </div>+ </div>+ ) : (+ <Button+ size="sm"+ className="w-full"+ disabled={rewrite.running || rewrite.blocked !== null || rebuilding}+ title={rewrite.blocked ?? undefined}+ onClick={() => setConfirmingRewrite(true)}+ >+ {rewrite.running ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Bot className="h-3.5 w-3.5" />+ )}+ {t(`rewrite.button.${method}`)}+ </Button>+ ))}+{confirming && (<div role="alert" className="space-y-2 rounded-md border px-3 py-2 text-xs"><p>{t('rebuildEdited')}</p>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 e19e3a1b8..a8e582b50 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@@ -77,6 +77,7 @@ import { HistoryMenu } from './_history-menu';import { HtmlBlock, copyToClipboard } from './_html-block';import { OwnCopies, ownCopyHtml } from './_own-copies';import { PageTypeMenu } from './_page-type-menu';+import type { AgentRewrite } from './_brief-tab';import { ruleStatusText, type AgentFix } from './_rules-tab';import { EditorPanelRail, EditorSidePanel, useSidePanelOpen, type PanelTab } from './_side-panel';import {@@ -178,7 +179,7 @@ export function DraftEditor({const [marking, setMarking] = useState(false);// The Content Agent couldn't finish the page Start gave it (CE-015).const [agentFailed, setAgentFailed] = useState(draft.agentState === 'failed');- const [retrying, setRetrying] = useState(false);+ const [starting, setStarting] = useState(false);const describeRule = useRuleDescriber();const [restoring, setRestoring] = useState(false);const format = useFormatter();@@ -747,12 +748,13 @@ export function DraftEditor({};/**- * Try again: the agent takes the page as saved now, with the rules in- * effect here, and the page waits for it.+ * The agent on this draft again (Try again, Rewrite from brief): it takes+ * the page as saved now, with the brief, the sources and the rules in effect+ * here, and the page waits for it.*/- const retryAgent = async () => {+ const startAgent = async () => {if (!editor) return;- setRetrying(true);+ setStarting(true);try {await autosave.settle();const request = await agentWriteRequest(@@ -782,11 +784,20 @@ export function DraftEditor({console.error('Failed to start the Content Agent again:', err);toast.error(t('agentFailed.errors.failed'));} finally {- setRetrying(false);+ setStarting(false);}};const canMarkReady = status === 'draft' || status === 'in_review';+ // Rewrite from brief, while the page is still open to the agent (not ready+ // or published), as the API allows.+ const agentRewrite: AgentRewrite | undefined = canMarkReady+ ? {+ run: () => void startAgent(),+ running: starting,+ blocked: openSuggestions > 0 ? t('suggestions.decideFirst') : null,+ }+ : undefined;const markReady = async () => {setMarking(true);try {@@ -975,7 +986,7 @@ export function DraftEditor({<div className="flex min-h-0 flex-1"><div className="flex min-w-0 flex-1 flex-col">- {agentFailed && status === 'draft' && (+ {agentFailed && canMarkReady && (<divrole="alert"className="flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-amber-200 bg-amber-50 px-4 py-1.5 text-[13px] text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300"@@ -987,10 +998,10 @@ export function DraftEditor({variant="outline"size="sm"className="h-7"- disabled={retrying || !editor}- onClick={() => void retryAgent()}+ disabled={starting || !editor}+ onClick={() => void startAgent()}>- {retrying && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {starting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{t('agentFailed.retry')}</Button><Button@@ -1112,6 +1123,7 @@ export function DraftEditor({reads={reads}tabRequest={tabRequest}agentFix={agentFix}+ agentRewrite={agentRewrite}/>) : (<EditorPanelRail onOpen={openPanelTab} />diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsxindex a62b6d4dd..c10c6546e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from 'react';import { useTranslations } from 'next-intl';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { isPageType, type ContentDraft } from '@/lib/content/drafts';-import { BriefTab } from './_brief-tab';+import { BriefTab, type AgentRewrite } from './_brief-tab';import { ImpactTab } from './_impact-tab';import { RulesTab, type AgentFix } from './_rules-tab';import { SourcesTab } from './_sources-tab';@@ -95,6 +95,7 @@ export function EditorSidePanel({reads,tabRequest,agentFix,+ agentRewrite,}: {draft: ContentDraft;/** The draft's title, page and type as written now: Sources and Brief read them. */@@ -109,6 +110,8 @@ export function EditorSidePanel({tabRequest: { tab: PanelTab; n: number } | null;/** Fix open rules with agent, for the Rules tab (CE-018). */agentFix?: AgentFix;+ /** Rewrite from brief, for the Brief tab; absent once the page is ready or published. */+ agentRewrite?: AgentRewrite;}) {const t = useTranslations('contentEditor.editor.panel');const [tab, setTab] = useState<PanelTab>('rules');@@ -169,10 +172,12 @@ export function EditorSidePanel({pageType={pageType}length={rules.length}sourceUrl={draft.sourceUrl}+ method={draft.method}rebuilding={rebuilding}onRebuild={() => void rebuild()}onRetry={reads.reloadBrief}onSaved={(saved) => reads.setBrief(saved)}+ rewrite={agentRewrite}/></div>)}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 96d2ae54b..e2c346c77 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@@ -1484,6 +1484,50 @@ describe('the side panel', () => {expect(getContentImpact).not.toHaveBeenCalled();});+ // Item 12 of the editor round: the brief built, the agent works from it.+ it('hands a page in review to the agent from its brief, and waits for it', async () => {+ getDraftBrief.mockResolvedValue({+ brief: {+ goal: 'Win forecasting searches',+ audience: 'Sales leaders',+ outline: [+ {+ heading: 'How pipeline forecasting works',+ keyPoints: [],+ fanout: null,+ platform: null,+ },+ ],+ keywords: [],+ origin: 'rebuild',+ builtAt: '2026-10-21T10:00:00Z',+ builtFrom: { prompts: 0, fanouts: 1, pages: 0, queries: 0 },+ },+ });+ getContentDraft.mockResolvedValue(draft({ status: 'in_review' }));+ window.innerWidth = 1440;+ await renderPage();+ const tab = [...panel()!.querySelectorAll<HTMLElement>('[role="tab"]')].find(+ (el) => el.textContent === 'Brief',+ )!;+ await act(async () => {+ tab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ tab.click();+ });++ await act(async () => button('Suggest changes from brief')!.click());+ await act(async () => button('Start the agent')!.click());+ await act(async () => {});+ expect(startAgentWriting).toHaveBeenCalledWith(+ 'd1',+ 'b1',+ expect.objectContaining({ textRules: [], locked: [] }),+ );+ expect(container.querySelector('[role="status"]')!.textContent).toContain(+ 'Content Agent is writing this page',+ );+ });+it('rebuilds the brief from Sources and opens it', async () => {getDraftSources.mockResolvedValue({data: {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsxindex 4f504f55c..089c7df27 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx@@ -94,7 +94,7 @@ export function LibraryTable({ drafts, tab }: { drafts: ContentDraftListItem[];<TableCell>{/* The agent works on drafts only: its state says more than "Draft".One marked ready by hand since reads Ready. */}- {draft.agentState && draft.status === 'draft' ? (+ {draft.agentState && (draft.status === 'draft' || draft.status === 'in_review') ? (<AgentStateBadge state={draft.agentState} />) : (<DraftStatusBadge status={draft.status} />