Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): recommend the next step from the header and the agent card (Next step basket) (#1428)
Cihan02fa6db9dac3
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 448bde66d..59debaa3d 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3669,6 +3669,8 @@"reviewedLine": "{accepted, number} accepted · Rules {met, number} of {total, number}{open, plural, =0 {} other { · # still open}}","more": "+{count, number} more","run": "Run Agent",+ "next": "Next: {action}",+ "allSteps": "All steps","working": "Content Agent is working","builtFrom": "built from {count, number} of your sources","seeSources": "See sources",@@ -4151,6 +4153,74 @@},"qualityChip": "Quality {score}","qualityChipHint": "An Ansvisor estimate of this page's quality. Open Quality.",+ "nextStep": {+ "label": "Next step",+ "short": "Next",+ "button": "Next · {step}",+ "buttonStep": "· {step}",+ "stepOf": "Step {n} of {total}",+ "allDone": "Every step is done",+ "path": "All steps",+ "skip": "Skip",+ "skipped": "· skipped",+ "working": "Content Agent is working",+ "stop": "Stop",+ "marking": "Marking it ready…",+ "tipsTitle": "If you see…",+ "tipLine": "{state} →",+ "states": {+ "done": "done",+ "now": "now",+ "skipped": "skipped",+ "ahead": "to do"+ },+ "steps": {+ "plan": "Plan the page",+ "write": "Write the first draft",+ "import": "Bring in your page",+ "lengthLong": "Shorten to your Length",+ "lengthShort": "Bring it up to your Length",+ "fixRules": "Fix open rules",+ "proof": "Add proof and author",+ "check": "Check and mark ready",+ "ready": "Ready to publish"+ },+ "reasons": {+ "plan": "No brief yet. I build one from your prompts, fan-outs and cited pages.",+ "write": "The page is empty. I write a first draft from your brief and sources; you review it before you mark it ready.",+ "writeMine": "The page is empty: write it, and the next step follows from what you write.",+ "import": "The live page didn't come in. I write a first draft from your sources, or you write it yourself.",+ "length": "{count, number} characters against a Length of {target, number}. Small fixes won't get there, so rewrite it in one go.",+ "fixRules": "{count, plural, one {# rule is} other {# rules are}} still open. Small, reviewable changes for them.",+ "proofTrust": "Trust is {trust}, under {gate}. The Quality tab names what raises it.",+ "proofTrustTodo": "Trust is {trust}, under {gate}. Only you can do this first: {todo}.",+ "proofTodo": "Only you can do this: {todo}.",+ "check": "Links, schema, placeholders and Trust {gate}+, before you mark it ready.",+ "checkRules": "The rules are met. Mark it ready when you are.",+ "ready": "Every step is done. Export it for your CMS.",+ "published": "It's published. Export it again when the page changes."+ },+ "actions": {+ "buildBrief": "Build brief",+ "writeWithAgent": "Write with Agent",+ "writeMyself": "I'll write it",+ "rewritePage": "Rewrite page",+ "fixRules": "Fix open rules",+ "pickAuthor": "Pick author",+ "addAuthor": "Add author",+ "showTodos": "Show to-dos",+ "beforePublish": "Before you publish",+ "markReady": "Mark ready",+ "export": "Export"+ },+ "tips": {+ "longPage": "Page far longer than Length",+ "shortPage": "Page far shorter than Length",+ "someRules": "1 to {max} rules open",+ "noBrief": "Brief is empty",+ "lowTrust": "Trust under {gate}"+ }+ },"exportDialog": {"title": "Export","untitled": "Untitled",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.tsxindex 6685e4cfd..04585b7e2 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@@ -62,7 +62,11 @@ afterEach(() => {container.remove();});-async function render(suggestions: DraftSuggestion[], working = false) {+async function render(+ suggestions: DraftSuggestion[],+ working = false,+ extra: Partial<Parameters<typeof AgentCard>[0]> = {},+) {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages}>@@ -72,6 +76,7 @@ async function render(suggestions: DraftSuggestion[], working = false) {busy={false}working={working}{...handlers}+ {...extra}/></NextIntlClientProvider>,);@@ -132,6 +137,41 @@ describe('AgentCard', () => {expect(handlers.onRun).toHaveBeenCalled();});+ it("offers the Next step basket's step in Run Agent's place, with All steps", async () => {+ const onNext = vi.fn();+ const onAllSteps = vi.fn();+ const reviewed = [+ suggestion({ status: 'accepted' }),+ suggestion({ id: 's2', status: 'rejected' }),+ ];+ await render(reviewed, false, {+ next: { label: 'Rewrite page', onRun: onNext, blocked: null },+ onAllSteps,+ });+ expect(buttons().slice(0, 3)).toEqual(['Undo all', 'All steps', 'Next: Rewrite page']);+ await click('Next: Rewrite page');+ expect(onNext).toHaveBeenCalled();+ expect(handlers.onRun).not.toHaveBeenCalled();+ await click('All steps');+ expect(onAllSteps).toHaveBeenCalled();+ // With every rule met it still says what's next, and why it waits when it can't run.+ await render(reviewed, false, {+ rules: { ...rules, met: 14 },+ next: { label: 'Before you publish', onRun: onNext, blocked: 'Saving first.' },+ onAllSteps,+ });+ const nextButton = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Next: Before you publish',+ )!;+ expect(nextButton.disabled).toBe(true);+ expect(container.textContent).toContain('Saving first.');+ // Suggestions still to decide come first.+ await render([suggestion()], false, {+ next: { label: 'Rewrite page', onRun: onNext, blocked: null },+ });+ expect(buttons()).not.toContain('Next: Rewrite page');+ });+it('says it is working, with nothing to press', async () => {await render([], true);const card = container.querySelector('[role="region"]')!;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.tsxindex c50e71da6..463d759b9 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@@ -198,6 +198,8 @@ export function AgentCard({run = null,onStop,stopping = false,+ next = null,+ onAllSteps,}: {suggestions: DraftSuggestion[];rules: CardRules;@@ -227,6 +229,13 @@ export function AgentCard({onStop?: () => void;/** Stop was pressed: it waits for the run to end. */stopping?: boolean;+ /**+ * The Next step basket's step (Next step spec §3), offered in Run Agent's+ * place once nothing is left to decide: its button, and why it can't run.+ */+ next?: { label: string; onRun: () => void; blocked: string | null } | null;+ /** Opens the basket with every step. */+ onAllSteps?: () => void;}) {const t = useTranslations('contentEditor.editor.agentCard');const locale = useLocale();@@ -243,7 +252,37 @@ export function AgentCard({// written in the card, never only on hover (as the Rules card does, CE-028).const runShown = !working && stillOpen > 0 && (page ? page.status !== 'open' : open === 0);const reasonId = useId();- const reason = runShown ? runBlocked : null;+ const nextShown = !!next && !working && (page ? page.status !== 'open' : open === 0);+ const reason = next ? (nextShown ? next.blocked : null) : runShown ? runBlocked : null;+ // What follows the review: the basket's next step, or Run Agent for the rules still open.+ const afterReview = next ? (+ <>+ {onAllSteps && (+ <Button variant="ghost" size="sm" className={GHOST} onClick={onAllSteps}>+ {t('allSteps')}+ </Button>+ )}+ <Button+ size="sm"+ disabled={busy || next.blocked !== null}+ aria-describedby={reason ? reasonId : undefined}+ onClick={next.onRun}+ >+ {t('next', { action: next.label })}+ </Button>+ </>+ ) : (+ stillOpen > 0 && (+ <Button+ size="sm"+ disabled={busy || runBlocked !== null}+ aria-describedby={reason ? reasonId : undefined}+ onClick={onRun}+ >+ {t('run')}+ </Button>+ )+ );const tone = working ? 'working' : open > 0 ? 'waiting' : 'done';// "built from 3 of your sources · See sources" (v1.1 §3b).const builtFrom = sourceCount > 0 && (@@ -417,16 +456,7 @@ export function AgentCard({>{tRewrite('undo')}</Button>- {stillOpen > 0 && (- <Button- size="sm"- disabled={busy || runBlocked !== null}- aria-describedby={reason ? reasonId : undefined}- onClick={onRun}- >- {t('run')}- </Button>- )}+ {afterReview}</>)}</>@@ -453,16 +483,7 @@ export function AgentCard({>{tSuggestions('undoAll')}</Button>- {stillOpen > 0 && (- <Button- size="sm"- disabled={busy || runBlocked !== null}- aria-describedby={reason ? reasonId : undefined}- onClick={onRun}- >- {t('run')}- </Button>- )}+ {afterReview}</>)}{open === 0 && (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 168d4f9b3..e8848787f 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@@ -10,7 +10,7 @@ import { TableKit } from '@tiptap/extension-table';import Image from '@tiptap/extension-image';import { CharacterCount, Placeholder } from '@tiptap/extensions';import { ArrowLeft, Bot, Check, Copy, Download, PanelRight, Target, X } from 'lucide-react';-import { Link } from '@/i18n/navigation';+import { Link, useRouter } from '@/i18n/navigation';import { Button } from '@/components/ui/button';import { buttonVariants } from '@/components/ui/button-variants';import {@@ -89,14 +89,29 @@ import { BAND_CLASSES, qualityAverage, qualityBand, qualityPhase } from '@/lib/cimport { eeat, linksToCheck, trust, trustBlocks } from '@/lib/content/quality-checks';import { qualityTodos } from '@/lib/content/quality-todos';import { readability } from '@/lib/content/readability';-import { aiTracesFound, fanoutsToUse, lengthWarns, openRulesForAgent } from '@/lib/content/rules';+import {+ liveSkips,+ nextStep,+ rulesForNext,+ stepState,+ type NextAction,+ type NextStepId,+ type NextStepState,+} from '@/lib/content/next-step';+import {+ aiTracesFound,+ fanoutsToUse,+ lengthWarns,+ openRulesForAgent,+ rewriteAdvice,+} from '@/lib/content/rules';import { saveBlob } from '@/lib/download';import { cn } from '@/lib/utils';import { useBrandStore } from '@/stores/use-brand-store';import { AgentCard } from './_agent-card';import { AgentDrafting, draftingKey } from './_agent-drafting';-import { AuthorMenu } from './_author-menu';-import { BeforePublish, type ReadyAnyway, type ReadyToPaste } from './_before-publish';+import { AuthorMenu, MANAGE_AUTHORS_PATH } from './_author-menu';+import { BeforePublish, TRUST_GATE, type ReadyAnyway, type ReadyToPaste } from './_before-publish';import { FlashBlock, findBlock, flashKey } from './_flash-block';import { useAgentRun } from './_use-agent-run';import { useLinkChecks } from './_use-link-checks';@@ -118,7 +133,8 @@ import { HtmlBlock, copyToClipboard } from './_html-block';import { OwnCopies, ownCopyHtml } from './_own-copies';import { NextNudge, useNextNudge } from './_next-nudge';import { PageInfoStrip, pageInfoKey } from './_page-info';-import type { QualityRead } from './_quality-tab';+import { NextStepButton, readSkips, wordsUnderTitle, writeSkips } from './_next-step';+import { useTodoCopy, type QualityRead } from './_quality-tab';import { PageTypeMenu } from './_page-type-menu';import type { AgentRewrite } from './_brief-tab';import { ruleStatusDetail, type AgentFix, type PageRewrite } from './_rules-tab';@@ -303,6 +319,8 @@ export function DraftEditor({n: number;/** A source to show in Sources: a "Based on" chip or mark clicked (CE-033). */source?: Pick<SuggestionSource, 'kind' | 'ref'>;+ /** The brief to build, from the Next step basket's Build brief. */+ build?: boolean;} | null>(null);const openPanelTab = (tab: PanelTarget, source?: SuggestionSource) => {if (!panelOpen) togglePanel();@@ -479,12 +497,15 @@ export function DraftEditor({const brandDomains = reads.sources?.data?.brandDomains;// The site's trust (Site Audit, CE-043), read once: Trust's last 5 points.const [siteTrust, setSiteTrust] = useState<SiteTrust | null>(null);+ // Read, or failed to: null alone can't tell "loading" from "none".+ const [siteTrustRead, setSiteTrustRead] = useState(false);useEffect(() => {if (!qualityOn) return;let live = true;getSiteTrust(draft.brandId).then((read) => live && setSiteTrust(read))- .catch((err) => console.error('Failed to read the site trust:', err));+ .catch((err) => console.error('Failed to read the site trust:', err))+ .finally(() => live && setSiteTrustRead(true));return () => {live = false;};@@ -1579,6 +1600,146 @@ export function DraftEditor({}};+ // The Next step basket (Next step spec): the one step to take now, chosen+ // from the draft's state by rules (no AI call), in the header and on the+ // agent card. With Quality's first phase: it reads Trust and the to-dos.+ const router = useRouter();+ const todoCopy = useTodoCopy();+ const [nextOpen, setNextOpen] = useState(false);+ // A click moves focus in; the basket opening by itself on a new page doesn't.+ const [nextFocus, setNextFocus] = useState(true);+ const [skipped, setSkipped] = useState(() => readSkips(draft.id));+ const pageHasWords = useMemo(+ () => !qualityOn || wordsUnderTitle(pageHtml),+ [qualityOn, pageHtml],+ );+ const trustNow = quality?.trust?.score ?? null;+ const nextState: NextStepState = {+ method: draft.method,+ open: canMarkReady,+ published: status === 'published',+ hasBrief: reads.brief.status === 'ready' ? reads.brief.brief !== null : null,+ empty: !pageHasWords,+ rewrite: rewriteAdvice(rules.rules),+ openRules: rulesForNext(rules.rules),+ quality: quality+ ? { trust: trustNow, trustLow: trustNow !== null && trustNow < TRUST_GATE, todos }+ : null,+ skipped,+ };+ const next = nextStep(nextState);+ const firstTodo = todos.find((todo) => !todo.done);+ const todoLine = firstTodo && quality ? todoCopy(firstTodo, quality).next : null;+ const skipStep = (id: NextStepId) => {+ const skips = { ...liveSkips(nextState), [id]: stepState(id, nextState) };+ setSkipped(skips);+ writeSkips(draft.id, skips);+ };+ // A skip whose step's state has changed is dropped, so it can't come back+ // to life; only once what the steps read is in (the brief, the rules, the+ // to-dos), not while a reopened page is still loading.+ // The sources (the fan-out rules read them), and with Quality the site's+ // trust and the link reads (Trust moves as they land).+ const nextRead =+ reads.brief.status !== 'loading' &&+ reads.sources !== null &&+ rules.ready &&+ (!qualityOn || (todosRead && siteTrustRead && linksPending === 0));+ const staleSkips =+ nextRead && Object.keys(liveSkips(nextState)).length !== Object.keys(skipped).length;+ useEffect(() => {+ if (!staleSkips) return;+ setSkipped((prev) => {+ const live = liveSkips({ ...nextState, skipped: prev });+ writeSkips(draft.id, live);+ return live;+ });+ // nextState is read as it is when a skip goes stale.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [staleSkips, draft.id]);+ // It starts open on a new page, and folds once its first step (the brief)+ // is done; Skip or another step doesn't fold it.+ const nextShownOnce = useRef<'no' | 'open' | 'done'>('no');+ const startsNew = next.step.id === 'plan' && nextState.empty;+ const planned = nextState.hasBrief === true;+ useEffect(() => {+ if (!qualityOn) return;+ if (nextShownOnce.current === 'no' && startsNew) {+ nextShownOnce.current = 'open';+ setNextFocus(false);+ setNextOpen(true);+ } else if (nextShownOnce.current === 'open' && planned) {+ nextShownOnce.current = 'done';+ setNextOpen(false);+ }+ }, [qualityOn, startsNew, planned]);+ /** Why a step's button can't run now, as the buttons it stands for say. */+ const nextBlocked = (action: NextAction): string | null => {+ switch (action) {+ case 'buildBrief':+ return agentBusy ? t('suggestions.agentBusy') : null;+ case 'writeWithAgent':+ return agentRewrite?.blocked ?? null;+ case 'rewritePage':+ return pageRewrite?.blocked ?? null;+ case 'fixRules':+ return agentFix.blocked;+ // As the header's Mark ready is held.+ case 'beforePublish':+ case 'markReady':+ return marking+ ? t('nextStep.marking')+ : autosave.state === 'conflict'+ ? t('save.conflict')+ : autosave.state === 'too_large'+ ? t('save.tooLarge')+ : null;+ default:+ return null;+ }+ };+ /** A step's button: the one the editor already has for it. */+ const runNext = (action: NextAction) => {+ setNextOpen(false);+ switch (action) {+ case 'buildBrief':+ if (!panelOpen) togglePanel();+ setTabRequest((prev) => ({ tab: 'brief', n: (prev?.n ?? 0) + 1, build: true }));+ return;+ case 'writeWithAgent':+ agentRewrite?.run();+ return;+ case 'writeMyself':+ skipStep(next.step.id);+ editor?.commands.focus('end');+ return;+ case 'rewritePage':+ pageRewrite?.run();+ return;+ case 'fixRules':+ agentFix.run();+ return;+ case 'pickAuthor':+ setAuthorMenuOpen(true);+ return;+ case 'addAuthor':+ router.push(MANAGE_AUTHORS_PATH);+ return;+ case 'showTodos':+ openPanelTab('quality');+ return;+ case 'beforePublish':+ openBeforePublish('markReady');+ return;+ case 'markReady':+ void markReady();+ return;+ case 'export':+ openBeforePublish('export');+ return;+ }+ };+// A version from History replaces the page: what's waiting is saved first,// as the server keeps the page it replaces, and the page can't change// while the restore runs.@@ -1646,6 +1807,31 @@ export function DraftEditor({{title.trim() || t('untitled')}</h1><div className="ml-auto flex shrink-0 items-center gap-1.5 sm:gap-3">+ {qualityOn && (+ <NextStepButton+ next={next}+ state={nextState}+ todoLine={todoLine}+ open={nextOpen}+ onOpenChange={(open) => {+ setNextFocus(true);+ setNextOpen(open);+ }}+ focusOnOpen={nextFocus}+ onAction={runNext}+ onSkip={skipStep}+ blocked={nextBlocked}+ working={+ agentWorking+ ? {+ run: agentRun,+ onStop: () => void stopAgent(),+ stopping: stoppingRun !== null && stoppingRun === agentRun?.id,+ }+ : null+ }+ />+ )}<SaveIndicator state={autosave.state} onRetry={() => void autosave.retry()} /><HistoryMenudraftId={draft.id}@@ -1871,6 +2057,20 @@ export function DraftEditor({if (pageSuggestion) void decidePage(pageSuggestion, to);}}runBlocked={cardRunBlocked}+ // Once nothing is left to decide, the basket's step (Next step spec §3).+ next={+ qualityOn+ ? {+ label: t(`nextStep.actions.${next.step.primary}`),+ onRun: () => runNext(next.step.primary),+ blocked: nextBlocked(next.step.primary),+ }+ : null+ }+ onAllSteps={() => {+ setNextFocus(true);+ setNextOpen(true);+ }}/>)}{editor && (@@ -1951,6 +2151,9 @@ export function DraftEditor({onSourceShown={() =>setTabRequest((prev) => (prev?.source ? { tab: prev.tab, n: prev.n } : prev))}+ onBuildStarted={() =>+ setTabRequest((prev) => (prev?.build ? { tab: prev.tab, n: prev.n } : prev))+ }onBriefRebuilding={onBriefRebuilding}briefBlocked={agentBusy && !briefRebuilding ? t('suggestions.agentBusy') : null}quality={quality}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.test.tsxnew file mode 100644index 000000000..505cd6d13--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.test.tsx@@ -0,0 +1,229 @@+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 messages from '../../../../../../../../messages/en.json';+import { nextStep, type NextStepState } from '@/lib/content/next-step';+import type { AgentRun } from '@/lib/content/agent-runs';++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, ...props }: { href: string } & Record<string, unknown>) => (+ <a href={href} {...props} />+ ),+}));++const { NextStepButton, wordsUnderTitle } = await import('./_next-step');++/**+ * The Next step basket (Next step spec §2–3): the header's button names+ * the step; the popover gives why, its buttons, Skip, the path and the+ * "If you see…" lines, or the run under way with Stop.+ */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const state = (over: Partial<NextStepState> = {}): NextStepState => ({+ method: 'create',+ open: true,+ published: false,+ hasBrief: true,+ empty: false,+ rewrite: null,+ openRules: [],+ quality: { trust: 72, trustLow: false, todos: [] },+ skipped: {},+ ...over,+});++let container: HTMLDivElement;+let root: Root;+const onAction = vi.fn();+const onSkip = vi.fn();+const onOpenChange = vi.fn();++async function render(+ s: NextStepState,+ {+ open = true,+ todoLine = null as string | null,+ blocked = (() => null) as (action: string) => string | null,+ working = null as { run: AgentRun | null; onStop: () => void; stopping: boolean } | null,+ } = {},+) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <NextStepButton+ next={nextStep(s)}+ state={s}+ todoLine={todoLine}+ open={open}+ onOpenChange={onOpenChange}+ focusOnOpen+ onAction={onAction}+ onSkip={onSkip}+ blocked={blocked}+ working={working}+ />+ </NextIntlClientProvider>,+ );+ });+}+const trigger = () => container.querySelector('button')!;+const popup = () => document.querySelector('[data-slot="popover-content"]');+const button = (name: string) =>+ [...(popup()?.querySelectorAll('button') ?? [])].find((b) => b.textContent === name);+const path = () => [...popup()!.querySelectorAll('ol li')].map((li) => li.textContent);++beforeEach(() => {+ onAction.mockReset();+ onSkip.mockReset();+ onOpenChange.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('NextStepButton', () => {+ it('names the step on the header button and opens the basket on a click', async () => {+ await render(state({ hasBrief: false, empty: true }), { open: false });+ expect(trigger().getAttribute('aria-label')).toBe('Next · Plan the page');+ expect(trigger().textContent).toBe('Next· Plan the page');+ expect(popup()).toBeNull();+ await act(async () => trigger().click());+ expect(onOpenChange).toHaveBeenCalledWith(true, expect.anything());+ });++ it('says why from the page, with its button, the other one and Skip', async () => {+ await render(+ state({+ method: 'optimize',+ rewrite: { reason: 'length', count: 19_203, target: 8_000, percent: 140 },+ openRules: ['rule0', 'rule1', 'rule2'],+ }),+ );+ expect(popup()!.textContent).toContain('Shorten to your Length');+ expect(popup()!.textContent).toContain(+ "19,203 characters against a Length of 8,000. Small fixes won't get there, so rewrite it in one go.",+ );+ await act(async () => button('Rewrite page')!.click());+ expect(onAction).toHaveBeenCalledWith('rewritePage');+ await act(async () => button('Fix open rules')!.click());+ expect(onAction).toHaveBeenCalledWith('fixRules');+ await act(async () => button('Skip')!.click());+ expect(onSkip).toHaveBeenCalledWith('length');+ expect(path()).toEqual([+ 'Plan the page · done',+ 'Bring in your page · done',+ '3Shorten to your Length · now',+ '4Add proof and author · to do',+ '5Check and mark ready · to do',+ ]);+ // If you see…: each line with its button, none repeating the step's own.+ expect(popup()!.textContent).not.toContain('Page far longer than Length');+ expect(popup()!.textContent).not.toContain('rules open →');+ // Fix open rules passed: the line names how few are open (the Rules tab's rewrite count less one).+ const few = state({ openRules: ['faq', 'summary'], skipped: { fixRules: 'faq,summary' } });+ await render(few);+ expect(popup()!.textContent).toContain('1 to 3 rules open → Fix open rules');+ });++ it('names the to-do only the person can do while Trust is low', async () => {+ await render(+ state({+ quality: {+ trust: 54,+ trustLow: true,+ todos: [{ id: 'byline', done: false, gain: 15, action: 'pickAuthor' }],+ },+ }),+ { todoLine: "pick the page's author" },+ );+ expect(popup()!.textContent).toContain(+ "Trust is 54, under 60. Only you can do this first: pick the page's author.",+ );+ await act(async () => button('Pick author')!.click());+ expect(onAction).toHaveBeenCalledWith('pickAuthor');+ });++ it("says why a button can't run now, and offers no Skip on the last step", async () => {+ await render(state({ openRules: ['rule0', 'rule1'] }), {+ blocked: (action) =>+ action === 'fixRules' ? 'Decide on the 2 open suggestions first.' : null,+ });+ expect(button('Fix open rules')!.disabled).toBe(true);+ expect(popup()!.textContent).toContain('Decide on the 2 open suggestions first.');+ await render(state());+ expect(popup()!.textContent).toContain('Check and mark ready');+ expect(button('Before you publish')).toBeDefined();+ expect(button('Skip')).toBeUndefined();+ // Published: Export, saying it went out.+ await render(state({ open: false, published: true }));+ expect(popup()!.textContent).toContain(+ "It's published. Export it again when the page changes.",+ );+ expect(button('Export')).toBeDefined();+ });++ it("moves focus to the next step's button after Skip, and reads the step out", async () => {+ const s = state({ openRules: ['faq'] });+ await render(s);+ await act(async () => button('Skip')!.click());+ expect(onSkip).toHaveBeenCalledWith('fixRules');+ // The editor passes the skip on: the step after it shows.+ await render({ ...s, skipped: { fixRules: 'faq' } });+ expect(document.activeElement).toBe(button('Before you publish'));+ expect(popup()!.querySelector('[aria-live="polite"]')!.textContent).toContain(+ 'Check and mark ready',+ );+ });++ it('shows the run under way with Stop instead of a step', async () => {+ const onStop = vi.fn();+ await render(state({ openRules: ['rule0', 'rule1'] }), {+ working: {+ run: {+ id: 'r1',+ kind: 'fix',+ steps: [+ { key: 'read_rules', count: null },+ { key: 'write_changes', count: null },+ ],+ step: 1,+ startedAt: new Date().toISOString(),+ finishedAt: null,+ stoppedAt: null,+ outcome: null,+ },+ onStop,+ stopping: false,+ },+ });+ expect(popup()!.textContent).toContain('Content Agent is working');+ expect(button('Fix open rules')).toBeUndefined();+ await act(async () => button('Stop')!.click());+ expect(onStop).toHaveBeenCalled();+ });+});++describe('wordsUnderTitle', () => {+ it('reads the words besides the block the title comes from', () => {+ expect(wordsUnderTitle('<h1>Pour-over</h1><p></p>')).toBe(false);+ expect(wordsUnderTitle('<h1>Pour-over</h1><p>Brew.</p>')).toBe(true);+ // An empty line or an image above the title changes nothing.+ expect(wordsUnderTitle('<p></p><h1>Pour-over</h1><p></p>')).toBe(false);+ expect(wordsUnderTitle('<p><img src="https://cdn.acme.com/a.jpg"></p><h1>Pour-over</h1>')).toBe(+ false,+ );+ // No H1: the first heading, else the first line, is the title.+ expect(wordsUnderTitle('<h2>Pour-over</h2><p>Brew.</p>')).toBe(true);+ expect(wordsUnderTitle('<p>Pour-over</p>')).toBe(false);+ expect(wordsUnderTitle('<p>Pour-over</p><p>Brew.</p>')).toBe(true);+ expect(wordsUnderTitle('')).toBe(false);+ });+});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.tsxnew file mode 100644index 000000000..5d50f510d--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.tsx@@ -0,0 +1,348 @@+'use client';++import { useEffect, useId, useRef } from 'react';+import { useTranslations } from 'next-intl';+import { Check } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@/components/ui/popover';+import type { AgentRun } from '@/lib/content/agent-runs';+import {+ FEW_OPEN_RULES,+ type NextAction,+ type NextPath,+ type NextStep,+ type NextStepId,+ type NextStepState,+ type PathState,+} from '@/lib/content/next-step';+import { cn } from '@/lib/utils';+import { RunSteps } from './_agent-card';+import { TRUST_GATE } from './_before-publish';+import { WorkingDots } from './_working-dots';++/**+ * The Next step basket (Next step spec §2–3): the header's "Next · {step}"+ * button, with the path as small bars, opens it as a popover under the+ * header. It names the one step to take now, why (from the page's own+ * numbers), its button and at most one other, Skip, the path of five+ * steps, and up to two "If you see…" lines. Each button is one the editor+ * already has; the basket only says which to use now. While the agent+ * works, it shows the run's step and Stop instead.+ */++/** The steps skipped on this draft, in this browser (Skip, spec §4). */+const skipsKey = (draftId: string) => `aeo:next-step-skips:${draftId}`;++export function readSkips(draftId: string): Partial<Record<NextStepId, string>> {+ try {+ const read = JSON.parse(localStorage.getItem(skipsKey(draftId)) ?? 'null') as unknown;+ if (read && typeof read === 'object') return read as Partial<Record<NextStepId, string>>;+ } catch {+ // Storage unavailable (private mode) or unreadable: nothing skipped.+ }+ return {};+}++export function writeSkips(draftId: string, skips: Partial<Record<NextStepId, string>>) {+ try {+ localStorage.setItem(skipsKey(draftId), JSON.stringify(skips));+ } catch {+ // Skipped 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: the+ * first H1 with words, else the first heading, else the first block with+ * words; an empty line or an image above it changes nothing.+ */+export function wordsUnderTitle(html: string): boolean {+ const template = document.createElement('template');+ template.innerHTML = html;+ const blocks = Array.from(template.content.children);+ const words = (el: Element) => /\S/.test(el.textContent ?? '');+ const title =+ blocks.find((el) => el.matches('h1') && words(el)) ??+ blocks.find((el) => el.matches('h1, h2, h3, h4, h5, h6') && words(el)) ??+ blocks.find(words);+ title?.remove();+ return /\S/.test(template.content.textContent ?? '');+}++type T = ReturnType<typeof useTranslations<'contentEditor.editor.nextStep'>>;++/** A step's name: the Length step says which way the page is off. */+function stepName(t: T, id: NextStepId, state: NextStepState): string {+ if (id === 'length' && state.rewrite?.reason === 'length') {+ return state.rewrite.count > state.rewrite.target+ ? t('steps.lengthLong')+ : t('steps.lengthShort');+ }+ return id === 'length' ? t('steps.lengthLong') : t(`steps.${id}`);+}++/** Why the step is next, from the page's own numbers. */+function stepReason(t: T, step: NextStep, state: NextStepState, todoLine: string | null): string {+ const { id } = step;+ switch (id) {+ case 'length':+ return state.rewrite?.reason === 'length'+ ? t('reasons.length', { count: state.rewrite.count, target: state.rewrite.target })+ : t('reasons.fixRules', { count: state.openRules.length });+ case 'fixRules':+ return t('reasons.fixRules', { count: state.openRules.length });+ case 'write':+ case 'import':+ // Once the person said they'd write it, the step is theirs.+ return step.primary === 'writeMyself' ? t('reasons.writeMine') : t(`reasons.${id}`);+ case 'proof': {+ const trust = state.quality?.trust;+ if (state.quality?.trustLow && trust !== null && trust !== undefined) {+ return todoLine+ ? t('reasons.proofTrustTodo', { trust, gate: TRUST_GATE, todo: todoLine })+ : t('reasons.proofTrust', { trust, gate: TRUST_GATE });+ }+ return t('reasons.proofTodo', { todo: todoLine ?? '' });+ }+ case 'check':+ return state.quality ? t('reasons.check', { gate: TRUST_GATE }) : t('reasons.checkRules');+ case 'ready':+ return state.published ? t('reasons.published') : t('reasons.ready');+ default:+ return t(`reasons.${id}`);+ }+}++/** The path as small bars: done, the one now, and those ahead. */+function Bars({ path, className }: { path: NextPath['path']; className?: string }) {+ return (+ <span aria-hidden className={cn('flex items-center gap-[3px]', className)}>+ {path.map((p) => (+ <i+ key={p.id}+ className={cn(+ 'block h-1.5 w-2.5 rounded-full',+ p.state === 'done'+ ? 'bg-foreground'+ : p.state === 'now'+ ? 'bg-foreground/60'+ : 'bg-foreground/15',+ )}+ />+ ))}+ </span>+ );+}++const PATH_DOT: Record<PathState, string> = {+ done: 'bg-foreground text-background',+ now: 'bg-foreground/10 text-foreground ring-1 ring-foreground',+ skipped: 'bg-muted text-muted-foreground',+ ahead: 'bg-muted text-muted-foreground',+};++export function NextStepButton({+ next,+ state,+ todoLine,+ open,+ onOpenChange,+ focusOnOpen,+ onAction,+ onSkip,+ blocked,+ working,+}: {+ next: NextPath;+ state: NextStepState;+ /** The first open to-do as "pick the page's author", for the proof step's reason. */+ todoLine: string | null;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Opened by a click: focus moves in. Opened by itself (a new draft): it doesn't. */+ focusOnOpen: boolean;+ onAction: (action: NextAction) => void;+ onSkip: (id: NextStepId) => void;+ /** Why an action can't run now (another run, suggestions to decide), or null. */+ blocked: (action: NextAction) => string | null;+ /** The agent's run under way from this page, with Stop; null while none. */+ working: { run: AgentRun | null; onStop: () => void; stopping: boolean } | null;+}) {+ const t = useTranslations('contentEditor.editor.nextStep');+ const { step, path, tips } = next;+ const name = stepName(t, step.id, state);+ const now = path.findIndex((p) => p.state === 'now');+ const why = blocked(step.primary);+ const whyId = useId();+ // After Skip, the new step's button takes focus (Skip itself may be gone).+ const primaryRef = useRef<HTMLButtonElement>(null);+ const skipped = useRef(false);+ useEffect(() => {+ if (!skipped.current) return;+ skipped.current = false;+ primaryRef.current?.focus();+ }, [step.id]);++ return (+ <Popover open={open} onOpenChange={onOpenChange}>+ <PopoverTrigger+ render={<Button variant="outline" size="sm" />}+ aria-label={t('button', { step: name })}+ title={t('button', { step: name })}+ >+ <Bars path={path} />+ <span>{t('short')}</span>+ {/* The step's name where there's room (§3b: "Next" with the bars at 1024px). */}+ <span className="hidden max-w-48 truncate xl:inline">+ {t('buttonStep', { step: name })}+ </span>+ </PopoverTrigger>+ <PopoverContent+ align="end"+ className="w-[340px] space-y-3"+ initialFocus={focusOnOpen}+ // Closing leaves focus where it went (a click into the page, a dialog,+ // a menu or a tab a step opened), else back on the button: Base UI's+ // own rule, which a finalFocus function would turn off.+ >+ <div className="flex items-center gap-2">+ <span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">+ {t('label')}+ </span>+ <Bars path={path} className="ml-auto" />+ <span className="sr-only">+ {now >= 0 ? t('stepOf', { n: now + 1, total: path.length }) : t('allDone')}+ </span>+ </div>++ {working ? (+ <div className="space-y-2">+ <PopoverTitle className="flex items-center">+ {t('working')}+ <WorkingDots />+ </PopoverTitle>+ {working.run && <RunSteps run={working.run} />}+ {working.run && (+ <Button+ variant="outline"+ size="sm"+ disabled={working.stopping}+ onClick={working.onStop}+ >+ {t('stop')}+ </Button>+ )}+ </div>+ ) : (+ // A step that changes (Skip, a run's end) is read out.+ <div className="space-y-2" aria-live="polite">+ <PopoverTitle>{name}</PopoverTitle>+ <p className="text-[13px] text-muted-foreground [overflow-wrap:anywhere]">+ {stepReason(t, step, state, todoLine)}+ </p>+ <div className="flex flex-wrap items-center gap-1.5">+ <Button+ ref={primaryRef}+ size="sm"+ disabled={why !== null}+ aria-describedby={why ? whyId : undefined}+ onClick={() => onAction(step.primary)}+ >+ {t(`actions.${step.primary}`)}+ </Button>+ {step.alternative && (+ <Button+ variant="outline"+ size="sm"+ disabled={blocked(step.alternative) !== null}+ onClick={() => onAction(step.alternative!)}+ >+ {t(`actions.${step.alternative}`)}+ </Button>+ )}+ {step.skippable && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => {+ skipped.current = true;+ onSkip(step.id);+ }}+ >+ {t('skip')}+ </Button>+ )}+ </div>+ {why && (+ <p+ id={whyId}+ className="text-xs text-amber-700 [overflow-wrap:anywhere] dark:text-amber-400"+ >+ {why}+ </p>+ )}+ </div>+ )}++ <ol aria-label={t('path')} className="space-y-1 border-t pt-3">+ {path.map((p, i) => (+ <li+ key={p.id}+ aria-current={p.state === 'now' ? 'step' : undefined}+ className={cn(+ 'flex items-center gap-2 text-[13px]',+ p.state === 'done' && 'text-muted-foreground line-through',+ p.state === 'now' && 'font-medium',+ (p.state === 'ahead' || p.state === 'skipped') && 'text-muted-foreground',+ )}+ >+ <span+ aria-hidden+ className={cn(+ 'flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold no-underline',+ PATH_DOT[p.state],+ )}+ >+ {p.state === 'done' ? <Check className="h-2.5 w-2.5" /> : i + 1}+ </span>+ <span className="min-w-0 [overflow-wrap:anywhere]">+ {stepName(t, p.id, state)}+ {p.state === 'skipped' && (+ <span aria-hidden className="ml-1.5 text-xs no-underline">+ {t('skipped')}+ </span>+ )}+ <span className="sr-only"> · {t(`states.${p.state}`)}</span>+ </span>+ </li>+ ))}+ </ol>++ {/* The lines' buttons start runs: none while one is under way. */}+ {tips.length > 0 && !working && (+ <div className="space-y-1 border-t pt-3">+ <p className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">+ {t('tipsTitle')}+ </p>+ {tips.map((tip) => (+ <p key={tip.id} className="text-[13px] text-muted-foreground">+ {t('tipLine', {+ state: t(`tips.${tip.id}`, { gate: TRUST_GATE, max: FEW_OPEN_RULES }),+ })}{' '}+ <button+ type="button"+ disabled={blocked(tip.action) !== null}+ onClick={() => onAction(tip.action)}+ className="font-medium text-foreground underline-offset-2 hover:underline focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none disabled:opacity-50"+ >+ {t(`actions.${tip.action}`)}+ </button>+ </p>+ ))}+ </div>+ )}+ </PopoverContent>+ </Popover>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsxindex 4e655a576..a3dc2e015 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@@ -2,6 +2,7 @@import { useEffect, useMemo, useRef, useState } from 'react';import { useTranslations } from 'next-intl';+import { toast } from 'sonner';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { isPageType, type ContentDraft } from '@/lib/content/drafts';import { buildSourceGroups, includedCounts, type DraftSourceKind } from '@/lib/content/sources';@@ -116,6 +117,7 @@ export function EditorSidePanel({agentRewrite,lastSuggestionAt,onSourceShown,+ onBuildStarted,onBriefRebuilding,briefBlocked = null,quality = null,@@ -141,6 +143,8 @@ export function EditorSidePanel({tab: PanelTarget;n: number;source?: { kind: DraftSourceKind; ref: string };+ /** The brief to build (the Next step basket's Build brief). */+ build?: boolean;} | null;/** Run Agent's Fix open rules, for Rules (CE-018, v1.1 CE-029). */agentFix?: AgentFix;@@ -152,6 +156,8 @@ export function EditorSidePanel({lastSuggestionAt: string | null;/** The source asked for was shown (or isn't listed): it isn't shown again. */onSourceShown?: () => void;+ /** The brief asked for is being built: the request is spent. */+ onBuildStarted?: () => 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. */@@ -241,6 +247,20 @@ export function EditorSidePanel({},});+ // Build brief from the Next step basket: once per request (an effect run+ // twice, as in development, builds once), never on a panel opened again+ // later; one that can't run says why.+ const buildHandled = useRef<number | null>(null);+ useEffect(() => {+ if (!tabRequest?.build || buildHandled.current === tabRequest.n) return;+ buildHandled.current = tabRequest.n;+ onBuildStarted?.();+ if (briefBlocked) toast(briefBlocked);+ else if (!rebuilding) void rebuild();+ // Only a new request builds.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [requested]);+// 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(() => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex bd352dc0a..3d1c5392c 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@@ -76,12 +76,14 @@ vi.mock('@/lib/actions/content-drafts', () => ({checkDraftLinks: (...args: unknown[]) => checkDraftLinks(...args),}));vi.mock('next/navigation', () => ({ useParams: () => ({ draftId: 'd1' }) }));+const routerPush = vi.hoisted(() => vi.fn());vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (<a href={href} {...props}>{children}</a>),+ useRouter: () => ({ push: routerPush }),}));const brandState = vi.hoisted(() => ({activeBrandId: 'b1' as string | null,@@ -3080,6 +3082,205 @@ describe('the side panel', () => {});});+ describe('Next step basket', () => {+ beforeEach(() => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';+ getContentAuthors.mockResolvedValue({+ authors: [],+ brands: [{ id: 'b1', name: 'Acme' }],+ me: { id: 'u1', role: 'analyst' },+ });+ });+ afterEach(() => {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ });+ const basket = () => document.querySelector('[data-slot="popover-content"]');+ const inBasket = (name: string) =>+ [...(basket()?.querySelectorAll('button') ?? [])].find((b) => b.textContent === name);+ const nextButton = () =>+ [...container.querySelectorAll<HTMLButtonElement>('header button')].find((b) =>+ b.getAttribute('aria-label')?.startsWith('Next · '),+ );++ it('opens by itself on a new page without taking focus, plans it, and folds after', async () => {+ getContentDraft.mockResolvedValue(+ draft({ method: 'create', bodyHtml: '<h1>Pipeline forecasting</h1><p></p>' }),+ );+ getDraftSources.mockResolvedValue({+ data: {+ prompts: [],+ fanouts: [],+ citedPages: [],+ gscQueries: [],+ brandDomains: [],+ competitorDomains: [],+ },+ choices: [],+ });+ rebuildDraftBrief.mockResolvedValue({+ brief: {+ goal: 'Win forecasting searches',+ audience: 'Sales leaders',+ outline: [],+ keywords: [],+ origin: 'rebuild',+ builtAt: '2026-10-21T10:00:00Z',+ builtFrom: { prompts: 0, fanouts: 0, pages: 0, queries: 0 },+ },+ });+ window.innerWidth = 1440;+ await renderPage();+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Plan the page');+ expect(basket()!.textContent).toContain(+ 'No brief yet. I build one from your prompts, fan-outs and cited pages.',+ );+ expect(basket()!.contains(document.activeElement)).toBe(false);++ await act(async () => inBasket('Build brief')!.click());+ await act(async () => {});+ expect(rebuildDraftBrief).toHaveBeenCalledTimes(1);+ expect(selectedSegment()).toBe('Brief');+ // Planned: the first draft is next, and the basket has folded.+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Write the first draft');+ expect(basket()).toBeNull();+ });++ it('skips a step on this draft until its state changes, and stays shut on a page with words', async () => {+ getContentDraft.mockResolvedValue(draft({ method: 'create' }));+ await renderPage();+ expect(basket()).toBeNull();+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Plan the page');+ await act(async () => nextButton()!.click());+ await act(async () => inBasket('Skip')!.click());+ expect(nextButton()!.getAttribute('aria-label')).not.toBe('Next · Plan the page');+ expect(JSON.parse(localStorage.getItem('aeo:next-step-skips:d1')!)).toEqual({+ plan: 'false',+ });++ // Opened again, the skip holds.+ await act(async () => root.unmount());+ root = createRoot(container);+ await renderPage();+ expect(nextButton()!.getAttribute('aria-label')).not.toBe('Next · Plan the page');+ });++ it("stays open on Skip, and leaves an empty page to the person once they'll write it", async () => {+ getContentDraft.mockResolvedValue(+ draft({ method: 'create', bodyHtml: '<h1>Pipeline forecasting</h1><p></p>' }),+ );+ await renderPage();+ expect(basket()).not.toBeNull();+ await act(async () => inBasket('Skip')!.click());+ expect(basket()).not.toBeNull();+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Write the first draft');++ await act(async () => inBasket("I'll write it")!.click());+ // The basket finishes closing (and the editor takes the caret) on the next frame.+ await act(async () => new Promise((resolve) => setTimeout(resolve, 100)));+ expect(basket()).toBeNull();+ // The caret goes to the end of the page, to write there.+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })+ .editor;+ expect(editor.state.selection.from).toBe(editor.state.doc.content.size - 1);+ // No agent work on an empty page the person writes: only their own step.+ await act(async () => nextButton()!.click());+ expect(basket()!.textContent).toContain(+ 'The page is empty: write it, and the next step follows from what you write.',+ );+ expect(inBasket('Write with Agent')).toBeUndefined();+ expect(inBasket('Skip')).toBeUndefined();+ });++ it('leaves focus where a click outside the basket put it', async () => {+ getContentDraft.mockResolvedValue(draft({ method: 'create' }));+ await renderPage();+ await act(async () => nextButton()!.click());+ expect(basket()).not.toBeNull();+ const elsewhere = document.createElement('button');+ document.body.append(elsewhere);+ try {+ await act(async () => {+ elsewhere.focus();+ for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {+ elsewhere.dispatchEvent(new MouseEvent(type, { bubbles: true }));+ }+ });+ await act(async () => new Promise((resolve) => setTimeout(resolve, 150)));+ expect(basket()).toBeNull();+ expect(document.activeElement).toBe(elsewhere);+ } finally {+ elsewhere.remove();+ }+ });++ it('keeps a skip while the sources load again, as the fan-out rules read them', async () => {+ const sources = {+ data: {+ prompts: [],+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],+ citedPages: [],+ gscQueries: [],+ brandDomains: [],+ competitorDomains: [],+ },+ choices: [],+ };+ getDraftSources.mockResolvedValue(sources);+ 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: [],+ },+ }),+ );+ await renderPage();+ expect(nextButton()!.getAttribute('aria-label')).toBe('Next · Fix open rules');+ await act(async () => nextButton()!.click());+ await act(async () => inBasket('Skip')!.click());+ const skips = () => JSON.parse(localStorage.getItem('aeo:next-step-skips:d1')!);+ const skippedAt = skips().fixRules;+ expect(skippedAt).toContain('fanoutH2');++ // Opened again, the sources come last: until then the fan-out rule reads+ // as "no fan-outs", and the skip mustn't be dropped for it.+ let answer: (value: unknown) => void = () => {};+ getDraftSources.mockReturnValue(new Promise((resolve) => (answer = resolve)));+ await act(async () => root.unmount());+ root = createRoot(container);+ await renderPage();+ expect(skips().fixRules).toBe(skippedAt);+ await act(async () => answer(sources));+ expect(skips().fixRules).toBe(skippedAt);+ expect(nextButton()!.getAttribute('aria-label')).not.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(+ draft({ bodyHtml: '<h1>Pipeline forecasting</h1><p></p>' }),+ );+ await renderPage();+ expect(nextButton()).toBeUndefined();+ expect(basket()).toBeNull();+ });+ });+describe('Run Agent: fix open rules', () => {const traced = draft({pageType: 'blog_post',diff --git a/web/src/components/ui/popover.tsx b/web/src/components/ui/popover.tsxnew file mode 100644index 000000000..04298c081--- /dev/null+++ b/web/src/components/ui/popover.tsx@@ -0,0 +1,67 @@+'use client';++import * as React from 'react';+import { Popover as PopoverPrimitive } from '@base-ui/react/popover';++import { cn } from '@/lib/utils';++function Popover({ ...props }: PopoverPrimitive.Root.Props) {+ return <PopoverPrimitive.Root data-slot="popover" {...props} />;+}++function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {+ return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;+}++function PopoverContent({+ align = 'start',+ alignOffset = 0,+ side = 'bottom',+ sideOffset = 6,+ className,+ ...props+}: PopoverPrimitive.Popup.Props &+ Pick<PopoverPrimitive.Positioner.Props, 'align' | 'alignOffset' | 'side' | 'sideOffset'>) {+ return (+ <PopoverPrimitive.Portal>+ <PopoverPrimitive.Positioner+ className="isolate z-50 outline-none"+ align={align}+ alignOffset={alignOffset}+ side={side}+ sideOffset={sideOffset}+ >+ <PopoverPrimitive.Popup+ data-slot="popover-content"+ className={cn(+ 'z-50 max-h-(--available-height) origin-(--transform-origin) overflow-y-auto rounded-xl bg-popover p-4 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',+ className,+ )}+ {...props}+ />+ </PopoverPrimitive.Positioner>+ </PopoverPrimitive.Portal>+ );+}++function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {+ return (+ <PopoverPrimitive.Title+ data-slot="popover-title"+ className={cn('text-sm font-semibold', className)}+ {...props}+ />+ );+}++function PopoverDescription({ className, ...props }: PopoverPrimitive.Description.Props) {+ return (+ <PopoverPrimitive.Description+ data-slot="popover-description"+ className={cn('text-[13px] text-muted-foreground', className)}+ {...props}+ />+ );+}++export { Popover, PopoverTrigger, PopoverContent, PopoverTitle, PopoverDescription };diff --git a/web/src/lib/content/next-step.test.ts b/web/src/lib/content/next-step.test.tsnew file mode 100644index 000000000..47e2e2357--- /dev/null+++ b/web/src/lib/content/next-step.test.ts@@ -0,0 +1,215 @@+import { describe, expect, it } from 'vitest';+import { liveSkips, nextStep, rulesForNext, stepState, type NextStepState } from './next-step';+import type { QualityTodo } from './quality-todos';++/**+ * The Next step basket's rules (Next step spec §4): the first state that+ * calls for a step wins; Skip passes a step until its state changes.+ */++const todo = (over: Partial<QualityTodo>): QualityTodo => ({+ id: 'byline',+ done: false,+ gain: 15,+ action: 'pickAuthor',+ ...over,+});++const state = (over: Partial<NextStepState> = {}): NextStepState => ({+ method: 'create',+ open: true,+ published: false,+ hasBrief: true,+ empty: false,+ rewrite: null,+ openRules: [],+ quality: { trust: 72, trustLow: false, todos: [] },+ skipped: {},+ ...over,+});++/** n open rule keys. */+const rules = (n: number) => Array.from({ length: n }, (_, i) => `rule${i}`);++const ids = (s: NextStepState) => nextStep(s).path.map((p) => `${p.id}:${p.state}`);++describe('nextStep', () => {+ it('plans a new page with no brief, then writes it (mockup: New page)', () => {+ const s = state({ hasBrief: false, empty: true, openRules: rules(13) });+ expect(nextStep(s).step).toEqual({+ id: 'plan',+ primary: 'buildBrief',+ alternative: null,+ skippable: true,+ });+ expect(ids(s)).toEqual([+ 'plan:now',+ 'write:ahead',+ 'fixRules:ahead',+ 'proof:ahead',+ 'check:ahead',+ ]);+ // An empty page: nothing to fix or rewrite yet, and no line repeats Build brief.+ expect(nextStep(s).tips).toEqual([]);+ expect(nextStep({ ...s, hasBrief: true }).step).toMatchObject({+ id: 'write',+ primary: 'writeWithAgent',+ alternative: 'writeMyself',+ });+ });++ it("stays on writing an empty page once the person said they'd write it", () => {+ const s = state({+ empty: true,+ openRules: rules(6),+ rewrite: { reason: 'length', count: 40, target: 3_000, percent: 99 },+ });+ // Its title alone isn't read against its Length.+ expect(ids(s)).toContain('fixRules:ahead');+ const mine = { ...s, skipped: { write: stepState('write', s) } };+ expect(nextStep(mine).step).toEqual({+ id: 'write',+ primary: 'writeMyself',+ alternative: null,+ skippable: false,+ });+ // Words in: the page moves on, and the skip has had its day.+ const written = { ...mine, empty: false };+ expect(nextStep(written).step.id).toBe('length');+ expect(liveSkips(written)).toEqual({});+ });++ it('rewrites a page far off its Length before fixing rules (mockup: Long imported page)', () => {+ const s = state({+ method: 'optimize',+ hasBrief: false,+ rewrite: { reason: 'length', count: 19_203, target: 8_000, percent: 140 },+ openRules: rules(3),+ });+ expect(nextStep(s).step).toMatchObject({+ id: 'length',+ primary: 'rewritePage',+ alternative: 'fixRules',+ });+ // An optimize draft starts here once its page is in.+ expect(ids(s)).toEqual([+ 'plan:done',+ 'import:done',+ 'length:now',+ 'proof:ahead',+ 'check:ahead',+ ]);+ // Rewrite page is the step's own button, and Fix open rules its other one: no line repeats them.+ expect(nextStep(s).tips).toEqual([]);+ });++ it('offers Rewrite page beside Fix open rules where the Rules tab recommends it', () => {+ expect(nextStep(state({ openRules: rules(3) })).step).toMatchObject({+ id: 'fixRules',+ alternative: null,+ });+ const many = state({ openRules: rules(4), rewrite: { reason: 'open', count: 4 } });+ expect(nextStep(many).step).toMatchObject({ id: 'fixRules', alternative: 'rewritePage' });+ // A page too long to send whole gets no rewrite advice, and no Rewrite page.+ expect(nextStep({ ...many, rewrite: null }).step.alternative).toBeNull();+ });++ it('names a few open rules once Fix open rules is passed', () => {+ const s = state({ openRules: ['faq', 'summary'] });+ expect(nextStep({ ...s, skipped: { fixRules: stepState('fixRules', s) } }).tips).toEqual([+ { id: 'someRules', action: 'fixRules' },+ ]);+ });++ it('asks for proof and the author while Trust is low or a to-do is open (mockup: Almost ready)', () => {+ const low = state({ quality: { trust: 54, trustLow: true, todos: [todo({})] } });+ expect(nextStep(low).step).toMatchObject({ id: 'proof', primary: 'pickAuthor' });+ expect(ids(low)).toEqual([+ 'plan:done',+ 'write:done',+ 'fixRules:done',+ 'proof:now',+ 'check:ahead',+ ]);+ expect(nextStep(low).tips).toEqual([{ id: 'lowTrust', action: 'showTodos' }]);+ expect(+ nextStep(state({ quality: { trust: 54, trustLow: true, todos: [] } })).step.primary,+ ).toBe('showTodos');+ expect(+ nextStep(+ state({ quality: { trust: 80, trustLow: false, todos: [todo({ action: 'addAuthor' })] } }),+ ).step.primary,+ ).toBe('addAuthor');+ });++ it('checks before marking ready, and exports once ready', () => {+ expect(nextStep(state()).step).toEqual({+ id: 'check',+ primary: 'beforePublish',+ alternative: null,+ skippable: false,+ });+ // Quality off: Mark ready, and no proof step on the path.+ expect(nextStep(state({ quality: null })).step.primary).toBe('markReady');+ expect(ids(state({ quality: null }))).toHaveLength(4);+ const ready = state({ open: false, openRules: rules(3) });+ expect(nextStep(ready).step).toMatchObject({ id: 'ready', primary: 'export' });+ expect(nextStep(ready).path.every((p) => p.state === 'done' || p.state === 'skipped')).toBe(+ true,+ );+ expect(nextStep(ready).tips).toEqual([]);+ });++ it('passes a skipped step until its state changes', () => {+ const s = state({ openRules: rules(3), quality: { trust: 54, trustLow: true, todos: [] } });+ const skipped = { ...s, skipped: { fixRules: stepState('fixRules', s) } };+ expect(nextStep(skipped).step.id).toBe('proof');+ expect(ids(skipped)).toContain('fixRules:skipped');+ // One rule met: it comes back.+ expect(nextStep({ ...skipped, openRules: rules(2) }).step.id).toBe('fixRules');+ // Typing doesn't bring a Length step back; turning from too long to too short does.+ const long = state({+ rewrite: { reason: 'length', count: 12_000, target: 8_000, percent: 50 },+ });+ const passed = { ...long, skipped: { length: stepState('length', long) } };+ expect(nextStep(passed).step.id).toBe('check');+ expect(+ nextStep({+ ...passed,+ rewrite: { reason: 'length', count: 9_000, target: 8_000, percent: 31 },+ }).step.id,+ ).toBe('check');+ expect(+ nextStep({+ ...passed,+ rewrite: { reason: 'length', count: 4_000, target: 8_000, percent: 50 },+ }).step.id,+ ).toBe('length');+ });++ it('drops a skip once its state changed, so it never comes back to life', () => {+ const s = state({ openRules: ['faq', 'summary'] });+ const skipped = { ...s, skipped: { fixRules: stepState('fixRules', s) } };+ expect(liveSkips(skipped)).toEqual({ fixRules: 'faq,summary' });+ expect(liveSkips({ ...skipped, openRules: ['faq'] })).toEqual({});+ });+});++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;+ expect(+ rulesForNext([+ { rule: rule('summary'), status: { state: 'bad', code: 'missing' } },+ { rule: rule('whoFor'), status: { state: 'bad', code: 'notSet' } },+ {+ rule: rule('length'),+ status: { state: 'bad', code: 'short', count: 2_500, min: 2_700, max: 3_300 },+ },+ { rule: rule('oneH1'), status: { state: 'bad', code: 'over', count: 2 } },+ { rule: rule('faq'), status: { state: 'ok' } },+ { rule: rule('aiTraces'), status: { state: 'bad', code: 'found', count: 1 } },+ ]),+ ).toEqual(['aiTraces', 'summary']);+ });+});diff --git a/web/src/lib/content/next-step.ts b/web/src/lib/content/next-step.tsnew file mode 100644index 000000000..56e84659d--- /dev/null+++ b/web/src/lib/content/next-step.ts@@ -0,0 +1,295 @@+import type { QualityTodo } from './quality-todos';+import {+ REWRITE_OPEN_RULES,+ openRulesForAgent,+ type ActiveRule,+ type RewriteAdvice,+ type RuleStatus,+} from './rules';++/**+ * The Content Editor's Next step basket (Next step spec §4): the one step to+ * take now, chosen from the draft's state by rules, with no AI call; the+ * path of five steps it sits on; and the "If you see…" lines that match the+ * page now. Nothing here runs a step: the editor maps each action to the+ * button that already does it.+ */++export type NextStepId =+ | 'plan'+ | 'write'+ | 'import'+ | 'length'+ | 'fixRules'+ | 'proof'+ | 'check'+ | 'ready';++/** What a step's buttons do: each is a button the editor already has. */+export type NextAction =+ | 'buildBrief'+ | 'writeWithAgent'+ | 'writeMyself'+ | 'rewritePage'+ | 'fixRules'+ | 'pickAuthor'+ | 'addAuthor'+ | 'showTodos'+ | 'beforePublish'+ | 'markReady'+ | 'export';++/**+ * The most open rules "If you see…" names for Fix open rules alone: from+ * REWRITE_OPEN_RULES, the Rules tab recommends rewriting the page whole, and+ * the basket offers Rewrite page beside it.+ */+export const FEW_OPEN_RULES = REWRITE_OPEN_RULES - 1;++/**+ * The open rules a run of Fix open rules can close: the ones the agent is+ * asked to fix, less a setting only the person fills (Who it's for) and+ * Length, which its own step takes once it is far off; a page a little off+ * its Length isn't sent round Fix again and again for it. Sorted keys, so+ * Skip can tell when the set changes.+ */+export function rulesForNext<T extends { rule: ActiveRule; status: RuleStatus }>(+ rules: T[],+): string[] {+ return openRulesForAgent(rules)+ .forAgent.filter(+ ({ rule, status }) =>+ rule.key !== 'length' && !(status.state === 'bad' && status.code === 'notSet'),+ )+ .map(({ rule }) => rule.key)+ .sort();+}++export interface NextStepState {+ method: 'create' | 'optimize';+ /** Draft or in review: open to the agent and to Mark ready. */+ open: boolean;+ /** Published (not only marked ready): Ready to publish says it went out. */+ published: boolean;+ /** Whether the draft has a brief; null while it isn't read, or couldn't be. */+ hasBrief: boolean | null;+ /** No words under the page's title. */+ empty: boolean;+ /** Why rewriting the page whole is recommended (rewriteAdvice), or null. */+ rewrite: RewriteAdvice | null;+ /** The open rules a Fix run can close (rulesForNext). */+ openRules: string[];+ /**+ * Quality's reads (Quality spec, CE-040/041): Trust under its gate (60),+ * and the to-dos only the person can do. Null while Quality is off.+ */+ 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>>;+}++export interface NextStep {+ id: NextStepId;+ primary: NextAction;+ alternative: NextAction | null;+ /** Skip moves past it; the last steps have nothing after them. */+ skippable: boolean;+}++export type PathState = 'done' | 'skipped' | 'now' | 'ahead';++export type TipId = 'longPage' | 'shortPage' | 'someRules' | 'noBrief' | 'lowTrust';++export interface NextPath {+ step: NextStep;+ /** The five steps in order (four while Quality is off). */+ path: { id: NextStepId; state: PathState }[];+ /** Up to two "If you see…" lines, each with its button, none repeating the step's own. */+ tips: { id: TipId; action: NextAction }[];+}++const openTodos = (s: NextStepState) => s.quality?.todos.filter((todo) => !todo.done) ?? [];++/**+ * A step's state as Skip remembers it: once it changes (a rule met or newly+ * open, Trust past 60, a to-do done), a skipped step comes back. Coarse on+ * purpose: which rules are open, not how far off each is, so typing a word+ * doesn't bring one back.+ */+export function stepState(id: NextStepId, s: NextStepState): string {+ switch (id) {+ case 'plan':+ return String(s.hasBrief);+ case 'write':+ case 'import':+ return String(s.empty);+ case 'length':+ return s.rewrite?.reason === 'length'+ ? s.rewrite.count > s.rewrite.target+ ? 'long'+ : 'short'+ : '';+ case 'fixRules':+ return s.openRules.join(',');+ case 'proof':+ return `${s.quality?.trustLow ?? false}:${openTodos(s)+ .map((todo) => todo.id)+ .join(',')}`;+ default:+ return '';+ }+}++/** 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(+ Object.entries(s.skipped).filter(([id, at]) => stepState(id as NextStepId, s) === at),+ );+}++/** Each step whose state calls for it now, in the order they are checked. */+function steps(s: NextStepState): NextStep[] {+ const todos = openTodos(s);+ const byline = todos.find((todo) => todo.id === 'byline');+ const writeId = s.method === 'create' ? ('write' as const) : ('import' as const);+ // An empty page has nothing for the agent to fix or rewrite: it is written+ // first. Once the person said they'd write it, only that is left to do.+ if (s.empty && s.skipped[writeId] === stepState(writeId, s)) {+ return [{ id: writeId, primary: 'writeMyself', alternative: null, skippable: false }];+ }+ return [+ ...(s.method === 'create' && s.hasBrief === false+ ? [+ {+ id: 'plan' as const,+ primary: 'buildBrief' as const,+ alternative: null,+ skippable: true,+ },+ ]+ : []),+ ...(s.empty+ ? [+ {+ id: writeId,+ primary: 'writeWithAgent' as const,+ alternative: 'writeMyself' as const,+ skippable: true,+ },+ ]+ : []),+ ...(!s.empty && s.rewrite?.reason === 'length'+ ? [+ {+ id: 'length' as const,+ primary: 'rewritePage' as const,+ alternative: s.openRules.length > 0 ? ('fixRules' as const) : null,+ skippable: true,+ },+ ]+ : []),+ ...(!s.empty && s.openRules.length > 0+ ? [+ {+ id: 'fixRules' as const,+ primary: 'fixRules' as const,+ // Where the Rules tab recommends rewriting it whole (rewriteAdvice):+ // the two say the same, and never for a page too long to send.+ alternative: s.rewrite !== null ? ('rewritePage' as const) : null,+ skippable: true,+ },+ ]+ : []),+ ...(s.quality && (s.quality.trustLow || todos.length > 0)+ ? [+ {+ id: 'proof' as const,+ primary: byline+ ? byline.action === 'addAuthor'+ ? ('addAuthor' as const)+ : ('pickAuthor' as const)+ : ('showTodos' as const),+ alternative: null,+ skippable: true,+ },+ ]+ : []),+ ];+}++/**+ * The step to take now (the first whose state calls for it and that wasn't+ * skipped at that state), the path, and the tips. A page marked ready or+ * published is ready to publish: Export.+ */+export function nextStep(s: NextStepState): NextPath {+ const due = s.open ? steps(s) : [];+ const check: NextStep = s.open+ ? {+ id: 'check',+ primary: s.quality ? 'beforePublish' : 'markReady',+ alternative: null,+ skippable: false,+ }+ : { id: 'ready', primary: 'export', alternative: null, skippable: false };+ const step = due.find((d) => !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).+ const third: NextStepId =+ step.id === 'length' || step.id === 'fixRules'+ ? step.id+ : !s.empty && s.rewrite?.reason === 'length'+ ? 'length'+ : 'fixRules';+ const ids: NextStepId[] = [+ 'plan',+ s.method === 'create' ? 'write' : 'import',+ third,+ ...(s.quality ? (['proof'] as const) : []),+ 'check',+ ];+ const now = step.id === 'ready' ? ids.length : ids.indexOf(step.id);+ const calledFor = new Set(due.map((d) => d.id));+ const path = ids.map((id, i) => ({+ id,+ state: (i === now+ ? 'now'+ : i > now+ ? 'ahead'+ : // Passed while its state still calls for it: it was skipped.+ calledFor.has(id)+ ? 'skipped'+ : 'done') as PathState,+ }));++ const tips: NextPath['tips'] =+ s.open && !s.empty+ ? [+ ...(s.rewrite?.reason === 'length'+ ? [+ {+ id:+ s.rewrite.count > s.rewrite.target+ ? ('longPage' as const)+ : ('shortPage' as const),+ action: 'rewritePage' as const,+ },+ ]+ : []),+ ...(s.openRules.length > 0 && s.rewrite === null+ ? [{ id: 'someRules' as const, action: 'fixRules' as const }]+ : []),+ ...(s.method === 'create' && s.hasBrief === false+ ? [{ id: 'noBrief' as const, action: 'buildBrief' as const }]+ : []),+ ...(s.quality?.trustLow+ ? [{ id: 'lowTrust' as const, action: 'showTodos' as const }]+ : []),+ ]+ .filter((tip) => tip.action !== step.primary)+ .slice(0, 2)+ : [];++ return { step, path, tips };+}