Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(content): put brief and rules under one Instructions tab with a split Run Agent (CE-028–CE-031) (#1396)

Cihanc9a9bbc68694
diff --git a/web/messages/en.json b/web/messages/en.json
index 2e6b0e893..c2f73402e 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3599,10 +3599,13 @@
"open_suggestions": "Accept or reject the open suggestions first, then try again.",
"not_draft": "This draft is no longer a draft, so the agent didn't start.",
"empty": "The page has no text to rewrite yet.",
- "too_long": "The page is too long to rewrite whole. Use Apply rules with Agent, or shorten it first.",
+ "too_long": "The page is too long to rewrite whole. Use Fix open rules, or shorten it first.",
"failed": "The agent couldn't start. Try again in a moment."
}
},
+ "run": {
+ "about": "What Run Agent does"
+ },
"agentCard": {
"waiting": "{count, plural, one {Content Agent has # suggestion for you} other {Content Agent has # suggestions for you}}",
"gain": "Rules {met, number} → {after, number} of {total, number}",
@@ -3664,7 +3667,7 @@
"fixedMax": "Content Agent suggested {count} changes, the most one run makes · review them, then run it again for the rules still open",
"nothingToFix": "Content Agent found nothing it could change without new facts.",
"notForAgent": "Content Agent doesn't change heading levels: make the extra H1s H2s in the toolbar.",
- "decideFirst": "Accept or reject the open suggestions first.",
+ "decideFirst": "{count, plural, one {Review the open suggestion first, then run the agent.} other {Review the open suggestions first, then run the agent.}}",
"citedLoading": "Reading which passages AI quotes, so the agent leaves them as they are…",
"agentBusy": "Content Agent is already working on this page. Wait for it to finish.",
"fixErrors": {
@@ -3769,7 +3772,7 @@
"html": "Edit as HTML",
"htmlBack": "Back to visual",
"openLink": "Open the link in a new tab (or ⌘/Ctrl + click it in the page)",
- "counter": "{count} / {target} characters"
+ "counter": "{count} / {target} characters · {words, plural, one {# word} other {# words}}"
},
"link": {
"title": "Add a link",
@@ -3795,11 +3798,17 @@
"show": "Show side panel",
"hide": "Hide side panel",
"openTab": "Open {tab} in the side panel",
+ "openRules": "{count, plural, one {# rule open} other {# rules open}}",
"tabs": {
- "impact": "Live page",
- "brief": "Brief",
+ "instructions": "Instructions",
"sources": "Sources",
- "rules": "Rules"
+ "impact": "Live page"
+ },
+ "segmentsLabel": "Brief or rules",
+ "segments": {
+ "brief": "Brief",
+ "rules": "Rules",
+ "open": "{count, number} open"
}
},
"impact": {
@@ -3951,19 +3960,28 @@
"pageType": "Page type",
"targetUrl": "Target URL",
"newPage": "A new page",
- "notSet": "Not set",
+ "notSet": "Not set yet",
"goal": "Goal",
"audience": "Audience",
"length": "Length",
- "lengthValue": "{count} characters · from the rules",
+ "lengthValue": "{count} characters · ~{words} words",
+ "lengthFrom": "From the rules",
"outline": "Outline",
"answers": "Answers “{fanout}”",
"keywords": "Keywords",
- "empty": "No outline yet. Rebuild outline writes one from the sources you keep, each H2 answering a search AI ran.",
- "fromOpportunity": "From the opportunity's brief. Rebuild outline maps each H2 to a fan-out.",
+ "empty": "Empty. Run Agent to draft one, or add H2s yourself.",
+ "emptyOutline": "No H2s yet. Rebuild brief to draft them, or add H2s yourself.",
+ "fromOpportunity": "From the opportunity's brief. Rebuild brief maps each H2 to a fan-out.",
"edited": "Edited by you.",
"builtFrom": "{count, plural, one {Built from # source} other {Built from # sources}} · {date}",
- "rebuild": "Rebuild outline",
+ "rebuild": "Rebuild brief",
+ "run": "Run Agent",
+ "info": "Run Agent writes the goal, audience and outline from your sources.",
+ "status": {
+ "empty": "No brief yet",
+ "emptyDetail": "Goal, audience and outline are empty.",
+ "ready": "Brief ready · {count, plural, =0 {no H2s yet} one {# H2} other {# H2s}}"
+ },
"rewrite": {
"button": {
"create": "Rewrite from brief",
@@ -3976,12 +3994,11 @@
"start": "Start the agent",
"cancel": "Cancel"
},
- "rebuildEdited": "Rebuild outline writes a new brief over the one you edited.",
+ "rebuildEdited": "Rebuild brief writes a new brief over the one you edited.",
"rebuildAnyway": "Rebuild anyway",
"keepEdited": "Keep my brief",
- "build": "Build brief",
"edit": "Edit brief",
- "usage": "Rebuilding uses your workspace's AI usage.",
+ "usage": "Writing the brief uses your workspace's AI usage.",
"rebuilt": "{count, plural, one {Brief rebuilt from # source} other {Brief rebuilt from # sources}}",
"rebuildErrors": {
"ai_budget": "This month's AI usage is used up. It resets when your subscription renews.",
@@ -4068,7 +4085,7 @@
"measureSteps": "How to measure, as numbered steps"
},
"hints": {
- "length": "A target, not a minimum: within 20% of it meets the rule. A page brought in to optimize starts at its own length. A page well over it is open, and Apply rules with Agent shortens it a few passages at a time.",
+ "length": "A target, not a minimum: within 20% of it meets the rule. A page brought in to optimize starts at its own length. A page well over it is open, and Fix open rules shortens it a few passages at a time.",
"oneH1": "A page has one H1, its title. Make any other H1 an H2 in the toolbar: Content Agent doesn't change heading levels.",
"summary": "A short summary under the H1 that answer engines can quote.",
"fanoutH2": "Takes the top fan-outs you keep in Sources, the most searched first, not every one.",
@@ -4125,13 +4142,28 @@
},
"mineName": "My rules · {type}",
"setPicked": "Rule set changed for this draft",
- "agentFix": "Apply rules with Agent",
- "agentFixing": "Content Agent is working…",
- "agentFixHint": "Content Agent suggests changes for the rules not met yet, for you to review in the page",
- "rewrite": "Rewrite the page to these rules",
- "rewriting": "Content Agent is rewriting…",
- "rewriteHint": "Content Agent rewrites the whole page in one go and shows it beside yours to accept or reject. Passages AI quotes, tables and images stay as they are.",
- "agentsHint": "Apply rules makes small edits, up to {max} a run. Rewrite does the whole page as one change to compare.",
+ "run": {
+ "notMet": "{count, plural, one {# rule is not met} other {# rules are not met}}",
+ "allMet": "All rules are met",
+ "info": "<b>Run Agent</b> fixes the open rules. You review each change. <b>▾ Rewrite page</b> rewrites the whole page. Uses more AI.",
+ "infoFix": "<b>Run Agent</b> fixes the open rules. You review each change.",
+ "names": "{names}{more, select, yes {…} other {}}",
+ "label": "Run Agent",
+ "rewriteLabel": "Rewrite page",
+ "working": "Working…",
+ "more": "More ways to run the agent",
+ "recommendedDetail": "Recommended · {detail}",
+ "fix": {
+ "title": "Fix open rules",
+ "detail": "{count, plural, one {# rule} other {# rules}} · small, reviewable changes",
+ "usage": "Less AI usage"
+ },
+ "rewrite": {
+ "title": "Rewrite the whole page",
+ "detail": "Every rule in “{set}” · one new version, cited passages kept",
+ "usage": "More AI usage"
+ }
+ },
"rewriteAdvice": {
"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."
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx
index bd582b4d2..4c748f17c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx
@@ -110,12 +110,17 @@ afterEach(() => {
describe('the Brief tab', () => {
it('shows the page, the brief and each H2 with the fan-out it answers', async () => {
await render({ status: 'ready', brief });
+ // The card first: the brief is there, so Rebuild brief, the secondary button.
+ expect(container.textContent).toContain('Brief ready · 2 H2s');
+ expect(button('Rebuild brief').className).not.toContain('bg-primary');
+ expect(button('What Run Agent does')).toBeDefined();
expect(fields()).toEqual({
'Page type': 'Buying guide',
'Target URL': '/guides/espresso',
Goal: 'Help home baristas pick a machine',
Audience: 'First-time espresso buyers',
- Length: '3,000 characters · from the rules',
+ // Characters first, as rules count; about as many words next to them.
+ Length: '3,000 characters · ~500 wordsFrom the rules',
});
const sections = [...container.querySelectorAll('ol > li')].map((li) => li.textContent);
expect(sections).toEqual([
@@ -125,41 +130,103 @@ describe('the Brief tab', () => {
expect(container.textContent).toContain('espresso machinegrinder');
expect(container.textContent).toContain('Built from 7 sources');
- await act(async () => button('Rebuild outline').click());
+ await act(async () => button('Rebuild brief').click());
expect(onRebuild).toHaveBeenCalled();
});
it('asks before rebuilding a brief the person edited', async () => {
await render({ status: 'ready', brief: { ...brief, origin: 'edit' } });
- await act(async () => button('Rebuild outline').click());
+ await act(async () => button('Rebuild brief').click());
expect(onRebuild).not.toHaveBeenCalled();
expect(container.querySelector('[role="alert"]')!.textContent).toContain(
- 'Rebuild outline writes a new brief over the one you edited.',
+ 'Rebuild brief writes a new brief over the one you edited.',
);
await act(async () => button('Keep my brief').click());
expect(container.querySelector('[role="alert"]')).toBeNull();
expect(onRebuild).not.toHaveBeenCalled();
- await act(async () => button('Rebuild outline').click());
+ await act(async () => button('Rebuild brief').click());
await act(async () => button('Rebuild anyway').click());
expect(onRebuild).toHaveBeenCalledTimes(1);
});
- it('offers to build a brief for a new page without one', async () => {
+ it('offers Run Agent for a new page without a brief, or H2s added by hand', async () => {
await render(
{ status: 'ready', brief: null },
{ pageType: 'product_page', sourceUrl: null, length: 1200 },
);
+ expect(container.textContent).toContain('No brief yetGoal, audience and outline are empty.');
expect(fields()).toMatchObject({
'Page type': 'Product page',
'Target URL': 'A new page',
- Goal: '—',
- Length: '1,200 characters · from the rules',
+ Goal: 'Not set yet',
+ Audience: 'Not set yet',
+ Length: '1,200 characters · ~200 wordsFrom the rules',
});
- expect(container.textContent).toContain('No outline yet.');
- expect(button('Edit brief')).toBeUndefined();
- await act(async () => button('Build brief').click());
+ expect(container.textContent).toContain('Empty. Run Agent to draft one, or add H2s yourself.');
+ // Run Agent is the black primary while there's nothing to rebuild.
+ expect(button('Run Agent').className).toContain('bg-primary');
+ await act(async () => button('Run Agent').click());
expect(onRebuild).toHaveBeenCalled();
+
+ // Or the person writes the H2s.
+ await act(async () => button('Edit brief').click());
+ expect(container.querySelectorAll('input[aria-label$="heading"]')).toHaveLength(0);
+ expect(button('Add section')).toBeDefined();
+ });
+
+ it('asks right under the card, before rebuilding an edited brief', async () => {
+ await render({ status: 'ready', brief: { ...brief, origin: 'edit' } });
+ await act(async () => button('Rebuild brief').click());
+ // The question sits with the button that asked, before the page type and outline.
+ const alert = container.querySelector('[role="alert"]')!;
+ expect(
+ alert.compareDocumentPosition(container.querySelector('dl')!) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it('says a brief with a goal but no H2s yet can be rebuilt', async () => {
+ await render({ status: 'ready', brief: { ...brief, outline: [] } });
+ expect(container.textContent).toContain('Brief ready · no H2s yet');
+ expect(container.textContent).toContain(
+ 'No H2s yet. Rebuild brief to draft them, or add H2s yourself.',
+ );
+ });
+
+ it('saves H2s added by hand on a draft without a brief', async () => {
+ saveDraftBrief.mockImplementation(async (_id, next: DraftBrief) => ({ ...next }));
+ await render({ status: 'ready', brief: null });
+ await act(async () => button('Edit brief').click());
+ await act(async () => button('Add section').click());
+ const heading = container.querySelector<HTMLInputElement>('input[aria-label$="heading"]')!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(
+ heading,
+ 'What pipeline forecasting is',
+ );
+ heading.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () => button('Save brief').click());
+ expect(saveDraftBrief).toHaveBeenCalledWith(
+ 'd1',
+ expect.objectContaining({
+ goal: '',
+ audience: '',
+ outline: [expect.objectContaining({ heading: 'What pipeline forecasting is' })],
+ }),
+ );
+ expect(onSaved).toHaveBeenCalled();
+ });
+
+ it('runs the agent without asking over an edited brief that is still empty', async () => {
+ await render({
+ status: 'ready',
+ brief: { ...brief, goal: '', audience: '', outline: [], origin: 'edit' },
+ });
+ await act(async () => button('Run Agent').click());
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ expect(onRebuild).toHaveBeenCalledTimes(1);
});
it('says where an opportunity’s brief comes from', async () => {
@@ -248,7 +315,10 @@ describe('the Brief tab', () => {
);
const suggest = button('Suggest changes from brief');
expect(suggest.disabled).toBe(true);
- expect(suggest.title).toBe('Accept or reject the open suggestions first.');
+ // Why, written under the button: not only on hover (v1.1 CE-031).
+ expect(suggest.parentElement!.textContent).toContain(
+ 'Accept or reject the open suggestions first.',
+ );
await render({ status: 'ready', brief }, { rewrite: { run, running: false, blocked: null } });
await act(async () => button('Suggest changes from brief').click());
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
index 2f24ed4d5..c0a8914f1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
@@ -3,7 +3,7 @@
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
-import { Bot, Loader2, Pencil, Plus, RefreshCw, Trash2 } from 'lucide-react';
+import { Bot, Loader2, Pencil, Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
@@ -12,7 +12,10 @@ import { MAX_BRIEF_SECTIONS, builtFromCount, type DraftBrief } from '@/lib/conte
import type { DraftMethod } from '@/lib/content/drafts';
import { platformNames } from '@/lib/content/impact';
import { pagePath } from '@/lib/content/overlap';
+import { wordsForLength } from '@/lib/content/rules';
import { formatDateTime, formatNumber } from '@/lib/format';
+import { cn } from '@/lib/utils';
+import { RunCard } from './_run-card';
/**
* Rewrite from brief: the Content Agent writes the page again from the brief
@@ -33,12 +36,14 @@ export type BriefState =
| { status: 'ready'; brief: DraftBrief | null };
/**
- * The Brief tab (Content Editor CE-007, spec §10): the page type and target
- * address at the top, then the goal, audience and length, and the outline
- * with each H2's fan-out and platform. Rebuild outline writes it from the
- * sources kept; Edit brief changes it by hand. Until the draft has a brief,
- * the opportunity's brief it started from is shown. Rewrite from brief hands
- * the page to the Content Agent with it.
+ * The Brief segment (Content Editor CE-007, spec §10; v1.1 CE-030): a card
+ * saying whether there is a brief, with Run Agent to write it from the
+ * sources kept (Rebuild brief once there is one), then the page type and
+ * target address, the goal, audience and length (in characters, and about
+ * as many words), and the outline with each H2's fan-out and platform. Edit
+ * brief changes it by hand. Until the draft has a brief, the opportunity's
+ * brief it started from is shown. Rewrite from brief hands the page to the
+ * Content Agent with it.
*/
export function BriefTab({
draftId,
@@ -94,11 +99,11 @@ export function BriefTab({
}
const brief = state.brief;
- if (editing && brief) {
+ if (editing) {
return (
<BriefEditor
draftId={draftId}
- brief={brief}
+ brief={brief ?? EMPTY_BRIEF}
onCancel={() => setEditing(false)}
onSaved={(saved) => {
setEditing(false);
@@ -109,22 +114,76 @@ export function BriefTab({
}
const typeLabel = pageType && (tTypes.has(pageType) ? tTypes(pageType) : pageType);
+ // Nothing written yet: Run Agent writes it. Once it is, Rebuild brief.
+ const empty = !brief || (!brief.goal && !brief.audience && brief.outline.length === 0);
+ const rebuild = () => (brief?.origin === 'edit' && !empty ? setConfirming(true) : onRebuild());
return (
<div className="space-y-4 text-sm">
+ <RunCard
+ title={empty ? t('status.empty') : t('status.ready', { count: brief?.outline.length ?? 0 })}
+ detail={empty ? t('status.emptyDetail') : undefined}
+ action={
+ <Button
+ size="sm"
+ variant={empty ? 'default' : 'outline'}
+ className="shrink-0"
+ disabled={rebuilding || confirming}
+ onClick={rebuild}
+ >
+ {rebuilding && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {empty ? t('run') : t('rebuild')}
+ </Button>
+ }
+ info={t('info')}
+ >
+ <p className="text-[11px] text-muted-foreground">{t('usage')}</p>
+ {/* Right under the button that asked, not past the outline. */}
+ {confirming && (
+ <div role="alert" className="space-y-2 rounded-md border px-3 py-2 text-xs">
+ <p>{t('rebuildEdited')}</p>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ setConfirming(false);
+ onRebuild();
+ }}
+ >
+ {t('rebuildAnyway')}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={() => setConfirming(false)}>
+ {t('keepEdited')}
+ </Button>
+ </div>
+ </div>
+ )}
+ </RunCard>
+
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1.5 text-xs">
<dt className="text-muted-foreground">{t('pageType')}</dt>
- <dd>{typeLabel || t('notSet')}</dd>
+ <dd className={cn(!typeLabel && 'text-muted-foreground')}>{typeLabel || t('notSet')}</dd>
<dt className="text-muted-foreground">{t('targetUrl')}</dt>
<dd className="min-w-0 truncate" title={sourceUrl ?? undefined}>
{sourceUrl ? pagePath(sourceUrl) : t('newPage')}
</dd>
<dt className="text-muted-foreground">{t('goal')}</dt>
- <dd>{brief?.goal || '—'}</dd>
+ <dd className={cn(!brief?.goal && 'text-muted-foreground')}>
+ {brief?.goal || t('notSet')}
+ </dd>
<dt className="text-muted-foreground">{t('audience')}</dt>
- <dd>{brief?.audience || '—'}</dd>
+ <dd className={cn(!brief?.audience && 'text-muted-foreground')}>
+ {brief?.audience || t('notSet')}
+ </dd>
<dt className="text-muted-foreground">{t('length')}</dt>
- <dd>{t('lengthValue', { count: formatNumber(length) })}</dd>
+ <dd>
+ {t('lengthValue', {
+ count: formatNumber(length),
+ words: formatNumber(wordsForLength(length)),
+ })}
+ <span className="block text-muted-foreground">{t('lengthFrom')}</span>
+ </dd>
</dl>
{brief && brief.outline.length > 0 ? (
@@ -165,7 +224,7 @@ export function BriefTab({
</section>
) : (
<p className="rounded-lg border border-dashed px-3 py-2 text-xs text-muted-foreground">
- {t('empty')}
+ {empty ? t('empty') : t('emptyOutline')}
</p>
)}
@@ -182,7 +241,7 @@ export function BriefTab({
</section>
)}
- {brief && (
+ {brief && !empty && (
<p className="text-[11px] text-muted-foreground">
{brief.origin === 'opportunity'
? t('fromOpportunity')
@@ -217,69 +276,48 @@ export function BriefTab({
</div>
</div>
) : (
- <Button
- size="sm"
- className="w-full"
- disabled={rewrite.running || rewrite.blocked !== null || rebuilding}
- title={rewrite.blocked ?? undefined}
- onClick={() => setConfirmingRewrite(true)}
- >
- {rewrite.running ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Bot className="h-3.5 w-3.5" />
- )}
- {t(`rewrite.button.${method}`)}
- </Button>
- ))}
-
- {confirming && (
- <div role="alert" className="space-y-2 rounded-md border px-3 py-2 text-xs">
- <p>{t('rebuildEdited')}</p>
- <div className="flex flex-wrap gap-2">
+ <div className="space-y-1.5">
<Button
size="sm"
- variant="outline"
- onClick={() => {
- setConfirming(false);
- onRebuild();
- }}
+ className="w-full"
+ disabled={rewrite.running || rewrite.blocked !== null || rebuilding}
+ onClick={() => setConfirmingRewrite(true)}
>
- {t('rebuildAnyway')}
- </Button>
- <Button size="sm" variant="ghost" onClick={() => setConfirming(false)}>
- {t('keepEdited')}
+ {rewrite.running ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Bot className="h-3.5 w-3.5" />
+ )}
+ {t(`rewrite.button.${method}`)}
</Button>
+ {/* Why it waits, written out (v1.1 CE-031), not only on hover. */}
+ {!rewrite.running && rewrite.blocked && (
+ <p className="text-xs text-amber-700 dark:text-amber-400">{rewrite.blocked}</p>
+ )}
</div>
- </div>
- )}
+ ))}
<div className="flex flex-wrap gap-2">
- <Button
- size="sm"
- variant="outline"
- disabled={rebuilding || confirming}
- onClick={() => (brief?.origin === 'edit' ? setConfirming(true) : onRebuild())}
- >
- {rebuilding ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <RefreshCw className="h-3.5 w-3.5" />
- )}
- {brief ? t('rebuild') : t('build')}
+ <Button size="sm" variant="ghost" disabled={rebuilding} onClick={() => setEditing(true)}>
+ <Pencil className="h-3.5 w-3.5" />
+ {t('edit')}
</Button>
- {brief && (
- <Button size="sm" variant="ghost" disabled={rebuilding} onClick={() => setEditing(true)}>
- <Pencil className="h-3.5 w-3.5" />
- {t('edit')}
- </Button>
- )}
</div>
- <p className="text-[11px] text-muted-foreground">{t('usage')}</p>
</div>
);
}
+/** What Edit brief starts from when the draft has no brief: H2s added by hand. */
+const EMPTY_BRIEF: DraftBrief = {
+ goal: '',
+ audience: '',
+ outline: [],
+ keywords: [],
+ origin: 'edit',
+ builtAt: null,
+ builtFrom: null,
+};
+
/** Edit brief: goal, audience, the outline's sections and key points, keywords. */
function BriefEditor({
draftId,
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 32533e9fe..6ee73e285 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
@@ -85,7 +85,12 @@ import { PageTypeMenu } from './_page-type-menu';
import type { AgentRewrite } from './_brief-tab';
import { ruleStatusDetail, type AgentFix, type PageRewrite } from './_rules-tab';
import { pageChangedSince } from './_page-rewrite';
-import { EditorPanelRail, EditorSidePanel, useSidePanelOpen, type PanelTab } from './_side-panel';
+import {
+ EditorPanelRail,
+ EditorSidePanel,
+ useSidePanelOpen,
+ type PanelTarget,
+} from './_side-panel';
import {
AgentSuggestions,
acceptInto,
@@ -174,7 +179,7 @@ export function DraftEditor({
draft: ContentDraft;
/**
* The Content Agent took the draft again (Try again, Rewrite from brief, or
- * Rewrite the page to these rules): the page waits for it.
+ * Rewrite the whole page): the page waits for it.
*/
onAgentStarted?: (run: 'write' | 'rewrite') => void;
}) {
@@ -237,8 +242,8 @@ export function DraftEditor({
const [panelOpen, togglePanel] = useSidePanelOpen();
// The header's rules chip opens the panel on Rules, and the closed panel's
// strip on the tab picked there.
- const [tabRequest, setTabRequest] = useState<{ tab: PanelTab; n: number } | null>(null);
- const openPanelTab = (tab: PanelTab) => {
+ const [tabRequest, setTabRequest] = useState<{ tab: PanelTarget; n: number } | null>(null);
+ const openPanelTab = (tab: PanelTarget) => {
if (!panelOpen) togglePanel();
setTabRequest((prev) => ({ tab, n: (prev?.n ?? 0) + 1 }));
};
@@ -464,7 +469,7 @@ export function DraftEditor({
useEffect(() => {
suggestionsNow.current = suggestions;
if (!editor || editor.isDestroyed) return;
- // A whole page (Rewrite the page to these rules) has its own bar, not a card.
+ // A whole page (Rewrite the whole page) has its own bar, not a card.
const cards = suggestions.filter((s) => s.kind !== 'page');
editor.view.dispatch(
editor.state.tr.setMeta(suggestionsKey, { suggestions: cards, labels: suggestionLabels }),
@@ -607,7 +612,7 @@ export function DraftEditor({
};
/**
- * A whole page rewritten (Rewrite the page to these rules): Accept puts it
+ * A whole page rewritten (Rewrite the whole page): Accept puts it
* in place of the page the agent read (History keeps that first), Reject
* leaves the page, and Undo puts the page back. A page changed since
* isn't written over: the person runs the rewrite again.
@@ -677,7 +682,7 @@ export function DraftEditor({
// One agent run at a time, and never before the locked passages are read.
if (!editor || fixing || starting || rewriting || !citedRead) return;
if (openSuggestions > 0) {
- toast(t('suggestions.decideFirst'));
+ toast(t('suggestions.decideFirst', { count: openSuggestions }));
return;
}
const { forAgent: open, notForAgent } = openRulesForAgent(rules.rules, only);
@@ -769,7 +774,7 @@ export function DraftEditor({
running: fixing,
blocked:
openSuggestions > 0
- ? t('suggestions.decideFirst')
+ ? t('suggestions.decideFirst', { count: openSuggestions })
: !citedRead
? t('suggestions.citedLoading')
: agentBusy && !fixing
@@ -928,7 +933,7 @@ export function DraftEditor({
running: starting,
blocked:
openSuggestions > 0
- ? t('suggestions.decideFirst')
+ ? t('suggestions.decideFirst', { count: openSuggestions })
: agentBusy && !starting
? t('suggestions.agentBusy')
: null,
@@ -936,7 +941,7 @@ export function DraftEditor({
: undefined;
/**
- * Rewrite the page to these rules: the page as saved now, the rules in
+ * Rewrite the whole page: the page as saved now, the rules in
* effect here (with how the page reads against each), the person's own
* rules and the passages still locked go to the Content Agent, which
* rewrites the whole page in the background; the page waits for it, then
@@ -969,7 +974,7 @@ export function DraftEditor({
// The passages still locked here, the ones the person didn't unlock.
[...locks.labels.keys()].filter((key) => !locks.unlocked.has(key)),
);
- // Each rule says how the page reads now, as Apply rules with Agent's do.
+ // Each rule says how the page reads now, as Fix open rules' do.
const statusOf = new Map(inEffect.map(({ rule, status }) => [rule.key, status]));
request.rules = request.rules.map((rule) => {
const status = statusOf.get(rule.key);
@@ -996,7 +1001,7 @@ export function DraftEditor({
running: rewriting,
blocked:
openSuggestions > 0
- ? t('suggestions.decideFirst')
+ ? t('suggestions.decideFirst', { count: openSuggestions })
: !citedRead
? t('suggestions.citedLoading')
: agentBusy && !rewriting
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 32924141c..f9ab31289 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
@@ -98,41 +98,153 @@ afterEach(() => {
});
describe('the Rules tab', () => {
- it('puts the agent’s two ways first, and recommends a rewrite far from Length', async () => {
- const fix = { run: vi.fn(), running: false, blocked: null };
- const rewrite = { run: vi.fn(), running: false, blocked: null };
- const show = async (props: Partial<Parameters<typeof RulesTab>[0]>) =>
+ describe('Run Agent', () => {
+ const fix = () => ({ run: vi.fn(), running: false, blocked: null as string | null });
+ const show = async (props: Partial<Parameters<typeof RulesTab>[0]>, s = state()) =>
act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages}>
<RoleProvider role="admin">
- <RulesTab state={state()} siteType="b2b" draftPageType="feature_page" {...props} />
+ <RulesTab state={s} siteType="b2b" draftPageType="feature_page" {...props} />
</RoleProvider>
</NextIntlClientProvider>,
);
});
- await show({ agentFix: fix, pageRewrite: rewrite });
- const labels = [...container.querySelectorAll('button')].map((b) => b.textContent);
- expect(labels.slice(0, 2)).toEqual([
- 'Apply rules with Agent',
- 'Rewrite the page to these rules',
- ]);
- const rewriteButton = () =>
- [...container.querySelectorAll('button')].find(
- (b) => b.textContent === 'Rewrite the page to these rules',
- )!;
- // 15,921 characters for a 3,000 Length.
- expect(container.querySelector('[role="note"]')!.textContent).toBe(
- 'Recommended: the page is 15,921 characters for a Length of 3,000 (431% off). A rewrite gets there in one go.',
- );
- await act(async () => rewriteButton().click());
- expect(rewrite.run).toHaveBeenCalled();
-
- // Suggestions still open: it says why it can't run.
- await show({ agentFix: fix, pageRewrite: { ...rewrite, blocked: 'Decide first' } });
- const blocked = rewriteButton();
- expect(blocked.disabled).toBe(true);
- expect(blocked.title).toBe('Decide first');
+ const buttons = () => [...container.querySelectorAll('button')];
+ const main = () =>
+ buttons().find((b) => ['Run Agent', 'Rewrite page', 'Working…'].includes(b.textContent!))!;
+ const trigger = () =>
+ container.querySelector<HTMLButtonElement>('[aria-label="More ways to run the agent"]')!;
+ const items = () => [...document.body.querySelectorAll<HTMLElement>('[role="menuitemradio"]')];
+ const reason = () => container.querySelector('[role="status"]')!;
+ const openRules = () =>
+ state().rules.filter(({ rule, status }) => rule.on && status.state === 'bad');
+
+ it('opens with the open rules and one split button, recommending a rewrite far from Length', async () => {
+ const agentFix = fix();
+ const pageRewrite = fix();
+ await show({ agentFix, pageRewrite });
+ // The card first: what's open, the split button, then the ⓘ.
+ expect(
+ buttons()
+ .map((b) => b.getAttribute('aria-label') ?? b.textContent)
+ .slice(0, 3),
+ ).toEqual(['Run Agent', 'More ways to run the agent', 'What Run Agent does']);
+ const open = openRules();
+ expect(container.textContent).toContain(`${open.length} rules are not met`);
+ // The first three by name, then "…".
+ const names = open.slice(0, 3).map(({ rule }) => rule.key);
+ expect(names).toHaveLength(3);
+ expect(container.textContent).toMatch(/rules are not met[^,]+, [^,]+, [^…]+…/);
+ // 15,921 characters for a 3,000 Length.
+ expect(container.querySelector('[role="note"]')!.textContent).toBe(
+ 'Recommended: the page is 15,921 characters for a Length of 3,000 (431% off). A rewrite gets there in one go.',
+ );
+ // Nothing in the way: the reason line is there for screen readers, empty.
+ expect(reason().textContent).toBe('');
+
+ // The main part runs the safe default: fix the open rules.
+ await act(async () => main().click());
+ expect(agentFix.run).toHaveBeenCalledTimes(1);
+ expect(pageRewrite.run).not.toHaveBeenCalled();
+
+ // ▾ offers both, Fix checked and the rewrite recommended here.
+ await act(async () => trigger().click());
+ expect(items().map((item) => [item.textContent, item.getAttribute('aria-checked')])).toEqual([
+ [`Fix open rules${open.length} rules · small, reviewable changesLess AI usage`, 'true'],
+ [
+ 'Rewrite the whole pageRecommended · Every rule in “Feature page · Ansvisor default” · one new version, cited passages keptMore AI usage',
+ 'false',
+ ],
+ ]);
+ // Picking the rewrite renames the button; once it runs, Fix is the default again.
+ await act(async () => items()[1].click());
+ expect(main().textContent).toBe('Rewrite page');
+ await act(async () => main().click());
+ expect(pageRewrite.run).toHaveBeenCalledTimes(1);
+ expect(main().textContent).toBe('Run Agent');
+ });
+
+ it('says why its choice waits under the card, for the choice picked', async () => {
+ const agentFix = {
+ ...fix(),
+ blocked: 'Review the open suggestions first, then run the agent.',
+ };
+ const pageRewrite = fix();
+ await show({ agentFix, pageRewrite });
+ expect(main().disabled).toBe(true);
+ expect(reason().textContent).toBe('Review the open suggestions first, then run the agent.');
+
+ // The rewrite isn't held up: picking it clears the reason.
+ await act(async () => trigger().click());
+ await act(async () => items()[1].click());
+ expect(main().textContent).toBe('Rewrite page');
+ expect(main().disabled).toBe(false);
+ expect(reason().textContent).toBe('');
+ });
+
+ it('shows the agent working, with ▾ closed until it is done', async () => {
+ await show({ agentFix: { ...fix(), running: true }, pageRewrite: fix() });
+ expect(main().textContent).toBe('Working…');
+ expect(main().disabled).toBe(true);
+ expect(trigger().disabled).toBe(true);
+ });
+
+ it('offers only the rewrite when the agent can fix none of the open rules', async () => {
+ // Only One H1 is open: Content Agent doesn't change heading levels.
+ const s = state();
+ const onlyH1 = {
+ ...s,
+ rules: s.rules.map((r) =>
+ r.rule.key === 'oneH1'
+ ? {
+ ...r,
+ rule: { ...r.rule, on: true },
+ status: { state: 'bad' as const, code: 'current' as const, count: 2 },
+ }
+ : r.status.state === 'bad'
+ ? { ...r, status: { state: 'ok' as const } }
+ : r,
+ ),
+ } as DraftRulesState;
+ await show({ agentFix: fix(), pageRewrite: fix() }, onlyH1);
+ expect(container.textContent).toContain('1 rule is not met');
+ expect(main().disabled).toBe(true);
+ expect(reason().textContent).toBe(
+ "Content Agent doesn't change heading levels: make the extra H1s H2s in the toolbar.",
+ );
+ await act(async () => trigger().click());
+ expect(items()[0].getAttribute('aria-disabled')).toBe('true');
+ // Nothing turned off is recommended, and the page is near Length: no rewrite advice.
+ expect(
+ items()
+ .map((item) => item.textContent)
+ .join(' '),
+ ).not.toContain('Recommended');
+ });
+
+ it('says all rules are met, with nothing to run', async () => {
+ const s = state();
+ const met = {
+ ...s,
+ rules: s.rules.map((r) =>
+ r.status.state === 'bad' ? { ...r, status: { state: 'ok' as const } } : r,
+ ),
+ } as DraftRulesState;
+ await show({ agentFix: fix(), pageRewrite: fix() }, met);
+ expect(container.textContent).toContain('All rules are met');
+ expect(main()).toBeUndefined();
+ expect(trigger()).toBeNull();
+ });
+
+ it('keeps Run Agent plain without a rewrite (a page ready or published)', async () => {
+ const agentFix = fix();
+ await show({ agentFix });
+ expect(trigger()).toBeNull();
+ expect(container.querySelector('[role="note"]')).toBeNull();
+ await act(async () => main().click());
+ expect(agentFix.run).toHaveBeenCalled();
+ });
});
it('lists the page type’s rules, then the shared groups, each with its status', async () => {
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 6bc75c95f..96950916d 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
@@ -1,9 +1,16 @@
'use client';
import { useState } from 'react';
-import { useTranslations } from 'next-intl';
-import { Bot, FileText, Loader2, Sparkles } from 'lucide-react';
+import { useFormatter, useTranslations } from 'next-intl';
+import { ChevronDown, Loader2, Sparkles } from 'lucide-react';
import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
import {
Dialog,
DialogContent,
@@ -25,6 +32,7 @@ import { SITE_PAGE_TYPES, type SiteType } from '@/lib/content/page-types';
import {
MAX_TEXT_RULE_LENGTH,
RULE_GROUPS,
+ openRulesForAgent,
rewriteAdvice,
splitRules,
type ActiveRule,
@@ -32,9 +40,9 @@ import {
type TextRule,
} from '@/lib/content/rules';
import { formatNumber } from '@/lib/format';
-import { AGENT_RUN_MAX } from '@/lib/content/suggestions';
import { cn } from '@/lib/utils';
import { useUserRole } from '@/hooks/use-user-role';
+import { RunCard } from './_run-card';
import type { DraftRulesState } from './_use-draft-rules';
/** Rules with an explanation on hover (spec §10). */
@@ -61,7 +69,7 @@ const HINTED = new Set([
* ("Your text rules"); Save as my rules keeps the set for the workspace's
* drafts of the type, and Reset goes back to Ansvisor's default.
*/
-/** Apply rules with Agent (CE-018), as the editor runs it. */
+/** Fix open rules with the agent (CE-018), as the editor runs it. */
export interface AgentFix {
/** Runs the agent on the open rules, or only on the ones named. */
run: (only?: string[]) => void;
@@ -70,7 +78,7 @@ export interface AgentFix {
blocked: string | null;
}
-/** Rewrite the page to these rules, as the editor runs it: the whole page, one suggestion. */
+/** Rewrite the whole page to these rules, as the editor runs it: one suggestion. */
export interface PageRewrite {
run: () => void;
running: boolean;
@@ -78,6 +86,119 @@ export interface PageRewrite {
blocked: string | null;
}
+/** Run Agent's two ways: the open rules fixed a few passages at a time, or the whole page. */
+type RunMode = 'fix' | 'rewrite';
+
+/**
+ * Run Agent ▾ (v1.1, CE-029): one control for both rule actions. The main
+ * part runs the choice, Fix open rules unless the person picked Rewrite the
+ * whole page in ▾, which then labels it "Rewrite page"; once a rewrite
+ * starts, it is back on the safe default. Each choice says what it does and
+ * its AI usage, Less or More, until a real estimate exists.
+ */
+function RunAgentButton({
+ mode,
+ onMode,
+ run,
+ running,
+ disabled,
+ split,
+ anyRunning,
+ fixable,
+ setName,
+ recommended,
+}: {
+ /** The choice the main part runs. */
+ mode: RunMode;
+ onMode: (mode: RunMode) => void;
+ run: () => void;
+ running: boolean;
+ disabled: boolean;
+ /** Both ways are offered: a page ready or published has no rewrite. */
+ split: boolean;
+ /** Either way is running: the choice waits for it. */
+ anyRunning: boolean;
+ /** The open rules the agent can fix. */
+ fixable: number;
+ /** The rule set's name, as the menu says what a rewrite follows. */
+ setName: string;
+ /** Rewrite when small edits can't get there (rewriteAdvice), else Fix; none when Fix is off. */
+ recommended: RunMode | null;
+}) {
+ const t = useTranslations('contentEditor.editor.rules.run');
+ const main = (
+ <Button
+ size="sm"
+ className={cn(split && 'rounded-r-none')}
+ disabled={running || disabled}
+ onClick={() => {
+ run();
+ if (mode === 'rewrite') onMode('fix');
+ }}
+ >
+ {running && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {running ? t('working') : mode === 'rewrite' ? t('rewriteLabel') : t('label')}
+ </Button>
+ );
+ if (!split) return main;
+ const choices: { value: RunMode; title: string; detail: string; usage: string }[] = [
+ {
+ value: 'fix',
+ title: t('fix.title'),
+ detail: t('fix.detail', { count: fixable }),
+ usage: t('fix.usage'),
+ },
+ {
+ value: 'rewrite',
+ title: t('rewrite.title'),
+ detail: t('rewrite.detail', { set: setName }),
+ usage: t('rewrite.usage'),
+ },
+ ];
+ return (
+ <span className="inline-flex shrink-0">
+ {main}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ disabled={anyRunning}
+ render={
+ <Button
+ size="sm"
+ aria-label={t('more')}
+ className="rounded-l-none border-l border-primary-foreground/20 px-1.5"
+ />
+ }
+ >
+ <ChevronDown className="h-3.5 w-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-72">
+ <DropdownMenuRadioGroup value={mode} onValueChange={(value) => onMode(value as RunMode)}>
+ {choices.map((choice) => (
+ <DropdownMenuRadioItem
+ key={choice.value}
+ value={choice.value}
+ closeOnClick
+ disabled={choice.value === 'fix' && fixable === 0}
+ className="items-start py-1.5"
+ >
+ <span className="grid min-w-0 gap-0.5">
+ <span className="text-[13px] font-medium">{choice.title}</span>
+ <span className="text-xs text-muted-foreground">
+ {recommended === choice.value
+ ? t('recommendedDetail', { detail: choice.detail })
+ : choice.detail}
+ </span>
+ <span className="text-[11px] text-muted-foreground/80">{choice.usage}</span>
+ </span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </span>
+ );
+}
+
export function RulesTab({
state,
siteType,
@@ -98,7 +219,9 @@ export function RulesTab({
onOpenSources?: () => void;
}) {
const t = useTranslations('contentEditor.editor.rules');
+ const tSuggestions = useTranslations('contentEditor.editor.suggestions');
const tTypes = useTranslations('contentEditor.pageTypes');
+ const format = useFormatter();
// The workspace's sets are saved by admins and managers, as its other settings are.
const { canManage } = useUserRole();
const types = [...SITE_PAGE_TYPES[siteType]];
@@ -118,7 +241,16 @@ export function RulesTab({
// Rewrite the page whole when small edits can't get there.
const advice = pageRewrite ? rewriteAdvice(state.rules) : null;
- const agents = (agentFix || pageRewrite) && state.met < state.total;
+ // 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;
+ // Run Agent's choice: the safe default, or the whole page (▾) while it is offered.
+ const [picked, setPicked] = useState<RunMode>('fix');
+ const mode: RunMode = picked === 'rewrite' && pageRewrite ? 'rewrite' : 'fix';
+ const runner = mode === 'rewrite' ? pageRewrite : agentFix;
+ // Why Run Agent can't run its choice now, said under the card.
+ const blocked =
+ runner?.blocked ?? (mode === 'fix' && fixable === 0 ? tSuggestions('notForAgent') : null);
// A draft on My rules for a type the workspace has none for (its type
// changed, or My rules couldn't be read) shows Ansvisor's set for it.
@@ -126,6 +258,8 @@ export function RulesTab({
state.source === 'mine' && state.setType && state.mineTypes.includes(state.setType)
? 'mine'
: 'default';
+ const setName =
+ items.find((item) => item.value === `${source}:${state.setType}`)?.label ?? t('pickSet');
return (
// Nothing changes before My rules are read: a change would leave them out.
@@ -134,64 +268,61 @@ export function RulesTab({
aria-busy={!state.ready}
className="m-0 min-w-0 space-y-4 border-0 p-0 text-sm"
>
- {/* The agent's two ways to meet the rules, first: a few edits a run,
- or the whole page rewritten as one change to compare. */}
- {agents && (
- <div className="space-y-1.5">
- {agentFix && (
- <Button
- size="sm"
- variant="outline"
- className="w-full"
- disabled={agentFix.running || agentFix.blocked !== null}
- title={agentFix.blocked ?? t('agentFixHint')}
- onClick={() => agentFix.run()}
- >
- {agentFix.running ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Bot className="h-3.5 w-3.5" />
- )}
- {agentFix.running ? t('agentFixing') : t('agentFix')}
- </Button>
- )}
- {pageRewrite && (
- <Button
- size="sm"
- variant={advice ? 'default' : 'outline'}
- className="w-full"
- disabled={pageRewrite.running || pageRewrite.blocked !== null}
- title={pageRewrite.blocked ?? t('rewriteHint')}
- onClick={() => pageRewrite.run()}
- >
- {pageRewrite.running ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <FileText className="h-3.5 w-3.5" />
- )}
- {pageRewrite.running ? t('rewriting') : t('rewrite')}
- </Button>
+ {/* What the agent can do about the rules, first (v1.1, CE-028/029): one
+ Run Agent, fixing the open rules a few passages at a time, or (▾)
+ rewriting the whole page as one change to compare. */}
+ {(agentFix || pageRewrite) && (
+ <RunCard
+ title={open.length > 0 ? t('run.notMet', { count: open.length }) : t('run.allMet')}
+ detail={
+ open.length > 0
+ ? t('run.names', {
+ names: format.list(
+ open.slice(0, 3).map(({ rule }) => t(`names.${rule.key}`)),
+ { type: 'unit' },
+ ),
+ more: open.length > 3 ? 'yes' : 'no',
+ })
+ : undefined
+ }
+ action={
+ open.length > 0 &&
+ runner && (
+ <RunAgentButton
+ mode={mode}
+ onMode={setPicked}
+ run={() => runner.run()}
+ running={runner.running}
+ disabled={blocked !== null}
+ split={!!agentFix && !!pageRewrite}
+ anyRunning={!!agentFix?.running || !!pageRewrite?.running}
+ fixable={fixable}
+ setName={setName}
+ // Nothing is recommended that is turned off (Fix with only One H1 open).
+ recommended={advice ? 'rewrite' : fixable > 0 ? 'fix' : null}
+ />
+ )
+ }
+ info={t.rich(pageRewrite ? 'run.info' : 'run.infoFix', {
+ b: (chunks) => <b>{chunks}</b>,
+ })}
+ blocked={open.length > 0 ? blocked : null}
+ >
+ {advice && (
+ <p className="flex gap-1.5 text-xs" role="note">
+ <Sparkles aria-hidden className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground" />
+ <span>
+ {advice.reason === 'length'
+ ? t('rewriteAdvice.length', {
+ count: advice.count,
+ target: advice.target,
+ percent: advice.percent,
+ })
+ : t('rewriteAdvice.open', { count: advice.count })}
+ </span>
+ </p>
)}
- {pageRewrite &&
- (advice ? (
- <p className="flex gap-1.5 text-xs" role="note">
- <Sparkles aria-hidden className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground" />
- <span>
- {advice.reason === 'length'
- ? t('rewriteAdvice.length', {
- count: advice.count,
- target: advice.target,
- percent: advice.percent,
- })
- : t('rewriteAdvice.open', { count: advice.count })}
- </span>
- </p>
- ) : (
- <p className="text-xs text-muted-foreground">
- {t('agentsHint', { max: AGENT_RUN_MAX })}
- </p>
- ))}
- </div>
+ </RunCard>
)}
<div className="space-y-1.5">
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_run-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_run-card.tsx
new file mode 100644
index 000000000..95167c33f
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_run-card.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { cn } from '@/lib/utils';
+
+/**
+ * The card each Instructions segment starts with (Content Editor v1.1,
+ * CE-028/CE-031): what stands, on the left (a status line and its detail),
+ * what the agent can do about it on the right, and an ⓘ whose tip opens
+ * below it. Why the agent can't run now is written under the card, in
+ * amber, never only in a hover.
+ */
+export function RunCard({
+ title,
+ detail,
+ action,
+ info,
+ blocked,
+ children,
+}: {
+ title: React.ReactNode;
+ detail?: React.ReactNode;
+ /** The button (or split button) that runs the agent; none when there's nothing to run. */
+ action?: React.ReactNode;
+ /** What the button does, in the ⓘ's tip. */
+ info: React.ReactNode;
+ /** Why the agent can't run now, or null. */
+ blocked?: string | null;
+ /** Under the card: the advice line, the data it uses. */
+ children?: React.ReactNode;
+}) {
+ const t = useTranslations('contentEditor.editor.run');
+ return (
+ <div className="space-y-1.5">
+ <div className="flex items-center gap-2 rounded-xl border px-3 py-2.5">
+ <div className="min-w-0 flex-1 text-xs leading-snug text-muted-foreground">
+ <p className="text-[13px] font-semibold text-foreground">{title}</p>
+ {detail && <p className="truncate">{detail}</p>}
+ </div>
+ {action}
+ <Tooltip>
+ <TooltipTrigger
+ delay={150}
+ closeDelay={0}
+ render={
+ <button
+ type="button"
+ aria-label={t('about')}
+ className="flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded-full border text-[11px] font-semibold text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none"
+ />
+ }
+ >
+ i
+ </TooltipTrigger>
+ {/* Below the icon, so the panel's edge never cuts it off. */}
+ <TooltipContent side="bottom" className="max-w-60 leading-relaxed">
+ {info}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ {/* Always there, so a screen reader hears the reason when it comes. */}
+ <p
+ role="status"
+ className={cn('text-xs text-amber-700 dark:text-amber-400', !blocked && 'sr-only')}
+ >
+ {blocked}
+ </p>
+ {children}
+ </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.tsx
index df77e73c2..f54c7c115 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
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { isPageType, type ContentDraft } from '@/lib/content/drafts';
+import { cn } from '@/lib/utils';
import { BriefTab, type AgentRewrite } from './_brief-tab';
import { ImpactTab } from './_impact-tab';
import { RulesTab, type AgentFix, type PageRewrite } from './_rules-tab';
@@ -44,10 +45,17 @@ export function useSidePanelOpen(): [boolean, () => void] {
return [open, toggle];
}
-// Rules first: what to act on before anything else (the user's call over the
-// spec's Impact-first order); the panel opens on it.
-const PANEL_TABS = ['rules', 'brief', 'sources', 'impact'] as const;
+// Instructions first (Content Editor v1.1, CE-028): Brief and Rules, what
+// the agent follows, in one tab, which the panel opens on (on Rules).
+const PANEL_TABS = ['instructions', 'sources', 'impact'] as const;
export type PanelTab = (typeof PANEL_TABS)[number];
+/** Instructions' two segments: what to write (Brief), then how to write it (Rules). */
+const SEGMENTS = ['brief', 'rules'] as const;
+export type InstructionSegment = (typeof SEGMENTS)[number];
+/** What the panel can be asked to open: a tab, or one of Instructions' segments. */
+export type PanelTarget = PanelTab | InstructionSegment;
+const isSegment = (target: PanelTarget): target is InstructionSegment =>
+ (SEGMENTS as readonly string[]).includes(target);
/**
* The panel's tabs while it is closed, down the editor's right edge, so the
@@ -78,11 +86,12 @@ export function EditorPanelRail({ onOpen }: { onOpen: (tab: PanelTab) => void })
/**
* The editor's right panel (Content Editor spec v2 §6), 400px beside the page.
- * The spec's tabs are Impact · Chat · Brief · Sources · Rules; each joins the
- * panel with the update that makes it work: Impact (CE-016), Brief (CE-007),
- * Sources (CE-008) and Rules (CE-009). Rules comes first and the panel opens
- * on it; each other tab mounts (and reads) when first opened, and stays
- * mounted, so switching back keeps it as it was. The brief and the sources are the editor's one read
+ * Its tabs are Instructions · Sources · Live page (v1.1, CE-028): Instructions
+ * holds what the agent follows, the Brief (CE-007) and the Rules (CE-009),
+ * under a Brief | Rules control, with the rules still open on both. The panel
+ * opens on Instructions, on Rules; each other tab or segment mounts (and
+ * reads) when first opened, and stays mounted, so switching back keeps it as
+ * it was. The brief and the sources are the editor's one read
* (useDraftReads), which the rules check against too: Sources' "Rebuild with
* selection" and Impact's "Use lost prompts" rebuild the brief, and open it.
*/
@@ -108,17 +117,18 @@ export function EditorSidePanel({
/** The draft's brief and sources, read once for the editor. */
reads: DraftReads;
/** A tab to open, from outside the panel (the header's rules chip). */
- tabRequest: { tab: PanelTab; n: number } | null;
- /** Fix open rules with agent, for the Rules tab (CE-018). */
+ tabRequest: { tab: PanelTarget; n: number } | null;
+ /** Run Agent's Fix open rules, for Rules (CE-018, v1.1 CE-029). */
agentFix?: AgentFix;
- /** Rewrite the page to these rules, for the Rules tab; absent once the page is ready or published. */
+ /** Run Agent ▾'s Rewrite the whole page, for Rules; absent once the page is ready or published. */
pageRewrite?: PageRewrite;
- /** Rewrite from brief, for the Brief tab; absent once the page is ready or published. */
+ /** Rewrite from brief, for Brief; absent once the page is ready or published. */
agentRewrite?: AgentRewrite;
}) {
const t = useTranslations('contentEditor.editor.panel');
- const [tab, setTab] = useState<PanelTab>('rules');
- const [opened, setOpened] = useState<Set<PanelTab>>(() => new Set(['rules']));
+ const [tab, setTab] = useState<PanelTab>('instructions');
+ const [segment, setSegment] = useState<InstructionSegment>('rules');
+ const [opened, setOpened] = useState<Set<PanelTarget>>(() => new Set(['instructions', 'rules']));
const page = useRef<PageNow>({ title, html: bodyHtml, length: rules.length });
const sourcesNow = useRef(reads.sources);
useEffect(() => {
@@ -126,10 +136,15 @@ export function EditorSidePanel({
sourcesNow.current = reads.sources;
});
- const open = (next: PanelTab) => {
- setTab(next);
- setOpened((prev) => (prev.has(next) ? prev : new Set([...prev, next])));
+ const open = (next: PanelTarget) => {
+ const nextTab = isSegment(next) ? 'instructions' : next;
+ if (isSegment(next)) setSegment(next);
+ setTab(nextTab);
+ setOpened((prev) =>
+ prev.has(next) && prev.has(nextTab) ? prev : new Set([...prev, next, nextTab]),
+ );
};
+ const rulesOpen = Math.max(0, rules.total - rules.met);
const requested = tabRequest?.n;
useEffect(() => {
@@ -162,28 +177,95 @@ export function EditorSidePanel({
{PANEL_TABS.map((value) => (
<TabsTrigger key={value} value={value}>
{t(`tabs.${value}`)}
+ {/* The rules still open, on the tab that holds them. */}
+ {value === 'instructions' && rulesOpen > 0 && (
+ <>
+ <span
+ aria-hidden
+ className="rounded-md bg-amber-50 px-1.5 text-[10.5px] font-semibold text-amber-700 dark:bg-amber-950 dark:text-amber-400"
+ >
+ {rulesOpen}
+ </span>
+ <span className="sr-only">{t('openRules', { count: rulesOpen })}</span>
+ </>
+ )}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
- {briefOpened && (
- <div hidden={tab !== 'brief'}>
- <BriefTab
- draftId={draft.id}
- state={reads.brief}
- pageType={pageType}
- length={rules.length}
- sourceUrl={draft.sourceUrl}
- method={draft.method}
- rebuilding={rebuilding}
- onRebuild={() => void rebuild()}
- onRetry={reads.reloadBrief}
- onSaved={(saved) => reads.setBrief(saved)}
- rewrite={agentRewrite}
- />
+ <div hidden={tab !== 'instructions'} className="space-y-4">
+ <div
+ role="radiogroup"
+ aria-label={t('segmentsLabel')}
+ className="flex rounded-[10px] border bg-muted p-[3px]"
+ // Arrow keys move between the two, as in any radio group.
+ onKeyDown={(e) => {
+ if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return;
+ e.preventDefault();
+ const next = SEGMENTS[(SEGMENTS.indexOf(segment) + 1) % SEGMENTS.length];
+ open(next);
+ e.currentTarget.querySelector<HTMLElement>(`[data-segment="${next}"]`)?.focus();
+ }}
+ >
+ {SEGMENTS.map((value) => (
+ <button
+ key={value}
+ type="button"
+ role="radio"
+ data-segment={value}
+ aria-checked={segment === value}
+ tabIndex={segment === value ? 0 : -1}
+ onClick={() => open(value)}
+ className={cn(
+ 'flex flex-1 items-center justify-center gap-1.5 rounded-lg py-1 text-[13px] font-medium text-muted-foreground transition-colors focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none',
+ segment === value && 'bg-background text-foreground shadow-xs',
+ )}
+ >
+ {t(`segments.${value}`)}
+ {value === 'rules' && rulesOpen > 0 && (
+ <span className="rounded-md bg-red-50 px-1.5 text-[10.5px] font-medium text-red-700 dark:bg-red-950 dark:text-red-400">
+ {t('segments.open', { count: rulesOpen })}
+ </span>
+ )}
+ </button>
+ ))}
</div>
- )}
+ {briefOpened && (
+ <div hidden={segment !== 'brief'}>
+ <BriefTab
+ draftId={draft.id}
+ state={reads.brief}
+ pageType={pageType}
+ length={rules.length}
+ sourceUrl={draft.sourceUrl}
+ method={draft.method}
+ rebuilding={rebuilding}
+ onRebuild={() => void rebuild()}
+ onRetry={reads.reloadBrief}
+ onSaved={(saved) => reads.setBrief(saved)}
+ rewrite={agentRewrite}
+ />
+ </div>
+ )}
+ {opened.has('rules') && (
+ <div hidden={segment !== 'rules'}>
+ <RulesTab
+ agentFix={agentFix}
+ pageRewrite={pageRewrite}
+ // Only a draft with no prompts gets no fan-outs for want of them.
+ onOpenSources={
+ reads.sources && !reads.sources.failed && reads.sources.data.prompts.length === 0
+ ? () => open('sources')
+ : undefined
+ }
+ state={rules}
+ siteType={draft.siteType}
+ draftPageType={isPageType(pageType) ? pageType : null}
+ />
+ </div>
+ )}
+ </div>
{opened.has('sources') && (
<div hidden={tab !== 'sources'}>
<SourcesTab
@@ -200,23 +282,6 @@ export function EditorSidePanel({
/>
</div>
)}
- {opened.has('rules') && (
- <div hidden={tab !== 'rules'}>
- <RulesTab
- agentFix={agentFix}
- pageRewrite={pageRewrite}
- // Only a draft with no prompts gets no fan-outs for want of them.
- onOpenSources={
- reads.sources && !reads.sources.failed && reads.sources.data.prompts.length === 0
- ? () => open('sources')
- : undefined
- }
- state={rules}
- siteType={draft.siteType}
- draftPageType={isPageType(pageType) ? pageType : null}
- />
- </div>
- )}
{opened.has('impact') && (
<div hidden={tab !== 'impact'}>
<ImpactTab
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
index 101108262..b27a7bda1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
@@ -104,6 +104,7 @@ export function EditorToolbar({
blockquote: e.isActive('blockquote'),
inTable: e.isActive('table'),
characters: e.storage.characterCount.characters() as number,
+ words: e.storage.characterCount.words() as number,
}),
});
@@ -237,6 +238,7 @@ export function EditorToolbar({
{t('counter', {
count: formatNumber(state.characters),
target: formatNumber(target),
+ words: state.words,
})}
</span>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
index a9dc3efef..a4847fcdc 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
@@ -176,10 +176,29 @@ const button = (name: string) =>
(b) => b.getAttribute('aria-label') === name || b.textContent === name,
);
-/** Picks one of the side panel's tabs. */
+/** A panel tab's name, without the open-rules count Instructions carries. */
+const tabName = (el: Element | null | undefined) => el?.firstChild?.textContent;
+/** The panel's tab picked now, and Instructions' segment. */
+const selectedTab = () =>
+ tabName(container.querySelector('aside [role="tab"][aria-selected="true"]'));
+const selectedSegment = () =>
+ container
+ .querySelector('aside [role="radio"][aria-checked="true"]')
+ ?.textContent?.replace(/\d+ open$/, '');
+
+/** Picks one of the side panel's tabs, or one of Instructions' segments. */
async function pickTab(name: string) {
+ // Brief and Rules are Instructions' two segments (Content Editor v1.1, CE-028).
+ if (name === 'Brief' || name === 'Rules') {
+ if (selectedTab() !== 'Instructions') await pickTab('Instructions');
+ const segment = [...container.querySelectorAll<HTMLElement>('aside [role="radio"]')].find(
+ (el) => el.textContent?.startsWith(name),
+ )!;
+ await act(async () => segment.click());
+ return;
+ }
const tab = [...container.querySelectorAll<HTMLElement>('aside [role="tab"]')].find(
- (el) => el.textContent === name,
+ (el) => tabName(el) === name,
)!;
await act(async () => {
tab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
@@ -249,7 +268,7 @@ describe('the content editor', () => {
// The page's text, against a feature page's 3,000-character target.
expect(container.querySelector('[role="toolbar"]')!.textContent).toContain(
- '35 / 3,000 characters',
+ '35 / 3,000 characters · 5 words',
);
for (const name of ['Heading 1', 'Bold', 'Link', 'Numbered list', 'Insert a table']) {
expect(button(name)).toBeDefined();
@@ -291,7 +310,7 @@ describe('the content editor', () => {
expect(header.textContent).toContain('Product page · New page');
expect(header.querySelector('h1')!.textContent).toBe('Untitled');
expect(container.querySelector('[role="toolbar"]')!.textContent).toContain(
- '0 / 1,200 characters',
+ '0 / 1,200 characters · 0 words',
);
});
@@ -1552,8 +1571,9 @@ describe('the side panel', () => {
await act(async () => button('Show side panel')!.click());
expect(panel()!.getAttribute('aria-label')).toBe('Side panel');
- // Rules first, what to act on; the live page reads only once it is picked.
- expect(panel()!.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toBe('Rules');
+ // Instructions first, on Rules, what to act on; the live page reads only once it is picked.
+ expect(selectedTab()).toBe('Instructions');
+ expect(selectedSegment()).toBe('Rules');
expect(getContentImpact).not.toHaveBeenCalled();
await pickTab('Live page');
// The page the draft optimizes, over 30 days.
@@ -1569,10 +1589,10 @@ describe('the side panel', () => {
expect(panel()).toBeNull();
const rail = () => container.querySelector('nav[aria-label="Side panel"]');
const tabs = [...rail()!.querySelectorAll('button')];
- expect(tabs.map((b) => b.textContent)).toEqual(['Rules', 'Brief', 'Sources', 'Live page']);
- expect(tabs[2].getAttribute('title')).toBe('Open Sources in the side panel');
+ expect(tabs.map((b) => b.textContent)).toEqual(['Instructions', 'Sources', 'Live page']);
+ expect(tabs[1].getAttribute('title')).toBe('Open Sources in the side panel');
- await act(async () => tabs[2].click());
+ await act(async () => tabs[1].click());
expect(panel()!.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toBe(
'Sources',
);
@@ -1702,13 +1722,7 @@ describe('the side panel', () => {
getContentDraft.mockResolvedValue(draft({ status: 'in_review' }));
window.innerWidth = 1440;
await renderPage();
- const tab = [...panel()!.querySelectorAll<HTMLElement>('[role="tab"]')].find(
- (el) => el.textContent === 'Brief',
- )!;
- await act(async () => {
- tab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
- tab.click();
- });
+ await pickTab('Brief');
await act(async () => button('Suggest changes from brief')!.click());
await act(async () => button('Start the agent')!.click());
@@ -1757,12 +1771,16 @@ describe('the side panel', () => {
window.innerWidth = 1440;
await renderPage();
- expect([...panel()!.querySelectorAll('[role="tab"]')].map((el) => el.textContent)).toEqual([
- 'Rules',
- 'Brief',
+ expect([...panel()!.querySelectorAll('[role="tab"]')].map(tabName)).toEqual([
+ 'Instructions',
'Sources',
'Live page',
]);
+ // Brief first, then Rules: what to write, then how.
+ expect([...panel()!.querySelectorAll('[role="radio"]')].map((el) => el.textContent)).toEqual([
+ 'Brief',
+ expect.stringMatching(/^Rules\d+ open$/),
+ ]);
await pickTab('Sources');
await act(async () => button('Rebuild with selection')!.click());
@@ -1775,8 +1793,8 @@ describe('the side panel', () => {
length: 3000,
});
expect(toast.success).toHaveBeenCalledWith('Brief rebuilt from 1 source');
- const selected = panel()!.querySelector('[role="tab"][aria-selected="true"]');
- expect(selected?.textContent).toBe('Brief');
+ expect(selectedTab()).toBe('Instructions');
+ expect(selectedSegment()).toBe('Brief');
expect(panel()!.textContent).toContain('How pipeline forecasting works');
expect(panel()!.textContent).toContain('Win forecasting searches');
@@ -1807,8 +1825,12 @@ describe('the side panel', () => {
expect(total).toBeGreaterThan(met);
await act(async () => chip.click());
- const selected = panel()!.querySelector('[role="tab"][aria-selected="true"]');
- expect(selected?.textContent).toBe('Rules');
+ expect(selectedTab()).toBe('Instructions');
+ expect(selectedSegment()).toBe('Rules');
+ // The open rules, on the tab and on the segment.
+ expect(panel()!.querySelector('[role="tab"] .sr-only')?.textContent).toBe(
+ `${total - met} rules open`,
+ );
expect(panel()!.textContent).toContain(`${met} of ${total} rules met`);
// Turning a rule off for this draft saves it and takes it out of the count.
@@ -1905,7 +1927,7 @@ describe('the side panel', () => {
}
});
- describe('Apply rules with Agent', () => {
+ describe('Run Agent: fix open rules', () => {
const traced = draft({
pageType: 'blog_post',
bodyHtml: '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>',
@@ -1944,7 +1966,7 @@ describe('the side panel', () => {
fixDraftRules.mockReturnValue(new Promise((resolve) => (answer = resolve)));
await openRules();
- await act(async () => panelButton('Apply rules with Agent').click());
+ await act(async () => panelButton('Run Agent').click());
await act(async () => {});
const card = () =>
container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;
@@ -1963,7 +1985,7 @@ describe('the side panel', () => {
fixDraftRules.mockResolvedValue({ count: 1 });
await openRules();
- await act(async () => panelButton('Apply rules with Agent').click());
+ await act(async () => panelButton('Run Agent').click());
await act(async () => {});
const [id, brandId, request] = fixDraftRules.mock.calls[0];
@@ -2006,7 +2028,7 @@ describe('the side panel', () => {
fixDraftRules.mockResolvedValue({ count: 0 });
await openRules();
- await act(async () => panelButton('Apply rules with Agent').click());
+ await act(async () => panelButton('Run Agent').click());
await act(async () => {});
expect(fixDraftRules.mock.calls[0][2].rules).toContainEqual(
@@ -2030,7 +2052,7 @@ describe('the side panel', () => {
fixDraftRules.mockResolvedValue({ count: 8 });
await openRules();
- await act(async () => panelButton('Apply rules with Agent').click());
+ await act(async () => panelButton('Run Agent').click());
await act(async () => {});
expect(toast.success).toHaveBeenCalledWith(
@@ -2056,7 +2078,7 @@ describe('the side panel', () => {
fixDraftRules.mockRejectedValue(new Error('An unexpected response was received'));
await openRules();
- await act(async () => panelButton('Apply rules with Agent').click());
+ await act(async () => panelButton('Run Agent').click());
await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));
expect(toast.error).not.toHaveBeenCalled();
await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));
@@ -2083,7 +2105,7 @@ describe('the side panel', () => {
fixDraftRules.mockResolvedValue({ error: 'unconfirmed' });
await openRules();
- await act(async () => panelButton('Apply rules with Agent').click());
+ await act(async () => panelButton('Run Agent').click());
await act(async () => void (await vi.advanceTimersByTimeAsync(85_000)));
expect(toast.error).not.toHaveBeenCalled();
await act(async () => void (await vi.advanceTimersByTimeAsync(10_000)));
@@ -2104,7 +2126,7 @@ describe('the side panel', () => {
expect(panel()!.querySelector('[aria-label="One H1 per page: on or off"]')).toBeNull();
expect(panel()!.querySelector('[aria-label="Length: on or off"]')).not.toBeNull();
- await act(async () => panelButton('Apply rules with Agent').click());
+ await act(async () => panelButton('Run Agent').click());
await act(async () => {});
const asked = fixDraftRules.mock.calls[0][2].rules.map((r: { key: string }) => r.key);
expect(asked).not.toContain('oneH1');
@@ -2131,7 +2153,7 @@ describe('the side panel', () => {
fixDraftRules.mockResolvedValue({ error: 'ai_budget' });
await openRules();
- await act(async () => panelButton('Apply rules with Agent').click());
+ await act(async () => panelButton('Run Agent').click());
await act(async () => {});
expect(toast.error).toHaveBeenCalledWith(
"This month's AI usage is spent. Upgrade for more, or try again next month.",
@@ -2143,9 +2165,12 @@ describe('the side panel', () => {
getDraftSuggestions.mockResolvedValue([agentSuggestion]);
await openRules();
- const fix = panelButton('Apply rules with Agent');
+ const fix = panelButton('Run Agent');
expect(fix.disabled).toBe(true);
- expect(fix.title).toBe('Accept or reject the open suggestions first.');
+ // Why, under the card: never only on hover.
+ expect(panel()!.querySelector('[role="status"]')!.textContent).toBe(
+ 'Review the open suggestion first, then run the agent.',
+ );
});
it('waits until the passages AI quotes are read, so they go to the agent locked', async () => {
@@ -2157,13 +2182,14 @@ describe('the side panel', () => {
getCitedPassages.mockReturnValue(new Promise((resolve) => (read = resolve)));
await openRules();
- const fix = () => panelButton('Apply rules with Agent');
+ const fix = () => panelButton('Run Agent');
expect(fix().disabled).toBe(true);
- expect(fix().title).toBe(
+ expect(panel()!.querySelector('[role="status"]')!.textContent).toBe(
'Reading which passages AI quotes, so the agent leaves them as they are…',
);
await act(async () => read([]));
expect(fix().disabled).toBe(false);
+ expect(panel()!.textContent).not.toContain('Reading which passages AI quotes');
});
it('shows the open suggestions another tab left, when the agent is refused for them', async () => {
@@ -2172,7 +2198,7 @@ describe('the side panel', () => {
fixDraftRules.mockResolvedValue({ error: 'open_suggestions' });
await openRules();
- await act(async () => panelButton('Apply rules with Agent').click());
+ await act(async () => panelButton('Run Agent').click());
await act(async () => {});
expect(toast.error).toHaveBeenCalledWith(
"This page has open suggestions, maybe from another tab. They're shown now: accept or reject them first.",
@@ -2183,7 +2209,7 @@ describe('the side panel', () => {
});
});
- describe('Rewrite the page to these rules', () => {
+ describe('Run Agent: rewrite the whole page', () => {
const long = draft({
pageType: 'blog_post',
bodyHtml: '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>',
@@ -2222,7 +2248,15 @@ describe('the side panel', () => {
getContentDraft.mockResolvedValue(long);
await openRules();
- await act(async () => button(panel()!, 'Rewrite the page to these rules').click());
+ // ▾ › Rewrite the whole page: the button says so, then runs it.
+ await act(async () =>
+ panel()!.querySelector<HTMLElement>('[aria-label="More ways to run the agent"]')!.click(),
+ );
+ const item = [...document.body.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].find(
+ (el) => el.textContent?.startsWith('Rewrite the whole page'),
+ )!;
+ await act(async () => item.click());
+ await act(async () => button(panel()!, 'Rewrite page').click());
await act(async () => {});
const [id, brandId, request] = startPageRewrite.mock.calls[0];
@@ -2353,13 +2387,7 @@ describe('the side panel', () => {
window.innerWidth = 1440;
await renderPage();
- const rulesTab = [...panel()!.querySelectorAll<HTMLElement>('[role="tab"]')].find(
- (el) => el.textContent === 'Rules',
- )!;
- await act(async () => {
- rulesTab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
- rulesTab.click();
- });
+ await pickTab('Rules');
expect(getMyRuleSets).toHaveBeenCalledWith('b1');
expect(panel()!.textContent).toContain('My rules · Blog post');
expect(panel()!.textContent).toContain('Your text rules');
diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.ts
index ebd354278..d0bb72d4f 100644
--- a/web/src/lib/content/rules.test.ts
+++ b/web/src/lib/content/rules.test.ts
@@ -12,6 +12,7 @@ import {
draftRulesSchema,
readPage,
ruleLength,
+ wordsForLength,
lengthWarns,
lengthConflict,
ruleSet,
@@ -142,6 +143,16 @@ describe('rule sets', () => {
expect(ruleLength(huge, 'category_page')).toBe(50_000);
});
+ it('says a length in characters as about so many words (v1.1 §3.2)', () => {
+ // To the nearest ten from 100 words on, as the Brief shows it.
+ expect(wordsForLength(4000)).toBe(670);
+ expect(wordsForLength(3000)).toBe(500);
+ expect(wordsForLength(50_000)).toBe(8330);
+ // Below 100 words, as is; never none.
+ expect(wordsForLength(300)).toBe(50);
+ expect(wordsForLength(1)).toBe(1);
+ });
+
it('keeps the draft’s choices to their limits', () => {
expect(
draftRulesSchema.safeParse({ set: 'blog_post', overrides: { faq: { on: false } } }).success,
diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.ts
index 0a07ca2c5..1d2945cb5 100644
--- a/web/src/lib/content/rules.ts
+++ b/web/src/lib/content/rules.ts
@@ -498,6 +498,19 @@ export function ruleLength(rules: ActiveRule[], pageType: PageType | null): numb
return Math.min(RULE_LENGTH_MAX, Math.max(RULE_LENGTH_MIN, value));
}
+/**
+ * About how many characters a word takes, its space and punctuation
+ * included: an English average, for showing a length in words too
+ * (Content Editor v1.1 §3.2). Characters stay the unit rules count in.
+ */
+export const CHARACTERS_PER_WORD = 6;
+
+/** A length in characters as about so many words, to the nearest ten from 100 on. */
+export function wordsForLength(characters: number): number {
+ const words = Math.max(1, Math.round(characters / CHARACTERS_PER_WORD));
+ return words >= 100 ? Math.round(words / 10) * 10 : words;
+}
+
// ─── The page as written ────────────────────────────────────────────────────
export interface PageBlock {