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.

fix(content-editor): head the agent card with the Next step, and read a rewrite against the Length (#1472)

Cihan3ccb6b41a29b
diff --git a/web/messages/en.json b/web/messages/en.json
index 5d48c3747..b5a0041ce 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3782,6 +3782,10 @@
"more": "+{count, number} more",
"run": "Run Agent",
"next": "Next: {action}",
+ "nextTitle": "Next · {step}",
+ "lastRun": "Last run: <run></run>",
+ "byAgent": "Content Agent takes this step",
+ "byYou": "only you can take this step",
"allSteps": "All steps",
"working": "Content Agent is working",
"builtFrom": "built from {count, number} of your sources",
@@ -3817,6 +3821,8 @@
"bar": "Rewritten page",
"ready": "Content Agent rewrote the page to its rules",
"characters": "{before, number} → {after, number} characters",
+ "lengthMissed": "Length {target, number} not reached",
+ "lengthKept": "({kept, number} characters are passages AI answers quote, tables and other blocks a rewrite keeps as they are)",
"accepted": "Rewrite accepted",
"rejected": "Rewrite rejected",
"rulesOpen": "{count, plural, one {# rule still open} other {# rules still open}}",
@@ -4934,6 +4940,7 @@
"length": "Recommended: the page is {count, number} characters for a Length of {target, number} ({percent, number}% off). A rewrite gets there in one go.",
"open": "Recommended: {count, number} rules are open. A rewrite meets them together."
},
+ "lengthOutOfReach": "The page is {count, number} characters for a Length of {target, number}, but {kept, number} of them are passages AI answers quote, tables and other blocks a rewrite keeps as they are. Raise the Length to about {suggested, number}, or unlock passages you're fine to have reworded.",
"lengthConflict": "The fan-out H2s, FAQ questions and summary these rules still ask for take about {need, number} characters, more than Length allows (up to {max, number}). Raise Length, or ask for fewer.",
"fixTrace": "Fix",
"fixTraceHint": "Content Agent rewrites only these phrases, for you to review",
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 04585b7e2..9bf6364a9 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
@@ -172,6 +172,84 @@ describe('AgentCard', () => {
expect(buttons()).not.toContain('Next: Rewrite page');
});
+ it('heads with the Next step and who takes it, what the agent left as its last run', async () => {
+ const reviewed = [suggestion({ status: 'accepted' })];
+ const step = {
+ label: 'Rewrite page',
+ onRun: vi.fn(),
+ blocked: null,
+ title: 'Shorten to your Length',
+ reason: '6,773 characters against a Length of 4,000.',
+ actor: 'agent' as const,
+ };
+ await render(reviewed, false, { next: step });
+ const card = container.querySelector('[role="region"]')!;
+ expect(card.textContent).toContain('Next · Shorten to your Length');
+ expect(card.textContent).toContain('Content Agent takes this step');
+ expect(card.textContent).toContain('6,773 characters against a Length of 4,000.');
+ expect(card.textContent).toContain('Last run: All suggestions reviewed · 1 accepted');
+ // The agent's step: its robot.
+ expect(card.querySelector('svg rect')).not.toBeNull();
+ // The step changes, and so does the card: the person's step, the person's tile.
+ await render(reviewed, false, {
+ next: {
+ ...step,
+ label: 'Pick author',
+ title: 'Add proof and author',
+ reason: "Only you can do this: pick the page's author.",
+ actor: 'you',
+ },
+ });
+ expect(card.textContent).toContain('Next · Add proof and author');
+ expect(card.textContent).toContain("Only you can do this: pick the page's author.");
+ expect(card.textContent).toContain('only you can take this step');
+ expect(card.querySelector('svg rect')).toBeNull();
+ // The agent's suggestions still to decide keep its tile and their count in sight.
+ await render([suggestion()], false, { next: { ...step, actor: 'you' } });
+ expect(card.querySelector('svg rect')).not.toBeNull();
+ // Working: the run, not the step.
+ await render([], true, { next: step });
+ expect(card.textContent).toBe('Content Agent is working');
+ // A rewrite to decide: still under the step, with its own buttons.
+ await render(
+ [
+ suggestion({
+ kind: 'page',
+ beforeHtml: '<h1>Old</h1><p>A much longer page than this one.</p>',
+ afterText: '<h1>New</h1><p>Shorter.</p>',
+ reason: 'cut to the Length',
+ }),
+ ],
+ false,
+ { next: step },
+ );
+ expect(card.textContent).toContain('Next · Shorten to your Length');
+ expect(card.textContent).toContain(
+ 'Last run: Content Agent rewrote the page to its rules · 37 → 12 characters · cut to the Length',
+ );
+ expect(buttons()).toEqual(['Compare', 'Reject', 'Accept']);
+ });
+
+ it('reads a rewrite against the Length, not the agent’s say, and says what it kept', async () => {
+ const page = suggestion({
+ kind: 'page',
+ beforeHtml: '<h1>Old</h1><p>A much longer page than this one.</p>',
+ afterText: '<h1>New</h1><p>Shorter.</p>',
+ reason: 'shortened the content to about 4 characters',
+ });
+ // 12 characters for a Length of 4 (3–5): missed, most of it kept.
+ await render([page], false, { length: { target: 4, min: 3, max: 5, kept: 4 } });
+ expect(container.textContent).toContain(
+ '37 → 12 characters · Length 4 not reached (4 characters are passages AI answers quote, tables and other blocks a rewrite keeps as they are)',
+ );
+ expect(container.textContent).not.toContain('shortened the content');
+ // Within the Length: the agent's own words.
+ await render([page], false, { length: { target: 12, min: 10, max: 14, kept: 0 } });
+ expect(container.textContent).toContain(
+ '37 → 12 characters · shortened the content to about 4 characters',
+ );
+ });
+
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.tsx
index 463d759b9..e128ce429 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 { Check, ChevronRight, X } from 'lucide-react';
+import { Check, ChevronRight, User, X } from 'lucide-react';
import { Link } from '@/i18n/navigation';
import { Button } from '@/components/ui/button';
import {
@@ -12,6 +12,7 @@ import {
type SuggestionStatus,
} from '@/lib/content/suggestions';
import { shownSteps, stepMessage, type AgentRun } from '@/lib/content/agent-runs';
+import { KEPT_LENGTH_SHARE } from '@/lib/content/rules';
import { cn } from '@/lib/utils';
import { PageCompareDialog, pageCharacters } from './_page-rewrite';
import { WorkingDots } from './_working-dots';
@@ -142,6 +143,18 @@ function AgentTile({
);
}
+/** The person's tile: a step only they can take (their to-dos, their checks). */
+function PersonTile() {
+ return (
+ <span
+ aria-hidden
+ className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border bg-background text-foreground"
+ >
+ <User className="h-[18px] w-[18px]" />
+ </span>
+ );
+}
+
/**
* 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.
@@ -200,6 +213,7 @@ export function AgentCard({
stopping = false,
next = null,
onAllSteps,
+ length = null,
}: {
suggestions: DraftSuggestion[];
rules: CardRules;
@@ -233,9 +247,24 @@ export function AgentCard({
* 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;
+ next?: {
+ label: string;
+ onRun: () => void;
+ blocked: string | null;
+ /** The step's name: the card heads with it, "Next · {title}" (Next step spec §3). */
+ title?: string;
+ /** Why it is next, from the page's numbers. */
+ reason?: string;
+ /** Who takes it: the agent's run, or the person. */
+ actor?: 'agent' | 'you';
+ } | null;
/** Opens the basket with every step. */
onAllSteps?: () => void;
+ /**
+ * The page's Length rule (its target and band) and what a rewrite keeps
+ * as it is: a rewrite's result is read against it, never the agent's say.
+ */
+ length?: { target: number; min: number; max: number; kept: number } | null;
}) {
const t = useTranslations('contentEditor.editor.agentCard');
const locale = useLocale();
@@ -334,10 +363,24 @@ export function AgentCard({
: page.status === 'accepted'
? tRewrite('accepted')
: tRewrite('rejected');
+ // Read against the Length, not the agent's say: a rewrite that missed it
+ // says so, and why when what it keeps is most of the Length.
+ const missed = length && (afterChars > length.max || afterChars < length.min) ? length : null;
line =
page.status === 'open' ? (
<>
- {tRewrite('characters', { before, after: afterChars })} · {page.reason}
+ {tRewrite('characters', { before, after: afterChars })}
+ {' · '}
+ {missed ? (
+ <span className="text-amber-700 dark:text-amber-400">
+ {tRewrite('lengthMissed', { target: missed.target })}
+ {afterChars > missed.max &&
+ missed.kept >= missed.target * KEPT_LENGTH_SHARE &&
+ ` ${tRewrite('lengthKept', { kept: missed.kept })}`}
+ </span>
+ ) : (
+ page.reason
+ )}
{builtFrom}
</>
) : page.status === 'accepted' && stillOpen > 0 ? (
@@ -387,6 +430,33 @@ export function AgentCard({
);
}
+ // With the basket (Next step spec §3), the card heads with the step and
+ // who takes it; what the agent left is its last run, under it.
+ const stepHead = !working && next?.title ? next : null;
+ let lastRun: React.ReactNode = null;
+ if (stepHead) {
+ const run = title;
+ const runLine = line;
+ lastRun = t.rich('lastRun', {
+ run: () => (
+ <>
+ {run}
+ {runLine && <> · {runLine}</>}
+ </>
+ ),
+ });
+ title = (
+ <>
+ {t('nextTitle', { step: stepHead.title! })}
+ <span className="sr-only">
+ {' · '}
+ {t(stepHead.actor === 'you' ? 'byYou' : 'byAgent')}
+ </span>
+ </>
+ );
+ line = stepHead.reason ?? null;
+ }
+
return (
<div
role="region"
@@ -394,7 +464,12 @@ export function AgentCard({
aria-busy={working}
className="mx-4 mt-3 mb-1 flex flex-wrap items-center gap-x-3.5 gap-y-2.5 rounded-2xl border bg-muted px-3.5 py-3 shadow-xs"
>
- <AgentTile tone={tone} count={working ? 0 : open} />
+ {/* The person's tile only with nothing of the agent's to decide: its count stays in sight. */}
+ {stepHead?.actor === 'you' && open === 0 && page?.status !== 'open' ? (
+ <PersonTile />
+ ) : (
+ <AgentTile tone={tone} count={working ? 0 : open} />
+ )}
{/* Room for a line of text first: on a narrow page the buttons go under it. */}
<div className="min-w-0 flex-1 basis-56">
<div className="text-sm font-semibold [overflow-wrap:anywhere]">{title}</div>
@@ -409,6 +484,11 @@ export function AgentCard({
{reason}
</div>
)}
+ {lastRun && (
+ <div className="text-[12px] text-muted-foreground/90 [overflow-wrap:anywhere]">
+ {lastRun}
+ </div>
+ )}
</div>
{/* Working, only Stop: it drops whatever the run had. */}
{working && onStop && run && (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.test.ts
index b6d4631f4..fa963f237 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.test.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.test.ts
@@ -6,6 +6,7 @@ import {
CITED_EDIT_ALLOWED,
CitedPassages,
citedPassagesKey,
+ keptCharacters,
lockedPassageCount,
type HeldEdit,
} from './_cited-passages';
@@ -58,6 +59,32 @@ beforeEach(() => {
afterEach(() => editor.destroy());
+describe('keptCharacters', () => {
+ it('counts what a page rewrite keeps as it is: quoted passages, quotes, lists holding one', () => {
+ const quote = 'A customer said it saved them a week.';
+ const small = new Editor({
+ extensions: [StarterKit, CitedPassages.configure({ onHeld: () => {} })],
+ content: `<p>${QUOTED}</p><p>Plain words to rewrite.</p><blockquote><p>${quote}</p></blockquote><ul><li><p>${QUOTED}</p></li></ul>`,
+ });
+ try {
+ const lock = (unlocked: string[] = []) =>
+ small.view.dispatch(
+ small.state.tr.setMeta(citedPassagesKey, {
+ labels: new Map([[passageKey(QUOTED), 'Cited by ChatGPT 3×']]),
+ unlocked: new Set(unlocked),
+ }),
+ );
+ lock();
+ expect(keptCharacters(small.state)).toBe(QUOTED.length * 2 + quote.length);
+ // Unlocked by the person: the agent may reword it.
+ lock([passageKey(QUOTED)]);
+ expect(keptCharacters(small.state)).toBe(quote.length);
+ } finally {
+ small.destroy();
+ }
+ });
+});
+
describe('locked passages', () => {
it('marks the quoted passage and counts it', () => {
expect(lockedPassageCount(editor.state)).toBe(1);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts
index 4508bde95..39e4ff990 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts
@@ -151,6 +151,44 @@ function lockedAtSelection(state: EditorState, locks: CitedLocks): string | null
return found;
}
+/** The top-level blocks a page rewrite keeps whole (content-rewrite.js KEPT_BLOCKS). */
+const KEPT_NODES = new Set([
+ 'table',
+ 'image',
+ 'blockquote',
+ 'codeBlock',
+ 'horizontalRule',
+ 'htmlBlock',
+ 'jsonLd',
+]);
+
+/**
+ * The characters a page rewrite keeps as they are (content-rewrite.js
+ * keepBlocks): each top-level block that holds a passage AI answers quote
+ * (still locked), or is a table, image, quote, code, rule, HTML block or
+ * JSON-LD, or holds an image or a table. Counted by their text, as the
+ * editor counts the page's.
+ */
+export function keptCharacters(state: EditorState): number {
+ const locks = citedLocks(state);
+ let kept = 0;
+ state.doc.forEach((block) => {
+ let keep =
+ KEPT_NODES.has(block.type.name) || (block.isTextblock && isLocked(blockKey(block), locks));
+ if (!keep) {
+ block.descendants((node) => {
+ if (keep) return false;
+ if (node.type.name === 'image' || node.type.name === 'table') keep = true;
+ else if (node.isTextblock && isLocked(blockKey(node), locks)) keep = true;
+ return !keep;
+ });
+ }
+ // As the editor's character count reads text: no separator between blocks.
+ if (keep) kept += block.textBetween(0, block.content.size, undefined, ' ').length;
+ });
+ return kept;
+}
+
/** How many quoted passages the page has now (the marks the plugin keeps). */
export function lockedPassageCount(state: EditorState): number {
return citedPassagesKey.getState(state)?.marks.find().length ?? 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.tsx
index c2164c8e9..eda040891 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
@@ -121,6 +121,7 @@ import {
fanoutsToUse,
lengthWarns,
openRulesForAgent,
+ lengthBand,
rewriteAdvice,
} from '@/lib/content/rules';
import { aiUsageTone } from '@/lib/billing/ai-usage';
@@ -142,6 +143,7 @@ import {
CitedPassages,
citedLocks,
citedPassagesKey,
+ keptCharacters,
lockedPassageCount,
type HeldEdit,
} from './_cited-passages';
@@ -158,7 +160,15 @@ import { ClaimMarksExtension, claimMarksKey, textRanges, writingBlock } from './
import { useClaims } from './_use-claims';
import { useSourceClasses } from './_use-source-classes';
import { HeaderTip } from './_header-tip';
-import { NextStepButton, readSkips, wordsUnderTitle, writeSkips } from './_next-step';
+import {
+ NextStepButton,
+ readSkips,
+ stepActor,
+ stepName,
+ stepReason,
+ wordsUnderTitle,
+ writeSkips,
+} from './_next-step';
import { useTodoCopy, type QualityRead } from './_quality-tab';
import { PageTypeMenu } from './_page-type-menu';
import type { AgentRewrite } from './_brief-tab';
@@ -284,6 +294,7 @@ export function DraftEditor({
agentFinished?: boolean;
}) {
const t = useTranslations('contentEditor.editor');
+ const tNext = useTranslations('contentEditor.editor.nextStep');
const autosave = useDraftAutosave(draft.id, draft);
const [title, setTitle] = useState(draft.title);
// The page as written now, for the side panel's Sources.
@@ -493,6 +504,16 @@ export function DraftEditor({
pageType,
reads,
});
+ // What a page rewrite keeps as it is (the passages AI answers quote, tables,
+ // images…), read as the characters are: a Length under it is out of reach.
+ const keptChars = editor && citedRead ? keptCharacters(editor.state) : 0;
+ // The Length the page is written to, for what the agent's rewrite reached.
+ const lengthRule = rules.rules.find(({ rule }) => rule.key === 'length' && rule.on)?.rule;
+ const lengthTarget = Number(lengthRule?.current);
+ const length =
+ lengthRule && Number.isFinite(lengthTarget) && lengthTarget > 0
+ ? { target: lengthTarget, ...lengthBand(lengthTarget), kept: keptChars }
+ : null;
// How well the page reads as written (Quality spec, CE-036/039): read in the
// browser, no AI cost; off until Quality's first phase is live. Read in the
// language the page is written in: its Language rule when that is on (the
@@ -1797,6 +1818,7 @@ export function DraftEditor({
? {
run: () => void rewritePage(),
running: rewriting,
+ kept: keptChars,
blocked:
aiUsedUp && !rewriting
? aiUsedUp
@@ -1925,7 +1947,7 @@ export function DraftEditor({
published: status === 'published',
hasBrief: reads.brief.status === 'ready' ? reads.brief.brief !== null : null,
empty: !pageHasWords,
- rewrite: rewriteAdvice(rules.rules),
+ rewrite: rewriteAdvice(rules.rules, keptChars),
openRules: rulesForNext(rules.rules),
quality: quality
? { trust: trustNow, trustLow: trustNow !== null && trustNow < TRUST_GATE, todos }
@@ -2554,9 +2576,14 @@ export function DraftEditor({
label: t(`nextStep.actions.${next.step.primary}`),
onRun: () => runNext(next.step.primary),
blocked: nextBlocked(next.step.primary),
+ // The card heads with the step and who takes it (Next step spec §3).
+ title: stepName(tNext, next.step.id, nextState),
+ reason: stepReason(tNext, next.step, nextState, todoLine),
+ actor: stepActor(next.step),
}
: null
}
+ length={length}
onAllSteps={() => {
setNextFocus(true);
setNextOpen(true);
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.tsx
index fa7f98e1b..ba2c55b3e 100644
--- 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.tsx
@@ -12,7 +12,7 @@ vi.mock('@/i18n/navigation', () => ({
),
}));
-const { NextStepButton, wordsUnderTitle } = await import('./_next-step');
+const { NextStepButton, wordsUnderTitle, stepActor } = await import('./_next-step');
/**
* The Next step basket (Next step spec §2–3): the header's button names
@@ -211,6 +211,29 @@ describe('NextStepButton', () => {
});
});
+describe('stepActor', () => {
+ it('gives the agent its runs and the person the rest', () => {
+ const actor = (primary: Parameters<typeof stepActor>[0]['primary']) =>
+ stepActor({ id: 'fixRules', primary, alternative: null, skippable: true });
+ expect(
+ (['buildBrief', 'writeWithAgent', 'rewritePage', 'fixRules'] as const).map(actor),
+ ).toEqual(['agent', 'agent', 'agent', 'agent']);
+ expect(
+ (
+ [
+ 'writeMyself',
+ 'pickAuthor',
+ 'addAuthor',
+ 'showTodos',
+ 'beforePublish',
+ 'markReady',
+ 'export',
+ ] as const
+ ).map(actor),
+ ).toEqual(['you', 'you', 'you', 'you', 'you', 'you', 'you']);
+ });
+});
+
describe('wordsUnderTitle', () => {
it('reads the words besides the block the title comes from', () => {
expect(wordsUnderTitle('<h1>Pour-over</h1><p></p>')).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.tsx
index 5d50f510d..417443e7b 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
@@ -70,10 +70,10 @@ export function wordsUnderTitle(html: string): boolean {
return /\S/.test(template.content.textContent ?? '');
}
-type T = ReturnType<typeof useTranslations<'contentEditor.editor.nextStep'>>;
+export 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 {
+export 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')
@@ -82,8 +82,24 @@ function stepName(t: T, id: NextStepId, state: NextStepState): string {
return id === 'length' ? t('steps.lengthLong') : t(`steps.${id}`);
}
+/** Who takes a step: the agent's run, or the person (their to-dos, their checks, their words). */
+const AGENT_ACTIONS: ReadonlySet<NextAction> = new Set([
+ 'buildBrief',
+ 'writeWithAgent',
+ 'rewritePage',
+ 'fixRules',
+]);
+export function stepActor(step: NextStep): 'agent' | 'you' {
+ return AGENT_ACTIONS.has(step.primary) ? 'agent' : 'you';
+}
+
/** Why the step is next, from the page's own numbers. */
-function stepReason(t: T, step: NextStep, state: NextStepState, todoLine: string | null): string {
+export function stepReason(
+ t: T,
+ step: NextStep,
+ state: NextStepState,
+ todoLine: string | null,
+): string {
const { id } = step;
switch (id) {
case 'length':
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx
index f9ab31289..b37dfb31d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx
@@ -165,6 +165,16 @@ describe('the Rules tab', () => {
expect(main().textContent).toBe('Run Agent');
});
+ it('says when the Length is out of a rewrite’s reach for what it keeps, recommending none for it', async () => {
+ // 15,921 characters for 3,000, 2,900 of them passages AI answers quote and tables.
+ await show({ agentFix: fix(), pageRewrite: { ...fix(), kept: 2_900 } });
+ const notes = [...container.querySelectorAll('[role="note"]')].map((n) => n.textContent);
+ expect(notes.some((n) => n?.startsWith('Recommended: the page is'))).toBe(false);
+ expect(notes).toContainEqual(
+ "The page is 15,921 characters for a Length of 3,000, but 2,900 of them are passages AI answers quote, tables and other blocks a rewrite keeps as they are. Raise the Length to about 4,500, or unlock passages you're fine to have reworded.",
+ );
+ });
+
it('says why its choice waits under the card, for the choice picked', async () => {
const agentFix = {
...fix(),
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 99b63c242..732b1bfe1 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, Sparkles } from 'lucide-react';
+import { ChevronDown, Info, Sparkles } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
@@ -33,6 +33,7 @@ import {
MAX_TEXT_RULE_LENGTH,
RULE_GROUPS,
openRulesForAgent,
+ lengthOutOfReach,
rewriteAdvice,
splitRules,
type ActiveRule,
@@ -85,6 +86,8 @@ export interface PageRewrite {
running: boolean;
/** Why it can't run now (suggestions still open), or null. */
blocked: string | null;
+ /** The characters it keeps as they are (keptCharacters): a Length under them is out of reach. */
+ kept?: number;
}
/** Run Agent's two ways: the open rules fixed a few passages at a time, or the whole page. */
@@ -244,7 +247,9 @@ export function RulesTab({
];
// Rewrite the page whole when small edits can't get there.
- const advice = pageRewrite ? rewriteAdvice(state.rules) : null;
+ const advice = pageRewrite ? rewriteAdvice(state.rules, pageRewrite.kept ?? 0) : null;
+ // A Length the rewrite can't reach for what it keeps: said, never recommended.
+ const outOfReach = pageRewrite ? lengthOutOfReach(state.rules, pageRewrite.kept ?? 0) : null;
// The rules the page doesn't meet now, in the tab's order, and those the agent fixes.
const open = state.rules.filter(({ rule, status }) => rule.on && status.state === 'bad');
const fixable = openRulesForAgent(state.rules).forAgent.length;
@@ -327,6 +332,12 @@ export function RulesTab({
</span>
</p>
)}
+ {outOfReach && (
+ <p className="flex gap-1.5 text-xs" role="note">
+ <Info aria-hidden className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground" />
+ <span>{t('lengthOutOfReach', { ...outOfReach })}</span>
+ </p>
+ )}
</RunCard>
)}
diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.ts
index fcf56f46e..00ee8f9d4 100644
--- a/web/src/lib/content/rules.test.ts
+++ b/web/src/lib/content/rules.test.ts
@@ -29,6 +29,7 @@ import {
RULE_LENGTH_MIN,
RULE_LENGTH_MAX,
lengthBand,
+ lengthOutOfReach,
rewriteAdvice,
type RuleStatus,
} from './rules';
@@ -716,6 +717,30 @@ describe('rewriteAdvice', () => {
expect(rewriteAdvice(statuses(60_001))).toBeNull();
});
+ it("doesn't recommend shortening a page whose kept blocks are most of its Length", () => {
+ // The user's page: 6,877 characters for 4,000, 3,799 of them quoted passages and tables.
+ const page = statuses(6_877, [], '4000');
+ expect(rewriteAdvice(page, 3_799)).toBeNull();
+ expect(lengthOutOfReach(page, 3_799)).toEqual({
+ count: 6_877,
+ target: 4_000,
+ kept: 3_799,
+ suggested: 6_000,
+ });
+ // Little kept: a rewrite still gets there.
+ expect(rewriteAdvice(page, 1_000)).toMatchObject({ reason: 'length' });
+ expect(lengthOutOfReach(page, 1_000)).toBeNull();
+ // Many rules open: still a rewrite, for them, the Length out of reach not among them.
+ expect(
+ rewriteAdvice(statuses(6_877, ['faq', 'summary', 'h2Answer'], '4000'), 3_799),
+ ).toBeNull();
+ expect(
+ rewriteAdvice(statuses(6_877, ['faq', 'summary', 'h2Answer', 'keywords'], '4000'), 3_799),
+ ).toMatchObject({ reason: 'open' });
+ // Under its Length, what is kept doesn't stop it.
+ expect(lengthOutOfReach(statuses(2_000, [], '4000'), 3_799)).toBeNull();
+ });
+
it('recommends it for 4 rules or more the agent can fix', () => {
expect(rewriteAdvice(statuses(null, ['faq', 'summary', 'h2Answer']))).toBeNull();
expect(rewriteAdvice(statuses(null, ['faq', 'summary', 'h2Answer', 'keywords']))).toEqual({
diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.ts
index a7cb2513f..bfe2ecfc3 100644
--- a/web/src/lib/content/rules.ts
+++ b/web/src/lib/content/rules.ts
@@ -772,6 +772,58 @@ export const REWRITE_OPEN_RULES = 4;
/** The most text a page sent whole may hold (content-rewrite.js MAX_REWRITE_CHARS). */
export const REWRITE_MAX_CHARS = 60_000;
+/**
+ * A Length out of a rewrite's reach: what a rewrite keeps as it is (the
+ * passages AI answers quote, tables, images, quotes, HTML blocks, the
+ * server's keepBlocks) is this share of it or more.
+ */
+export const KEPT_LENGTH_SHARE = 0.85;
+
+/** A long page whose Length a rewrite can't reach, and a Length it could. */
+export interface LengthOutOfReach {
+ count: number;
+ target: number;
+ /** The characters a rewrite keeps as they are. */
+ kept: number;
+ /** A Length with room for the kept blocks and the words around them, to the 500. */
+ suggested: number;
+}
+
+/**
+ * Whether the page is over its Length by more than a rewrite could take out:
+ * the blocks it keeps are KEPT_LENGTH_SHARE of the Length or more. Null
+ * otherwise, and for a page under its Length.
+ */
+export function lengthOutOfReach<T extends { rule: ActiveRule; status: RuleStatus }>(
+ rules: T[],
+ kept: number,
+): LengthOutOfReach | null {
+ const length = rules.find(({ rule }) => rule.key === 'length' && rule.on);
+ const target = Number(length?.rule.current);
+ const status = length?.status;
+ if (
+ status?.state !== 'bad' ||
+ status.code !== 'long' ||
+ !Number.isFinite(target) ||
+ target <= 0
+ ) {
+ return null;
+ }
+ if (kept < target * KEPT_LENGTH_SHARE) return null;
+ // Room for the kept blocks and the words around them, not past the page
+ // as it is (that would read short) nor the rule's own top.
+ const roundUp = (n: number) => Math.ceil(n / 500) * 500;
+ return {
+ count: status.count,
+ target,
+ kept,
+ suggested: Math.min(
+ RULE_LENGTH_MAX,
+ Math.max(target, Math.min(roundUp(kept * 1.5), roundUp(status.count))),
+ ),
+ };
+}
+
/** Why the Rules tab recommends rewriting the page whole. */
export type RewriteAdvice =
| { reason: 'length'; count: number; target: number; percent: number }
@@ -780,10 +832,12 @@ export type RewriteAdvice =
/**
* Whether the Rules tab recommends Rewrite the page to these rules over
* Apply rules with Agent's few edits a run: the page more than 30% off its
- * Length, or 4 rules or more open that the agent can fix. Null otherwise.
+ * Length (one a rewrite can reach, given the `kept` characters it keeps),
+ * or 4 rules or more open that the agent can fix. Null otherwise.
*/
export function rewriteAdvice<T extends { rule: ActiveRule; status: RuleStatus }>(
rules: T[],
+ kept = 0,
): RewriteAdvice | null {
const length = rules.find(({ rule }) => rule.key === 'length' && rule.on);
const target = Number(length?.rule.current);
@@ -799,11 +853,15 @@ export function rewriteAdvice<T extends { rule: ActiveRule; status: RuleStatus }
target > 0
) {
const off = Math.abs(status.count - target) / target;
- if (off > REWRITE_LENGTH_OFF) {
+ if (off > REWRITE_LENGTH_OFF && !lengthOutOfReach(rules, kept)) {
return { reason: 'length', count: status.count, target, percent: Math.round(off * 100) };
}
}
- const open = openRulesForAgent(rules).forAgent.length;
+ // A Length out of reach is no rule a rewrite meets.
+ const outOfReach = lengthOutOfReach(rules, kept) !== null;
+ const open = openRulesForAgent(rules).forAgent.filter(
+ ({ rule }) => !(outOfReach && rule.key === 'length'),
+ ).length;
return open >= REWRITE_OPEN_RULES ? { reason: 'open', count: open } : null;
}