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): open the editor on the Content Agent at work, step by step (#1349)
Cihan4e5119ad906f
diff --git a/web/messages/en.json b/web/messages/en.jsonindex e68b9020d..af0b6157a 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3347,8 +3347,6 @@"sendFailed": "The draft is in the Library, but it couldn't be sent to the Action Center.","openDraft": "Open draft","startAgent": "Start the agent",- "agentStarted": "Content Agent is drafting",- "agentStartedDescription": "You'll review it in Library › In review.","agentErrors": {"ai_budget": "This month's AI usage is spent, so the agent didn't start. The draft is in the Library for you to write.","no_subscription": "The agent needs an active subscription, so it didn't start. The draft is in the Library for you to write.",@@ -3491,8 +3489,24 @@"markedReady": "Marked ready. Publish it on your site when you're ready.","markedReadyAction": "Marked ready, and {count, plural, one {its task} other {its # tasks}} in Action AC-{no} {count, plural, one {is} other {are}} done. Publish it on your site when you're ready.","agentWriting": {- "title": "Content Agent is writing this page",- "body": "It opens here for your review when it's done, usually within a minute or two. You can leave this page meanwhile; it waits in Library › In review."+ "title": "Content Agent is working on this page",+ "usual": "Usually a minute or two.",+ "slow": "Taking longer than usual. If it can't finish within a few minutes, this page says so and you can try again.",+ "leave": "You can leave this page meanwhile: the draft waits in Library › In review.",+ "steps": {+ "create": {+ "read": "Read the sources and the brief",+ "rules": "Set out the page type's rules",+ "write": "Writing the page",+ "review": "Opens here for you to review"+ },+ "optimize": {+ "read": "Read the live page and its sources",+ "rules": "Set aside the passages AI answers quote",+ "write": "Suggesting changes",+ "review": "Opens here with the suggestions to review"+ }+ }},"agentFailed": {"text": "The Content Agent couldn't finish this page. Write it yourself, or try again.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsxnew file mode 100644index 000000000..7e0f0ddb1--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsx@@ -0,0 +1,121 @@+'use client';++import { useNow, useTranslations } from 'next-intl';+import { ArrowLeft, Bot, Check, Circle, Loader2 } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { buttonVariants } from '@/components/ui/button-variants';+import { CONTENT_LIBRARY_PATH, type DraftMethod } from '@/lib/content/drafts';+import { cn } from '@/lib/utils';++/**+ * What the agent does with a draft, in order (content-writer.js): it reads+ * what it was given, sets out the rules (or, on a live page, the passages it+ * keeps), writes, and the page opens for review.+ */+const STEPS = ['read', 'rules', 'write', 'review'] as const;+/**+ * The step it is on while the draft says it writes: the first two take it a+ * second from the start, the model's call is the wait.+ */+const WRITING = STEPS.indexOf('write');++/**+ * Past this, the wait is longer than usual: the model's call is cut at three+ * minutes (content-writer.js CALL_TIMEOUT_MS), and the page then says it+ * couldn't finish.+ */+const SLOW_AFTER_S = 120;++/** The seconds since the agent started, null when the start isn't known. */+function elapsedSeconds(since: string | null, now: Date): number | null {+ const start = since ? new Date(since).getTime() : NaN;+ if (!Number.isFinite(start)) return null;+ return Math.max(0, Math.floor((now.getTime() - start) / 1000));+}++/** "1:05". */+const clock = (seconds: number) =>+ `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;++/**+ * The draft while the Content Agent writes it (CE-015): nothing to edit yet,+ * so the page shows the agent at work, step by step as Chat shows its tools,+ * with the time it has taken, and says when that's longer than usual. The+ * editor opens on what it wrote.+ */+export function AgentWriting({+ title,+ method,+ since,+}: {+ title: string;+ method: DraftMethod;+ /** When the agent started (content_drafts.agent_state_at). */+ since: string | null;+}) {+ const t = useTranslations('contentEditor.editor');+ const seconds = elapsedSeconds(since, useNow({ updateInterval: 1000 }));+ return (+ <>+ <header className="flex items-center gap-2.5 border-b px-4 py-2.5">+ <Link+ href={CONTENT_LIBRARY_PATH}+ aria-label={t('back')}+ title={t('back')}+ className={buttonVariants({ variant: 'ghost', size: 'icon-sm' })}+ >+ <ArrowLeft className="h-4 w-4" />+ </Link>+ <h1 className="min-w-0 truncate text-sm font-medium">{title.trim() || t('untitled')}</h1>+ </header>+ <div role="status" className="flex flex-1 flex-col items-center justify-center px-6">+ <div className="w-full max-w-sm space-y-4">+ <div className="flex items-center gap-2.5">+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted">+ <Bot aria-hidden className="h-4 w-4" />+ </span>+ <p className="text-sm font-medium">{t('agentWriting.title')}</p>+ </div>+ <ol className="space-y-2.5 rounded-xl border bg-card px-4 py-3.5">+ {STEPS.map((step, i) => (+ <li+ key={step}+ aria-current={i === WRITING ? 'step' : undefined}+ className={cn(+ 'flex items-center gap-2.5 text-sm',+ i > WRITING && 'text-muted-foreground',+ )}+ >+ {i < WRITING ? (+ <Check+ aria-hidden+ className="h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400"+ />+ ) : i === WRITING ? (+ <Loader2 aria-hidden className="h-4 w-4 shrink-0 animate-spin" />+ ) : (+ <Circle aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground/60" />+ )}+ <span className="min-w-0 flex-1">{t(`agentWriting.steps.${method}.${step}`)}</span>+ {/* Hidden from screen readers: a status that reads out every second. */}+ {i === WRITING && seconds !== null && (+ <span aria-hidden className="shrink-0 text-xs text-muted-foreground tabular-nums">+ {clock(seconds)}+ </span>+ )}+ </li>+ ))}+ </ol>+ <p className="text-xs text-muted-foreground">+ {seconds !== null && seconds >= SLOW_AFTER_S ? (+ <span className="font-medium text-foreground">{t('agentWriting.slow')}</span>+ ) : (+ t('agentWriting.usual')+ )}{' '}+ {t('agentWriting.leave')}+ </p>+ </div>+ </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 372939e23..569be57ee 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@@ -146,6 +146,7 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({rules: { set: null, source: null, overrides: {}, textRules: [] },action: null,agentState: null,+ agentSince: null,updatedAt: '2026-10-20T10:00:00Z',...over,});@@ -427,13 +428,26 @@ describe('the content editor', () => {draft({status: 'draft',agentState: 'writing',+ agentSince: new Date(Date.now() - 65_000).toISOString(),bodyHtml: '<h1>Pipeline forecasting</h1>',}),);await renderPage();- expect(container.querySelector('[role="status"]')!.textContent).toContain(- 'Content Agent is writing this page',- );+ const status = container.querySelector('[role="status"]')!;+ expect(status.textContent).toContain('Content Agent is working on this page');+ // Its steps on a live page, the one it is on with the time it has taken.+ const steps = [...status.querySelectorAll('li')];+ expect(steps.map((li) => li.textContent?.replace(/\d+:\d\d$/, ''))).toEqual([+ 'Read the live page and its sources',+ 'Set aside the passages AI answers quote',+ 'Suggesting changes',+ 'Opens here with the suggestions to review',+ ]);+ expect(steps[2].getAttribute('aria-current')).toBe('step');+ expect(steps[2].textContent).toMatch(/1:0[56]$/);+ // Under two minutes, the usual wait.+ expect(status.textContent).toContain('Usually a minute or two.');+ expect(status.textContent).not.toContain('Taking longer than usual');expect(container.querySelector('.ProseMirror')).toBeNull();getContentDraft.mockResolvedValue(@@ -453,6 +467,24 @@ describe('the content editor', () => {}});+ it('says when the wait is longer than usual', async () => {+ getContentDraft.mockResolvedValue(+ draft({+ status: 'draft',+ method: 'create',+ agentState: 'writing',+ agentSince: new Date(Date.now() - 150_000).toISOString(),+ }),+ );+ await renderPage();+ const status = container.querySelector('[role="status"]')!;+ expect(status.querySelector('[aria-current="step"]')!.textContent).toMatch(+ /^Writing the page2:3[01]$/,+ );+ expect(status.textContent).toContain('Taking longer than usual.');+ expect(status.textContent).not.toContain('Usually a minute or two.');+ });+it('says the agent couldn’t finish, and tries again with the page and rules in effect', async () => {getContentDraft.mockResolvedValue(draft({ status: 'draft', agentState: 'failed' }));await renderPage();@@ -470,7 +502,7 @@ describe('the content editor', () => {expect(request.rules.length).toBeGreaterThan(0);// The page now waits for the agent.expect(container.querySelector('[role="status"]')!.textContent).toContain(- 'Content Agent is writing this page',+ 'Content Agent is working on this page',);});@@ -1524,7 +1556,7 @@ describe('the side panel', () => {expect.objectContaining({ textRules: [], locked: [] }),);expect(container.querySelector('[role="status"]')!.textContent).toContain(- 'Content Agent is writing this page',+ 'Content Agent is working on this page',);});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsxindex 46aabdc2e..c10e519a3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx@@ -3,13 +3,14 @@import { useEffect, useState } from 'react';import { useParams } from 'next/navigation';import { useTranslations } from 'next-intl';-import { ArrowLeft, Bot, Loader2 } from 'lucide-react';+import { Loader2 } from 'lucide-react';import { Link } from '@/i18n/navigation';import { Button } from '@/components/ui/button';import { buttonVariants } from '@/components/ui/button-variants';import { getContentDraft } from '@/lib/actions/content-drafts';import { AGENT_POLL_MS, CONTENT_LIBRARY_PATH, type ContentDraft } from '@/lib/content/drafts';import { useBrandStore } from '@/stores/use-brand-store';+import { AgentWriting } from './_agent-writing';import { DraftEditor } from './_draft-editor';type DraftRead = { id: string; draft: ContentDraft } | { id: string; draft: null; failed: boolean };@@ -86,14 +87,27 @@ export default function ContentEditorPage() {<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>) : current.draft && writing ? (- <AgentWriting title={current.draft.title} />+ <AgentWriting+ title={current.draft.title}+ method={current.draft.method}+ since={current.draft.agentSince}+ />) : current.draft ? (<DraftEditorkey={current.draft.id}draft={current.draft}onAgentStarted={() =>setRead((prev) =>- prev?.draft ? { id: prev.id, draft: { ...prev.draft, agentState: 'writing' } } : prev,+ prev?.draft+ ? {+ id: prev.id,+ draft: {+ ...prev.draft,+ agentState: 'writing',+ agentSince: new Date().toISOString(),+ },+ }+ : prev,)}/>@@ -127,37 +141,3 @@ export default function ContentEditorPage() {</div>);}--/** The draft while the Content Agent writes it: nothing to edit yet. */-function AgentWriting({ title }: { title: string }) {- const t = useTranslations('contentEditor.editor');- return (- <>- <header className="flex items-center gap-2.5 border-b px-4 py-2.5">- <Link- href={CONTENT_LIBRARY_PATH}- aria-label={t('back')}- title={t('back')}- className={buttonVariants({ variant: 'ghost', size: 'icon-sm' })}- >- <ArrowLeft className="h-4 w-4" />- </Link>- <h1 className="min-w-0 truncate text-sm font-medium">{title.trim() || t('untitled')}</h1>- </header>- <div- role="status"- className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center"- >- <span className="relative">- <Bot aria-hidden className="h-6 w-6 text-muted-foreground" />- <Loader2- aria-hidden- className="absolute -right-2 -bottom-2 h-3.5 w-3.5 animate-spin text-muted-foreground"- />- </span>- <p className="text-sm font-medium">{t('agentWriting.title')}</p>- <p className="max-w-sm text-sm text-muted-foreground">{t('agentWriting.body')}</p>- </div>- </>- );-}diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsxindex 2861f79fd..641e897bf 100644--- a/web/src/components/content/new-content-dialog.test.tsx+++ b/web/src/components/content/new-content-dialog.test.tsx@@ -882,14 +882,21 @@ describe('New content', () => {...document.querySelectorAll<HTMLElement>('[aria-labelledby="start-who"] [role="radio"]'),].find((r) => r.textContent?.startsWith(name))!;- it('opens the editor for me by default', async () => {+ it('offers the agent first, and opens the editor for me by default', async () => {await startNewPage();+ expect(+ [+ ...document.querySelectorAll<HTMLElement>(+ '[aria-labelledby="start-who"] [role="radio"] .font-medium',+ ),+ ].map((el) => el.textContent),+ ).toEqual(['Agent', 'Me', 'Team']);expect(whoOption('Me').getAttribute('aria-checked')).toBe('true');expect(whoOption('Agent').textContent).toBe('AgentDrafts, I review');expect(button('Open editor')).toBeDefined();});- it('hands the draft to the Content Agent, which drafts it for review in the Library', async () => {+ it('hands the draft to the Content Agent, and opens the editor to watch it work', async () => {startAgentWriting.mockResolvedValue({ started: true });await startNewPage();await click(whoOption('Agent'));@@ -905,13 +912,10 @@ describe('New content', () => {describeRule,);expect(startAgentWriting).toHaveBeenCalledWith('d9', 'b1', { sources: 'kept', rules: [] });- expect(push).not.toHaveBeenCalled();expect(onSent).toHaveBeenCalled();- const [message, options] = toast.success.mock.calls[0];- expect(message).toBe('Content Agent is drafting');- expect(options.description).toBe("You'll review it in Library › In review.");- options.action.onClick();+ // At once, no toast to click: the editor shows the agent at work.expect(push).toHaveBeenCalledWith('/dashboard/content/editor/d9');+ expect(toast.success).not.toHaveBeenCalled();});it('keeps the draft for me when the agent can’t start', async () => {@@ -923,6 +927,8 @@ describe('New content', () => {"This month's AI usage is spent, so the agent didn't start. The draft is in the Library for you to write.",);expect(onSent).toHaveBeenCalled();+ // Nothing to watch: the editor isn't opened, the toast offers the draft.+ expect(push).not.toHaveBeenCalled();});it('says the draft is the person’s to write when the agent is busy with another', async () => {diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsxindex 7140ffbaa..06d270ea1 100644--- a/web/src/components/content/new-content-dialog.tsx+++ b/web/src/components/content/new-content-dialog.tsx@@ -153,9 +153,13 @@ export type DialogPreset = (who?: 'team';};-/** Who does the page (Start, CE-015): the person, the Content Agent, or the team. */+/**+ * Who does the page (Start, CE-015): the Content Agent, the person, or the+ * team. The agent is offered first; the person stays the default, as the+ * agent's run is metered from the AI usage.+ */type Who = 'me' | 'agent' | 'team';-const WHO: Who[] = ['me', 'agent', 'team'];+const WHO: Who[] = ['agent', 'me', 'team'];/** The Overview's read for one source: null while it runs. */interface OverlapRead {@@ -525,8 +529,9 @@ export function NewContentDialog({/*** Agent: the Content Agent does the page in the background — a new page- * written, an existing one's suggestions left — and the draft waits in- * Library › In review. It stays in the Library as a draft if it can't start.+ * written, an existing one's suggestions left — and the editor opens at+ * once, showing the agent at work until the page is there to review. It+ * stays in the Library as a draft if it can't start.*/const sendToAgent = async (id: string, bodyHtml: string | undefined) => {const openDraft = {@@ -560,11 +565,7 @@ export function NewContentDialog({toast.error(t(`start.agentErrors.${started.error}`), { action: openDraft });return;}- toast.success(t('start.agentStarted'), {- description: t('start.agentStartedDescription'),- duration: 10_000,- action: openDraft,- });+ router.push(contentEditorPath(id));};/**diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex bb3b70e91..bf767d164 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -234,6 +234,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>? { id: data.action_id, number: data.actions.action_no }: null,agentState: agentStateOf(data.agent_state, data.agent_state_at),+ agentSince: data.agent_state_at,updatedAt: data.updated_at,};}diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.tsindex 4ce0d4026..9534555b5 100644--- a/web/src/lib/content/drafts.ts+++ b/web/src/lib/content/drafts.ts@@ -136,6 +136,8 @@ export interface ContentDraft {action: { id: string; number: number } | null;/** Where the Content Agent is on it (CE-015): the editor waits while it writes. */agentState: AgentState;+ /** When the agent's state last changed: while it writes, when it started. */+ agentSince: string | null;updatedAt: string;}