Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): list what only you can do in Quality, and nudge the next one (CE-040) (#1419)
Cihan98972c8c7084
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 44a78dc1d..6ff8de7c6 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4174,6 +4174,55 @@"pickAuthor": "Pick author","addAuthor": "Add author","editAuthor": "Edit author",+ "todos": {+ "title": "Your to-dos",+ "left": "{count, plural, =0 {All done} other {# left · only you can do these}}",+ "done": "Done",+ "open": "To do",+ "byline": {+ "title": {+ "pickAuthor": "Pick the page's author",+ "addAuthor": "Add an author for the page"+ },+ "next": {+ "pickAuthor": "pick the page's author",+ "addAuthor": "add an author for the page"+ },+ "detail": {+ "pickAuthor": "It's by {byline} now: a named person shows who stands behind the page",+ "addAuthor": "Add the people who write for you in Settings › Authors. Real people only: the agent can't add them"+ },+ "done": "By {name}"+ },+ "authorProfile": {+ "title": "Complete {name}'s profile",+ "titleNoAuthor": "Complete the author's profile",+ "next": "complete {name}'s profile",+ "nextNoAuthor": "complete the author's profile",+ "detail": {+ "noAuthor": "Once the page has an author: two sentences on what they know, and a profile link",+ "both": "Add them in Settings › Authors: two sentences on what they know, and a LinkedIn or other profile link",+ "bio": "Add a short bio in Settings › Authors: two sentences on what they know",+ "links": "Add a LinkedIn or other profile link in Settings › Authors"+ },+ "askOthers": {+ "both": "{member, select, yes {{name}, whoever added them or an admin can add a short bio and a profile link in Settings › Authors} other {Whoever added {name} or an admin can add a short bio and a profile link in Settings › Authors}}",+ "bio": "{member, select, yes {{name}, whoever added them or an admin can add a short bio in Settings › Authors} other {Whoever added {name} or an admin can add a short bio in Settings › Authors}}",+ "links": "{member, select, yes {{name}, whoever added them or an admin can add a profile link in Settings › Authors} other {Whoever added {name} or an admin can add a profile link in Settings › Authors}}"+ },+ "done": "Short bio and profile links are in"+ }+ },+ "nudge": {+ "label": "Your next step",+ "text": "Next for you: <b>{todo}</b> · {position} of {count}",+ "act": {+ "pickAuthor": "Pick now",+ "addAuthor": "Add now",+ "editAuthor": "Edit now"+ },+ "later": "Later"+ },"notThisLanguage": "Readability isn't read for this language yet.","suggestionsLabel": "What would raise it","nothingToRaise": "Nothing to raise here for now: every live check has its points.",@@ -4200,27 +4249,6 @@"line": "{count, plural, one {# link doesn't} other {# links don't}} work","detail": "{count, plural, one {Fix or remove it: {url}} other {Fix or remove them, starting with {url}}}"},- "byline": {- "line": "The page is by {byline}, not a person",- "detail": "Pick the person who wrote it: a named author with a short bio and profile links shows who stands behind the page."- },- "authorProfile": {- "line": {- "both": "{name} has no short bio or profile links",- "bio": "{name} has no short bio",- "links": "{name} has no profile links"- },- "detail": {- "both": "Add them in Settings › Authors: two sentences on what they know, and a LinkedIn or other profile link.",- "bio": "Add a short bio in Settings › Authors: two sentences on what they know.",- "links": "Add a LinkedIn or other profile link in Settings › Authors."- },- "askOthers": {- "both": "{member, select, yes {{name}, whoever added them or an admin can add a short bio and a profile link in Settings › Authors.} other {Whoever added {name} or an admin can add a short bio and a profile link in Settings › Authors.}}",- "bio": "{member, select, yes {{name}, whoever added them or an admin can add a short bio in Settings › Authors.} other {Whoever added {name} or an admin can add a short bio in Settings › Authors.}}",- "links": "{member, select, yes {{name}, whoever added them or an admin can add a profile link in Settings › Authors.} other {Whoever added {name} or an admin can add a profile link in Settings › Authors.}}"- }- },"avgSentence": {"line": "Sentences average {words, number} words","detail": "Aim for 15–20 words: shorter sentences read faster, and AI answers quote them whole.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsxindex b2059f00e..78091adf0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsx@@ -73,7 +73,7 @@ export function AgentWriting({/** Rewrite the page to these rules, as this tab started it. */rewrite?: boolean;/** The run ended (stopped, done or failed): the page reads the draft again. */- onRunEnded?: () => void;+ onRunEnded?: (stopped?: boolean) => void;}) {const t = useTranslations('contentEditor.editor');const seconds = elapsedSeconds(since, useNow({ updateInterval: 1000 }));@@ -103,7 +103,7 @@ export function AgentWriting({} else if (result.stopped) {// The page opens again as it was: the server let go of the draft.toast(t('agentCard.stopped'));- onRunEnded?.();+ onRunEnded?.(true);} else {setStopping(false);}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 79c08b444..907ba3433 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@@ -77,6 +77,7 @@ import { JsonLd } from '@/lib/content/json-ld-node';import { detectPageType } from '@/lib/content/page-types';import { BAND_CLASSES, qualityAverage, qualityBand, qualityPhase } from '@/lib/content/quality';import { eeat, linksToCheck, trust, trustBlocks } from '@/lib/content/quality-checks';+import { qualityTodos } from '@/lib/content/quality-todos';import { readability } from '@/lib/content/readability';import { aiTracesFound, fanoutsToUse, lengthWarns, openRulesForAgent } from '@/lib/content/rules';import { saveBlob } from '@/lib/download';@@ -103,6 +104,7 @@ import { sourceDetail } from './_sources-tab';import { HistoryMenu } from './_history-menu';import { HtmlBlock, copyToClipboard } from './_html-block';import { OwnCopies, ownCopyHtml } from './_own-copies';+import { NextNudge, useNextNudge } from './_next-nudge';import { PageInfoStrip, pageInfoKey } from './_page-info';import type { QualityRead } from './_quality-tab';import { PageTypeMenu } from './_page-type-menu';@@ -203,6 +205,7 @@ async function agentBatch(draftId: string, until: number): Promise<DraftSuggestiexport function DraftEditor({draft,onAgentStarted,+ agentFinished = false,}: {draft: ContentDraft;/**@@ -210,6 +213,8 @@ export function DraftEditor({* Rewrite the whole page): the page waits for it.*/onAgentStarted?: (run: 'write' | 'rewrite') => void;+ /** The editor opens on what the agent just wrote here: the next-step nudge's moment. */+ agentFinished?: boolean;}) {const t = useTranslations('contentEditor.editor');const autosave = useDraftAutosave(draft.id, draft);@@ -486,20 +491,39 @@ export function DraftEditor({trustScore?.score ?? null,readable?.score ?? null,]);+ const hasAuthors = (authorsRead?.authors.length ?? 0) > 0;+ // What only the person can do (CE-040), and the nudge to the first of it+ // when the agent's run ends, after Accept all and on Mark ready.+ // Who may edit the page's author: only they get Edit author (CE-037's rule).+ const canEditPageAuthor =+ !!pageAuthor && !!authorsRead && canEditAuthor(pageAuthor, authorsRead.me);+ const todos = qualityOn+ ? qualityTodos({ eeat: eeatScore, author: pageAuthor, hasAuthors, canEdit: canEditPageAuthor })+ : [];const quality: QualityRead | null = qualityOn? {readability: readable,eeat: eeatScore,trust: trustScore,author: pageAuthor,- canEdit: !!pageAuthor && !!authorsRead && canEditAuthor(pageAuthor, authorsRead.me),- hasAuthors: (authorsRead?.authors.length ?? 0) > 0,+ canEdit: canEditPageAuthor,+ hasAuthors,brandName,siteTrust,+ todos,}: null;// Quality's Pick author opens the header's menu.const [authorMenuOpen, setAuthorMenuOpen] = useState(false);+ const nudge = useNextNudge(draft.id, todos);+ const { at: nudgeAt } = nudge;+ const todosRead = todos.length > 0;+ const agentNudged = useRef(false);+ useEffect(() => {+ if (!agentFinished || !todosRead || agentNudged.current) return;+ agentNudged.current = true;+ nudgeAt('agent');+ }, [agentFinished, todosRead, nudgeAt]);const byline = authorsRead? [t('author.by', {@@ -825,6 +849,8 @@ export function DraftEditor({}}setSuggestions(next);+ // The last open one accepted (Accept all, or one by one): the nudge's moment.+ if (decision === 'accept' && !next.some((s) => s.status === 'open')) nudgeAt('acceptAll');if (decision === 'accept')toast.success(t('suggestions.acceptedToast', { count: changed.length }));else if (decision === 'reject')@@ -936,8 +962,11 @@ export function DraftEditor({.run();}setSuggestions((prev) => prev.map((x) => (x.id === s.id ? { ...x, status: to } : x)));- if (to === 'accepted') toast.success(t('rewrite.acceptedToast'));- else if (to === 'rejected') toast(t('rewrite.rejectedToast'));+ if (to === 'accepted') {+ toast.success(t('rewrite.acceptedToast'));+ // The rewrite is the whole batch: as Accept all.+ nudgeAt('acceptAll');+ } else if (to === 'rejected') toast(t('rewrite.rejectedToast'));else toast(t('rewrite.undoneToast'));} catch (err) {console.error('Failed to decide the rewritten page:', err);@@ -1040,6 +1069,7 @@ export function DraftEditor({setBarClosed(false);agentBeforeKept.current = false;toast.success(fixedMessage(landed.filter((s) => s.status === 'open').length));+ nudgeAt('agent');return;}if ('error' in result && result.error === 'stopped') {@@ -1065,6 +1095,7 @@ export function DraftEditor({// A new batch: History keeps the page again before its first change.agentBeforeKept.current = false;toast.success(fixedMessage(result.count));+ nudgeAt('agent');} catch (err) {console.error('Failed to run the Content Agent:', err);toast.error(t('suggestions.fixErrors.failed'));@@ -1350,6 +1381,8 @@ export function DraftEditor({}: undefined;const markReady = async () => {+ // Opened with to-dos open: the nudge names the first; marking goes on.+ nudgeAt('markReady');setMarking(true);try {// What's waiting goes out first, so the ready draft (and the version@@ -1702,6 +1735,15 @@ export function DraftEditor({</div></div>{dragging && <DropOverlay />}+ {quality && (+ <NextNudge+ shown={nudge.shown}+ quality={quality}+ onPickAuthor={() => setAuthorMenuOpen(true)}+ onLater={nudge.later}+ onAct={nudge.close}+ />+ )}</div>{attachments.ui}</div>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.test.tsxnew file mode 100644index 000000000..971d8b51e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.test.tsx@@ -0,0 +1,160 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../../../messages/en.json';+import type { ContentAuthor } from '@/lib/content/authors';+import type { QualityTodo } from '@/lib/content/quality-todos';++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, ...props }: { href: string } & Record<string, unknown>) => (+ <a href={href} {...props} />+ ),+}));++const { NextNudge, useNextNudge } = await import('./_next-nudge');+type NudgeMoment = import('./_next-nudge').NudgeMoment;++/**+ * The next-step nudge (Quality spec §4, CE-040): "Next for you: {first open+ * to-do} · 1 of n", at the agent's end, Accept all and Mark ready, once per+ * moment and to-do; Later hides it for the session.+ */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const ada: ContentAuthor = {+ id: 'a1',+ name: 'Ada Lovelace',+ title: null,+ bio: null,+ photoUrl: null,+ sameAs: [],+ userId: null,+ createdBy: null,+ defaultFor: [],+ pages: null,+};+const pick: QualityTodo = { id: 'byline', done: false, gain: 60, action: 'pickAuthor' };+const profile: QualityTodo = { id: 'authorProfile', done: false, gain: 40, action: 'editAuthor' };++let container: HTMLDivElement;+let root: Root;+const onPickAuthor = vi.fn();+const MOMENTS: NudgeMoment[] = ['agent', 'acceptAll', 'markReady'];++/** The editor's part: the hook, a button per moment, and the nudge while it shows. */+function Harness({ todos, author }: { todos: QualityTodo[]; author: ContentAuthor | null }) {+ const nudge = useNextNudge('d1', todos);+ return (+ <>+ {MOMENTS.map((moment) => (+ <button key={moment} type="button" data-moment={moment} onClick={() => nudge.at(moment)} />+ ))}+ <NextNudge+ shown={nudge.shown}+ quality={{ author, brandName: 'Acme', canEdit: true }}+ onPickAuthor={onPickAuthor}+ onLater={nudge.later}+ onAct={nudge.close}+ />+ </>+ );+}++async function render(todos: QualityTodo[], author: ContentAuthor | null = null) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <Harness todos={todos} author={author} />+ </NextIntlClientProvider>,+ );+ });+}+const nudge = () => container.querySelector('[aria-label="Your next step"]');+const status = () => container.querySelector('[role="status"]')!.textContent;+const nudgeAt = (moment: NudgeMoment) =>+ container.querySelector<HTMLButtonElement>(`[data-moment="${moment}"]`)!.click();+const button = (name: string) =>+ [...container.querySelectorAll<HTMLElement>('button, a')].find((b) => b.textContent === name)!;++beforeEach(() => {+ sessionStorage.clear();+ onPickAuthor.mockReset();+ container = document.createElement('div');+ root = createRoot(container);+});+afterEach(() => act(() => root.unmount()));++describe('NextNudge', () => {+ it('names the first open to-do at a moment, and opens the author menu', async () => {+ await render([pick]);+ expect(nudge()).toBeNull();+ // A status kept on the page, so screen readers hear the nudge when it shows.+ expect(status()).toBe('');+ await act(async () => nudgeAt('agent'));+ expect(nudge()!.textContent).toBe("Next for you: pick the page's author · 1 of 1Pick nowLater");+ expect(nudge()!.querySelector('b')!.textContent).toBe("pick the page's author");+ expect(status()).toBe("Next for you: pick the page's author · 1 of 1");+ await act(async () => button('Pick now').click());+ expect(onPickAuthor).toHaveBeenCalled();+ expect(nudge()).toBeNull();+ expect(status()).toBe('');+ });++ it('counts the open ones and skips the done', async () => {+ await render([{ ...pick, done: true }, profile], ada);+ await act(async () => nudgeAt('markReady'));+ expect(nudge()!.textContent).toContain(+ "Next for you: complete Ada Lovelace's profile · 1 of 1",+ );+ expect(button('Edit now').getAttribute('href')).toBe('/dashboard/settings/authors');+ });++ it('shows once per moment and to-do, and not with none open', async () => {+ await render([pick]);+ await act(async () => nudgeAt('acceptAll'));+ await act(async () => button('Pick now').click());+ await act(async () => nudgeAt('acceptAll'));+ expect(nudge()).toBeNull();+ // Another moment for the same to-do still shows.+ await act(async () => nudgeAt('markReady'));+ expect(nudge()).not.toBeNull();++ await render([{ ...pick, done: true }]);+ expect(nudge()).toBeNull();+ sessionStorage.clear();+ await act(async () => nudgeAt('agent'));+ expect(nudge()).toBeNull();+ });++ it('hides for the session on Later', async () => {+ await render([pick, profile]);+ await act(async () => nudgeAt('agent'));+ expect(nudge()!.textContent).toContain('1 of 2');+ await act(async () => button('Later').click());+ expect(nudge()).toBeNull();+ await act(async () => nudgeAt('markReady'));+ expect(nudge()).toBeNull();+ expect(JSON.parse(sessionStorage.getItem('aeo:quality-nudge:d1')!)).toMatchObject({+ later: true,+ });+ });++ it('goes once the to-dos are done, and moves on to the next one meanwhile', async () => {+ await render([pick]);+ await act(async () => nudgeAt('agent'));+ // Picked from the header instead: the profile is next.+ await render([{ ...pick, done: true }, profile], ada);+ expect(nudge()!.textContent).toContain("complete Ada Lovelace's profile");+ await render([+ { ...pick, done: true },+ { ...profile, done: true },+ ]);+ expect(nudge()).toBeNull();+ // A to-do open again later waits for its moment.+ await render([pick]);+ expect(nudge()).toBeNull();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.tsxnew file mode 100644index 000000000..1a89d0a03--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.tsx@@ -0,0 +1,157 @@+'use client';++import { useCallback, useEffect, useRef, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Link } from '@/i18n/navigation';+import type { QualityTodo } from '@/lib/content/quality-todos';+import { MANAGE_AUTHORS_PATH } from './_author-menu';+import { useTodoCopy, type QualityRead } from './_quality-tab';++/** The moments the nudge shows at (Quality spec §4). */+export type NudgeMoment = 'agent' | 'acceptAll' | 'markReady';++/** What the nudge showed for this draft in this session, and whether Later hid it. */+const nudgeKey = (draftId: string) => `aeo:quality-nudge:${draftId}`;+interface NudgeSeen {+ later: boolean;+ /** "{moment}:{to-do}" it showed for. */+ steps: string[];+}++function readSeen(draftId: string): NudgeSeen {+ try {+ const seen = JSON.parse(sessionStorage.getItem(nudgeKey(draftId)) ?? 'null') as NudgeSeen;+ if (seen && Array.isArray(seen.steps)) return { later: !!seen.later, steps: seen.steps };+ } catch {+ // Storage unavailable (private mode) or unreadable: as if nothing showed.+ }+ return { later: false, steps: [] };+}++function writeSeen(draftId: string, seen: NudgeSeen) {+ try {+ sessionStorage.setItem(nudgeKey(draftId), JSON.stringify(seen));+ } catch {+ // It may show again this session.+ }+}++/**+ * The next-step nudge's timing (Quality spec §4, CE-040): at a moment (the+ * agent's run ended, Accept all, Mark ready) with a to-do open, it shows the+ * first open one, once per moment and to-do in the session; Later hides it+ * for the session, while the to-do stays on the list.+ */+export function useNextNudge(draftId: string, todos: QualityTodo[]) {+ const [showing, setShowing] = useState(false);+ const open = todos.filter((todo) => !todo.done);+ // All done: it goes, and a to-do open again later waits for its moment.+ if (showing && open.length === 0) setShowing(false);+ // The to-dos as they are when a moment comes, after an await.+ const openNow = useRef(open);+ useEffect(() => {+ openNow.current = open;+ });++ const at = useCallback(+ (moment: NudgeMoment) => {+ const first = openNow.current[0];+ if (!first) return;+ const seen = readSeen(draftId);+ const step = `${moment}:${first.id}`;+ if (seen.later || seen.steps.includes(step)) return;+ writeSeen(draftId, { ...seen, steps: [...seen.steps, step] });+ setShowing(true);+ },+ [draftId],+ );+ const later = () => {+ writeSeen(draftId, { ...readSeen(draftId), later: true });+ setShowing(false);+ };++ return {+ /** The first open to-do and how many are open, while it shows. */+ shown: showing && open.length > 0 ? { todo: open[0], count: open.length } : null,+ at,+ later,+ close: () => setShowing(false),+ };+}++/**+ * The nudge (bottom right of the draft, a dark pill): "Next for you: {the+ * first open to-do} · 1 of 3", its one action now, and Later. Its words go+ * to a status kept on the page, so screen readers hear it when it shows.+ */+export function NextNudge({+ shown,+ quality,+ onPickAuthor,+ onLater,+ onAct,+}: {+ shown: { todo: QualityTodo; count: number } | null;+ quality: Pick<QualityRead, 'author' | 'brandName' | 'canEdit'>;+ onPickAuthor: () => void;+ onLater: () => void;+ /** It was acted on: it goes. */+ onAct: () => void;+}) {+ const t = useTranslations('contentEditor.editor.quality.nudge');+ const copy = useTodoCopy();+ const text =+ shown &&+ t.rich('text', {+ todo: copy(shown.todo, quality).next,+ position: 1,+ count: shown.count,+ b: (chunks) => <b className="font-semibold">{chunks}</b>,+ });+ const action = shown?.todo.action;+ const actClass =+ 'shrink-0 rounded-full bg-background px-2.5 py-1 font-medium text-foreground hover:bg-background/90';+ return (+ <>+ <p role="status" className="sr-only">+ {text}+ </p>+ {shown && (+ <div+ role="group"+ aria-label={t('label')}+ className="absolute right-4 bottom-4 z-20 flex max-w-[min(440px,calc(100%-2rem))] items-center gap-2 rounded-2xl bg-foreground py-1.5 pr-1.5 pl-3.5 text-xs text-background shadow-lg"+ >+ <span aria-hidden className="min-w-0 flex-1 [overflow-wrap:anywhere]">+ {text}+ </span>+ {action === 'pickAuthor' ? (+ <button+ type="button"+ className={actClass}+ onClick={() => {+ onAct();+ onPickAuthor();+ }}+ >+ {t('act.pickAuthor')}+ </button>+ ) : (+ action && (+ <Link href={MANAGE_AUTHORS_PATH} className={actClass} onClick={onAct}>+ {t(`act.${action}`)}+ </Link>+ )+ )}+ <button+ type="button"+ className="shrink-0 rounded-full px-2 py-1 text-background/70 hover:text-background"+ onClick={onLater}+ >+ {t('later')}+ </button>+ </div>+ )}+ </>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.test.tsxindex a9fbcb8a0..a80ce06fa 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.test.tsx@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../../../messages/en.json';import { eeat, trust, trustBlocks, type LinkCheck } from '@/lib/content/quality-checks';import type { ContentAuthor } from '@/lib/content/authors';+import { qualityTodos } from '@/lib/content/quality-todos';import type { Readability } from '@/lib/content/readability';vi.mock('@/i18n/navigation', () => ({@@ -16,7 +17,10 @@ vi.mock('@/i18n/navigation', () => ({const { QualityTab } = await import('./_quality-tab');type QualityRead = import('./_quality-tab').QualityRead;-/** Instructions › Quality (Quality spec §3, CE-039): the scores, their label, what would raise them. */+/**+ * Instructions › Quality (Quality spec §3, CE-039): the scores, their label,+ * the person's to-dos (CE-040) and what would raise them.+ */(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =true;@@ -63,15 +67,17 @@ function read(hasAuthors = true,canEdit = true,): QualityRead {+ const score = eeat({ author });return {readability,- eeat: eeat({ author }),+ eeat: score,trust: null,author,canEdit,hasAuthors,brandName: 'Acme',siteTrust: null,+ todos: qualityTodos({ eeat: score, author, hasAuthors, canEdit }),};}@@ -114,13 +120,14 @@ describe('QualityTab', () => {it('lists what would raise it, the biggest gain first, each with what to do', async () => {await render(result);- const rows = [...container.querySelectorAll('li')].map((li) => li.textContent);+ const suggestions = container.querySelector('[aria-label="What would raise it"]')!;+ const rows = [...suggestions.querySelectorAll('li')].map((li) => li.textContent);expect(rows).toEqual(['+9 Readability3 sentences over 35 wordsSplit each into two. Show goes to the first.Show','+5 ReadabilitySentences average 22.4 wordsAim for 15–20 words: shorter sentences read faster, and AI answers quote them whole.','+5 ReadabilityReading level 52 (Flesch Reading Ease)Aim for 60 or more: shorter words and sentences.',]);- await act(async () => container.querySelector<HTMLButtonElement>('li button')!.click());+ await act(async () => suggestions.querySelector<HTMLButtonElement>('li button')!.click());expect(onShow).toHaveBeenCalledWith('A very long sentence.');});@@ -138,7 +145,7 @@ describe('QualityTab', () => {it('says when the page is too short to read, or reads well', async () => {await render({ score: null, unscored: 'tooShort', checks: [], words: 12 });expect(container.textContent).toContain('Write a few paragraphs');- expect(container.querySelector('li')).toBeNull();+ expect(container.querySelector('[aria-label="What would raise it"]')).toBeNull();await render({...result,score: 100,@@ -147,35 +154,53 @@ describe('QualityTab', () => {expect(container.textContent).toContain('Nothing to raise here for now');});- it('asks for a real author when the page is by the team, and opens the menu', async () => {+ it("lists picking the page's author as a to-do, and opens the menu", async () => {await render(read(result, null));const scores = container.querySelector('[aria-label="Quality scores"]')!;expect(scores.textContent).toContain('E-E-A-T0Needs work');- const first = container.querySelector('li')!;- expect(first.textContent).toBe(- '+60 E-E-A-TThe page is by Acme Team, not a personPick the person who wrote it: a named author with a short bio and profile links shows who stands behind the page.Pick author',+ const todos = container.querySelector('[aria-label="Your to-dos"]')!;+ expect(todos.querySelector('h4')!.textContent).toBe(+ 'Your to-dos 2 left · only you can do these',+ );+ const [row, profile] = [...todos.querySelectorAll('li')];+ expect(row.textContent).toBe(+ "Pick the page's author · To doIt's by Acme Team now: a named person shows who stands behind the page · +60 E-E-A-TPick author",+ );+ // The profile waits on the author: listed, with no button yet.+ expect(profile.textContent).toBe(+ "Complete the author's profile · To doOnce the page has an author: two sentences on what they know, and a profile link · +40 E-E-A-T",);- await act(async () => first.querySelector('button')!.click());+ expect(profile.querySelector('button, a')).toBeNull();+ await act(async () => row.querySelector('button')!.click());expect(onPickAuthor).toHaveBeenCalled();+ // Not a suggestion: the agent can't pick an author.+ expect(+ container.querySelector('[aria-label="What would raise it"]')!.textContent,+ ).not.toContain('author');});- it("asks to complete the author's profile in Settings › Authors", async () => {+ it('checks the author off, then asks to complete their profile in Settings › Authors', async () => {await render(read(result, { ...ada, bio: null, sameAs: [] }));- const row = [...container.querySelectorAll('li')].find((li) =>- li.textContent?.includes('Ada Lovelace'),- )!;- expect(row.textContent).toContain('+40 E-E-A-TAda Lovelace has no short bio or profile links');- expect(row.querySelector('a')!.getAttribute('href')).toBe('/dashboard/settings/authors');+ const todos = container.querySelector('[aria-label="Your to-dos"]')!;+ expect(todos.querySelector('h4')!.textContent).toContain('1 left');+ const [byline, profile] = [...todos.querySelectorAll('li')];+ expect(byline.textContent).toBe("Pick the page's author · DoneBy Ada Lovelace");+ expect(byline.querySelector('.line-through')).not.toBeNull();+ expect(byline.querySelector('button, a')).toBeNull();+ expect(profile.textContent).toContain(+ "Complete Ada Lovelace's profile · To doAdd them in Settings › Authors: two sentences on what they know, and a LinkedIn or other profile link · +40 E-E-A-T",+ );+ expect(profile.querySelector('a')!.textContent).toBe('Edit author');+ expect(profile.querySelector('a')!.getAttribute('href')).toBe('/dashboard/settings/authors');});it("says who can complete the profile when the reader can't edit the author", async () => {await render(read(result, { ...ada, bio: null }, true, false));const row = [...container.querySelectorAll('li')].find((li) =>- li.textContent?.includes('Ada Lovelace'),+ li.textContent?.includes("Complete Ada Lovelace's profile"),)!;- expect(row.textContent).toContain('Ada Lovelace has no short bio');expect(row.textContent).toContain(- 'Whoever added Ada Lovelace or an admin can add a short bio in Settings › Authors.',+ 'Whoever added Ada Lovelace or an admin can add a short bio in Settings › Authors',);expect(row.querySelector('a')).toBeNull();expect(row.querySelector('button')).toBeNull();@@ -184,21 +209,49 @@ describe('QualityTab', () => {it('names the author among who can when they are a member', async () => {await render(read(result, { ...ada, sameAs: [], userId: 'u2' }, true, false));const row = [...container.querySelectorAll('li')].find((li) =>- li.textContent?.includes('Ada Lovelace'),+ li.textContent?.includes("Complete Ada Lovelace's profile"),)!;expect(row.textContent).toContain(- 'Ada Lovelace, whoever added them or an admin can add a profile link in Settings › Authors.',+ 'Ada Lovelace, whoever added them or an admin can add a profile link in Settings › Authors',);expect(row.querySelector('a')).toBeNull();});it('sends to Settings › Authors when the workspace has no author yet', async () => {await render(read(result, null, false));- const row = container.querySelector('li')!;+ const row = container.querySelector('[aria-label="Your to-dos"] li')!;+ expect(row.textContent).toContain('Add an author for the page');expect(row.querySelector('a')!.textContent).toBe('Add author');expect(row.querySelector('a')!.getAttribute('href')).toBe('/dashboard/settings/authors');});+ it('says all done when every to-do is, and nothing is left to raise', async () => {+ await render({+ ...read(result),+ readability: {+ ...result,+ score: 100,+ checks: result.checks.map((c) => ({ ...c, points: c.max })),+ },+ });+ const todos = container.querySelector('[aria-label="Your to-dos"]')!;+ expect(todos.querySelector('h4')!.textContent).toBe('Your to-dos All done');+ expect(container.textContent).toContain('Nothing to raise here for now');+ });++ it('says nothing is left to raise only once the to-dos are done', async () => {+ await render({+ ...read(result, null),+ readability: {+ ...result,+ score: 100,+ checks: result.checks.map((c) => ({ ...c, points: c.max })),+ },+ });+ expect(container.textContent).not.toContain('Nothing to raise');+ expect(container.querySelector('[aria-label="What would raise it"]')).toBeNull();+ });+it('says only that a short page is too short, with nothing else to raise', async () => {await render(read({ score: null, checks: [], words: 12 }));expect(container.textContent).toContain('Write a few paragraphs');@@ -234,7 +287,8 @@ describe('QualityTab', () => {const scores = container.querySelector('[aria-label="Quality scores"]')!;// Figures 0 of 30, fresh 0 of 7, links 1.5 of 3: 4 of 100.expect(scores.textContent).toContain('Trust4Needs work');- const rows = [...container.querySelectorAll('li')].map((li) => li.textContent);+ const suggestions = container.querySelector('[aria-label="What would raise it"]')!;+ const rows = [...suggestions.querySelectorAll('li')].map((li) => li.textContent);expect(rows).toContainEqual(expect.stringContaining('1 sentence with a figure has no source'));expect(rows).toContainEqual(expect.stringContaining('1 of 1 dated source is over 24 months old'),@@ -242,7 +296,7 @@ describe('QualityTab', () => {expect(rows).toContainEqual(expect.stringContaining("1 link doesn't workFix or remove it: https://gone.example/Show"),);- const figure = [...container.querySelectorAll('li')].find((li) =>+ const figure = [...suggestions.querySelectorAll('li')].find((li) =>li.textContent?.includes('figure'),)!;await act(async () => figure.querySelector('button')!.click());@@ -322,6 +376,6 @@ describe('QualityTab', () => {await render({ score: null, unscored: 'language', checks: [], words: 240 });expect(container.textContent).toContain("Readability isn't read for this language yet.");expect(container.textContent).not.toContain('Write a few paragraphs');- expect(container.querySelector('li')).toBeNull();+ expect(container.querySelector('[aria-label="What would raise it"]')).toBeNull();});});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsxindex e7e2864b5..285573047 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx@@ -1,6 +1,7 @@'use client';import { useFormatter, useTranslations } from 'next-intl';+import { Check } from 'lucide-react';import { Link } from '@/i18n/navigation';import { Button, buttonVariants } from '@/components/ui/button';import type { ContentAuthor } from '@/lib/content/authors';@@ -8,12 +9,12 @@ import { BAND_CLASSES, qualityBand } from '@/lib/content/quality';import {authorProfile,FRESH_MONTHS,- scoreGain,trustGain,type EeatCheckId,type Score,type TrustRead,} from '@/lib/content/quality-checks';+import type { QualityTodo } from '@/lib/content/quality-todos';import {readabilityGain,SECTION_WORDS,@@ -41,28 +42,29 @@ export interface QualityRead {brandName: string;/** The site's trust in Site Audit (CE-043), or null while not read. */siteTrust: SiteTrust | null;+ /** What only the person can do (qualityTodos, CE-040). */+ todos: QualityTodo[];}type ScoreName = 'eeat' | 'trust' | 'readability';interface Suggestion {key: string;- score: ScoreName;+ // E-E-A-T's are the person's to-dos.+ score: Exclude<ScoreName, 'eeat'>;gain: number;line: string;detail: string;- action:- | { kind: 'show'; text: string }- | { kind: 'pickAuthor' }- | { kind: 'manageAuthors'; label: 'addAuthor' | 'editAuthor' }- | { kind: 'none' };+ /** The passage Show goes to, if any. */+ show: string | null;}/*** Instructions › Quality (Quality spec §3, CE-039): the three scores read* from the draft and its author, each labelled an Ansvisor estimate, then- * what would raise them, the biggest gain first. A score shows once one of- * its checks is live for the page.+ * what only the person can do (Your to-dos, CE-040) and what would raise+ * them, the biggest gain first. A score shows once one of its checks is+ * live for the page.*/export function QualityTab({quality,@@ -76,7 +78,6 @@ export function QualityTab({onPickAuthor: () => void;}) {const t = useTranslations('contentEditor.editor.quality');- const tAuthor = useTranslations('contentEditor.editor.author');const tSite = useTranslations('audit.siteTrust.checks');const format = useFormatter();const { readability, eeat, trust, siteTrust } = quality;@@ -86,13 +87,14 @@ export function QualityTab({{ name: 'trust', score: trust?.score ?? null, empty: t('notScored') },{ name: 'readability', score: readability?.score ?? null, empty: t('tooShortShort') },];- const suggestions = [- ...readabilitySuggestions(t, readability),- ...eeatSuggestions(t, quality, tAuthor('organization', { brand: quality.brandName })),- ...trustSuggestions(t, trust),- ]+ const { todos } = quality;+ const todosLeft = todos.filter((todo) => !todo.done).length;+ const suggestions = [...readabilitySuggestions(t, readability), ...trustSuggestions(t, trust)].filter((s) => s.gain > 0).sort((a, b) => b.gain - a.gain);+ // Every live check has its points: none to raise, none of the person's left+ // (a page too short to read says so instead).+ const allDone = suggestions.length === 0 && todosLeft === 0 && readability?.score !== null;return (<div className="space-y-4 text-sm">@@ -127,32 +129,54 @@ export function QualityTab({)}</section>- <section aria-label={t('suggestionsLabel')} className="space-y-2">- <h4 className="text-xs font-medium text-muted-foreground">{t('suggestionsLabel')}</h4>- {suggestions.length === 0 ? (- // A page too short to read says so above.- readability?.score !== null && (- <p className="text-xs text-muted-foreground">{t('nothingToRaise')}</p>- )- ) : (+ {todos.length > 0 && (+ <section aria-label={t('todos.title')} className="space-y-2">+ <h4 className="text-xs text-muted-foreground">+ <span className="font-medium">{t('todos.title')}</span>{' '}+ {t('todos.left', { count: todosLeft })}+ </h4><ul className="space-y-2">- {suggestions.map((s) => (- <li key={s.key} className="flex items-start gap-2.5 rounded-xl border px-3 py-2.5">- <span className="mt-0.5 shrink-0 rounded-md bg-emerald-50 px-1.5 text-[11px] font-medium text-emerald-700 tabular-nums dark:bg-emerald-950 dark:text-emerald-300">- {t('gain', { gain: s.gain, score: t(`names.${s.score}`) })}- </span>- <div className="min-w-0 flex-1">- <p className="font-medium [overflow-wrap:anywhere]">{s.line}</p>- <p className="text-xs text-muted-foreground [overflow-wrap:anywhere]">- {s.detail}- </p>- </div>- <SuggestionAction action={s.action} onShow={onShow} onPickAuthor={onPickAuthor} />- </li>+ {todos.map((todo) => (+ <TodoRow key={todo.id} todo={todo} quality={quality} onPickAuthor={onPickAuthor} />))}</ul>- )}- </section>+ </section>+ )}++ {(suggestions.length > 0 || allDone) && (+ <section aria-label={t('suggestionsLabel')} className="space-y-2">+ <h4 className="text-xs font-medium text-muted-foreground">{t('suggestionsLabel')}</h4>+ {allDone ? (+ <p className="text-xs text-muted-foreground">{t('nothingToRaise')}</p>+ ) : (+ <ul className="space-y-2">+ {suggestions.map((s) => (+ <li key={s.key} className="flex items-start gap-2.5 rounded-xl border px-3 py-2.5">+ <span className="mt-0.5 shrink-0 rounded-md bg-emerald-50 px-1.5 text-[11px] font-medium text-emerald-700 tabular-nums dark:bg-emerald-950 dark:text-emerald-300">+ {t('gain', { gain: s.gain, score: t(`names.${s.score}`) })}+ </span>+ <div className="min-w-0 flex-1">+ <p className="font-medium [overflow-wrap:anywhere]">{s.line}</p>+ <p className="text-xs text-muted-foreground [overflow-wrap:anywhere]">+ {s.detail}+ </p>+ </div>+ {s.show !== null && (+ <Button+ variant="outline"+ size="sm"+ className="h-7 shrink-0"+ onClick={() => onShow(s.show!)}+ >+ {t('show')}+ </Button>+ )}+ </li>+ ))}+ </ul>+ )}+ </section>+ )}{siteTrust && (<section@@ -182,47 +206,133 @@ export function QualityTab({);}-/** A suggestion's one button. */-function SuggestionAction({- action,- onShow,+/** A to-do's words: its title, the nudge's "Next for you" phrase and its detail line. */+export function useTodoCopy() {+ const t = useTranslations('contentEditor.editor.quality.todos');+ const tAuthor = useTranslations('contentEditor.editor.author');+ return (+ todo: QualityTodo,+ { author, brandName, canEdit }: Pick<QualityRead, 'author' | 'brandName' | 'canEdit'>,+ ) => {+ if (todo.id === 'byline') {+ const action = todo.action === 'addAuthor' ? 'addAuthor' : 'pickAuthor';+ return {+ title: t(`byline.title.${action}`),+ next: t(`byline.next.${action}`),+ detail:+ todo.done && author+ ? t('byline.done', { name: author.name })+ : action === 'addAuthor'+ ? t('byline.detail.addAuthor')+ : t('byline.detail.pickAuthor', {+ byline: tAuthor('organization', { brand: brandName }),+ }),+ };+ }+ if (!author) {+ return {+ title: t('authorProfile.titleNoAuthor'),+ next: t('authorProfile.nextNoAuthor'),+ detail: t('authorProfile.detail.noAuthor'),+ };+ }+ const { bio, links } = authorProfile(author);+ const missing = !bio && !links ? 'both' : !bio ? 'bio' : 'links';+ return {+ title: t('authorProfile.title', { name: author.name }),+ next: t('authorProfile.next', { name: author.name }),+ // Only whoever can edit the author is sent to; anyone else is told who can.+ detail: todo.done+ ? t('authorProfile.done')+ : canEdit+ ? t(`authorProfile.detail.${missing}`)+ : t(`authorProfile.askOthers.${missing}`, {+ name: author.name,+ member: author.userId ? 'yes' : 'no',+ }),+ };+ };+}++/**+ * A to-do: its box (checked once done, which the checks decide), what to+ * do, what it adds, and its one button while open.+ */+function TodoRow({+ todo,+ quality,onPickAuthor,}: {- action: Suggestion['action'];- onShow: (text: string) => void;+ todo: QualityTodo;+ quality: QualityRead;onPickAuthor: () => void;}) {const t = useTranslations('contentEditor.editor.quality');- switch (action.kind) {- case 'show':- return (- <Button- variant="outline"- size="sm"- className="h-7 shrink-0"- onClick={() => onShow(action.text)}+ const { title, detail } = useTodoCopy()(todo, quality);+ return (+ <li+ className={cn(+ 'flex items-start gap-2.5 rounded-xl border px-3 py-2.5',+ todo.done && 'bg-muted/40',+ )}+ >+ <span+ aria-hidden+ className={cn(+ 'mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border',+ todo.done+ ? 'border-emerald-600 bg-emerald-600 text-white dark:border-emerald-500 dark:bg-emerald-500 dark:text-emerald-950'+ : 'border-input bg-background',+ )}+ >+ {todo.done && <Check className="h-3 w-3" />}+ </span>+ <div className="min-w-0 flex-1">+ <p+ className={cn(+ 'font-medium [overflow-wrap:anywhere]',+ todo.done && 'text-muted-foreground line-through',+ )}>- {t('show')}- </Button>- );- case 'pickAuthor':- return (- <Button variant="outline" size="sm" className="h-7 shrink-0" onClick={onPickAuthor}>- {t('pickAuthor')}- </Button>- );- case 'manageAuthors':- return (- <Link- href={MANAGE_AUTHORS_PATH}- className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 shrink-0')}+ {title}+ <span className="sr-only">+ {' · '}+ {todo.done ? t('todos.done') : t('todos.open')}+ </span>+ </p>+ <p+ className={cn(+ 'text-xs text-muted-foreground [overflow-wrap:anywhere]',+ todo.done && 'line-through',+ )}>- {t(action.label)}- </Link>- );- case 'none':- return null;- }+ {detail}+ {!todo.done && todo.gain > 0 && (+ <>+ {' · '}+ <span className="font-medium whitespace-nowrap text-emerald-700 tabular-nums dark:text-emerald-300">+ {t('gain', { gain: todo.gain, score: t('names.eeat') })}+ </span>+ </>+ )}+ </p>+ </div>+ {!todo.done &&+ todo.action &&+ (todo.action === 'pickAuthor' ? (+ <Button variant="outline" size="sm" className="h-7 shrink-0" onClick={onPickAuthor}>+ {t('pickAuthor')}+ </Button>+ ) : (+ <Link+ href={MANAGE_AUTHORS_PATH}+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 shrink-0')}+ >+ {t(todo.action)}+ </Link>+ ))}+ </li>+ );}type T = ReturnType<typeof useTranslations<'contentEditor.editor.quality'>>;@@ -236,52 +346,11 @@ function readabilitySuggestions(t: T, readability: Readability | null): Suggestigain: readabilityGain(readability, check.id),line: line(t, check),detail: detail(t, check),- action: check.at ? { kind: 'show', text: check.at } : { kind: 'none' },+ show: check.at || null,}),);}-/**- * E-E-A-T's: with no person on the page, picking one is the fix (its gain is- * the byline's: what the author's profile adds depends on them), or adding- * one when the workspace has none; with one, completing their profile. Only- * whoever added the author, the author themself or an admin can, so anyone- * else is told who to ask instead of being sent where they can't edit.- */-function eeatSuggestions(t: T, quality: QualityRead, teamByline: string): Suggestion[] {- const { eeat, author, canEdit, hasAuthors } = quality;- if (!eeat || eeat.score === null) return [];- if (!author) {- return [- {- key: 'eeat:byline',- score: 'eeat',- gain: scoreGain(eeat, ['byline']),- line: t('checks.byline.line', { byline: teamByline }),- detail: t('checks.byline.detail'),- action: hasAuthors ? { kind: 'pickAuthor' } : { kind: 'manageAuthors', label: 'addAuthor' },- },- ];- }- const { bio, links } = authorProfile(author);- const missing = !bio && !links ? 'both' : !bio ? 'bio' : 'links';- return [- {- key: 'eeat:authorProfile',- score: 'eeat',- gain: scoreGain(eeat, ['authorBio']),- line: t(`checks.authorProfile.line.${missing}`, { name: author.name }),- detail: canEdit- ? t(`checks.authorProfile.detail.${missing}`)- : t(`checks.authorProfile.askOthers.${missing}`, {- name: author.name,- member: author.userId ? 'yes' : 'no',- }),- action: canEdit ? { kind: 'manageAuthors', label: 'editAuthor' } : { kind: 'none' },- },- ];-}-/*** Trust's: figures without a source, sources past FRESH_MONTHS, links that* don't answer, each with Show on the first one in the page. A broken link@@ -297,7 +366,7 @@ function trustSuggestions(t: T, trust: TrustRead | null): Suggestion[] {gain: trustGain(trust, ['claimsSourced']),line: t('checks.claimsSourced.line', { count: trust.unsourced.length }),detail: t('checks.claimsSourced.detail'),- action: { kind: 'show', text: trust.unsourced[0] },+ show: trust.unsourced[0],});}if (trust.stale.length) {@@ -311,7 +380,7 @@ function trustSuggestions(t: T, trust: TrustRead | null): Suggestion[] {months: FRESH_MONTHS,}),detail: t('checks.freshSources.detail'),- action: { kind: 'show', text: trust.stale[0].text },+ show: trust.stale[0].text,});}if (trust.broken.length) {@@ -324,7 +393,7 @@ function trustSuggestions(t: T, trust: TrustRead | null): Suggestion[] {count: trust.broken.length,url: trust.broken[0].url,}),- action: { kind: 'show', text: trust.broken[0].text },+ show: trust.broken[0].text,});}return out;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 d4f4d8ce4..0835a5f35 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@@ -2412,6 +2412,242 @@ describe('the side panel', () => {});});+ describe('Your to-dos: the next-step nudge (CE-040)', () => {+ const ada = {+ id: 'a1',+ name: 'Ada Lovelace',+ title: null,+ bio: null,+ photoUrl: null,+ sameAs: [],+ userId: null,+ createdBy: null,+ defaultFor: [],+ pages: null,+ };+ beforeEach(() => {+ sessionStorage.clear();+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';+ getContentAuthors.mockResolvedValue({+ authors: [ada],+ brands: [{ id: 'b1', name: 'Acme' }],+ me: { id: 'u1', role: 'analyst' },+ });+ });+ afterEach(() => {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ });+ const nudge = () => container.querySelector('[aria-label="Your next step"]');++ it('names the first to-do once the agent has written the page, and opens the author menu', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ getContentDraft.mockResolvedValue(+ draft({ status: 'draft', agentState: 'writing', agentSince: new Date().toISOString() }),+ );+ await renderPage();+ expect(nudge()).toBeNull();+ getContentDraft.mockResolvedValue(+ draft({ status: 'in_review', author: 'agent', authorId: null }),+ );+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));+ await act(async () => {});+ } finally {+ vi.useRealTimers();+ }+ expect(nudge()!.textContent).toBe(+ "Next for you: pick the page's author · 1 of 2Pick nowLater",+ );+ await act(async () => button('Pick now')!.click());+ expect(nudge()).toBeNull();+ expect(document.querySelectorAll('[role="menuitemradio"]').length).toBe(2);+ });++ it('stays away when the agent was stopped from the wait screen', async () => {+ getContentDraft.mockResolvedValue(+ draft({ status: 'draft', agentState: 'writing', agentSince: new Date().toISOString() }),+ );+ readAgentRun.mockResolvedValue({+ id: 'r1',+ kind: 'write',+ steps: [{ key: 'write_page', count: null }],+ step: 0,+ startedAt: new Date().toISOString(),+ finishedAt: null,+ stoppedAt: null,+ outcome: null,+ });+ await renderPage();+ await act(async () => {});+ getContentDraft.mockResolvedValue(draft({ authorId: null }));+ await act(async () => button('Stop')!.click());+ await act(async () => {});+ expect(container.querySelector('.ProseMirror')).not.toBeNull();+ expect(nudge()).toBeNull();+ });++ it('names it when Run Agent leaves its batch', async () => {+ getContentDraft.mockResolvedValue(+ draft({+ authorId: null,+ pageType: 'blog_post',+ bodyHtml: '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>',+ }),+ );+ getDraftSuggestions.mockResolvedValueOnce([]).mockResolvedValueOnce([+ {+ id: 'n1',+ batchId: 'b2',+ actionId: null,+ actionNo: null,+ kind: 'replace',+ blockText: 'We delve into how teams forecast.',+ beforeText: 'delve into',+ afterText: 'look at',+ reason: 'remove an AI trace (rule)',+ ruleKeys: ['aiTraces'],+ status: 'open',+ },+ ]);+ fixDraftRules.mockResolvedValue({ count: 1 });+ window.innerWidth = 1024;+ await renderPage();+ await act(async () =>+ container.querySelector<HTMLButtonElement>('header button[aria-label^="Rules "]')!.click(),+ );+ await act(async () =>+ [...panel()!.querySelectorAll<HTMLButtonElement>('button')]+ .find((b) => b.textContent === 'Run Agent')!+ .click(),+ );+ await act(async () => {});+ expect(fixDraftRules).toHaveBeenCalled();+ expect(nudge()!.textContent).toContain("Next for you: pick the page's author · 1 of 2");+ });++ it("doesn't show when Accept all can't be saved", async () => {+ getContentDraft.mockResolvedValue(+ draft({+ authorId: null,+ bodyHtml: '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>',+ }),+ );+ getDraftSuggestions.mockResolvedValue([+ {+ id: 'n1',+ batchId: 'b2',+ actionId: null,+ actionNo: null,+ kind: 'replace',+ blockText: 'We delve into how teams forecast.',+ beforeText: 'delve into',+ afterText: 'look at',+ reason: 'remove an AI trace (rule)',+ ruleKeys: ['aiTraces'],+ status: 'open',+ },+ ]);+ decideDraftSuggestions.mockRejectedValue(new Error('offline'));+ await renderPage();+ await act(async () =>+ [...container.querySelectorAll<HTMLButtonElement>('button')]+ .find((b) => b.textContent === 'Accept all')!+ .click(),+ );+ await act(async () => {});+ expect(toast.error).toHaveBeenCalled();+ expect(nudge()).toBeNull();+ });++ it("doesn't show on opening a draft, nor after Accept all with nothing left to do", async () => {+ getContentDraft.mockResolvedValue(+ draft({+ authorId: 'a1',+ bodyHtml: '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>',+ }),+ );+ getContentAuthors.mockResolvedValue({+ authors: [{ ...ada, bio: 'Writes about forecasting.', sameAs: ['https://x.com/ada'] }],+ brands: [{ id: 'b1', name: 'Acme' }],+ me: { id: 'u1', role: 'analyst' },+ });+ getDraftSuggestions.mockResolvedValue([+ {+ id: 'n1',+ batchId: 'b2',+ actionId: null,+ actionNo: null,+ kind: 'replace',+ blockText: 'We delve into how teams forecast.',+ beforeText: 'delve into',+ afterText: 'look at',+ reason: 'remove an AI trace (rule)',+ ruleKeys: ['aiTraces'],+ status: 'open',+ },+ ]);+ await renderPage();+ expect(nudge()).toBeNull();+ const accept = [...container.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent === 'Accept all',+ )!;+ await act(async () => accept.click());+ await act(async () => {});+ expect(decideDraftSuggestions).toHaveBeenCalledWith(['n1'], 'accepted');+ expect(nudge()).toBeNull();+ });++ it('names it after Accept all, and on Mark ready while marking goes on; Later hides it', async () => {+ getContentDraft.mockResolvedValue(+ draft({+ authorId: 'a1',+ bodyHtml: '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>',+ }),+ );+ getDraftSuggestions.mockResolvedValue([+ {+ id: 'n1',+ batchId: 'b2',+ actionId: null,+ actionNo: null,+ kind: 'replace',+ blockText: 'We delve into how teams forecast.',+ beforeText: 'delve into',+ afterText: 'look at',+ reason: 'remove an AI trace (rule)',+ ruleKeys: ['aiTraces'],+ status: 'open',+ },+ ]);+ markContentDraftReady.mockResolvedValue({ status: 'ready', tasksDone: 0 });+ await renderPage();+ const accept = [...container.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent === 'Accept all',+ )!;+ await act(async () => accept.click());+ await act(async () => {});+ expect(nudge()!.textContent).toContain(+ "Next for you: complete Ada Lovelace's profile · 1 of 1",+ );+ await act(async () => button('Later')!.click());+ expect(nudge()).toBeNull();++ // Later holds for the session: Mark ready marks, with no nudge.+ await act(async () => button('Mark ready')!.click());+ expect(markContentDraftReady).toHaveBeenCalledWith('d1');+ expect(nudge()).toBeNull();+ });++ it('names it on Mark ready with a to-do open', async () => {+ getContentDraft.mockResolvedValue(draft({ authorId: null }));+ markContentDraftReady.mockResolvedValue({ status: 'ready', tasksDone: 0 });+ await renderPage();+ await act(async () => button('Mark ready')!.click());+ expect(markContentDraftReady).toHaveBeenCalledWith('d1');+ expect(nudge()!.textContent).toContain("Next for you: pick the page's author");+ });+ });+describe('Run Agent: fix open rules', () => {const traced = draft({pageType: 'blog_post',diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsxindex 3fa1e62df..9c8b4eb28 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx@@ -79,14 +79,35 @@ export default function ContentEditorPage() {clearTimeout(timer);};}, [draftId, writing, read]);+ // The run ended with the page written (not failed, nor stopped from here):+ // the editor that opens on it nudges the person's next step (Quality spec+ // §4, CE-040).+ const [agentFinishedFor, setAgentFinishedFor] = useState<string | null>(null);+ const [stoppedFor, setStoppedFor] = useState<string | null>(null);+ const [wasWriting, setWasWriting] = useState(writing);+ if (writing !== wasWriting) {+ setWasWriting(writing);+ if (writing) setStoppedFor(null);+ else if (current?.draft) {+ const { id, agentState } = current.draft;+ setAgentFinishedFor(agentState === 'failed' || stoppedFor === id ? null : id);+ }+ }// The agent's run ended, or was stopped: read the draft now, not on the next look.- const rereadDraft = useCallback(() => {- getContentDraft(draftId).then(- (draft) => draft && setRead({ id: draftId, draft }),- // The next look tries again.- () => {},- );- }, [draftId]);+ const rereadDraft = useCallback(+ (stopped?: boolean) => {+ if (stopped) {+ setStoppedFor(draftId);+ setAgentFinishedFor(null);+ }+ getContentDraft(draftId).then(+ (draft) => draft && setRead({ id: draftId, draft }),+ // The next look tries again.+ () => {},+ );+ },+ [draftId],+ );return (<div className="-m-6 flex h-[calc(100vh-4rem)] flex-col md:h-screen">@@ -108,6 +129,7 @@ export default function ContentEditorPage() {<DraftEditorkey={current.draft.id}draft={current.draft}+ agentFinished={agentFinishedFor === current.draft.id}onAgentStarted={(run) =>setRead((prev) =>prev?.draftdiff --git a/web/src/lib/content/quality-todos.test.ts b/web/src/lib/content/quality-todos.test.tsnew file mode 100644index 000000000..683240855--- /dev/null+++ b/web/src/lib/content/quality-todos.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';+import type { ContentAuthor } from './authors';+import { eeat } from './quality-checks';+import { qualityTodos } from './quality-todos';++/** Your to-dos (Quality spec §4, CE-040): only what the person can do, read from the checks. */++const author = (over: Partial<ContentAuthor> = {}): ContentAuthor => ({+ id: 'a1',+ name: 'Ada Lovelace',+ title: null,+ bio: 'Writes about forecasting.',+ photoUrl: null,+ sameAs: ['https://www.linkedin.com/in/ada'],+ userId: null,+ createdBy: null,+ defaultFor: [],+ pages: null,+ ...over,+});+const todos = (a: ContentAuthor | null, hasAuthors = true, canEdit = true) =>+ qualityTodos({ eeat: eeat({ author: a }), author: a, hasAuthors, canEdit });++describe('qualityTodos', () => {+ it("asks to pick the page's author, with the byline's gain, and lists the profile after it", () => {+ expect(todos(null)).toEqual([+ { id: 'byline', done: false, gain: 60, action: 'pickAuthor' },+ { id: 'authorProfile', done: false, gain: 40, action: null },+ ]);+ });++ it('asks to add an author when the workspace has none', () => {+ expect(todos(null, false)[0]).toEqual({+ id: 'byline',+ done: false,+ gain: 60,+ action: 'addAuthor',+ });+ });++ it("keeps the byline done, then asks to complete the author's profile", () => {+ expect(todos(author({ bio: null, sameAs: [] }))).toEqual([+ { id: 'byline', done: true, gain: 0, action: 'pickAuthor' },+ { id: 'authorProfile', done: false, gain: 40, action: 'editAuthor' },+ ]);+ expect(todos(author({ sameAs: [] }))[1]).toEqual({+ id: 'authorProfile',+ done: false,+ gain: 20,+ action: 'editAuthor',+ });+ });++ it('checks both off for an author with a bio and profile links', () => {+ expect(todos(author()).map((t) => [t.id, t.done, t.gain])).toEqual([+ ['byline', true, 0],+ ['authorProfile', true, 0],+ ]);+ });++ it('offers Edit author only to who can edit the author', () => {+ expect(todos(author({ bio: null }), true, false)[1]).toMatchObject({+ id: 'authorProfile',+ action: null,+ });+ });++ it('has none before E-E-A-T is read', () => {+ expect(qualityTodos({ eeat: null, author: null, hasAuthors: true })).toEqual([]);+ });+});diff --git a/web/src/lib/content/quality-todos.ts b/web/src/lib/content/quality-todos.tsnew file mode 100644index 000000000..0785db07b--- /dev/null+++ b/web/src/lib/content/quality-todos.ts@@ -0,0 +1,64 @@+import type { ContentAuthor } from './authors';+import { authorProfile, scoreGain, type EeatCheckId, type Score } from './quality-checks';++/**+ * Your to-dos (Content Editor Quality spec §4, CE-040): what only the person+ * can do for the page, read from the check results (nothing entered by+ * hand). Everything else is a suggestion the agent can fix. Phase 1's are+ * the author's: the Content Agent can't add, pick or edit authors.+ */++export type QualityTodoId = 'byline' | 'authorProfile';++/** A to-do's one button: the header's author menu, or Settings › Authors. */+export type QualityTodoAction = 'pickAuthor' | 'addAuthor' | 'editAuthor';++export interface QualityTodo {+ id: QualityTodoId;+ done: boolean;+ /** What E-E-A-T gains once it is done; 0 when done. */+ gain: number;+ /** None while it waits on the one before it. */+ action: QualityTodoAction | null;+}++/**+ * The page's to-dos, in the order to do them: pick its author (or add one+ * when the workspace has none), then complete their profile, listed from the+ * start so the count holds. Done ones stay on the list, checked. None until+ * E-E-A-T is read.+ */+export function qualityTodos({+ eeat,+ author,+ hasAuthors,+ canEdit = false,+}: {+ eeat: Score<EeatCheckId> | null;+ author: ContentAuthor | null;+ hasAuthors: boolean;+ /**+ * Whether the member may edit the page's author (whoever added them, the+ * author themself or an admin): only they get Edit author; anyone else is+ * told who can.+ */+ canEdit?: boolean;+}): QualityTodo[] {+ if (!eeat || eeat.score === null) return [];+ const byline: QualityTodo = {+ id: 'byline',+ done: !!author,+ gain: scoreGain(eeat, ['byline']),+ action: author || hasAuthors ? 'pickAuthor' : 'addAuthor',+ };+ const { bio, links } = authorProfile(author);+ return [+ byline,+ {+ id: 'authorProfile',+ done: !!author && bio && links,+ gain: scoreGain(eeat, ['authorBio']),+ action: author && canEdit ? 'editAuthor' : null,+ },+ ];+}