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): show the content agent's steps while it works, and stop it (CE-027, CE-035) (#1401)

Cihan3cd20512b064
diff --git a/web/messages/en.json b/web/messages/en.json
index 908a12208..2f4b071f1 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3625,7 +3625,33 @@
"run": "Run Agent",
"working": "Content Agent is working",
"builtFrom": "built from {count, number} of your sources",
- "seeSources": "See sources"
+ "seeSources": "See sources",
+ "stop": "Stop",
+ "stopped": "Stopped · nothing was changed",
+ "stopFailed": "Couldn't stop the agent. It may still finish.",
+ "drafting": "Content Agent is drafting a change here…",
+ "draftingFrom": "Drafting from {pages, plural, one {# cited page} other {# cited pages}} and {fanouts, plural, one {# fan-out} other {# fan-outs}}…",
+ "draftingFromPages": "Drafting from {pages, plural, one {# cited page} other {# cited pages}}…",
+ "draftingFromFanouts": "Drafting from {fanouts, plural, one {# fan-out} other {# fan-outs}}…",
+ "draftingRules": "Drafting from your rules…",
+ "steps": {
+ "readRules": "Reading {count, plural, one {# rule} other {# rules}}",
+ "readRulesAny": "Reading rules",
+ "gatherSources": "Gathering {count, plural, one {# source} other {# sources}}",
+ "gatherSourcesAny": "Gathering sources",
+ "writeChanges": "Writing {count, plural, one {# change} other {# changes}}",
+ "writeChangesAny": "Writing changes",
+ "rewritePage": "Rewriting the page",
+ "rewritePageAny": "Rewriting the page",
+ "writePage": "Writing the page",
+ "writePageAny": "Writing the page",
+ "writeOutline": "Writing the outline",
+ "writeOutlineAny": "Writing the outline",
+ "matchFanouts": "Matching {count, plural, one {# fan-out} other {# fan-outs}}",
+ "matchFanoutsAny": "Matching fan-outs",
+ "checkSources": "Checking sources",
+ "checkSourcesAny": "Checking sources"
+ }
},
"rewrite": {
"bar": "Rewritten page",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
index d81b0a646..6685e4cfd 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
@@ -2,6 +2,7 @@ import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AgentRun } from '@/lib/content/agent-runs';
import messages from '../../../../../../../../messages/en.json';
import type { DraftSuggestion } from '@/lib/content/suggestions';
import { AgentCard, rulesAfter, type CardRules } from './_agent-card';
@@ -192,6 +193,57 @@ describe('AgentCard', () => {
expect(container.textContent).not.toContain('built from');
});
+ it('shows the run’s steps while working, done ones checked, and only Stop (CE-027/035)', async () => {
+ const onStop = vi.fn();
+ const run: AgentRun = {
+ id: 'r1',
+ kind: 'rewrite',
+ steps: [
+ { key: 'read_rules', count: 14 },
+ { key: 'gather_sources', count: 52 },
+ { key: 'rewrite_page', count: null },
+ { key: 'check_sources', count: null },
+ ],
+ step: 1,
+ startedAt: new Date().toISOString(),
+ finishedAt: null,
+ stoppedAt: null,
+ outcome: null,
+ };
+ const show = (stopping: boolean) =>
+ act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <AgentCard
+ suggestions={[]}
+ rules={rules}
+ busy={false}
+ working
+ run={run}
+ onStop={onStop}
+ stopping={stopping}
+ {...handlers}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+ await show(false);
+ const steps = [...container.querySelectorAll('li')];
+ expect(steps.map((li) => li.textContent)).toEqual([
+ 'Reading 14 rules',
+ 'Gathering 52 sources',
+ 'Rewriting the page',
+ 'Checking sources',
+ ]);
+ expect(steps[0].querySelector('svg')).not.toBeNull();
+ expect(steps[1].querySelector('[aria-current="step"]')).not.toBeNull();
+ expect(buttons()).toEqual(['Stop']);
+ await click('Stop');
+ expect(onStop).toHaveBeenCalledTimes(1);
+ await show(true);
+ expect(container.querySelector('button')!.disabled).toBe(true);
+ });
+
it('stops all of its motion with reduced motion, in every state', async () => {
for (const [list, working] of [
[[suggestion()], false],
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
index d79fe2f6b..c50e71da6 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
@@ -2,7 +2,7 @@
import { useId, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
-import { X } from 'lucide-react';
+import { Check, ChevronRight, X } from 'lucide-react';
import { Link } from '@/i18n/navigation';
import { Button } from '@/components/ui/button';
import {
@@ -11,8 +11,10 @@ import {
type DraftSuggestion,
type SuggestionStatus,
} from '@/lib/content/suggestions';
+import { shownSteps, stepMessage, type AgentRun } from '@/lib/content/agent-runs';
import { cn } from '@/lib/utils';
import { PageCompareDialog, pageCharacters } from './_page-rewrite';
+import { WorkingDots } from './_working-dots';
/**
* The Content Agent card over the page (Content Editor v1.1, CE-025/026):
@@ -140,18 +142,41 @@ function AgentTile({
);
}
-/** Three dots that bounce in turn, after "Content Agent is working". */
-function WorkingDots() {
+/**
+ * A run's steps as chips (CE-027/035), named by the data they use: the ones
+ * done in green with a check, the one under way in full, the rest muted.
+ */
+export function RunSteps({ run }: { run: AgentRun }) {
+ const t = useTranslations('contentEditor.editor.agentCard.steps');
+ const shown = shownSteps(run);
return (
- <span aria-hidden className="ml-1.5 inline-flex gap-[3px] align-middle">
- {[0, 1, 2].map((i) => (
- <span
- key={i}
- className="h-1 w-1 animate-agent-dot rounded-full bg-foreground opacity-25 motion-reduce:animate-none"
- style={{ animationDelay: `${i * 0.2}s` }}
- />
- ))}
- </span>
+ <ol className="mt-1 flex flex-wrap items-center gap-1 text-[12px]">
+ {shown.map(({ step, index }, i) => {
+ const { key, count } = stepMessage(step);
+ const done = index < run.step;
+ const now = index === run.step;
+ return (
+ <li key={step.key} className="flex items-center gap-1">
+ {i > 0 && (
+ <ChevronRight aria-hidden className="h-3 w-3 shrink-0 text-muted-foreground/60" />
+ )}
+ <span
+ aria-current={now ? 'step' : undefined}
+ className={cn(
+ 'inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5',
+ done &&
+ 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-300',
+ now && 'bg-background font-medium text-foreground',
+ !done && !now && 'border-dashed text-muted-foreground',
+ )}
+ >
+ {done && <Check aria-hidden className="h-3 w-3 shrink-0" />}
+ {t(key, count === undefined ? {} : { count })}
+ </span>
+ </li>
+ );
+ })}
+ </ol>
);
}
@@ -170,6 +195,9 @@ export function AgentCard({
runBlocked = null,
sourceCount = 0,
onSeeSources,
+ run = null,
+ onStop,
+ stopping = false,
}: {
suggestions: DraftSuggestion[];
rules: CardRules;
@@ -193,6 +221,12 @@ export function AgentCard({
sourceCount?: number;
/** Opens the Sources tab. */
onSeeSources?: () => void;
+ /** The run under way, step by step (CE-027/035), or null before its first step reads. */
+ run?: AgentRun | null;
+ /** Stops the run under way: nothing it had is kept. */
+ onStop?: () => void;
+ /** Stop was pressed: it waits for the run to end. */
+ stopping?: boolean;
}) {
const t = useTranslations('contentEditor.editor.agentCard');
const locale = useLocale();
@@ -241,13 +275,17 @@ export function AgentCard({
</>
);
line = (
- <span
- aria-hidden
- className="mt-2 block h-[3px] w-full overflow-hidden rounded-full bg-border"
- >
- {/* Without motion, a faint full line: never a still bar that reads as progress. */}
- <span className="block h-full w-[30%] animate-agent-slide rounded-full bg-foreground motion-reduce:w-full motion-reduce:animate-none motion-reduce:opacity-30" />
- </span>
+ <>
+ {/* Its real steps, as the run says them; none until its first is read. */}
+ {run && <RunSteps run={run} />}
+ <span
+ aria-hidden
+ className="mt-2 block h-[3px] w-full overflow-hidden rounded-full bg-border"
+ >
+ {/* Without motion, a faint full line: never a still bar that reads as progress. */}
+ <span className="block h-full w-[30%] animate-agent-slide rounded-full bg-foreground motion-reduce:w-full motion-reduce:animate-none motion-reduce:opacity-30" />
+ </span>
+ </>
);
} else if (page) {
const { before, after: afterChars } = pageCharacters(page);
@@ -319,22 +357,28 @@ export function AgentCard({
>
<AgentTile tone={tone} count={working ? 0 : open} />
{/* Room for a line of text first: on a narrow page the buttons go under it. */}
- <span className="min-w-0 flex-1 basis-56">
- <span className="block text-sm font-semibold [overflow-wrap:anywhere]">{title}</span>
+ <div className="min-w-0 flex-1 basis-56">
+ <div className="text-sm font-semibold [overflow-wrap:anywhere]">{title}</div>
{line && (
- <span className="block text-[12.5px] text-muted-foreground [overflow-wrap:anywhere]">
- {line}
- </span>
+ <div className="text-[12.5px] text-muted-foreground [overflow-wrap:anywhere]">{line}</div>
)}
{reason && (
- <span
+ <div
id={reasonId}
- className="block text-[12.5px] text-amber-700 [overflow-wrap:anywhere] dark:text-amber-400"
+ className="text-[12.5px] text-amber-700 [overflow-wrap:anywhere] dark:text-amber-400"
>
{reason}
- </span>
+ </div>
)}
- </span>
+ </div>
+ {/* Working, only Stop: it drops whatever the run had. */}
+ {working && onStop && run && (
+ <span className="ml-auto flex shrink-0 items-center">
+ <Button variant="outline" size="sm" disabled={stopping} onClick={onStop}>
+ {t('stop')}
+ </Button>
+ </span>
+ )}
{!working && (
<span className="ml-auto flex max-w-full flex-wrap items-center justify-end gap-1.5">
{page ? (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-drafting.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-drafting.ts
new file mode 100644
index 000000000..644823758
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-drafting.ts
@@ -0,0 +1,87 @@
+import { Extension } from '@tiptap/core';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+
+/**
+ * While the Content Agent fixes the open rules (v1.1 CE-027/035), a dashed
+ * card in the page where its change will most likely land — under the H1,
+ * where a summary goes — saying it is drafting, and from which data. A
+ * decoration, never the page's: no save, export or copy has it.
+ */
+
+interface Drafting {
+ /** "Content Agent is drafting a change here…". */
+ title: string;
+ /** "Drafting from 4 cited pages and 2 fan-outs…", or null when it isn't drafting. */
+ text: string | null;
+}
+
+interface DraftingState extends Drafting {
+ marks: DecorationSet;
+}
+
+export const draftingKey = new PluginKey<DraftingState>('agentDrafting');
+
+function el<K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text?: string) {
+ const node = document.createElement(tag);
+ node.className = className;
+ if (text !== undefined) node.textContent = text;
+ return node;
+}
+
+/** The card: what it does, from which data, and lines that shimmer (still without motion). */
+function card({ title, text }: Drafting): HTMLElement {
+ const box = el('div', 'not-prose my-3 rounded-xl border border-dashed bg-muted/30 px-3 py-2.5');
+ box.setAttribute('role', 'status');
+ box.dataset.agentDrafting = '';
+ box.append(
+ el('p', 'text-[13px] font-medium text-foreground', title),
+ el('p', 'text-xs text-muted-foreground', text ?? ''),
+ );
+ const lines = el('div', 'mt-2 space-y-1.5');
+ lines.setAttribute('aria-hidden', 'true');
+ for (const width of ['w-full', 'w-5/6', 'w-3/5']) {
+ lines.append(
+ el('div', `h-2 ${width} animate-pulse rounded bg-muted motion-reduce:animate-none`),
+ );
+ }
+ box.append(lines);
+ return box;
+}
+
+export const AgentDrafting = Extension.create({
+ name: 'agentDrafting',
+
+ addProseMirrorPlugins() {
+ return [
+ new Plugin<DraftingState>({
+ key: draftingKey,
+ state: {
+ init: () => ({ title: '', text: null, marks: DecorationSet.empty }),
+ apply: (tr, value, _old, state) => {
+ const meta = tr.getMeta(draftingKey) as Drafting | undefined;
+ if (!meta && !tr.docChanged) return value;
+ const next = meta ?? { title: value.title, text: value.text };
+ if (!next.text) return { ...next, marks: DecorationSet.empty };
+ // After the first block (the H1), else at the top.
+ const pos = state.doc.firstChild?.nodeSize ?? 0;
+ return {
+ ...next,
+ marks: DecorationSet.create(state.doc, [
+ Decoration.widget(pos, () => card(next), {
+ key: `drafting:${next.title}:${next.text}`,
+ side: 1,
+ ignoreSelection: true,
+ stopEvent: () => true,
+ }),
+ ]),
+ };
+ },
+ },
+ props: {
+ decorations: (state) => draftingKey.getState(state)?.marks ?? null,
+ },
+ }),
+ ];
+ },
+});
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.tsx
index ef420102a..b2059f00e 100644
--- 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.tsx
@@ -1,11 +1,18 @@
'use client';
+import { useEffect, useState } from 'react';
import { useNow, useTranslations } from 'next-intl';
-import { ArrowLeft, Bot, Check, Circle, Loader2 } from 'lucide-react';
+import { toast } from 'sonner';
+import { ArrowLeft, Bot, Check, Circle } from 'lucide-react';
import { Link } from '@/i18n/navigation';
+import { Button } from '@/components/ui/button';
import { buttonVariants } from '@/components/ui/button-variants';
+import { stopAgentRun } from '@/lib/content/agent-runs-client';
import { CONTENT_LIBRARY_PATH, type DraftMethod } from '@/lib/content/drafts';
import { cn } from '@/lib/utils';
+import { RunSteps } from './_agent-card';
+import { WorkingDots } from './_working-dots';
+import { useAgentRun } from './_use-agent-run';
/**
* What the agent does with a draft, in order (content-writer.js): it reads
@@ -26,6 +33,9 @@ const WRITING = STEPS.indexOf('write');
*/
const SLOW_AFTER_S = 120;
+/** The runs this page waits on: a new page, or the whole page rewritten. */
+const WRITING_RUNS = ['write', 'rewrite'] as const;
+
/** 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;
@@ -41,23 +51,63 @@ const clock = (seconds: number) =>
* 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.
+ * editor opens on what it wrote. Once its run reads (v1.1 CE-027/035), its
+ * real steps, named by the data they use, and Stop, which leaves the page as
+ * it was.
*/
export function AgentWriting({
+ draftId,
+ brandId,
title,
method,
since,
rewrite = false,
+ onRunEnded,
}: {
+ draftId: string;
+ brandId: string;
title: string;
method: DraftMethod;
/** When the agent started (content_drafts.agent_state_at). */
since: string | null;
/** Rewrite the page to these rules, as this tab started it. */
rewrite?: boolean;
+ /** The run ended (stopped, done or failed): the page reads the draft again. */
+ onRunEnded?: () => void;
}) {
const t = useTranslations('contentEditor.editor');
const seconds = elapsedSeconds(since, useNow({ updateInterval: 1000 }));
+ const live = useAgentRun(draftId, true, WRITING_RUNS);
+ const [stopping, setStopping] = useState(false);
+ // The last run read stays until the editor opens: the fixed list never
+ // comes back for a moment at its end.
+ const [shown, setShown] = useState(live);
+ if (live && live !== shown) setShown(live);
+ const run = live ?? shown;
+ // It ended (done, failed, or gone stale): the draft is read at once, not
+ // on the page's next look.
+ const ended = shown !== null && live === null;
+ useEffect(() => {
+ if (ended) onRunEnded?.();
+ }, [ended, onRunEnded]);
+ const stop = async () => {
+ setStopping(true);
+ const result = await stopAgentRun(draftId, brandId, run?.id ?? null).catch(
+ (): { error: 'failed' } => ({
+ error: 'failed',
+ }),
+ );
+ if ('error' in result) {
+ toast.error(t('agentCard.stopFailed'));
+ setStopping(false);
+ } else if (result.stopped) {
+ // The page opens again as it was: the server let go of the draft.
+ toast(t('agentCard.stopped'));
+ onRunEnded?.();
+ } else {
+ setStopping(false);
+ }
+ };
return (
<>
<header className="flex items-center gap-2.5 border-b px-4 py-2.5">
@@ -71,46 +121,63 @@ export function AgentWriting({
</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 flex-1 flex-col items-center justify-center px-6">
+ <div role="status" 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.${rewrite ? 'rewrite' : 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)}
+ {run ? (
+ <div className="space-y-2 rounded-xl border bg-card px-4 py-3.5">
+ <RunSteps run={run} />
+ {seconds !== null && (
+ <p aria-hidden className="text-xs text-muted-foreground tabular-nums">
+ {clock(seconds)}
+ </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 ? (
+ // No spinning ring (v1.1 §2.4): the agent's dots.
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center">
+ <WorkingDots className="ml-0" />
+ </span>
+ ) : (
+ <Circle aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground/60" />
+ )}
+ <span className="min-w-0 flex-1">
+ {t(`agentWriting.steps.${rewrite ? 'rewrite' : method}.${step}`)}
</span>
- )}
- </li>
- ))}
- </ol>
+ {/* 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>
@@ -120,6 +187,14 @@ export function AgentWriting({
{rewrite ? t('agentWriting.leaveRewrite') : t('agentWriting.leave')}
</p>
</div>
+ {/* Outside the status, which a screen reader reads as it changes. */}
+ {run && (
+ <div className="mt-4 w-full max-w-sm">
+ <Button variant="outline" size="sm" disabled={stopping} onClick={() => void stop()}>
+ {t('agentCard.stop')}
+ </Button>
+ </div>
+ )}
</div>
</>
);
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.tsx
index 67525e0f8..052d50a68 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
@@ -16,6 +16,7 @@ import { wordsForLength } from '@/lib/content/rules';
import { formatDateTime, formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import { RunCard } from './_run-card';
+import { WorkingDots } from './_working-dots';
/**
* Rewrite from brief: the Content Agent writes the page again from the brief
@@ -58,6 +59,7 @@ export function BriefTab({
onSaved,
rewrite,
dataLine,
+ blocked = null,
}: {
draftId: string;
state: BriefState;
@@ -74,6 +76,8 @@ export function BriefTab({
rewrite?: AgentRewrite;
/** "Uses your data", under Run Agent's card (v1.1 CE-032). */
dataLine?: React.ReactNode;
+ /** Why Run Agent waits (another agent run from the page), or null. */
+ blocked?: string | null;
}) {
const t = useTranslations('contentEditor.editor.brief');
const tTypes = useTranslations('contentEditor.pageTypes');
@@ -131,15 +135,16 @@ export function BriefTab({
size="sm"
variant={empty ? 'default' : 'outline'}
className="shrink-0"
- disabled={rebuilding || confirming}
+ disabled={rebuilding || confirming || blocked !== null}
onClick={rebuild}
>
- {rebuilding && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {rebuilding && <WorkingDots className="ml-0" />}
{empty ? t('run') : t('rebuild')}
</Button>
}
info={t('info')}
data={dataLine}
+ blocked={rebuilding ? null : blocked}
>
<p className="text-[11px] text-muted-foreground">{t('usage')}</p>
{/* Under the card that asked, not past the outline. */}
@@ -287,11 +292,7 @@ export function BriefTab({
disabled={rewrite.running || rewrite.blocked !== null || rebuilding}
onClick={() => setConfirmingRewrite(true)}
>
- {rewrite.running ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Bot className="h-3.5 w-3.5" />
- )}
+ {rewrite.running ? <WorkingDots className="ml-0" /> : <Bot className="h-3.5 w-3.5" />}
{t(`rewrite.button.${method}`)}
</Button>
{/* Why it waits, written out (v1.1 CE-031), not only on hover. */}
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 81f0d0290..db5a978d7 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
@@ -35,6 +35,7 @@ import {
startAgentWriting,
startPageRewrite,
} from '@/lib/actions/content-drafts';
+import { stopAgentRun } from '@/lib/content/agent-runs-client';
import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';
import {
AGENT_POLL_MS,
@@ -57,8 +58,8 @@ import {
type SuggestionSource,
type SuggestionStatus,
} from '@/lib/content/suggestions';
-import { rebuildSources } from '@/lib/content/brief';
-import { buildSourceGroups } from '@/lib/content/sources';
+import { REBUILD_LIMITS, rebuildSources } from '@/lib/content/brief';
+import { buildSourceGroups, includedCounts } from '@/lib/content/sources';
import {
cleanHtml,
formatHtmlSource,
@@ -72,6 +73,9 @@ import { aiTracesFound, fanoutsToUse, lengthWarns, openRulesForAgent } from '@/l
import { saveBlob } from '@/lib/download';
import { cn } from '@/lib/utils';
import { AgentCard } from './_agent-card';
+import { AgentDrafting, draftingKey } from './_agent-drafting';
+import { useAgentRun } from './_use-agent-run';
+import { WorkingDots } from './_working-dots';
import { DropOverlay, useAttachments } from './_attach';
import {
CITED_EDIT_ALLOWED,
@@ -140,6 +144,10 @@ const DOCUMENT_CLASS = cn(
*/
const FIX_WAIT_MS = 90_000;
+/** The runs the agent card shows: Fix open rules', or the brief's. */
+const FIX_RUNS = ['fix'] as const;
+const BRIEF_RUNS = ['brief'] as const;
+
/**
* The draft's suggestions once a new open batch lands, read every few
* seconds until the deadline; null if none did. Fix open rules only runs
@@ -220,6 +228,15 @@ export function DraftEditor({
const [deciding, setDeciding] = useState(false);
const [barClosed, setBarClosed] = useState(false);
const [fixing, setFixing] = useState(false);
+ // The brief the agent writes from the side panel: the card shows it working too.
+ const [briefRebuilding, setBriefRebuilding] = useState(false);
+ // The run Stop was pressed for: the card waits for it to end (CE-027). Another
+ // run under way (one a restarted server left was shown first) can be stopped.
+ const [stoppingRun, setStoppingRun] = useState<string | null>(null);
+ // The Stop sent, and whether it stopped a run: an answer lost after it is no failure.
+ const stopSent = useRef<Promise<boolean> | null>(null);
+ // Whether the side panel's brief is rebuilding, as it last said.
+ const briefNow = useRef(false);
const tRules = useTranslations('contentEditor.editor.rules');
const tStatus = useTranslations('contentEditor.editor.rules.status');
// History keeps the page before the first suggestion accepted here.
@@ -297,6 +314,7 @@ export function DraftEditor({
onSource: (source) => onSource.current(source),
}),
OneH1,
+ AgentDrafting,
],
content: draft.bodyHtml,
// Rendered on the client only, so the server's HTML can't disagree with it.
@@ -522,6 +540,42 @@ export function DraftEditor({
);
}, [editor, suggestions, suggestionLabels]);
+ // While Fix open rules runs, a dashed card in the page where its change
+ // will most likely land, from which of the kept data (CE-027/035).
+ const keptCounts = useMemo(
+ () =>
+ reads.sources?.data
+ ? includedCounts(
+ buildSourceGroups(reads.sources.data, reads.sources.choices, {
+ title: draft.title,
+ sourceUrl: draft.sourceUrl,
+ }),
+ )
+ : null,
+ [reads.sources, draft.title, draft.sourceUrl],
+ );
+ // As many as the agent gets (rebuildSources).
+ const pages = Math.min(keptCounts?.cited_page ?? 0, REBUILD_LIMITS.pages);
+ const fanouts = Math.min(keptCounts?.fanout ?? 0, REBUILD_LIMITS.fanouts);
+ const draftingText = !fixing
+ ? null
+ : pages && fanouts
+ ? t('agentCard.draftingFrom', { pages, fanouts })
+ : pages
+ ? t('agentCard.draftingFromPages', { pages })
+ : fanouts
+ ? t('agentCard.draftingFromFanouts', { fanouts })
+ : t('agentCard.draftingRules');
+ useEffect(() => {
+ if (!editor || editor.isDestroyed) return;
+ editor.view.dispatch(
+ editor.state.tr.setMeta(draftingKey, {
+ title: t('agentCard.drafting'),
+ text: draftingText,
+ }),
+ );
+ }, [editor, draftingText, t]);
+
/**
* Accept, reject, undo (an accepted one) or restore (a rejected one): the
* page changes first, then the decision is kept. Accepting keeps the page
@@ -776,6 +830,8 @@ export function DraftEditor({
}
: {}),
};
+ setStoppingRun(null);
+ stopSent.current = null;
setFixing(true);
const asked = Date.now();
try {
@@ -786,6 +842,12 @@ export function DraftEditor({
console.error('Failed to hear back from the Content Agent:', err);
return { error: 'unconfirmed' as const };
});
+ const stop = stopSent.current;
+ if ('error' in result && result.error === 'unconfirmed' && stop && (await stop)) {
+ // Stopped, and the answer was lost on the way: nothing it had is kept.
+ toast(t('agentCard.stopped'));
+ return;
+ }
if ('error' in result && result.error === 'unconfirmed') {
// No answer is not a failure: its batch shows if it lands in time.
const landed = await agentBatch(draft.id, asked + FIX_WAIT_MS);
@@ -799,6 +861,11 @@ export function DraftEditor({
toast.success(fixedMessage(landed.filter((s) => s.status === 'open').length));
return;
}
+ if ('error' in result && result.error === 'stopped') {
+ // Stopped from the card: no failure, and nothing changed.
+ toast(t('agentCard.stopped'));
+ return;
+ }
if ('error' in result) {
toast.error(t(`suggestions.fixErrors.${result.error}`));
// Another tab (or the API) left them: show them here to decide.
@@ -822,10 +889,45 @@ export function DraftEditor({
toast.error(t('suggestions.fixErrors.failed'));
} finally {
setFixing(false);
+ setStoppingRun(null);
+ stopSent.current = null;
+ }
+ };
+
+ // The agent at work from this page: Fix open rules, or the brief. Its run,
+ // step by step, and Stop (CE-027/035).
+ const agentWorking = fixing || briefRebuilding;
+ const agentRun = useAgentRun(draft.id, agentWorking, fixing ? FIX_RUNS : BRIEF_RUNS);
+ const stopAgent = async () => {
+ if (!agentRun) return;
+ setStoppingRun(agentRun.id);
+ const request = stopAgentRun(draft.id, draft.brandId, agentRun.id).catch(
+ (): { error: 'failed' } => ({
+ error: 'failed',
+ }),
+ );
+ const sent = request.then((result) => !('error' in result) && result.stopped);
+ stopSent.current = sent;
+ const result = await request;
+ // Nothing to stop, or it couldn't: the run goes on, and says how it ends.
+ if ('error' in result || !result.stopped) {
+ if ('error' in result) toast.error(t('agentCard.stopFailed'));
+ if (stopSent.current === sent) stopSent.current = null;
+ setStoppingRun(null);
}
};
+ const onBriefRebuilding = useCallback((on: boolean) => {
+ // Only the brief's end clears its Stop: the panel says "not rebuilding" as
+ // it opens and closes, while Fix may be the one stopping.
+ if (briefNow.current && !on) {
+ setStoppingRun(null);
+ stopSent.current = null;
+ }
+ briefNow.current = on;
+ setBriefRebuilding(on);
+ }, []);
// One agent run at a time from this page: the others wait for it.
- const agentBusy = fixing || starting || rewriting;
+ const agentBusy = fixing || starting || rewriting || briefRebuilding;
const agentFix: AgentFix = {
run: (only) => void fixRules(only),
running: fixing,
@@ -1273,7 +1375,7 @@ export function DraftEditor({
disabled={agentBusy || !editor || (failedRewrite && !citedRead)}
onClick={() => void (failedRewrite ? rewritePage() : startAgent())}
>
- {(starting || rewriting) && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {(starting || rewriting) && <WorkingDots className="ml-0" />}
{t('agentFailed.retry')}
</Button>
<Button
@@ -1308,7 +1410,7 @@ export function DraftEditor({
</span>
</p>
)}
- {(fixing || (suggestions.length > 0 && !(barClosed && openSuggestions === 0))) && (
+ {(agentWorking || (suggestions.length > 0 && !(barClosed && openSuggestions === 0))) && (
<AgentCard
suggestions={suggestions}
rules={cardRules}
@@ -1316,7 +1418,10 @@ export function DraftEditor({
onSeeSources={() => openPanelTab('sources')}
// Not while the HTML view holds the page: it would write over it.
busy={deciding || htmlSource !== null}
- working={fixing}
+ working={agentWorking}
+ run={agentRun}
+ onStop={() => void stopAgent()}
+ stopping={stoppingRun !== null && stoppingRun === agentRun?.id}
onAcceptAll={() =>
void decide(
suggestions.filter((s) => s.status === 'open').map((s) => s.id),
@@ -1411,6 +1516,8 @@ export function DraftEditor({
onSourceShown={() =>
setTabRequest((prev) => (prev?.source ? { tab: prev.tab, n: prev.n } : prev))
}
+ onBriefRebuilding={onBriefRebuilding}
+ briefBlocked={agentBusy && !briefRebuilding ? t('suggestions.agentBusy') : null}
/>
) : (
<EditorPanelRail onOpen={openPanelTab} />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx
index 39fb20ab5..db9aacf49 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx
@@ -24,6 +24,7 @@ import { formatPctChange } from '@/lib/traffic-kpis';
import type { VisitChange } from '@/lib/traffic-change';
import { cn } from '@/lib/utils';
import { ImpactResults } from './_impact-results';
+import { WorkingDots } from './_working-dots';
/** One read of the tab, for one period: null while it runs. */
interface ImpactRead {
@@ -45,12 +46,15 @@ export function ImpactTab({
brandId,
pageUrl,
rebuilding = false,
+ blocked = null,
onUseLostPrompts,
}: {
brandId: string;
pageUrl: string | null;
/** Use lost prompts in this draft: they join its sources and the brief is rebuilt. */
rebuilding?: boolean;
+ /** Why the brief can't be rebuilt now (the agent is at work on the page), or null. */
+ blocked?: string | null;
onUseLostPrompts?: (promptIds: string[]) => void;
}) {
const t = useTranslations('contentEditor.editor.impact');
@@ -140,6 +144,7 @@ export function ImpactTab({
period={period}
pageUrl={pageUrl}
rebuilding={rebuilding}
+ blocked={blocked}
onUseLostPrompts={onUseLostPrompts}
/>
)}
@@ -153,6 +158,7 @@ function ImpactBody({
period,
pageUrl,
rebuilding,
+ blocked,
onUseLostPrompts,
}: {
impact: ContentImpact;
@@ -160,6 +166,7 @@ function ImpactBody({
period: ImpactPeriod;
pageUrl: string;
rebuilding: boolean;
+ blocked: string | null;
onUseLostPrompts?: (promptIds: string[]) => void;
}) {
const t = useTranslations('contentEditor.editor.impact');
@@ -280,14 +287,17 @@ function ImpactBody({
<Button
size="sm"
variant="outline"
- disabled={rebuilding}
+ disabled={rebuilding || blocked !== null}
onClick={() => onUseLostPrompts(lostPrompts.map((p) => p.id))}
>
- {rebuilding && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {rebuilding && <WorkingDots className="ml-0" />}
{t('prompts.useLost', { count: lostPrompts.length })}
</Button>
)}
</div>
+ {lostPrompts.length > 0 && onUseLostPrompts && !rebuilding && blocked && (
+ <p className="text-xs text-amber-700 dark:text-amber-400">{blocked}</p>
+ )}
</section>
{results && <ImpactResults results={results} />}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
index 5379090f2..99b63c242 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
@@ -2,7 +2,7 @@
import { useState } from 'react';
import { useFormatter, useTranslations } from 'next-intl';
-import { ChevronDown, Loader2, Sparkles } from 'lucide-react';
+import { ChevronDown, Sparkles } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
@@ -43,6 +43,7 @@ import { formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import { useUserRole } from '@/hooks/use-user-role';
import { RunCard } from './_run-card';
+import { WorkingDots } from './_working-dots';
import type { DraftRulesState } from './_use-draft-rules';
/** Rules with an explanation on hover (spec §10). */
@@ -136,7 +137,7 @@ function RunAgentButton({
if (mode === 'rewrite') onMode('fix');
}}
>
- {running && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {running && <WorkingDots className="ml-0" />}
{running ? t('working') : mode === 'rewrite' ? t('rewriteLabel') : t('label')}
</Button>
);
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.tsx
index f22239880..4914e2359 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
@@ -111,6 +111,8 @@ export function EditorSidePanel({
agentRewrite,
lastSuggestionAt,
onSourceShown,
+ onBriefRebuilding,
+ briefBlocked = null,
}: {
draft: ContentDraft;
/** The draft's title, page and type as written now: Sources and Brief read them. */
@@ -140,6 +142,10 @@ export function EditorSidePanel({
lastSuggestionAt: string | null;
/** The source asked for was shown (or isn't listed): it isn't shown again. */
onSourceShown?: () => void;
+ /** Whether the agent is writing the brief: the agent card shows it working (CE-027). */
+ onBriefRebuilding?: (rebuilding: boolean) => void;
+ /** Why the brief's Run Agent waits (another agent run from this page), or null. */
+ briefBlocked?: string | null;
}) {
const t = useTranslations('contentEditor.editor.panel');
const [tab, setTab] = useState<PanelTab>('instructions');
@@ -212,6 +218,13 @@ export function EditorSidePanel({
},
});
+ // The agent card shows the brief's run too, with its steps and Stop; a
+ // panel closed meanwhile says it no longer waits on it.
+ useEffect(() => {
+ onBriefRebuilding?.(rebuilding);
+ return () => onBriefRebuilding?.(false);
+ }, [rebuilding, onBriefRebuilding]);
+
return (
<aside aria-label={t('label')} className="flex w-[400px] shrink-0 flex-col border-l bg-card">
<Tabs
@@ -306,6 +319,7 @@ export function EditorSidePanel({
onSaved={(saved) => reads.setBrief(saved)}
rewrite={agentRewrite}
dataLine={dataLine}
+ blocked={briefBlocked}
/>
</div>
)}
@@ -340,6 +354,7 @@ export function EditorSidePanel({
sourceUrl={draft.sourceUrl}
bodyHtml={bodyHtml}
rebuilding={rebuilding}
+ blocked={briefBlocked}
onRebuild={(sources) => void rebuild({ sources })}
agentUsedAt={agentUsedAt}
// Only while Sources shows: a hidden row can't be scrolled to.
@@ -358,6 +373,7 @@ export function EditorSidePanel({
brandId={draft.brandId}
pageUrl={draft.sourceUrl}
rebuilding={rebuilding}
+ blocked={briefBlocked}
onUseLostPrompts={(promptIds) => void rebuild({ addPrompts: promptIds })}
/>
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
index 94888b0b4..4d02d9c0d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
@@ -30,6 +30,7 @@ import {
import { formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import { AddSourceDialog } from './_add-source-dialog';
+import { WorkingDots } from './_working-dots';
import type { SourcesRead } from './_use-draft-reads';
/**
@@ -51,6 +52,7 @@ export function SourcesTab({
sourceUrl,
bodyHtml,
rebuilding,
+ blocked = null,
onRebuild,
agentUsedAt,
highlight = null,
@@ -68,6 +70,8 @@ export function SourcesTab({
bodyHtml: string;
/** Rebuild with selection: the brief from the sources as checked here. */
rebuilding: boolean;
+ /** Why Rebuild with selection can't run now (the agent is at work on the page), or null. */
+ blocked?: string | null;
onRebuild: (sources: { data: DraftSourcesData; choices: DraftSourceChoice[] }) => void;
/** When the Content Agent last wrote from them (a run's suggestions, a brief), or null. */
agentUsedAt: string | null;
@@ -207,14 +211,10 @@ export function SourcesTab({
<div className="flex flex-wrap gap-2">
<Button
size="sm"
- disabled={rebuilding || total === 0}
+ disabled={rebuilding || total === 0 || blocked !== null}
onClick={() => onRebuild({ data: read.data, choices: read.choices })}
>
- {rebuilding ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <RefreshCw className="h-3.5 w-3.5" />
- )}
+ {rebuilding ? <WorkingDots className="ml-0" /> : <RefreshCw className="h-3.5 w-3.5" />}
{t('rebuild')}
</Button>
<Button variant="outline" size="sm" onClick={() => setAdding(true)}>
@@ -222,6 +222,9 @@ export function SourcesTab({
{t('add.button')}
</Button>
</div>
+ {!rebuilding && blocked && (
+ <p className="text-xs text-amber-700 dark:text-amber-400">{blocked}</p>
+ )}
<AddSourceDialog
open={adding}
onOpenChange={setAdding}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-agent-run.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-agent-run.test.tsx
new file mode 100644
index 000000000..dfc0c3910
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-agent-run.test.tsx
@@ -0,0 +1,80 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AgentRun } from '@/lib/content/agent-runs';
+import { AGENT_POLL_MS } from '@/lib/content/drafts';
+import { RUN_POLL_MS, useAgentRun } from './_use-agent-run';
+
+/**
+ * The run's steps read while the editor waits on the agent (CE-027/035): a
+ * second after each read, less often in a hidden tab, and at once when it
+ * shows again.
+ */
+
+const readAgentRun = vi.fn();
+vi.mock('@/lib/content/agent-runs-client', () => ({
+ readAgentRun: (...args: unknown[]) => readAgentRun(...args),
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const run = (): AgentRun => ({
+ id: 'r1',
+ kind: 'fix',
+ steps: [{ key: 'write_changes', count: null }],
+ step: 0,
+ startedAt: new Date().toISOString(),
+ finishedAt: null,
+ stoppedAt: null,
+ outcome: null,
+});
+
+/** The hook as the editor uses it: the run it reads, by id. */
+function Harness() {
+ const run = useAgentRun('d1', true, ['fix']);
+ return <span data-run={run?.id ?? ''} />;
+}
+const seen = () => container.querySelector('[data-run]')!.getAttribute('data-run');
+
+let container: HTMLDivElement;
+let root: Root;
+let hidden = false;
+
+beforeEach(async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ hidden = false;
+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden });
+ readAgentRun.mockReset().mockResolvedValue(run());
+ container = document.createElement('div');
+ root = createRoot(container);
+ await act(async () => root.render(<Harness />));
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ vi.useRealTimers();
+});
+
+describe('useAgentRun', () => {
+ it('reads the run a second after each read', async () => {
+ expect(seen()).toBe('r1');
+ expect(readAgentRun).toHaveBeenCalledTimes(1);
+ await act(async () => void (await vi.advanceTimersByTimeAsync(RUN_POLL_MS)));
+ expect(readAgentRun).toHaveBeenCalledTimes(2);
+ });
+
+ it('reads less often in a hidden tab, and at once when it shows again', async () => {
+ hidden = true;
+ await act(async () => void (await vi.advanceTimersByTimeAsync(RUN_POLL_MS)));
+ // The read due now goes; the one after waits the longer step.
+ expect(readAgentRun).toHaveBeenCalledTimes(2);
+ await act(async () => void (await vi.advanceTimersByTimeAsync(RUN_POLL_MS * 2)));
+ expect(readAgentRun).toHaveBeenCalledTimes(2);
+
+ hidden = false;
+ await act(async () => void document.dispatchEvent(new Event('visibilitychange')));
+ expect(readAgentRun).toHaveBeenCalledTimes(3);
+ expect(AGENT_POLL_MS).toBeGreaterThan(RUN_POLL_MS * 2);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-agent-run.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-agent-run.ts
new file mode 100644
index 000000000..651957ebb
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-agent-run.ts
@@ -0,0 +1,59 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { runUnderWay, sameRun, type AgentRun, type AgentRunKind } from '@/lib/content/agent-runs';
+import { readAgentRun } from '@/lib/content/agent-runs-client';
+import { AGENT_POLL_MS } from '@/lib/content/drafts';
+
+/** How long after one read of the run the next goes: its steps take a second or more. */
+export const RUN_POLL_MS = 1000;
+
+/**
+ * The draft's Content Agent run while one is under way (v1.1 CE-027/035),
+ * read from the browser while `active` (the editor waits on the agent): its
+ * steps as the server writes them. The next read goes a second after the last
+ * answered, so slow reads never pile up; in a hidden tab every AGENT_POLL_MS,
+ * and at once when it shows again. Null otherwise, and before the run's
+ * first step reads — never an earlier run's steps, nor another kind's (a
+ * rewrite still under way when Fix starts, until the server closes it).
+ */
+export function useAgentRun(
+ draftId: string,
+ active: boolean,
+ kinds: readonly AgentRunKind[],
+): AgentRun | null {
+ const [run, setRun] = useState<AgentRun | null>(null);
+ const kindsKey = kinds.join();
+ useEffect(() => {
+ if (!active) return;
+ const wanted = kindsKey.split(',');
+ let done = false;
+ let reading = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const read = async () => {
+ reading = true;
+ const next = await readAgentRun(draftId).catch(() => null);
+ reading = false;
+ if (done) return;
+ const shown = next && runUnderWay(next) && wanted.includes(next.kind) ? next : null;
+ setRun((last) => (sameRun(last, shown) ? last : shown));
+ timer = setTimeout(() => void read(), document.hidden ? AGENT_POLL_MS : RUN_POLL_MS);
+ };
+ // Shown again: read now, unless a read is out (it sets the next one).
+ const onVisible = () => {
+ if (document.hidden || reading) return;
+ clearTimeout(timer);
+ void read();
+ };
+ document.addEventListener('visibilitychange', onVisible);
+ void read();
+ return () => {
+ done = true;
+ clearTimeout(timer);
+ document.removeEventListener('visibilitychange', onVisible);
+ // The next wait starts from nothing, never this one's last steps.
+ setRun(null);
+ };
+ }, [draftId, active, kindsKey]);
+ return active && run && runUnderWay(run) ? run : null;
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.test.tsx
index 3f342bbcd..8591fce19 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.test.tsx
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../../../messages/en.json';
import type { ContentDraft } from '@/lib/content/drafts';
import type { DraftSourceChoice, DraftSourcesData } from '@/lib/content/sources';
+import { toast } from 'sonner';
import { useBriefRebuild } from './_use-brief-rebuild';
import type { SourcesRead } from './_use-draft-reads';
@@ -22,7 +23,9 @@ vi.mock('@/lib/actions/content-drafts', () => ({
getDraftSources: (...args: unknown[]) => getDraftSources(...args),
rebuildDraftBrief: (...args: unknown[]) => rebuildDraftBrief(...args),
}));
-vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('sonner', () => ({
+ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),
+}));
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
true;
@@ -69,6 +72,8 @@ let root: Root;
beforeEach(async () => {
for (const fn of [addDraftPrompts, getDraftSources, rebuildDraftBrief, onSourcesRead, onRebuilt])
fn.mockReset();
+ vi.mocked(toast).mockClear();
+ vi.mocked(toast.error).mockClear();
addDraftPrompts.mockResolvedValue(undefined);
getDraftSources.mockResolvedValue(SOURCES);
rebuildDraftBrief.mockResolvedValue({ brief: { builtFrom: null } });
@@ -108,4 +113,12 @@ describe('useBriefRebuild', () => {
expect(onSourcesRead).toHaveBeenCalledWith({ data: null, choices: [], failed: true });
expect(rebuildDraftBrief).not.toHaveBeenCalled();
});
+
+ it('says a rebuild stopped from the agent card changed nothing, not that it failed', async () => {
+ rebuildDraftBrief.mockResolvedValue({ error: 'stopped' });
+ await press('rebuild');
+ expect(toast).toHaveBeenCalledWith('Stopped · nothing was changed');
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(onRebuilt).not.toHaveBeenCalled();
+ });
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts
index 643292903..70bcb3181 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts
@@ -40,6 +40,7 @@ export function useBriefRebuild({
onRebuilt: (brief: DraftBrief) => void;
}) {
const t = useTranslations('contentEditor.editor.brief');
+ const tCard = useTranslations('contentEditor.editor.agentCard');
const [rebuilding, setRebuilding] = useState(false);
const rebuild = async (
@@ -80,7 +81,9 @@ export function useBriefRebuild({
}),
);
if ('error' in result) {
- toast.error(t(`rebuildErrors.${result.error}`));
+ // Stopped from the agent card (CE-027): no failure, nothing changed.
+ if (result.error === 'stopped') toast(tCard('stopped'));
+ else toast.error(t(`rebuildErrors.${result.error}`));
return false;
}
toast.success(t('rebuilt', { count: builtFromCount(result.brief) }));
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_working-dots.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_working-dots.tsx
new file mode 100644
index 000000000..b0b84824b
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_working-dots.tsx
@@ -0,0 +1,19 @@
+import { cn } from '@/lib/utils';
+
+/**
+ * The Content Agent at work (v1.1 CE-035): three dots that bounce in turn, in
+ * the text's color — never a spinning ring. Still with reduced motion.
+ */
+export function WorkingDots({ className }: { className?: string }) {
+ return (
+ <span aria-hidden className={cn('ml-1.5 inline-flex gap-[3px] align-middle', className)}>
+ {[0, 1, 2].map((i) => (
+ <span
+ key={i}
+ className="h-1 w-1 animate-agent-dot rounded-full bg-current opacity-25 motion-reduce:animate-none"
+ style={{ animationDelay: `${i * 0.2}s` }}
+ />
+ ))}
+ </span>
+ );
+}
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 0187ce882..ad40eeab3 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
@@ -19,6 +19,12 @@ const getContentImpact = vi.fn();
const getContentResults = vi.fn();
const getDraftSources = vi.fn();
const setDraftSourceIncluded = vi.fn();
+const readAgentRun = vi.fn();
+const stopAgentRun = vi.fn();
+vi.mock('@/lib/content/agent-runs-client', () => ({
+ readAgentRun: (...args: unknown[]) => readAgentRun(...args),
+ stopAgentRun: (...args: unknown[]) => stopAgentRun(...args),
+}));
const getDraftBrief = vi.fn();
const rebuildDraftBrief = vi.fn();
const saveDraftRules = vi.fn();
@@ -222,6 +228,8 @@ beforeEach(() => {
getContentImpact.mockReset().mockResolvedValue(null);
getContentResults.mockReset().mockResolvedValue(null);
getDraftSources.mockReset().mockResolvedValue(null);
+ readAgentRun.mockReset().mockResolvedValue(null);
+ stopAgentRun.mockReset().mockResolvedValue({ stopped: true });
getDraftBrief.mockReset().mockResolvedValue({ brief: null });
rebuildDraftBrief.mockReset();
saveDraftRules.mockReset().mockResolvedValue(undefined);
@@ -527,6 +535,101 @@ describe('the content editor', () => {
expect(status.textContent).not.toContain('Usually a minute or two.');
});
+ it('shows its real steps, and stops it with nothing changed (CE-027/035)', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ status: 'draft',
+ method: 'create',
+ agentState: 'writing',
+ agentSince: new Date().toISOString(),
+ }),
+ );
+ readAgentRun.mockResolvedValue({
+ id: 'r1',
+ kind: 'write',
+ steps: [
+ { key: 'read_rules', count: 9 },
+ { key: 'gather_sources', count: 52 },
+ { key: 'write_page', count: null },
+ { key: 'check_sources', count: null },
+ ],
+ step: 2,
+ startedAt: new Date().toISOString(),
+ finishedAt: null,
+ stoppedAt: null,
+ outcome: null,
+ });
+ await renderPage();
+ await act(async () => {});
+ const status = container.querySelector('[role="status"]')!;
+ expect([...status.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Reading 9 rules',
+ 'Gathering 52 sources',
+ 'Writing the page',
+ 'Checking sources',
+ ]);
+ expect(status.querySelector('[aria-current="step"]')!.textContent).toBe('Writing the page');
+ // No spinning ring anywhere (v1.1 §2.4).
+ expect(status.querySelector('.animate-spin')).toBeNull();
+
+ const reads = getContentDraft.mock.calls.length;
+ await act(async () => button('Stop')!.click());
+ expect(stopAgentRun).toHaveBeenCalledWith('d1', 'b1', 'r1');
+ expect(toast).toHaveBeenCalledWith('Stopped · nothing was changed');
+ // The page as the server left it, let go of.
+ expect(getContentDraft.mock.calls.length).toBe(reads + 1);
+ });
+
+ it('reads the draft at once when its run ends, its steps shown till then', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ try {
+ getContentDraft.mockResolvedValue(
+ draft({
+ status: 'draft',
+ method: 'create',
+ agentState: 'writing',
+ agentSince: new Date().toISOString(),
+ }),
+ );
+ const writingRun = {
+ id: 'r1',
+ kind: 'write' as const,
+ steps: [
+ { key: 'write_page' as const, count: null },
+ { key: 'check_sources' as const, count: null },
+ ],
+ step: 1,
+ startedAt: new Date().toISOString(),
+ finishedAt: null,
+ stoppedAt: null,
+ outcome: null,
+ };
+ readAgentRun.mockResolvedValue(writingRun);
+ await renderPage();
+ await act(async () => {});
+ const reads = getContentDraft.mock.calls.length;
+
+ readAgentRun.mockResolvedValue({
+ ...writingRun,
+ step: 2,
+ finishedAt: new Date().toISOString(),
+ outcome: 'done',
+ });
+ await act(async () => void (await vi.advanceTimersByTimeAsync(1000)));
+ await act(async () => {});
+ // Not on the page's next look (5 s): now.
+ expect(getContentDraft.mock.calls.length).toBe(reads + 1);
+ // The run's steps stay, never the fixed list for a moment.
+ const status = container.querySelector('[role="status"]')!;
+ expect([...status.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Writing the page',
+ 'Checking sources',
+ ]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
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();
@@ -1807,6 +1910,60 @@ describe('the side panel', () => {
).toContain('forecast accuracy, pipeline');
});
+ it('shows the agent working while the brief rebuilds, and a stopped rebuild changes nothing', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ let answer: (value: { error: 'stopped' }) => void = () => {};
+ rebuildDraftBrief.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ getContentDraft.mockResolvedValue(draft({ sourceUrl: 'https://acme.example.com/pricing' }));
+ window.innerWidth = 1440;
+ await renderPage();
+ await pickTab('Sources');
+ await act(async () => button('Rebuild with selection')!.click());
+ const card = () => container.querySelector('[role="region"][aria-label="Agent suggestions"]');
+ expect(card()!.getAttribute('aria-busy')).toBe('true');
+
+ await act(async () => answer({ error: 'stopped' }));
+ expect(toast).toHaveBeenCalledWith('Stopped · nothing was changed');
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(card()).toBeNull();
+ });
+
+ it('stops showing the agent at work when the panel closes mid-rebuild', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ rebuildDraftBrief.mockReturnValue(new Promise(() => {}));
+ getContentDraft.mockResolvedValue(draft({ sourceUrl: 'https://acme.example.com/pricing' }));
+ window.innerWidth = 1440;
+ await renderPage();
+ await pickTab('Sources');
+ await act(async () => button('Rebuild with selection')!.click());
+ const card = () => container.querySelector('[role="region"][aria-label="Agent suggestions"]');
+ expect(card()).not.toBeNull();
+
+ // The rebuild is the panel's: once it's gone, nothing here waits on it.
+ await act(async () => button('Hide side panel')!.click());
+ expect(card()).toBeNull();
+ });
+
it('says under Run Agent which sources the agent writes from, live as Sources changes them', async () => {
getDraftSources.mockResolvedValue({
data: {
@@ -2059,12 +2216,268 @@ describe('the side panel', () => {
const card = () =>
container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;
expect(card().getAttribute('aria-busy')).toBe('true');
+ // No run read yet: no steps, and nothing for Stop to stop.
expect(card().textContent).toBe('Content Agent is working');
+ // Where its change will most likely land, a card that it is drafting.
+ const drafting = () => container.querySelector('.ProseMirror [data-agent-drafting]');
+ expect(drafting()!.textContent).toBe(
+ 'Content Agent is drafting a change here…Drafting from your rules…',
+ );
await act(async () => answer({ count: 1 }));
await act(async () => {});
expect(card().getAttribute('aria-busy')).toBe('false');
expect(card().textContent).toContain('Content Agent has 1 suggestion for you');
+ expect(drafting()).toBeNull();
+ });
+
+ it('shows the run’s steps while it works, and Stop leaves the page as it was', async () => {
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ let answer: (value: { error: 'stopped' }) => void = () => {};
+ fixDraftRules.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ readAgentRun.mockResolvedValue({
+ id: 'r1',
+ kind: 'fix',
+ steps: [
+ { key: 'read_rules', count: 4 },
+ { key: 'gather_sources', count: 0 },
+ { key: 'write_changes', count: null },
+ { key: 'check_sources', count: null },
+ ],
+ step: 2,
+ startedAt: new Date().toISOString(),
+ finishedAt: null,
+ stoppedAt: null,
+ outcome: null,
+ });
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ const card = container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;
+ // Its steps, short names for the work; none about data it has none of.
+ expect([...card.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Reading 4 rules',
+ 'Writing changes',
+ 'Checking sources',
+ ]);
+ expect(card.querySelector('[aria-current="step"]')!.textContent).toBe('Writing changes');
+
+ const stop = [...card.querySelectorAll('button')].find((b) => b.textContent === 'Stop')!;
+ await act(async () => stop.click());
+ expect(stopAgentRun).toHaveBeenCalledWith('d1', 'b1', 'r1');
+ expect(stop.disabled).toBe(true);
+ await act(async () => answer({ error: 'stopped' }));
+ await act(async () => {});
+ expect(toast).toHaveBeenCalledWith('Stopped · nothing was changed');
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(container.querySelector('[role="region"][aria-label="Agent suggestions"]')).toBeNull();
+ });
+
+ const fixRun = {
+ id: 'r1',
+ kind: 'fix' as const,
+ steps: [{ key: 'write_changes' as const, count: null }],
+ step: 0,
+ startedAt: new Date().toISOString(),
+ finishedAt: null,
+ stoppedAt: null,
+ outcome: null,
+ };
+ const agentStop = () =>
+ [
+ ...container
+ .querySelector('[role="region"][aria-label="Agent suggestions"]')!
+ .querySelectorAll('button'),
+ ].find((b) => b.textContent === 'Stop')!;
+
+ it('says stopped when the answer is lost after Stop, and waits for no batch', async () => {
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ let answer: (value: { error: 'unconfirmed' }) => void = () => {};
+ fixDraftRules.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ readAgentRun.mockResolvedValue(fixRun);
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ const reads = getDraftSuggestions.mock.calls.length;
+ await act(async () => agentStop().click());
+ await act(async () => answer({ error: 'unconfirmed' }));
+ await act(async () => {});
+ expect(toast).toHaveBeenCalledWith('Stopped · nothing was changed');
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(getDraftSuggestions.mock.calls.length).toBe(reads);
+ });
+
+ it('lets Stop be pressed again when the run had already ended', async () => {
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ let answer: (value: { count: number }) => void = () => {};
+ fixDraftRules.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ readAgentRun.mockResolvedValue(fixRun);
+ stopAgentRun.mockResolvedValue({ stopped: false });
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ await act(async () => agentStop().click());
+ expect(agentStop().disabled).toBe(false);
+ expect(toast).not.toHaveBeenCalled();
+ expect(toast.error).not.toHaveBeenCalled();
+ await act(async () => answer({ count: 0 }));
+ });
+
+ it('shows no steps of another kind’s run, still open when Fix starts', async () => {
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ let answer: (value: { count: number }) => void = () => {};
+ fixDraftRules.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ // A rewrite the server hasn't closed yet: not this run.
+ readAgentRun.mockResolvedValue({
+ ...fixRun,
+ kind: 'rewrite',
+ steps: [{ key: 'read_rules', count: 14 }],
+ });
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ const card = container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;
+ expect(card.textContent).toBe('Content Agent is working');
+ // The agent's dots on Run Agent too: no spinning ring anywhere.
+ expect(container.querySelector('.animate-spin')).toBeNull();
+ await act(async () => answer({ count: 0 }));
+ });
+
+ it('stops the brief from the card; a later Fix’s lost answer still waits for its batch', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ try {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ let rebuilt: (value: { error: 'stopped' }) => void = () => {};
+ rebuildDraftBrief.mockReturnValue(new Promise((resolve) => (rebuilt = resolve)));
+ readAgentRun.mockResolvedValue({
+ ...fixRun,
+ kind: 'brief',
+ steps: [
+ { key: 'gather_sources', count: 1 },
+ { key: 'write_outline', count: null },
+ { key: 'match_fanouts', count: null },
+ ],
+ step: 1,
+ });
+ await openRules();
+ await pickTab('Sources');
+ await act(async () => button('Rebuild with selection')!.click());
+ await act(async () => {});
+ const card = () =>
+ container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;
+ expect([...card().querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Gathering 1 source',
+ 'Writing the outline',
+ 'Matching fan-outs',
+ ]);
+ // The agent's dots on the button, not a spinning ring.
+ expect(container.querySelector('.animate-spin')).toBeNull();
+
+ await act(async () => agentStop().click());
+ expect(stopAgentRun).toHaveBeenCalledWith('d1', 'b1', 'r1');
+ await act(async () => rebuilt({ error: 'stopped' }));
+ expect(toast).toHaveBeenCalledTimes(1);
+ expect(toast).toHaveBeenCalledWith('Stopped · nothing was changed');
+
+ // Fix next, its answer lost on the way: no Stop was pressed for it.
+ readAgentRun.mockResolvedValue(null);
+ fixDraftRules.mockResolvedValue({ error: 'unconfirmed' });
+ await pickTab('Rules');
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ expect(toast).toHaveBeenCalledTimes(1);
+ getDraftSuggestions.mockResolvedValue([agentSuggestion]);
+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));
+ await act(async () => {});
+ expect(toast.success).toHaveBeenCalledWith(
+ 'Content Agent suggested 1 change · review them in the page',
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps the brief’s buttons from starting it while Fix runs', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [],
+ citedPages: [
+ {
+ url: 'https://a.example/x',
+ title: null,
+ domain: 'a.example',
+ citations: 3,
+ answers: 2,
+ },
+ {
+ url: 'https://b.example/y',
+ title: null,
+ domain: 'b.example',
+ citations: 1,
+ answers: 1,
+ },
+ ],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ let answer: (value: { count: number }) => void = () => {};
+ fixDraftRules.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ // Only cited pages kept: no "0 fan-outs".
+ expect(container.querySelector('.ProseMirror [data-agent-drafting]')!.textContent).toContain(
+ 'Drafting from 2 cited pages…',
+ );
+ await pickTab('Sources');
+ expect(button('Rebuild with selection')!.disabled).toBe(true);
+ expect(panel()!.textContent).toContain(
+ 'Content Agent is already working on this page. Wait for it to finish.',
+ );
+ await act(async () => answer({ count: 0 }));
+ expect(button('Rebuild with selection')!.disabled).toBe(false);
+ });
+
+ it('shows no steps of a run that has ended', async () => {
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ let answer: (value: { count: number }) => void = () => {};
+ fixDraftRules.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ // The draft's last run, before this one is written.
+ readAgentRun.mockResolvedValue({
+ ...fixRun,
+ finishedAt: new Date().toISOString(),
+ outcome: 'done',
+ });
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ const card = container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;
+ expect(card.textContent).toBe('Content Agent is working');
+ expect(card.querySelector('li')).toBeNull();
+ await act(async () => answer({ count: 0 }));
});
it('sends the open rules and leaves the agent’s batch for review', async () => {
@@ -2297,6 +2710,56 @@ describe('the side panel', () => {
expect(card.querySelector('p')!.textContent).toBe('In 2026 teams plan; by 20261, most do.');
});
+ it('says when Stop couldn’t reach the agent, and drafts from the kept data', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],
+ citedPages: [
+ {
+ url: 'https://a.example/x',
+ title: null,
+ domain: 'a.example',
+ citations: 3,
+ answers: 2,
+ },
+ ],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ let answer: (value: { count: number }) => void = () => {};
+ fixDraftRules.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ readAgentRun.mockResolvedValue({
+ id: 'r1',
+ kind: 'fix',
+ steps: [{ key: 'write_changes', count: null }],
+ step: 0,
+ startedAt: new Date().toISOString(),
+ finishedAt: null,
+ stoppedAt: null,
+ outcome: null,
+ });
+ stopAgentRun.mockResolvedValue({ error: 'failed' });
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ expect(container.querySelector('.ProseMirror [data-agent-drafting]')!.textContent).toContain(
+ 'Drafting from 1 cited page and 1 fan-out…',
+ );
+ const card = container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;
+ const stop = [...card.querySelectorAll('button')].find((b) => b.textContent === 'Stop')!;
+ await act(async () => stop.click());
+ expect(toast.error).toHaveBeenCalledWith("Couldn't stop the agent. It may still finish.");
+ // It can be pressed again.
+ expect(stop.disabled).toBe(false);
+ await act(async () => answer({ count: 0 }));
+ });
+
it('says a full batch is the most one run makes, to run it again (C)', async () => {
getContentDraft.mockResolvedValue(traced);
const full = Array.from({ length: 8 }, (_, i) => ({
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.tsx
index 80012a8ad..34948db29 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
@@ -1,6 +1,6 @@
'use client';
-import { useEffect, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { Loader2 } from 'lucide-react';
@@ -79,6 +79,14 @@ export default function ContentEditorPage() {
clearTimeout(timer);
};
}, [draftId, writing, read]);
+ // The agent's run ended, or was stopped: read the draft now, not on the next look.
+ const rereadDraft = useCallback(() => {
+ getContentDraft(draftId).then(
+ (draft) => draft && setRead({ id: draftId, draft }),
+ // The next look tries again.
+ () => {},
+ );
+ }, [draftId]);
return (
<div className="-m-6 flex h-[calc(100vh-4rem)] flex-col md:h-screen">
@@ -88,10 +96,13 @@ export default function ContentEditorPage() {
</div>
) : current.draft && writing ? (
<AgentWriting
+ draftId={current.draft.id}
+ brandId={current.draft.brandId}
title={current.draft.title}
method={current.draft.method}
since={current.draft.agentSince}
rewrite={current.draft.agentRun === 'rewrite'}
+ onRunEnded={rereadDraft}
/>
) : current.draft ? (
<DraftEditor
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 868d369ca..a91da88e3 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -1672,7 +1672,14 @@ export async function saveDraftBrief(id: string, brief: DraftBrief): Promise<Dra
return parsed.data;
}
-const BRIEF_REBUILD_ERRORS = ['ai_budget', 'no_subscription', 'no_sources', 'failed'] as const;
+const BRIEF_REBUILD_ERRORS = [
+ 'ai_budget',
+ 'no_subscription',
+ 'no_sources',
+ /** Stopped from the editor (CE-027): the brief stays as it was. */
+ 'stopped',
+ 'failed',
+] as const;
export type BriefRebuildError = (typeof BRIEF_REBUILD_ERRORS)[number];
/**
@@ -1724,6 +1731,8 @@ const AGENT_FIX_ERRORS = [
'published',
/** Start or a rewrite holds the draft (another tab, another member). */
'writing',
+ /** Stopped from the editor (CE-027): nothing it wrote is kept. */
+ 'stopped',
'failed',
/** No answer from the API (a timeout on the way): the agent may still finish. */
'unconfirmed',
diff --git a/web/src/lib/content/agent-runs-client.test.ts b/web/src/lib/content/agent-runs-client.test.ts
new file mode 100644
index 000000000..97985ed6a
--- /dev/null
+++ b/web/src/lib/content/agent-runs-client.test.ts
@@ -0,0 +1,97 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { readAgentRun, stopAgentRun } from './agent-runs-client';
+
+/**
+ * The Content Agent's run, read and stopped from the browser (CE-027/035):
+ * the draft's latest run through RLS, and Stop through the API's proxy.
+ */
+
+let row: { 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) => {
+ expect(table).toBe('content_agent_runs');
+ const chain = {
+ select: () => chain,
+ eq: (_col: string, value: string) => ((query.draft = value), chain),
+ order: (col: string) => ((query.order = col), chain),
+ limit: (n: number) => ((query.limit = n), chain),
+ maybeSingle: async () => row,
+ };
+ return chain;
+ },
+ }),
+}));
+
+const fetchMock = vi.fn();
+
+beforeEach(() => {
+ row = { data: null, error: null };
+ session = { access_token: 'token-1' };
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+describe('readAgentRun', () => {
+ it('reads the draft’s latest run', async () => {
+ row.data = {
+ id: 'r1',
+ kind: 'fix',
+ steps: [{ key: 'read_rules', count: 4 }],
+ step: 0,
+ started_at: '2026-10-23T10:00:00Z',
+ finished_at: null,
+ stopped_at: null,
+ outcome: null,
+ };
+ expect(await readAgentRun('d1')).toMatchObject({
+ id: 'r1',
+ kind: 'fix',
+ steps: [{ key: 'read_rules', count: 4 }],
+ startedAt: '2026-10-23T10:00:00Z',
+ });
+ expect(query).toEqual({ draft: 'd1', order: 'started_at', limit: 1 });
+ });
+
+ it('is null when it can’t be read', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ row = { data: null, error: new Error('down') };
+ expect(await readAgentRun('d1')).toBeNull();
+ });
+});
+
+describe('stopAgentRun', () => {
+ it('asks the API to stop the draft’s run, signed in', async () => {
+ fetchMock.mockResolvedValue(new Response(JSON.stringify({ stopped: true })));
+ expect(await stopAgentRun('d1', 'b1')).toEqual({ stopped: true });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('/api/aeo/api/content-drafts/d1/stop');
+ expect(init.method).toBe('POST');
+ expect(init.headers.Authorization).toBe('Bearer token-1');
+ expect(JSON.parse(init.body)).toEqual({ brandId: 'b1' });
+ // The run the editor shows, when it names it: another tab's goes on.
+ await stopAgentRun('d1', 'b1', 'r9');
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ brandId: 'b1', runId: 'r9' });
+ });
+
+ it('says when no run was under way', async () => {
+ fetchMock.mockResolvedValue(new Response(JSON.stringify({ stopped: false })));
+ expect(await stopAgentRun('d1', 'b1')).toEqual({ stopped: false });
+ });
+
+ it('fails without a session, on an error answer, or when the request fails', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ session = null;
+ expect(await stopAgentRun('d1', 'b1')).toEqual({ error: 'failed' });
+ expect(fetchMock).not.toHaveBeenCalled();
+
+ session = { access_token: 'token-1' };
+ fetchMock.mockResolvedValueOnce(new Response('{}', { status: 403 }));
+ expect(await stopAgentRun('d1', 'b1')).toEqual({ error: 'failed' });
+ fetchMock.mockRejectedValueOnce(new Error('offline'));
+ expect(await stopAgentRun('d1', 'b1')).toEqual({ error: 'failed' });
+ });
+});
diff --git a/web/src/lib/content/agent-runs-client.ts b/web/src/lib/content/agent-runs-client.ts
new file mode 100644
index 000000000..8886e7e5f
--- /dev/null
+++ b/web/src/lib/content/agent-runs-client.ts
@@ -0,0 +1,62 @@
+import { BROWSER_API_BASE_URL } from '@/config/api';
+import { createClient } from '@/lib/supabase/client';
+import { agentRunFrom, type AgentRun } from './agent-runs';
+
+/**
+ * The Content Agent's run, read and stopped from the browser (v1.1
+ * CE-027/035): never through a server action, which Next runs one at a time —
+ * Fix open rules' and the brief's wait for the whole run, so a read or a Stop
+ * behind them would only go out once it ended.
+ */
+
+/** The draft's latest run (00249, its members may read it), or null. */
+export async function readAgentRun(draftId: string): Promise<AgentRun | null> {
+ const { data, error } = await createClient()
+ .from('content_agent_runs')
+ .select('id, kind, steps, step, started_at, finished_at, stopped_at, outcome')
+ .eq('draft_id', draftId)
+ .order('started_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (error) {
+ console.error('Failed to read the agent run:', error);
+ return null;
+ }
+ return agentRunFrom(data);
+}
+
+/**
+ * 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-origin
+ * proxy; it keeps nothing of what it had. stopped is false when no run was
+ * under way.
+ */
+export async function stopAgentRun(
+ draftId: string,
+ brandId: string,
+ runId: string | null = null,
+): Promise<{ stopped: boolean } | { error: 'failed' }> {
+ const {
+ data: { session },
+ } = await createClient().auth.getSession();
+ if (!session) return { error: 'failed' };
+ try {
+ const res = await fetch(
+ `${BROWSER_API_BASE_URL}/api/content-drafts/${encodeURIComponent(draftId)}/stop`,
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${session.access_token}`,
+ },
+ body: JSON.stringify(runId ? { brandId, runId } : { brandId }),
+ },
+ );
+ if (!res.ok) return { error: 'failed' };
+ const body = (await res.json().catch(() => ({}))) as { stopped?: unknown };
+ return { stopped: body.stopped === true };
+ } catch (err) {
+ console.error('Failed to stop the Content Agent:', err);
+ return { error: 'failed' };
+ }
+}
diff --git a/web/src/lib/content/agent-runs.test.ts b/web/src/lib/content/agent-runs.test.ts
new file mode 100644
index 000000000..57ff034bc
--- /dev/null
+++ b/web/src/lib/content/agent-runs.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest';
+import {
+ RUN_STALE_MS,
+ agentRunFrom,
+ runUnderWay,
+ sameRun,
+ shownSteps,
+ stepMessage,
+} from './agent-runs';
+
+/** The Content Agent's runs as the editor reads them (00249, CE-027/035). */
+describe('agent runs', () => {
+ const row = (over: Record<string, unknown> = {}) => ({
+ id: 'r1',
+ kind: 'fix',
+ steps: [
+ { key: 'read_rules', count: 4 },
+ { key: 'gather_sources', count: 0 },
+ { key: 'made_up', count: 1 },
+ { key: 'write_changes', count: null },
+ ],
+ step: 9,
+ started_at: '2026-10-23T10:00:00Z',
+ finished_at: null,
+ stopped_at: null,
+ outcome: null,
+ ...over,
+ });
+
+ it('reads a run, keeping the steps it can name and its step within them', () => {
+ const run = agentRunFrom(row())!;
+ expect(run.steps.map((s) => s.key)).toEqual(['read_rules', 'gather_sources', 'write_changes']);
+ expect(run.step).toBe(3);
+ expect(agentRunFrom(row({ kind: 'other' }))).toBeNull();
+ expect(agentRunFrom(row({ steps: [] }))).toBeNull();
+ expect(agentRunFrom(null)).toBeNull();
+ });
+
+ it('is under way until it ends, or until a stopped server’s run goes stale', () => {
+ const run = agentRunFrom(row())!;
+ const started = Date.parse('2026-10-23T10:00:00Z');
+ expect(runUnderWay(run, started + 1000)).toBe(true);
+ expect(runUnderWay(run, started + RUN_STALE_MS + 1)).toBe(false);
+ expect(runUnderWay(agentRunFrom(row({ finished_at: '2026-10-23T10:01:00Z' })), started)).toBe(
+ false,
+ );
+ expect(runUnderWay(null)).toBe(false);
+ });
+
+ it('tells a read that changed nothing from one that moved on', () => {
+ const run = agentRunFrom(row())!;
+ expect(sameRun(run, agentRunFrom(row()))).toBe(true);
+ expect(sameRun(run, agentRunFrom(row({ step: 1 })))).toBe(false);
+ expect(sameRun(run, agentRunFrom(row({ stopped_at: '2026-10-23T10:00:30Z' })))).toBe(false);
+ expect(sameRun(run, agentRunFrom(row({ steps: [{ key: 'read_rules', count: 5 }] })))).toBe(
+ false,
+ );
+ expect(sameRun(run, null)).toBe(false);
+ expect(sameRun(null, null)).toBe(true);
+ });
+
+ it('shows no step about data it has none of, and names each with or without its count', () => {
+ const run = agentRunFrom(row())!;
+ expect(shownSteps(run).map(({ step }) => step.key)).toEqual(['read_rules', 'write_changes']);
+ expect(stepMessage({ key: 'read_rules', count: 4 })).toEqual({ key: 'readRules', count: 4 });
+ expect(stepMessage({ key: 'write_changes', count: null })).toEqual({ key: 'writeChangesAny' });
+ });
+});
diff --git a/web/src/lib/content/agent-runs.ts b/web/src/lib/content/agent-runs.ts
new file mode 100644
index 000000000..27b4625c6
--- /dev/null
+++ b/web/src/lib/content/agent-runs.ts
@@ -0,0 +1,110 @@
+/**
+ * The Content Agent's runs, step by step (Content Editor v1.1, CE-027 and
+ * CE-035; content_agent_runs, 00249): the server writes each run's steps as
+ * it reaches them, named by the data they use, and the editor shows them while
+ * it works, with Stop.
+ */
+
+export const RUN_STEP_KEYS = [
+ 'read_rules',
+ 'gather_sources',
+ 'write_changes',
+ 'rewrite_page',
+ 'write_page',
+ 'write_outline',
+ 'match_fanouts',
+ 'check_sources',
+] as const;
+export type RunStepKey = (typeof RUN_STEP_KEYS)[number];
+
+export interface RunStep {
+ key: RunStepKey;
+ /** How many of what it reads ("20 cited pages"), or null. */
+ count: number | null;
+}
+
+export type AgentRunKind = 'fix' | 'rewrite' | 'write' | 'brief';
+
+export interface AgentRun {
+ id: string;
+ kind: AgentRunKind;
+ steps: RunStep[];
+ /** The step under way; steps.length once done. */
+ step: number;
+ startedAt: string;
+ finishedAt: string | null;
+ stoppedAt: string | null;
+ outcome: 'done' | 'stopped' | 'failed' | null;
+}
+
+/**
+ * How long a run may say it is under way: the longest model call (three
+ * minutes, content-writer.js) and a margin. One older was left by a server
+ * that stopped, and is no run under way.
+ */
+export const RUN_STALE_MS = 10 * 60_000;
+
+/** A run as stored, or null when it isn't one the editor can show. */
+export function agentRunFrom(row: Record<string, unknown> | null): AgentRun | null {
+ if (!row || typeof row.id !== 'string' || !Array.isArray(row.steps)) return null;
+ const keys: readonly string[] = RUN_STEP_KEYS;
+ const steps = (row.steps as Partial<RunStep>[]).flatMap((s) =>
+ keys.includes(s?.key as string)
+ ? [
+ {
+ key: s.key as RunStepKey,
+ count: Number.isInteger(s.count) ? (s.count as number) : null,
+ },
+ ]
+ : [],
+ );
+ const kind = row.kind;
+ if (!steps.length || !['fix', 'rewrite', 'write', 'brief'].includes(kind as string)) return null;
+ const outcome = row.outcome;
+ return {
+ id: row.id,
+ kind: kind as AgentRun['kind'],
+ steps,
+ step: Number.isInteger(row.step) ? Math.min(row.step as number, steps.length) : 0,
+ startedAt: String(row.started_at ?? ''),
+ finishedAt: typeof row.finished_at === 'string' ? row.finished_at : null,
+ stoppedAt: typeof row.stopped_at === 'string' ? row.stopped_at : null,
+ outcome: outcome === 'done' || outcome === 'stopped' || outcome === 'failed' ? outcome : null,
+ };
+}
+
+/** Whether a run is still under way: not finished, and not one a stopped server left. */
+export function runUnderWay(run: AgentRun | null, now = Date.now()): boolean {
+ if (!run || run.finishedAt) return false;
+ const started = Date.parse(run.startedAt);
+ return Number.isFinite(started) && now - started < RUN_STALE_MS;
+}
+
+/** Whether two reads of a run show the same: a read that changed nothing redraws nothing. */
+export function sameRun(a: AgentRun | null, b: AgentRun | null): boolean {
+ if (a === b) return true;
+ if (!a || !b) return false;
+ return (
+ a.id === b.id &&
+ a.step === b.step &&
+ a.finishedAt === b.finishedAt &&
+ a.stoppedAt === b.stoppedAt &&
+ JSON.stringify(a.steps) === JSON.stringify(b.steps)
+ );
+}
+
+/**
+ * The steps a run shows: a step about data it has none of ("Checking 0
+ * Search Console queries") says nothing, and is left out.
+ */
+export function shownSteps(run: AgentRun): { step: RunStep; index: number }[] {
+ return run.steps
+ .map((step, index) => ({ step, index }))
+ .filter(({ step }) => step.count !== 0 || step.key === 'write_changes');
+}
+
+/** A step's message key: with its count, or the one without. */
+export function stepMessage(step: RunStep): { key: string; count?: number } {
+ const name = step.key.replace(/_(\w)/g, (_, c: string) => c.toUpperCase());
+ return step.count === null ? { key: `${name}Any` } : { key: name, count: step.count };
+}
diff --git a/web/src/lib/content/brief.ts b/web/src/lib/content/brief.ts
index 4859d6948..f970d0806 100644
--- a/web/src/lib/content/brief.ts
+++ b/web/src/lib/content/brief.ts
@@ -98,6 +98,15 @@ export interface RebuildSources {
length: number;
}
+/** The most of each the agent takes (content-brief.js rebuildSources). */
+export const REBUILD_LIMITS = {
+ prompts: 100,
+ fanouts: 40,
+ pages: 30,
+ queries: 20,
+ headings: 30,
+} as const;
+
/**
* The sources a rebuild uses: the ones checked in the Sources tab, as it
* lists them; the page's H2s and H3s as written now; and the length the
@@ -115,20 +124,20 @@ export function rebuildSources(
return {
promptIds: kept('prompt')
.map((r) => r.ref)
- .slice(0, 100),
+ .slice(0, REBUILD_LIMITS.prompts),
fanouts: kept('fanout')
.flatMap((r) => (r.kind === 'fanout' ? [{ query: r.name, platforms: r.platforms }] : []))
- .slice(0, 40),
+ .slice(0, REBUILD_LIMITS.fanouts),
pages: kept('cited_page')
.flatMap((r) => (r.kind === 'cited_page' ? [{ url: r.name, kind: r.category }] : []))
- .slice(0, 30),
+ .slice(0, REBUILD_LIMITS.pages),
queries: kept('gsc_query')
.map((r) => r.name)
- .slice(0, 20),
+ .slice(0, REBUILD_LIMITS.queries),
headings: readDraftDoc(draft.html)
.headings.filter((h) => h.level > 1 && h.text)
.map((h) => h.text)
- .slice(0, 30),
+ .slice(0, REBUILD_LIMITS.headings),
length: draft.length,
};
}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 9a3b50c80..69946caee 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1083,6 +1083,53 @@ export type Database = {
},
]
}
+ content_agent_runs: {
+ Row: {
+ claimed_at: string | null
+ draft_id: string
+ finished_at: string | null
+ id: string
+ kind: string
+ outcome: string | null
+ started_at: string
+ step: number
+ steps: Json
+ stopped_at: string | null
+ }
+ Insert: {
+ claimed_at?: string | null
+ draft_id: string
+ finished_at?: string | null
+ id?: string
+ kind: string
+ outcome?: string | null
+ started_at?: string
+ step?: number
+ steps: Json
+ stopped_at?: string | null
+ }
+ Update: {
+ claimed_at?: string | null
+ draft_id?: string
+ finished_at?: string | null
+ id?: string
+ kind?: string
+ outcome?: string | null
+ started_at?: string
+ step?: number
+ steps?: Json
+ stopped_at?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "content_agent_runs_draft_id_fkey"
+ columns: ["draft_id"]
+ isOneToOne: false
+ referencedRelation: "content_drafts"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
content_draft_sources: {
Row: {
added: boolean