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
fix(content): move Next on to the fourth step once the agent has taken the third, with rules still open or the Length off (#1550)
Cihanbb743ee74f8e
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 29f98debe..866adeb60 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@@ -159,9 +159,11 @@ import {nextStep,rulesForNext,stepState,+ thirdStepTried,type NextAction,type NextStepId,type NextStepState,+ type ThirdTry,} from '@/lib/content/next-step';import {aiTracesFound,@@ -233,11 +235,13 @@ import { HeaderTip } from './_header-tip';import {NextStepButton,readSkips,+ readThirdTry,stepActor,stepName,stepReason,wordsUnderTitle,writeSkips,+ writeThirdTry,} from './_next-step';import { qualitySuggestions, useTodoCopy, type HandOff, type QualityRead } from './_quality-tab';import { PageTypeMenu } from './_page-type-menu';@@ -433,6 +437,29 @@ export function DraftEditor({// The agent's last run failed (Fix or hand-off): the card says so over an earlier batch.const [lastRunFailed, setLastRunFailed] = useState(false);const suggestionsNow = useRef(suggestions);+ // The agent's run on the Next step basket's third step (Fix open rules,+ // Rewrite page), and that step as it is now: once the run's changes are+ // decided, Next moves on to the fourth (thirdStepTried).+ const [thirdTry, setThirdTry] = useState<ThirdTry | null>(() => readThirdTry(draft.id));+ const thirdTryNow = useRef(thirdTry);+ const nextStepNow = useRef<NextStepId | null>(null);+ const saveThirdTry = (attempt: ThirdTry | null) => {+ thirdTryNow.current = attempt;+ setThirdTry(attempt);+ writeThirdTry(draft.id, attempt);+ };+ /**+ * Notes a run the third step takes, from the batch on the page now; the+ * attempt before it, to put back when the run doesn't happen or is stopped.+ * Null when the third step isn't Next's.+ */+ const beginThirdTry = (): { prev: ThirdTry | null } | null => {+ if (nextStepNow.current !== 'length' && nextStepNow.current !== 'fixRules') return null;+ const prev = thirdTryNow.current;+ if (prev?.passed) return null;+ saveThirdTry({ batch: suggestionsNow.current[0]?.batchId ?? null });+ return { prev };+ };const [deciding, setDeciding] = useState(false);const [barClosed, setBarClosed] = useState(false);const [fixing, setFixing] = useState(false);@@ -2339,7 +2366,12 @@ export function DraftEditor({}),...agentContext(editor),};- await runAgentFix(() => fixDraftRules(draft.id, draft.brandId, request));+ await runAgentFix(+ () => fixDraftRules(draft.id, draft.brandId, request),+ undefined,+ false,+ beginThirdTry(),+ );};/**@@ -2376,8 +2408,18 @@ export function DraftEditor({// The editor's own run (the automatic hand-off): what the person didn't// start isn't said when it doesn't run or finds nothing, only logged.quiet = false,+ // Fix open rules as Next's third step (beginThirdTry): found nothing, it+ // is taken; failed, stopped or never run, the attempt before it is back.+ third: { prev: ThirdTry | null } | null = null,) => {+ const untried = () => {+ if (third) saveThirdTry(third.prev);+ };+ const nothing = () => {+ if (third) saveThirdTry({ ...(thirdTryNow.current ?? { batch: null }), ended: true });+ };const failed = (key: string, error: string) => {+ untried();if (quiet) {console.warn('The automatic hand-off did not run:', error);return;@@ -2404,6 +2446,7 @@ export function DraftEditor({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.+ untried();toast(t('agentCard.stopped'));return;}@@ -2411,10 +2454,12 @@ export function DraftEditor({// No answer is not a failure: how its run ended says (its batch, or its row).const outcome = await agentOutcome(draft.id, before, asked + FIX_WAIT_MS);if (outcome && 'stopped' in outcome) {+ untried();toast(t('agentCard.stopped'));return;}if (outcome && 'nothing' in outcome) {+ nothing();if (!quiet) {toast(t(@@ -2440,6 +2485,7 @@ export function DraftEditor({}if ('error' in result && result.error === 'stopped') {// Stopped from the card: no failure, and nothing changed.+ untried();toast(t('agentCard.stopped'));return;}@@ -2453,6 +2499,7 @@ export function DraftEditor({return;}if (result.count === 0) {+ nothing();// Why, so the person knows what to do: every change it had was in a quoted passage.if (!quiet) {toast(@@ -2945,6 +2992,8 @@ export function DraftEditor({toast.error(t(`agentFailed.errors.${result.error}`));return;}+ // Under way: the page it leaves takes Next's third step, if it is that.+ beginThirdTry();onAgentStarted?.('rewrite');} catch (err) {console.error('Failed to start the page rewrite:', err);@@ -3105,6 +3154,20 @@ export function DraftEditor({[qualityOn, pageHtml],);const trustNow = quality?.trust?.score ?? null;+ // Taken, it stays passed: a later run (a hand-off, Run Agent on step 4)+ // doesn't bring the step back while it works or its changes wait.+ const thirdTried = thirdStepTried(thirdTry, {+ batch: suggestions[0]?.batchId ?? null,+ open: openSuggestions,+ busy: agentWorking || rewriting,+ });+ useEffect(() => {+ if (!thirdTried || !thirdTry || thirdTry.passed) return;+ const passed = { ...thirdTry, passed: true };+ thirdTryNow.current = passed;+ writeThirdTry(draft.id, passed);+ setThirdTry(passed);+ }, [thirdTried, thirdTry, draft.id]);const nextState: NextStepState = {method: draft.method,open: canMarkReady,@@ -3118,8 +3181,12 @@ export function DraftEditor({? { trust: trustNow, trustLow: trustNow !== null && trustNow < TRUST_GATE, todos }: null,skipped,+ thirdTried,};const next = nextStep(nextState);+ useEffect(() => {+ nextStepNow.current = next.step.id;+ });const firstTodo = todos.find((todo) => !todo.done);const todoLine = firstTodo && quality ? todoCopy(firstTodo, quality).next : null;const skipStep = (id: NextStepId) => {@@ -3364,7 +3431,12 @@ export function DraftEditor({);// Its card goes as if closed, with its Undo all and last run: they were// for the page before (editor test 2026-10-25). A new batch opens it.- if (!samePage) setBarClosed(true);+ // And Next's third step is the restored page's again: its open+ // suggestions set aside are no decision of the agent's.+ if (!samePage) {+ setBarClosed(true);+ saveThirdTry(null);+ }} catch (err) {console.error('Failed to restore the version:', err);toast.error(t('history.restoreFailed'));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.tsxindex 4a13cb9a7..14b67260b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.tsx@@ -14,6 +14,7 @@ import {type NextStepId,type NextStepState,type PathState,+ type ThirdTry,} from '@/lib/content/next-step';import { cn } from '@/lib/utils';import { RunSteps } from './_agent-card';@@ -51,6 +52,28 @@ export function writeSkips(draftId: string, skips: Partial<Record<NextStepId, st}}+/** The agent's run on the third step on this draft, in this browser (thirdStepTried). */+const thirdTryKey = (draftId: string) => `aeo:next-step-third-try:${draftId}`;++export function readThirdTry(draftId: string): ThirdTry | null {+ try {+ const read = JSON.parse(localStorage.getItem(thirdTryKey(draftId)) ?? 'null') as unknown;+ if (read && typeof read === 'object' && 'batch' in read) return read as ThirdTry;+ } catch {+ // Storage unavailable (private mode) or unreadable: none taken.+ }+ return null;+}++export function writeThirdTry(draftId: string, attempt: ThirdTry | null) {+ try {+ if (attempt) localStorage.setItem(thirdTryKey(draftId), JSON.stringify(attempt));+ else localStorage.removeItem(thirdTryKey(draftId));+ } catch {+ // Kept for this visit only.+ }+}+/*** Words besides the page's title: a page with none is empty (Write the first* draft). The title is read from the block draftTitleFromDoc picks: thediff --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 3f6275d52..f7127f8c4 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@@ -6439,6 +6439,141 @@ describe('the side panel', () => {expect(basket()!.textContent).toContain('Content Agent is working');});+ describe('once the agent took Fix open rules (editor test 2026-10-26)', () => {+ beforeEach(() => {+ getDraftSources.mockResolvedValue({+ data: {+ prompts: [],+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],+ citedPages: [],+ gscQueries: [],+ brandDomains: [],+ competitorDomains: [],+ },+ choices: [],+ });+ getDraftBrief.mockResolvedValue({+ brief: {+ goal: 'Win forecasting searches',+ audience: 'Sales leaders',+ outline: [],+ keywords: [],+ origin: 'rebuild',+ builtAt: '2026-10-21T10:00:00Z',+ builtFrom: { prompts: 0, fanouts: 1, pages: 0, queries: 0 },+ },+ });+ getContentDraft.mockResolvedValue(+ draft({+ method: 'create',+ pageType: 'blog_post',+ rules: {+ set: null,+ source: 'default',+ overrides: { length: { on: false } },+ textRules: [],+ },+ }),+ );+ });+ // Where Next goes from Fix open rules on this page: step 4.+ const MOVED_ON = 'Next · Add proof and author';+ const runFix = async () => {+ await renderPage();+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Fix open rules');+ await act(async () => nextButton()!.click());+ await act(async () => inBasket('Fix open rules')!.click());+ await act(async () => {});+ };++ it('moves on once its changes are decided, with the rule still open', async () => {+ getDraftSuggestions.mockResolvedValueOnce([]).mockResolvedValue([+ {+ id: 'n9',+ batchId: 'b9',+ actionId: null,+ actionNo: null,+ kind: 'replace' as const,+ blockText: 'Teams trust it.',+ beforeText: 'trust',+ afterText: 'rely on',+ reason: 'answer the AI search (rule)',+ ruleKeys: ['fanoutH2'],+ status: 'open' as const,+ },+ ]);+ fixDraftRules.mockResolvedValue({ count: 1 });+ await runFix();+ // Its change waits for a decision: the step stays.+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Fix open rules');+ const card = container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;+ await act(async () =>+ [...card.querySelectorAll('button')].find((b) => b.textContent === 'Reject all')!.click(),+ );+ await act(async () => {});+ // Rejected, the fan-out rule is still open, and Next moves on.+ expect(nextButton()!.getAttribute('aria-label')).toBe(MOVED_ON);+ expect(JSON.parse(localStorage.getItem('aeo:next-step-third-try:d1')!)).toEqual({+ batch: null,+ passed: true,+ });+ });++ it('moves on when it found nothing to change', async () => {+ getDraftSuggestions.mockResolvedValue([]);+ fixDraftRules.mockResolvedValue({ count: 0 });+ await runFix();+ expect(nextButton()!.getAttribute('aria-label')).toBe(MOVED_ON);+ // Opened again, it holds.+ await act(async () => root.unmount());+ root = createRoot(container);+ await renderPage();+ expect(nextButton()!.getAttribute('aria-label')).toBe(MOVED_ON);+ });++ it('stays when the run failed, or never ran', async () => {+ getDraftSuggestions.mockResolvedValue([]);+ fixDraftRules.mockResolvedValue({ error: 'failed' });+ await runFix();+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Fix open rules');+ expect(localStorage.getItem('aeo:next-step-third-try:d1')).toBeNull();+ });++ it('stays when the changes it shows are another tab’s, decided here', async () => {+ getDraftSuggestions.mockResolvedValueOnce([]).mockResolvedValue([+ {+ id: 'n8',+ batchId: 'b8',+ actionId: null,+ actionNo: null,+ kind: 'replace' as const,+ blockText: 'Teams trust it.',+ beforeText: 'trust',+ afterText: 'rely on',+ reason: 'answer the AI search (rule)',+ ruleKeys: ['fanoutH2'],+ status: 'open' as const,+ },+ ]);+ // Another tab's run left changes to decide first: this one never ran.+ fixDraftRules.mockResolvedValue({ error: 'open_suggestions' });+ await runFix();+ const card = container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;+ await act(async () =>+ [...card.querySelectorAll('button')].find((b) => b.textContent === 'Reject all')!.click(),+ );+ await act(async () => {});+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Fix open rules');+ });++ it('stays when the run is stopped', async () => {+ getDraftSuggestions.mockResolvedValue([]);+ fixDraftRules.mockResolvedValue({ error: 'stopped' });+ await runFix();+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Fix open rules');+ });+ });+it('stays out of the header while Quality is off', async () => {delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;getContentDraft.mockResolvedValue(diff --git a/web/src/lib/content/next-step.test.ts b/web/src/lib/content/next-step.test.tsindex 899551051..b8d9996dd 100644--- a/web/src/lib/content/next-step.test.ts+++ b/web/src/lib/content/next-step.test.ts@@ -1,5 +1,12 @@import { describe, expect, it } from 'vitest';-import { liveSkips, nextStep, rulesForNext, stepState, type NextStepState } from './next-step';+import {+ liveSkips,+ nextStep,+ rulesForNext,+ stepState,+ thirdStepTried,+ type NextStepState,+} from './next-step';import type { QualityTodo } from './quality-todos';/**@@ -235,6 +242,65 @@ describe('nextStep', () => {});});+describe('the third step, once the agent took it (editor test 2026-10-26)', () => {+ it('moves on to proof with a rule still open and the Length off', () => {+ // As on the tested page: Trust 47, under its gate.+ const quality = { trust: 47, trustLow: true, todos: [] };+ const fix = state({ method: 'optimize', openRules: ['h2Answer'], quality });+ expect(nextStep(fix).step.id).toBe('fixRules');+ expect(nextStep({ ...fix, thirdTried: true }).step.id).toBe('proof');+ expect(ids({ ...fix, thirdTried: true })).toEqual([+ 'plan:done',+ 'import:done',+ 'fixRules:done',+ 'proof:now',+ 'check:ahead',+ ]);+ // A page far off its Length passes its rewrite step the same way.+ const long = state({+ method: 'optimize',+ rewrite: { reason: 'length', count: 17_683, target: 13_998, percent: 26 },+ openRules: ['h2Answer'],+ quality,+ });+ expect(nextStep(long).step.id).toBe('length');+ expect(nextStep({ ...long, thirdTried: true }).step.id).toBe('proof');+ // With Quality off, to Mark ready.+ expect(nextStep({ ...long, quality: null, thirdTried: true }).step.id).toBe('check');+ });++ it('keeps the steps before it: an empty page is still written first', () => {+ const s = state({ empty: true, openRules: rules(3), thirdTried: true });+ expect(nextStep(s).step.id).toBe('write');+ });++ it("reads the agent's run as taken once what it left is decided, or it ended with nothing", () => {+ const attempt = { batch: 'b1' };+ // The run is under way, or its batch waits for a decision: not yet.+ expect(thirdStepTried(attempt, { batch: 'b1', open: 0, busy: true })).toBe(false);+ expect(thirdStepTried(attempt, { batch: 'b2', open: 3, busy: false })).toBe(false);+ // Its batch, every change decided (accepted or rejected).+ expect(thirdStepTried(attempt, { batch: 'b2', open: 0, busy: false })).toBe(true);+ // The batch from before it is no answer of its: stopped, the step stays.+ expect(thirdStepTried(attempt, { batch: 'b1', open: 0, busy: false })).toBe(false);+ // It found nothing to change: there's nothing to decide.+ expect(thirdStepTried({ ...attempt, ended: true }, { batch: 'b1', open: 0, busy: false })).toBe(+ true,+ );+ // A first batch, on a page that had none.+ expect(thirdStepTried({ batch: null }, { batch: 'b1', open: 0, busy: false })).toBe(true);+ expect(thirdStepTried(null, { batch: 'b1', open: 0, busy: false })).toBe(false);+ // Found nothing, but another run is under way: not yet.+ expect(thirdStepTried({ ...attempt, ended: true }, { batch: 'b1', open: 0, busy: true })).toBe(+ false,+ );+ // Once taken, a later run working or its changes waiting don't bring it back.+ expect(thirdStepTried({ ...attempt, passed: true }, { batch: 'b3', open: 2, busy: true })).toBe(+ true,+ );+ });+});+describe('rulesForNext', () => {it('counts the open rules a Fix run can close: not a setting only the person fills, not Length', () => {const rule = (key: string) => ({ key, on: true, current: '' }) as never;diff --git a/web/src/lib/content/next-step.ts b/web/src/lib/content/next-step.tsindex b787e8fba..a93aef429 100644--- a/web/src/lib/content/next-step.ts+++ b/web/src/lib/content/next-step.ts@@ -93,6 +93,12 @@ export interface NextStepState {quality: { trust: number | null; trustLow: boolean; todos: QualityTodo[] } | null;/** The steps skipped, each with the state it was skipped at (stepState). */skipped: Partial<Record<NextStepId, string>>;+ /**+ * The agent took the third step (thirdStepTried): it is passed, with rules+ * still open or the Length still off, and what's left is the person's in+ * the Rules tab.+ */+ thirdTried?: boolean;}export interface NextStep {@@ -150,6 +156,36 @@ export function stepState(id: NextStepId, s: NextStepState): string {}}+/** The third step, as the page needs it: its Length, or its open rules. */+const THIRD_STEPS: readonly NextStepId[] = ['length', 'fixRules'];++/**+ * A run of the agent on the third step (Fix open rules, or Rewrite page+ * while it was the step): the latest batch on the page when it began;+ * whether it found nothing to change; and, once taken, `passed`, which holds+ * whatever runs after. A run that fails, is stopped or never runs isn't one.+ */+export interface ThirdTry {+ batch: string | null;+ ended?: boolean;+ passed?: boolean;+}++/**+ * Whether the agent has taken the third step (editor test 2026-10-26): its+ * run found nothing to change, or left a batch since and every change in it+ * is decided. Next then moves on to the fourth, whatever the rules read+ * after; the page doesn't wait on rules no run of the agent closes.+ */+export function thirdStepTried(+ attempt: ThirdTry | null,+ now: { batch: string | null; open: number; busy: boolean },+): boolean {+ if (attempt?.passed) return true;+ if (!attempt || now.busy || now.open > 0) return false;+ return attempt.ended === true || (now.batch !== null && now.batch !== attempt.batch);+}+/** The skips that still hold: one whose step's state has changed since is dropped. */export function liveSkips(s: NextStepState): Partial<Record<NextStepId, string>> {return Object.fromEntries(@@ -248,7 +284,10 @@ export function nextStep(s: NextStepState): NextPath {alternative: s.published ? null : 'markPublished',skippable: false,};- const step = due.find((d) => !d.skippable || s.skipped[d.id] !== stepState(d.id, s)) ?? check;+ const tried = (id: NextStepId) => s.thirdTried === true && THIRD_STEPS.includes(id);+ const step =+ due.find((d) => !tried(d.id) && (!d.skippable || s.skipped[d.id] !== stepState(d.id, s))) ??+ check;// The third step is the one the page needs: its Length, or its open rules// (an empty page, its title alone, isn't read against its Length).@@ -273,8 +312,9 @@ export function nextStep(s: NextStepState): NextPath {? 'now': i > now? 'ahead'- : // Passed while its state still calls for it: it was skipped.- calledFor.has(id)+ : // Passed while its state still calls for it: it was skipped,+ // unless the agent took it.+ calledFor.has(id) && !tried(id)? 'skipped': 'done') as PathState,}));