Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(content): one count for the rules and for a rewrite's characters, as the editor shows them (#1521)
Cihane8daeaf7c532
diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.jsindex 3e6689460..d40e15882 100644--- a/server/src/lib/content-writer.js+++ b/server/src/lib/content-writer.js@@ -119,6 +119,12 @@ export const writeDraftInput = z.object({textRules: z.array(z.string().trim().min(1).max(300)).max(50).default([]),/** The passages AI answers quote today, by passageKey (an existing page's). */locked: z.array(z.string().max(5000)).max(500).default([]),+ /**+ * How many rules the editor counts (its "met of total": those it checks on+ * the page), for the run's "Reading N rules" step; the rules sent also+ * hold those only AI can read (tone, language).+ */+ counted: z.number().int().min(0).max(60).optional(),});export const pageSchema = z.object({@@ -796,7 +802,8 @@ function startWritingRun(draft, input, rewrite) {claimedAt: draft.agent_state === 'writing' ? (draft.agent_state_at ?? null) : null,kind: rewrite ? 'rewrite' : draft.method === 'create' ? 'write' : 'fix',counts: {- rules: input.rules.length,+ // As the editor counts them, so the step and its rules chip agree (editor test 2026-10-25).+ rules: input.counted ?? input.rules.length,sources: promptIds.length + fanouts.length + pages.length + queries.length,},});diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.jsindex b18a446ce..868492a71 100644--- a/server/src/lib/content-writer.test.js+++ b/server/src/lib/content-writer.test.js@@ -245,6 +245,18 @@ describe('startDraftWriting', () => {expect(writes.find((w) => w.table === 'content_agent_runs' && w.kind === 'insert').value,).toMatchObject({ kind: 'write', claimed_at: draftUpdates()[0].agent_state_at });+ await vi.waitFor(() => expect(draftUpdates()).toHaveLength(2));+ });++ it('says it reads as many rules as the editor counts, when it says so', async () => {+ await startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input({ counted: 7 }) });+ const run = writes.find((w) => w.table === 'content_agent_runs' && w.kind === 'insert').value;+ expect(run.steps.find((s) => s.key === 'read_rules')).toMatchObject({ count: 7 });+ await vi.waitFor(() => expect(draftUpdates()).toHaveLength(2));+ });++ it('writes the new page for review once claimed', async () => {+ await startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() });await vi.waitFor(() => expect(draftUpdates()).toHaveLength(2));// It ends only its own claim: a newer run's, after a Stop let go, is left alone.diff --git a/web/messages/en.json b/web/messages/en.jsonindex 114e458cc..f739ad4fb 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4416,6 +4416,7 @@"webflowChanged": "{tables, plural, =0 {} one {# table went as a list. } other {# tables went as lists. }}{images, plural, =0 {} one {# image wasn't sent: add it in Webflow.} other {# images weren't sent: add them in Webflow.}}"},"rulesChip": "Rules {met}/{total}",+ "rulesChipReading": "Rules · reading","rulesChipHint": "Rules this page meets now. Open the Rules tab.","reviewer": {"title": "Reviewed by",@@ -5138,6 +5139,7 @@"setName": "{type} · Ansvisor default","pickSet": "Pick a page type","met": "{met} of {total} rules met",+ "metReading": "Reading the rules…","typeGroup": "{type} rules","groups": {"type": "Page type rules",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 6d774db12..7332bb5e1 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@@ -344,6 +344,17 @@ describe('AgentCard', () => {);});+ it('counts a rewrite’s characters as the toolbar does, when the editor gives them', 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: 'cut it',+ });+ await render([page], false, { pageChars: { before: 6_617, after: 5_468 } });+ expect(container.textContent).toContain('6,617 → 5,468 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.tsxindex 564c04be0..690f55904 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@@ -222,6 +222,7 @@ export function AgentCard({onAllSteps,length = null,lastRunFailed = false,+ pageChars = null,}: {suggestions: DraftSuggestion[];rules: CardRules;@@ -270,6 +271,8 @@ export function AgentCard({onAllSteps?: () => void;/** The agent's last run failed: said in place of an earlier batch's review. */lastRunFailed?: boolean;+ /** A rewrite's characters, before and after, as the toolbar counts them (the editor's count). */+ pageChars?: { before: number; after: number } | null;/*** 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.@@ -396,7 +399,7 @@ export function AgentCard({</>);} else if (page) {- const { before, after: afterChars } = pageCharacters(page);+ const { before, after: afterChars } = pageChars ?? pageCharacters(page);title =page.status === 'open'? tRewrite('ready')@@ -677,6 +680,7 @@ export function AgentCard({onOpenChange={setComparing}busy={busy}onDecide={onDecidePage}+ chars={pageChars}/>)}</div>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 33ea5e960..9195957be 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@@ -3,7 +3,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useFormatter, useTranslations } from 'next-intl';import { toast } from 'sonner';-import { getHTMLFromFragment } from '@tiptap/core';+import { createDocument, getHTMLFromFragment } from '@tiptap/core';import { EditorContent, useEditor, type Editor } from '@tiptap/react';import type { Node as PmNode } from '@tiptap/pm/model';import { TextSelection, type Transaction } from '@tiptap/pm/state';@@ -656,6 +656,15 @@ export function DraftEditor({editor && citedRead? rewriteFloor(editor.state, { summary: summaryAsked }): { kept: 0, floor: 0 };+ // A page's characters as the toolbar counts them (the editor's own+ // count), for a rewrite's before and after (editor test 2026-10-25: the+ // card said 6,725 → 5,571 where the counter said 6,617 → 5,468).+ const htmlChars = (html: string) =>+ editor && !editor.isDestroyed+ ? ((editor.storage.characterCount.characters({+ node: createDocument(html, editor.schema),+ }) as number | undefined) ?? pageTextLength(html))+ : pageTextLength(html);// 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);@@ -1741,11 +1750,11 @@ export function DraftEditor({.map(({ rule }) => rule.key),});// A whole page rewritten: its Length is its own line on the card (read- // the same way, pageTextLength), so it isn't named again as broken.+ // the same way, the editor's count), so it isn't named again as broken.if (page) {return {each: new Map<string, string[]>(),- all: effect(check(page.afterText, pageTextLength(page.afterText)), ['length']),+ all: effect(check(page.afterText, htmlChars(page.afterText)), ['length']),};}const each = new Map<string, string[]>();@@ -1941,7 +1950,33 @@ export function DraftEditor({cancelled = true;};}, [draft.id, shownRewriteId]);- const reach: RewriteReach = { kept: keptChars, floor: floorChars, last: lastRewrite };+ // A rewrite's characters, before and after, as the toolbar counts them.+ const pageChars = useMemo(+ () =>+ pageSuggestion+ ? {+ before: htmlChars(pageSuggestion.beforeHtml ?? ''),+ after: htmlChars(pageSuggestion.afterText),+ }+ : null,+ // eslint-disable-next-line react-hooks/exhaustive-deps -- the rewrite's two pages, once+ [pageSuggestion?.id, pageSuggestion?.afterText, pageSuggestion?.beforeHtml, editor],+ );+ // The rewrite shown, counted as the toolbar counts it, not as the API did:+ // its Length band is the editor's.+ const lastCounted =+ lastRewrite && pageChars && lastRewrite.id === pageSuggestion?.id+ ? { ...lastRewrite, chars: pageChars.after }+ : lastRewrite;+ const reach: RewriteReach = { kept: keptChars, floor: floorChars, last: lastCounted };+ // The rules' count stands once My rules and the fan-outs (the fan-out+ // rules' own) are read: before, rules come and go from it.+ const rulesSettled =+ rules.ready &&+ reads.sources !== null &&+ // The keywords rule reads the brief, the feed rule the catalog.+ reads.brief.status !== 'loading' &&+ (!feedOn || catalog !== undefined);// Open rules no run can close on this page (editor test 2026-10-25): every// long sentence inside a passage AI answers quote, a Length out of a// rewrite's reach. They leave the agent's work and Next step; the Rules tab@@ -1969,6 +2004,8 @@ export function DraftEditor({[heldKey],);// The rules as the agent card counts its gain: met now, and the ones still open.+ // The rules as the side panel shows them: their count once it stands.+ const rulesShown = { ...rules, settled: rulesSettled };const effect = ruleEffects?.all ?? null;const cardRules = useMemo(() => ({@@ -1979,7 +2016,8 @@ export function DraftEditor({.filter(({ rule, status }) => rule.on && status.state === 'bad').map(({ rule }) => rule.key),),- ...(effect+ // The gain once the count stands: never one a read still to land moves.+ ...(effect && rulesSettled? {after: {now: effect.now,@@ -1989,7 +2027,7 @@ export function DraftEditor({}: {}),}),- [rules.met, rules.total, rules.rules, effect], // eslint-disable-line react-hooks/exhaustive-deps+ [rules.met, rules.total, rules.rules, effect, rulesSettled], // eslint-disable-line react-hooks/exhaustive-deps);/**@@ -2792,7 +2830,11 @@ export function DraftEditor({textRules: rules.textRules.filter(({ rule }) => rule.on).map(({ rule }) => rule.text),},);- const result = await startAgentWriting(draft.id, draft.brandId, request);+ const result = await startAgentWriting(draft.id, draft.brandId, {+ ...request,+ // "Reading N rules" says what the rules chip counts.+ counted: rulesSettled ? rules.total : undefined,+ });if ('error' in result) {toast.error(t(`agentFailed.errors.${result.error}`));return;@@ -2871,7 +2913,11 @@ export function DraftEditor({const now = `${tRules('agent.now')}: ${ruleStatusDetail(tStatus, status)}`;return { ...rule, detail: [rule.detail, now].filter(Boolean).join(' · ').slice(0, 500) };});- const result = await startPageRewrite(draft.id, draft.brandId, request);+ const result = await startPageRewrite(draft.id, draft.brandId, {+ ...request,+ // "Reading N rules" says what the rules chip counts.+ counted: rulesSettled ? rules.total : undefined,+ });if ('error' in result) {toast.error(t(`agentFailed.errors.${result.error}`));return;@@ -3565,16 +3611,26 @@ export function DraftEditor({type="button"onClick={() => openPanelTab('rules')}title={t('rulesChipHint')}- aria-label={t('rulesChip', { met: rules.met, total: rules.total })}+ aria-label={+ rulesSettled+ ? t('rulesChip', { met: rules.met, total: rules.total })+ : t('rulesChipReading')+ }className={cn('inline-flex h-5 shrink-0 items-center gap-1.5 rounded-full border px-2 text-xs font-medium',- rules.total > 0 && rules.met === rules.total- ? 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300'- : 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300',+ !rulesSettled+ ? 'text-muted-foreground'+ : rules.total > 0 && rules.met === rules.total+ ? 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300'+ : 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300',)}><span aria-hidden className="h-1.5 w-1.5 rounded-full bg-current" />- {t('rulesChip', { met: rules.met, total: rules.total })}+ {/* One count once the set and the fan-outs are read (editor test+ 2026-10-25: 8 of 12 on first paint, then 11 of 15). */}+ {rulesSettled+ ? t('rulesChip', { met: rules.met, total: rules.total })+ : t('rulesChipReading')}</button>{qualityOn && shownQuality === null && (<button@@ -3741,6 +3797,7 @@ export function DraftEditor({}// The kept blocks are named only when they put the Length out of reach.length={length && { ...length, outOfReach: keptOutOfReach(rules.rules, reach) }}+ pageChars={pageChars}onAllSteps={() => {setNextFocus(true);setNextOpen(true);@@ -3827,7 +3884,7 @@ export function DraftEditor({title={title}bodyHtml={pageHtml}pageType={pageType}- rules={rules}+ rules={rulesShown}reads={reads}tabRequest={tabRequest}agentFix={agentFix}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.tsxindex f2cbc17aa..d55951a7d 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.tsx@@ -94,15 +94,18 @@ export function PageCompareDialog({onOpenChange,busy,onDecide,+ chars = null,}: {suggestion: DraftSuggestion;open: boolean;onOpenChange: (open: boolean) => void;busy: boolean;onDecide: (status: SuggestionStatus) => void;+ /** Its characters as the toolbar counts them, when the editor gives them. */+ chars?: { before: number; after: number } | null;}) {const t = useTranslations('contentEditor.editor.rewrite');- const { before, after } = pageCharacters(suggestion);+ const { before, after } = chars ?? pageCharacters(suggestion);const decide = (status: SuggestionStatus) => {onOpenChange(false);onDecide(status);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.tsxindex 3e1e6a8ac..faf8b91e0 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@@ -432,7 +432,9 @@ export function RulesTab({</SelectContent></Select><p className="text-xs text-muted-foreground" role="status">- {t('met', { met: state.met, total: state.total })}+ {state.settled === false+ ? t('metReading')+ : t('met', { met: state.met, total: state.total })}</p></div>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 bb3956dd9..1d07fa9d6 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@@ -252,7 +252,8 @@ export function EditorSidePanel({prev.has(next) && prev.has(nextTab) ? prev : new Set([...prev, next, nextTab]),);};- const rulesOpen = Math.max(0, rules.total - rules.met);+ // None said while the count is still read (the header's chip says so).+ const rulesOpen = rules.settled === false ? 0 : Math.max(0, rules.total - rules.met);// Quality shows once its first phase is live (NEXT_PUBLIC_CONTENT_QUALITY_PHASE).const segments = SEGMENTS.filter((value) => value !== 'quality' || qualityPhase() >= 1);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.tsindex b4ac92d68..f65194eeb 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts@@ -49,6 +49,11 @@ export interface DraftRulesState {total: number;/** The page length the rules ask for. */length: number;+ /**+ * Whether the count stands (set by the editor once the set, the fan-outs,+ * the brief and the catalog are read): before, rules come and go from it.+ */+ settled?: boolean;/** The sections and questions the rules ask for take more than Length allows. */lengthConflict: { need: number; max: number } | null;/**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 effc92f5d..8d069dfe4 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@@ -2599,6 +2599,15 @@ describe('the side panel', () => {expect(panel()!.textContent).toContain('Not used by Content Agent yet');});+ it('holds the rules chip’s count until the rule set and the fan-outs are read', async () => {+ getContentDraft.mockResolvedValue(draft());+ getDraftSources.mockReturnValue(new Promise(() => {}));+ await renderPage();+ // 8 of 12 then 11 of 15 on first paint (editor test 2026-10-25): no count until it stands.+ const chip = container.querySelector<HTMLButtonElement>('header button[aria-label^="Rules "]')!;+ expect(chip.getAttribute('aria-label')).toBe('Rules · reading');+ });+it('shows how many rules the page meets, and opens them from the header', async () => {getContentDraft.mockResolvedValue(draft({diff --git a/web/src/lib/actions/content-drafts-rewrite.test.ts b/web/src/lib/actions/content-drafts-rewrite.test.tsindex 00245dc7c..2de313442 100644--- a/web/src/lib/actions/content-drafts-rewrite.test.ts+++ b/web/src/lib/actions/content-drafts-rewrite.test.ts@@ -37,13 +37,14 @@ beforeEach(() => {describe('getLastPageRewrite', () => {it('reads the numbers of the latest page rewrite, not the page', async () => {- row = { after_chars: 5_468, length_target: 4_000, kept_chars: 3_125 };+ row = { id: 'p1', after_chars: 5_468, length_target: 4_000, kept_chars: 3_125 };await expect(getLastPageRewrite(DRAFT)).resolves.toEqual({+ id: 'p1',chars: 5_468,target: 4_000,kept: 3_125,});- expect(selected).toBe('after_chars, length_target, kept_chars');+ expect(selected).toBe('id, after_chars, length_target, kept_chars');expect(filters).toEqual([['draft_id', DRAFT],['kind', 'page'],@@ -54,8 +55,9 @@ describe('getLastPageRewrite', () => {await expect(getLastPageRewrite(DRAFT)).resolves.toBeNull();row = { after_chars: null, length_target: null, kept_chars: null };await expect(getLastPageRewrite(DRAFT)).resolves.toBeNull();- row = { after_chars: 6_000, length_target: null, kept_chars: 900 };+ row = { id: 'p2', after_chars: 6_000, length_target: null, kept_chars: 900 };await expect(getLastPageRewrite(DRAFT)).resolves.toEqual({+ id: 'p2',chars: 6_000,target: null,kept: 900,diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 4a066e3fb..72add5045 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -1868,7 +1868,7 @@ export async function getLastPageRewrite(id: string): Promise<LastRewrite | nullconst supabase = await createClient();const { data, error } = await supabase.from('content_draft_suggestions')- .select('after_chars, length_target, kept_chars')+ .select('id, after_chars, length_target, kept_chars').eq('draft_id', id).eq('kind', 'page').order('created_at', { ascending: false })@@ -1876,7 +1876,12 @@ export async function getLastPageRewrite(id: string): Promise<LastRewrite | null.maybeSingle();if (error) throw new Error(error.message);if (!data || data.after_chars === null || data.kept_chars === null) return null;- return { chars: data.after_chars, target: data.length_target, kept: data.kept_chars };+ return {+ id: data.id,+ chars: data.after_chars,+ target: data.length_target,+ kept: data.kept_chars,+ };}/**diff --git a/web/src/lib/content/agent-write.ts b/web/src/lib/content/agent-write.tsindex a519dd752..6c8445980 100644--- a/web/src/lib/content/agent-write.ts+++ b/web/src/lib/content/agent-write.ts@@ -31,6 +31,8 @@ export interface AgentWriteRequest {rules: { key: string; name: string; detail: string }[];textRules: string[];locked: string[];+ /** How many rules the editor counts ("met of total"): the run's "Reading N rules" says the same. */+ counted?: number;}/** The server's limit on rules (content-writer.js writeDraftInput). */diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.tsindex 61053f383..4149a6726 100644--- a/web/src/lib/content/rules.ts+++ b/web/src/lib/content/rules.ts@@ -838,6 +838,8 @@ export const REWRITE_MAX_CHARS = 60_000;/** The page's last rewrite, as the API keeps it (00285). */export interface LastRewrite {+ /** Its suggestion's id, so the one shown is counted as the toolbar counts it. */+ id?: string;/** The characters it came to. */chars: number;/** The Length it was written to; null with Length off. */