Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(content): low items from the Content stack review (#1314)
Cihan4ac82ce58b46
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 0a256e0ea..cb5e4fe88 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3189,6 +3189,7 @@"score": "AEO score"},"scoreHint": "The page's AEO score, before → after the changes",+ "latestOnly": "Showing the {shown} changed most recently of {count}.","untitled": "Untitled","you": "You","contentAgent": "Content Agent",@@ -3782,6 +3783,9 @@"edited": "Edited by you.","builtFrom": "{count, plural, one {Built from # source} other {Built from # sources}} · {date}","rebuild": "Rebuild outline",+ "rebuildEdited": "Rebuild outline 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.",@@ -3890,6 +3894,8 @@"note": "Values you change apply to this draft only. Save as my rules keeps them for the workspace's next drafts of this type. Rules marked AI check are judged by the Content Agent and aren't counted yet.","updated": "Rule updated for this draft","saveFailed": "Couldn't update the rule. Try again.",+ "tooLong": "These rules are too long to save. Shorten or remove a rule first.",+ "tooLongMine": "These rules are too long to keep as My rules. Shorten or remove a rule first.","status": {"off": "Off","over": "{count} over",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.tsxindex 736f7c4c7..2d94033d7 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@@ -120,6 +120,22 @@ describe('the Brief tab', () => {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());+ expect(onRebuild).not.toHaveBeenCalled();+ expect(container.querySelector('[role="alert"]')!.textContent).toContain(+ 'Rebuild outline 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 anyway').click());+ expect(onRebuild).toHaveBeenCalledTimes(1);+ });+it('offers to build a brief for a new page without one', async () => {await render({ status: 'ready', brief: null },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.tsxindex 045d3ddb1..f2687ce47 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@@ -51,6 +51,8 @@ export function BriefTab({const t = useTranslations('contentEditor.editor.brief');const tTypes = useTranslations('contentEditor.pageTypes');const [editing, setEditing] = useState(false);+ // A brief edited by hand is rebuilt only once the person says so.+ const [confirming, setConfirming] = useState(false);if (state.status === 'loading') {return (@@ -172,8 +174,34 @@ export function BriefTab({</p>)}+ {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>+ )}+<div className="flex flex-wrap gap-2">- <Button size="sm" variant="outline" disabled={rebuilding} onClick={onRebuild}>+ <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" />) : (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.tsindex 9216486b9..4508bde95 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts@@ -28,7 +28,11 @@ export interface CitedLocks {export interface HeldEdit {/** The passage it touches. */key: string;- /** The change itself, to apply on "Edit anyway"; none for typing, which is typed again. */+ /**+ * The change itself, to apply on "Edit anyway": a held key's too (its+ * character, or the one character it deletes). None for a key that joins+ * blocks, which is pressed again.+ */tr: Transaction | null;}@@ -152,6 +156,22 @@ export function lockedPassageCount(state: EditorState): number {return citedPassagesKey.getState(state)?.marks.find().length ?? 0;}+/**+ * What a held key would do, for Edit anyway: type its character over the+ * selection, or delete the selection or the one character beside the cursor+ * in its block. Null when it would join two blocks.+ */+export function keyTransaction(state: EditorState, key: string): Transaction | null {+ const { selection } = state;+ if (key.length === 1) return state.tr.insertText(key);+ if (!selection.empty) return state.tr.deleteSelection();+ const { $from, from } = selection;+ if (key === 'Backspace') {+ return $from.parentOffset > 0 ? state.tr.delete(from - 1, from) : null;+ }+ return $from.parentOffset < $from.parent.content.size ? state.tr.delete(from, from + 1) : null;+}+export const CitedPassages = Extension.create<{ onHeld: (edit: HeldEdit) => void }>({name: 'citedPassages',@@ -216,7 +236,7 @@ export const CitedPassages = Extension.create<{ onHeld: (edit: HeldEdit) => voidif (!edits) return false;const key = lockedAtSelection(view.state, citedLocks(view.state));if (!key) return false;- onHeld({ key, tr: null });+ onHeld({ key, tr: keyTransaction(view.state, event.key) });return true;},},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 cb91255e3..b79dab630 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@@ -35,7 +35,12 @@ import {startAgentWriting,} from '@/lib/actions/content-drafts';import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';-import { CONTENT_LIBRARY_PATH, type ContentDraft, type PageType } from '@/lib/content/drafts';+import {+ CONTENT_LIBRARY_PATH,+ isPageType,+ type ContentDraft,+ type PageType,+} from '@/lib/content/drafts';import { CITED_DAYS, MAX_PASSAGES, type CitedPassage } from '@/lib/content/cited-passages';import type { DraftVersion } from '@/lib/content/history';import type { DraftSuggestion, SuggestionStatus } from '@/lib/content/suggestions';@@ -62,6 +67,7 @@ import {} from './_cited-passages';import { HistoryMenu } from './_history-menu';import { HtmlBlock, copyToClipboard } from './_html-block';+import { OwnCopies, ownCopyHtml } from './_own-copies';import { PageTypeMenu } from './_page-type-menu';import { ruleStatusText, type AgentFix } from './_rules-tab';import { EditorSidePanel, useSidePanelOpen } from './_side-panel';@@ -69,6 +75,7 @@ import {AgentSuggestions,acceptInto,suggestionsKey,+ redoDecision,undoInto,type SuggestionDecision,type SuggestionLabels,@@ -165,11 +172,17 @@ export function DraftEditor({// History keeps the page before the first suggestion accepted here.const agentBeforeKept = useRef(false);const onDecide = useRef<(id: string, decision: SuggestionDecision) => void>(() => {});- // A picked page type, or the one the page shows as it is written.+ // A picked page type, or the one the page shows as it is written. As on+ // a save, a page that shows no type keeps the one it had (the stored one+ // to start with), so the header and the Library agree.const [picked, setPicked] = useState(draft.pageTypeSource === 'user' ? draft.pageType : null);- const [detectedType, setDetectedType] = useState(() =>- detectPageType({ title: draft.title, html: draft.bodyHtml }, draft.siteType),+ const [detectedType, setDetectedType] = useState(+ () =>+ detectPageType({ title: draft.title, html: draft.bodyHtml }, draft.siteType) ??+ (isPageType(draft.pageType) ? draft.pageType : null),);+ const detectType = (title: string, html: string) =>+ setDetectedType((had) => detectPageType({ title, html }, draft.siteType) ?? had);const pageType = picked ?? detectedType;// The HTML view's text while it is open; null in the visual editor.const [htmlSource, setHtmlSource] = useState<string | null>(null);@@ -204,6 +217,7 @@ export function DraftEditor({label: (type) => (type ? t('jsonLd', { type }) : t('jsonLdUntyped')),}),HtmlBlock,+ OwnCopies,CitedPassages.configure({// The first change held is the one asked about: some keyboards// still send the text of a key whose keydown was held, and the@@ -218,9 +232,11 @@ export function DraftEditor({editorProps: {attributes: { class: DOCUMENT_CLASS, 'aria-label': t('documentLabel') },transformPastedHTML: (html) => {- // A copy from this editor keeps its images, and needs no word about it.- if (html.includes('data-pm-slice')) {- return cleanHtml(html, { keepImages: true, keepHtmlBlocks: true }).html;+ // A copy from this editor keeps its images and HTML blocks, and needs+ // no word about it. Only this tab's copies carry its mark.+ const own = ownCopyHtml(html);+ if (own !== null) {+ return cleanHtml(own, { keepImages: true, keepHtmlBlocks: true }).html;}// Images from elsewhere wait for attachments (CE-006): Docs' and// Word's are temporary addresses or embedded data.@@ -265,7 +281,7 @@ export function DraftEditor({clearTimeout(pageReadTimer.current);pageReadTimer.current = setTimeout(() => {setPageHtml(bodyHtml);- setDetectedType(detectPageType({ title: next, html: bodyHtml }, draft.siteType));+ detectType(next, bodyHtml);}, PAGE_READ_DELAY_MS);},});@@ -362,7 +378,7 @@ export function DraftEditor({unlocked: new Set(locks.unlocked).add(held.key),}),);- // A held paste, cut or join goes through; typed text is typed again.+ // The held change goes through: a paste, a cut, or the key pressed.if (held.tr && held.tr.before.eq(editor.state.doc)) {editor.view.dispatch(held.tr.setMeta(CITED_EDIT_ALLOWED, true));}@@ -465,7 +481,28 @@ export function DraftEditor({} finally {if (editable) editor.setEditable(true, false);}- if (tr?.docChanged && tr.before.eq(editor.state.doc)) editor.view.dispatch(tr);+ if (tr?.docChanged) {+ let change = tr;+ if (!tr.before.eq(editor.state.doc)) {+ // The page changed while the decision was saved: the change is made+ // again on the page as it is now. What it no longer fits goes back+ // to how it was, saved as well, so the cards and the page agree.+ const redo = redoDecision(+ editor.state,+ all,+ changed,+ decision === 'accept' ? 'accept' : 'undo',+ );+ change = redo.tr;+ if (redo.failed.length > 0) {+ const back: SuggestionStatus = decision === 'accept' ? 'open' : 'accepted';+ await decideDraftSuggestions(redo.failed, back);+ for (const s of next) if (redo.failed.includes(s.id)) s.status = back;+ toast(t('suggestions.notApplied', { count: redo.failed.length }));+ }+ }+ if (change.docChanged) editor.view.dispatch(change);+ }setSuggestions(next);if (decision === 'accept')toast.success(t('suggestions.acceptedToast', { count: changed.length }));@@ -716,7 +753,7 @@ export function DraftEditor({editor.setEditable(false, false);try {await autosave.settle();- const restored = await restoreDraftVersion(version.id);+ const restored = await restoreDraftVersion(draft.id, version.id);editor.chain().setMeta(CITED_EDIT_ALLOWED, true)@@ -728,7 +765,7 @@ export function DraftEditor({const html = editor.getHTML();setTitle(restored.title);setPageHtml(html);- setDetectedType(detectPageType({ title: restored.title, html }, draft.siteType));+ detectType(restored.title, html);toast.success(t('history.restored', { version: label }));void loadCited();} catch (err) {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_own-copies.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_own-copies.tsnew file mode 100644index 000000000..86a5c6c01--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_own-copies.ts@@ -0,0 +1,59 @@+import { Extension } from '@tiptap/core';+import { DOMSerializer, type Fragment } from '@tiptap/pm/model';+import { Plugin } from '@tiptap/pm/state';++/**+ * This editor's own copies (CE-005): a paste may bring HTML blocks back only+ * when it is a copy made here. ProseMirror's `data-pm-slice` can't tell:+ * every ProseMirror-based site puts it on its clipboard, and any page can+ * set it in a copy handler. So each copy made here carries a mark that only+ * this tab knows, and a paste keeps blocks only when it carries it.+ */++const OWN_COPY_ATTR = 'data-ce-copy';++/** Made once per tab: another page can't guess it. */+const nonce =+ typeof crypto !== 'undefined' && 'randomUUID' in crypto+ ? crypto.randomUUID()+ : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;++const MARKS = new RegExp(` ${OWN_COPY_ATTR}="[^"]*"`, 'g');++/**+ * Pasted HTML as a copy made in this tab's editor, its marks taken off (an+ * HTML block is read only in its plain form); null for any other paste.+ */+export function ownCopyHtml(html: string): string | null {+ return html.includes(`${OWN_COPY_ATTR}="${nonce}"`) ? html.replace(MARKS, '') : null;+}++/** The schema's own serializer, marking the top-level blocks of a copy. */+class MarkedSerializer extends DOMSerializer {+ serializeFragment(+ fragment: Fragment,+ options: { document?: Document } = {},+ target?: HTMLElement | DocumentFragment,+ ): HTMLElement | DocumentFragment {+ const out = super.serializeFragment(fragment, options, target);+ // Nested content is serialized into a target; only the copy itself is marked.+ if (!target) {+ for (const child of Array.from(out.childNodes)) {+ if (child.nodeType === 1) (child as Element).setAttribute(OWN_COPY_ATTR, nonce);+ }+ }+ return out;+ }+}++export const OwnCopies = Extension.create({+ name: 'ownCopies',+ addProseMirrorPlugins() {+ const base = DOMSerializer.fromSchema(this.editor.schema);+ return [+ new Plugin({+ props: { clipboardSerializer: new MarkedSerializer(base.nodes, base.marks) },+ }),+ ];+ },+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsxindex c8643068c..816542417 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@@ -108,6 +108,7 @@ export function EditorSidePanel({draft,pageNow: () => page.current,sourcesNow: () => sourcesNow.current,+ onSourcesRead: (read) => reads.setSources(read),onRebuilt: (next) => {reads.setBrief(next);open('brief');@@ -135,9 +136,7 @@ export function EditorSidePanel({brandId={draft.brandId}pageUrl={draft.sourceUrl}rebuilding={rebuilding}- onUseLostPrompts={(promptIds) =>- void rebuild({ addPrompts: promptIds }).then(() => reads.reloadSources())- }+ onUseLostPrompts={(promptIds) => void rebuild({ addPrompts: promptIds })}/></div>{briefOpened && (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.tsindex e9adbea32..ea2ce44ce 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts@@ -265,6 +265,34 @@ export function undoInto(return false;}+/**+ * A decision's page change made again on the page as it is now, for when the+ * page changed while the decision was saved (an attachment read in, say):+ * each suggestion in the order it was first applied. An undo leaves alone a+ * suggestion that was only rejected (it changed nothing on the page).+ * `failed` names the ones the page no longer has room for.+ */+export function redoDecision(+ state: EditorState,+ all: DraftSuggestion[],+ ids: string[],+ kind: 'accept' | 'undo',+): { tr: Transaction; failed: string[] } {+ const tr = state.tr;+ const list = all.map((s) => ({ ...s }));+ const failed: string[] = [];+ for (const id of ids) {+ const s = list.find((x) => x.id === id);+ if (!s || (kind === 'undo' && s.status !== 'accepted')) continue;+ if (kind === 'accept' ? acceptInto(tr, state, s, list) : undoInto(tr, state, s, list)) {+ s.status = kind === 'accept' ? 'accepted' : 'open';+ } else {+ failed.push(id);+ }+ }+ return { tr, failed };+}+// ─── The cards ────────────────────────────────────────────────────────────────const BUTTON =diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsxindex a6b6d2a25..d81cb3fd0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.test.tsx@@ -131,14 +131,28 @@ describe('the editor’s autosave', () => {await retry();expect(saveContentDraft).toHaveBeenCalledTimes(2);+ // The lost save may have been written: its page goes along, to be taken as ours.expect(saveContentDraft).toHaveBeenLastCalledWith('d1', {...content('<p>x</p>'),- base: loadedBase,+ base: { ...loadedBase, unconfirmedHash: 'hash:<p>x</p>' },});expect(state()).toBe('saved');++ // Once a save is answered, nothing is unconfirmed.+ edit('<p>last</p>');+ await act(async () => vi.advanceTimersByTime(1500));+ expect(saveContentDraft.mock.calls[2][1].base).toEqual({ updatedAt: 'now', bodyHash: 'h1' });error.mockRestore();});+ it('sends no unconfirmed page after a save the server answered with a failure', async () => {+ saveContentDraft.mockResolvedValueOnce({ ok: false, reason: 'invalid' });+ edit('<p>x</p>');+ await act(async () => vi.advanceTimersByTime(1500));+ await retry();+ expect(saveContentDraft.mock.calls[1][1].base).toEqual(loadedBase);+ });+it('stops saving when the page was changed elsewhere, rather than overwriting it', async () => {saveContentDraft.mockResolvedValueOnce({ ok: false, reason: 'conflict' });edit('<p>x</p>');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.tsindex 1f8699320..9b423f9f3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-autosave.ts@@ -28,8 +28,10 @@ interface DraftContent {** Each save goes only over the version this editor loaded or last saved, so* a page someone else changed meanwhile is never overwritten: the editor says- * so and stops saving until it's reloaded. A page over the size limit isn't- * sent at all.+ * so and stops saving until it's reloaded. A save whose answer never came+ * back may have been written: its page goes along with the next save, which+ * then takes it as this editor's own. A page over the size limit isn't sent+ * at all.** Before a step that reads the saved page (Mark ready keeps it in History) or* replaces it (a restore), settle() saves what is waiting and waits for a@@ -51,10 +53,16 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; bbodyHash: null,});const loadedBody = useRef(loaded.bodyHtml);+ // The page of a save sent whose answer never came back.+ const unconfirmed = useRef<string | null>(null);const baseVersion = useCallback(async () => {base.current.bodyHash ??= await bodyHash(loadedBody.current);- return { updatedAt: base.current.updatedAt, bodyHash: base.current.bodyHash };+ return {+ updatedAt: base.current.updatedAt,+ bodyHash: base.current.bodyHash,+ ...(unconfirmed.current && { unconfirmedHash: unconfirmed.current }),+ };}, []);const flush = useCallback(async () => {@@ -87,6 +95,7 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; breturn;}base.current = { updatedAt: result.updatedAt, bodyHash: result.bodyHash };+ unconfirmed.current = null;failed.current = false;if (pending.current) {// Typed while it saved: that waits for its own pause.@@ -97,6 +106,8 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; b}} catch (err) {console.error('Failed to save the draft:', err);+ // No answer: the write may have gone through all the same.+ unconfirmed.current = await bodyHash(content.bodyHtml).catch(() => null);saving.current = false;failed.current = true;pending.current ??= content;@@ -141,6 +152,7 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; bpending.current = null;failed.current = false;stopped.current = false;+ unconfirmed.current = null;base.current = { updatedAt: version.updatedAt, bodyHash: null };loadedBody.current = version.bodyHtml;if (!saving.current) setState('saved');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.test.tsxnew file mode 100644index 000000000..3f342bbcd--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.test.tsx@@ -0,0 +1,111 @@+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 { ContentDraft } from '@/lib/content/drafts';+import type { DraftSourceChoice, DraftSourcesData } from '@/lib/content/sources';+import { useBriefRebuild } from './_use-brief-rebuild';+import type { SourcesRead } from './_use-draft-reads';++/**+ * Rebuild outline (CE-007): from the sources in hand, or read afresh once+ * prompts were added — and that fresh read becomes the editor's, so the+ * Sources tab doesn't read them again.+ */++const addDraftPrompts = vi.fn();+const getDraftSources = vi.fn();+const rebuildDraftBrief = vi.fn();+vi.mock('@/lib/actions/content-drafts', () => ({+ addDraftPrompts: (...args: unknown[]) => addDraftPrompts(...args),+ getDraftSources: (...args: unknown[]) => getDraftSources(...args),+ rebuildDraftBrief: (...args: unknown[]) => rebuildDraftBrief(...args),+}));+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const SOURCES: { data: DraftSourcesData; choices: DraftSourceChoice[] } = {+ data: {+ prompts: [],+ fanouts: [{ query: 'espresso ratio', platforms: ['copilot-web'], searched: 3 }],+ citedPages: [],+ gscQueries: [],+ brandDomains: [],+ competitorDomains: [],+ },+ choices: [],+};+const draft = { id: 'd1', brandId: 'b1', sourceUrl: null } as unknown as ContentDraft;+const onSourcesRead = vi.fn();+const onRebuilt = vi.fn();+let inHand: SourcesRead | null;++/** The hook behind buttons, as the side panel drives it. */+function Harness() {+ const { rebuild } = useBriefRebuild({+ draft,+ pageNow: () => ({ title: 'T', html: '<h1>T</h1>', length: 3000 }),+ sourcesNow: () => inHand,+ onSourcesRead,+ onRebuilt,+ });+ return (+ <>+ <button data-rebuild onClick={() => void rebuild()} />+ <button data-lost onClick={() => void rebuild({ addPrompts: ['p1'] })} />+ </>+ );+}++const press = (name: 'rebuild' | 'lost') =>+ act(async () => container.querySelector<HTMLButtonElement>(`[data-${name}]`)!.click());++let container: HTMLDivElement;+let root: Root;++beforeEach(async () => {+ for (const fn of [addDraftPrompts, getDraftSources, rebuildDraftBrief, onSourcesRead, onRebuilt])+ fn.mockReset();+ addDraftPrompts.mockResolvedValue(undefined);+ getDraftSources.mockResolvedValue(SOURCES);+ rebuildDraftBrief.mockResolvedValue({ brief: { builtFrom: null } });+ inHand = { ...SOURCES, failed: false };+ container = document.createElement('div');+ root = createRoot(container);+ await act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <Harness />+ </NextIntlClientProvider>,+ ),+ );+});++afterEach(() => act(() => root.unmount()));++describe('useBriefRebuild', () => {+ it('builds from the sources in hand, reading nothing', async () => {+ await press('rebuild');+ expect(getDraftSources).not.toHaveBeenCalled();+ expect(onSourcesRead).not.toHaveBeenCalled();+ expect(onRebuilt).toHaveBeenCalled();+ });++ it('reads the sources once after adding prompts, and hands that read to the editor', async () => {+ await press('lost');+ expect(addDraftPrompts).toHaveBeenCalledWith('d1', ['p1']);+ expect(getDraftSources).toHaveBeenCalledTimes(1);+ expect(onSourcesRead).toHaveBeenCalledWith({ ...SOURCES, failed: false });+ });++ it('says the fresh read failed, so the Sources tab can try again', async () => {+ getDraftSources.mockResolvedValue(null);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ await press('lost');+ expect(onSourcesRead).toHaveBeenCalledWith({ data: null, choices: [], failed: true });+ expect(rebuildDraftBrief).not.toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.tsindex a0a6421a1..643292903 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts@@ -28,12 +28,15 @@ export function useBriefRebuild({draft,pageNow,sourcesNow,+ onSourcesRead,onRebuilt,}: {draft: ContentDraft;pageNow: () => PageNow;/** The sources as the editor has them; null until read. */sourcesNow: () => SourcesRead | null;+ /** The sources read afresh once prompts were added: the editor's copy, so they aren't read again. */+ onSourcesRead: (read: SourcesRead) => void;onRebuilt: (brief: DraftBrief) => void;}) {const t = useTranslations('contentEditor.editor.brief');@@ -49,10 +52,21 @@ export function useBriefRebuild({try {const added = !!options.addPrompts?.length;if (added) await addDraftPrompts(draft.id, options.addPrompts!);- // Prompts just added aren't in the sources in hand: those are read afresh.+ // Prompts just added aren't in the sources in hand: those are read+ // afresh, and the fresh read becomes the editor's.const inHand = added ? null : sourcesNow();- const read =- options.sources ?? (inHand && !inHand.failed ? inHand : await getDraftSources(draft.id));+ let read: { data: DraftSourcesData; choices: DraftSourceChoice[] } | null =+ options.sources ?? (inHand && !inHand.failed ? inHand : null);+ if (!read) {+ read = await getDraftSources(draft.id);+ if (added) {+ onSourcesRead(+ read+ ? { data: read.data, choices: read.choices, failed: false }+ : { data: null, choices: [], failed: true },+ );+ }+ }if (!read) throw new Error('not_found');const page = pageNow();const result = await rebuildDraftBrief(diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.tsindex d32802e6a..b9b445c87 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts@@ -1,6 +1,6 @@'use client';-import { useDeferredValue, useEffect, useMemo, useState } from 'react';+import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';import { getMyRuleSets, saveDraftRules, saveMyRuleSet } from '@/lib/actions/content-drafts';@@ -9,10 +9,12 @@ import {MAX_TEXT_RULES,activeRules,checkRule,+ draftRulesFit,effectiveRules,readPage,ruleLength,ruleSet,+ ruleSetFits,rulesMet,textRuleCheck,type ActiveRule,@@ -23,6 +25,7 @@ import {type TextRule,} from '@/lib/content/rules';import { buildSourceGroups } from '@/lib/content/sources';+import { useBrandStore } from '@/stores/use-brand-store';import type { DraftReads } from './_use-draft-reads';export interface DraftRulesState {@@ -88,6 +91,11 @@ export function useDraftRules({const [choices, setChoices] = useState<DraftRules>(draft.rules);const [mine, setMine] = useState<Partial<Record<PageType, SavedRuleSet>>>({});const [mineRead, setMineRead] = useState(false);+ const language = useBrandStore((s) => s.brands.find((b) => b.id === draft.brandId)?.language);+ // One save at a time, the latest waiting; what the database holds, to go back to.+ const saving = useRef(false);+ const waiting = useRef<{ rules: DraftRules; message: string } | null>(null);+ const saved = useRef<DraftRules>(draft.rules);useEffect(() => {let cancelled = false;@@ -133,8 +141,8 @@ export function useDraftRules({[choices, setType, mine],);const rules = useMemo(- () => activeRules(ruleSet(setType, { keywords }), effective),- [setType, keywords, effective],+ () => activeRules(ruleSet(setType, { keywords, language }), effective),+ [setType, keywords, language, effective],);// The checks follow the page a beat behind typing.const deferredHtml = useDeferredValue(html);@@ -149,19 +157,46 @@ export function useDraftRules({);const { met, total } = rulesMet(checked);- const save = (next: DraftRules, message: string) => {- // Before My rules are read, the draft would save Ansvisor's set over the workspace's.- if (!mineRead) return;- const before = choices;- setChoices(next);+ /**+ * Saves the latest change: one save at a time, so two quick changes can't+ * land out of order. A change made meanwhile waits and goes next (it holds+ * the earlier ones); only the last says it saved, or failed, and a failure+ * puts back what the database holds.+ */+ const flush = () => {+ if (saving.current || !waiting.current) return;+ const { rules: next, message } = waiting.current;+ waiting.current = null;+ saving.current = true;saveDraftRules(draft.id, next)- .then(() => toast(message))+ .then(() => {+ saved.current = next;+ if (!waiting.current) toast(message);+ }).catch((err) => {console.error('Failed to save the rules:', err);- setChoices(before);- toast.error(t('saveFailed'));+ if (!waiting.current) {+ setChoices(saved.current);+ toast.error(t('saveFailed'));+ }+ })+ .finally(() => {+ saving.current = false;+ flush();});};+ const save = (next: DraftRules, message: string) => {+ // Before My rules are read, the draft would save Ansvisor's set over the workspace's.+ if (!mineRead) return;+ // Past the database's size check the save would fail: the change stays out.+ if (!draftRulesFit(next)) {+ toast.error(t('tooLong'));+ return;+ }+ setChoices(next);+ waiting.current = { rules: next, message };+ flush();+ };// A change keeps the set the draft's rules come from.const edited = (change: Partial<DraftRules>, message = t('updated')) =>save({ ...effective, source: effective.source ?? 'default', ...change }, message);@@ -227,6 +262,10 @@ export function useDraftRules({saveAsMine: () => {if (!setType) return;const set: SavedRuleSet = { overrides: effective.overrides, textRules: effective.textRules };+ if (!ruleSetFits(set)) {+ toast.error(t('tooLongMine'));+ return;+ }saveMyRuleSet(draft.brandId, setType, set).then(() => {setMine((prev) => ({ ...prev, [setType]: set }));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 da871bae5..a8f2344fc 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@@ -8,6 +8,7 @@ import { RoleProvider } from '@/components/providers/role-provider';import type { ContentDraft } from '@/lib/content/drafts';import type { DraftSuggestion } from '@/lib/content/suggestions';import { passageKey, type CitedPassage } from '@/lib/content/cited-passages';+import { encodeHtmlBlock } from '@/lib/content/html-allowlist';import ContentEditorPage from './page';const getContentDraft = vi.fn();@@ -368,6 +369,27 @@ describe('the content editor', () => {expect(typeMenu().title).toBe('https://northwind.example/features/pipeline-forecasting/');});+ it('keeps the type it had while the page shows none, as a save does', async () => {+ getContentDraft.mockResolvedValue(+ draft({+ title: 'Notes',+ bodyHtml: '<h1>Notes</h1>',+ pageType: 'blog_post',+ pageTypeSource: 'detected',+ }),+ );+ await renderPage();+ expect(typeMenu().textContent).toContain('Blog post');+ await rewrite('<h1>Northwind vs HubSpot</h1>');+ // It reads the page once typing pauses.+ await act(() => new Promise((resolve) => setTimeout(resolve, 450)));+ expect(typeMenu().textContent).toContain('Comparison');+ // Then nothing on the page tells a type: the last one stays.+ await rewrite('<h1>More notes</h1>');+ await act(() => new Promise((resolve) => setTimeout(resolve, 450)));+ expect(typeMenu().textContent).toContain('Comparison');+ });+it('says when no type is detected yet', async () => {getContentDraft.mockResolvedValue(draft({ pageType: null, pageTypeSource: 'detected', method: 'create' }),@@ -563,7 +585,7 @@ describe('the content editor', () => {bodyHash: expect.stringMatching(/^[0-9a-f]{64}$/),},});- expect(restoreDraftVersion).toHaveBeenCalledWith('v1');+ expect(restoreDraftVersion).toHaveBeenCalledWith('d1', 'v1');expect(saveContentDraft.mock.invocationCallOrder[0]).toBeLessThan(restoreDraftVersion.mock.invocationCallOrder[0],);@@ -710,7 +732,7 @@ describe('the content editor', () => {expect(container.querySelector('header')!.textContent).not.toContain('cited passage');});- it('holds a key once, even when its text follows the held keydown', async () => {+ it('holds a key once, even when its text follows the held keydown, and types it on Edit anyway', async () => {getContentDraft.mockResolvedValue(page);getCitedPassages.mockResolvedValue(cited);await renderPage();@@ -725,7 +747,28 @@ describe('the content editor', () => {editorOf().commands.insertContentAt(at, 'x');});await act(async () => dialogButton('Edit anyway').click());- expect(container.querySelector('.cited-passage')!.textContent).toBe(QUOTED);+ // The key pressed is typed, once.+ expect(container.querySelector('.ProseMirror')!.textContent).toContain(+ `${QUOTED.slice(0, 4)}x${QUOTED.slice(4)}`,+ );+ expect(container.querySelector('.cited-passage')).toBeNull();+ });++ it('deletes the character a held Backspace would, on Edit anyway', async () => {+ getContentDraft.mockResolvedValue(page);+ getCitedPassages.mockResolvedValue(cited);+ await renderPage();++ await act(async () => {+ editorOf().commands.setTextSelection(quotedAt() + 4);+ editorOf().view.dom.dispatchEvent(+ new KeyboardEvent('keydown', { key: 'Backspace', bubbles: true, cancelable: true }),+ );+ });+ await act(async () => dialogButton('Edit anyway').click());+ expect(container.querySelector('.ProseMirror')!.textContent).toContain(+ `${QUOTED.slice(0, 3)}${QUOTED.slice(4)}`,+ );});it('lets typing through once the person chose to edit it', async () => {@@ -846,6 +889,34 @@ describe('the content editor', () => {expect(keepAgentBeforeVersion).toHaveBeenCalledTimes(1);});+ it('makes an accept again on the page when it changed while the decision was saved', async () => {+ getContentDraft.mockResolvedValue(page);+ getDraftSuggestions.mockResolvedValue(batch);+ let saved: () => void = () => {};+ decideDraftSuggestions.mockReturnValueOnce(new Promise<void>((r) => (saved = r)));+ await renderPage();++ await act(async () => {+ cardOf('s1')!+ .querySelectorAll('button')+ .forEach((b) => b.textContent === 'Accept' && b.click());+ });+ // An attachment read in while the decision is being saved.+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })+ .editor;+ await act(async () => {+ editor.commands.insertContentAt(editor.state.doc.content.size, '<p>From a file.</p>');+ });+ await act(async () => saved());+ await act(async () => {});++ expect(pageText()).toContain(+ 'Accuracy is shown per team, each week, against closed revenue.',+ );+ expect(pageText()).toContain('From a file.');+ expect(cardOf('s1')!.textContent).toContain('Accepted');+ });+it('rejects one, and restores it to review', async () => {getContentDraft.mockResolvedValue(page);getDraftSuggestions.mockResolvedValue(batch);@@ -1007,6 +1078,41 @@ describe('the content editor', () => {expect(container.querySelector('header')!.textContent).toContain('Saved');});+ it('keeps HTML blocks only in a paste copied from this editor', async () => {+ getContentDraft.mockResolvedValue(+ draft({+ bodyHtml: `<h1>Trail Runner X</h1><div data-html-block="${encodeHtmlBlock('<p>hi</p>')}"></div><p>End.</p>`,+ }),+ );+ await renderPage();+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })+ .editor;+ const blocks = () => container.querySelectorAll('[data-html-block-view]').length;+ expect(blocks()).toBe(1);++ // jsdom has no ClipboardEvent, which pasteHTML makes.+ if (!('ClipboardEvent' in globalThis)) {+ Object.assign(globalThis, { ClipboardEvent: class extends Event {} });+ }+ // Copied here: the editor's own clipboard HTML.+ const { dom } = editor.view.serializeForClipboard(+ editor.state.doc.slice(0, editor.state.doc.content.size),+ );+ const own = dom.innerHTML;+ // Another ProseMirror site's copy says data-pm-slice too, without this tab's mark.+ const foreign = own.replace(/ data-ce-copy="[^"]*"/g, '');+ expect(foreign).toContain('data-pm-slice');+ await act(async () => {+ editor.commands.setTextSelection(editor.state.doc.content.size - 1);+ editor.view.pasteHTML(foreign);+ });+ expect(blocks()).toBe(1);+ await act(async () => {+ editor.view.pasteHTML(own);+ });+ expect(blocks()).toBe(2);+ });+it('adds HTML blocks, shows their code as text, and copies one or the whole page', async () => {const writeText = vi.fn().mockResolvedValue(undefined);Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });@@ -1367,6 +1473,85 @@ describe('the side panel', () => {expect(toast).toHaveBeenCalledWith('Rule updated for this draft');});+ it('saves rule changes one at a time, the latest last, and says so once', async () => {+ getContentDraft.mockResolvedValue(draft({ pageType: 'blog_post' }));+ let finish: () => void = () => {};+ saveDraftRules.mockImplementationOnce(() => new Promise<void>((r) => (finish = r)));+ window.innerWidth = 1024;+ await renderPage();+ const chip = container.querySelector<HTMLButtonElement>('header button[aria-label^="Rules "]')!;+ await act(async () => chip.click());+ const toggle = (label: string) =>+ act(async () =>+ panel()!+ .querySelector<HTMLElement>(`[role="switch"][aria-label="${label}: on or off"]`)!+ .click(),+ );++ await toggle('Max sentence length');+ await toggle('FAQ block');+ await toggle('Max sentence length');+ // The first save is still under way: the others wait.+ expect(saveDraftRules).toHaveBeenCalledTimes(1);+ await act(async () => finish());+ await act(async () => {});+ // Then only the latest goes, holding every change.+ expect(saveDraftRules).toHaveBeenCalledTimes(2);+ expect(saveDraftRules.mock.calls[1][1].overrides).toEqual({+ sentence: { on: true },+ faq: { on: false },+ });+ expect(+ vi.mocked(toast).mock.calls.filter(([m]) => m === 'Rule updated for this draft'),+ ).toHaveLength(1);+ });++ it('says when the rules are too long to save, rather than failing the save', async () => {+ // 40 rules of 300 characters in a script of 3 bytes each: past the 32 KB check.+ const textRules = Array.from({ length: 40 }, (_, i) => ({+ id: `r${i}`,+ text: '日'.repeat(300),+ on: true,+ }));+ getContentDraft.mockResolvedValue(+ draft({+ pageType: 'blog_post',+ rules: { set: null, source: 'default', overrides: {}, textRules },+ }),+ );+ window.innerWidth = 1024;+ await renderPage();+ const chip = container.querySelector<HTMLButtonElement>('header button[aria-label^="Rules "]')!;+ await act(async () => chip.click());+ await act(async () =>+ panel()!+ .querySelector<HTMLElement>('[role="switch"][aria-label="Max sentence length: on or off"]')!+ .click(),+ );+ expect(saveDraftRules).not.toHaveBeenCalled();+ expect(toast.error).toHaveBeenCalledWith(+ 'These rules are too long to save. Shorten or remove a rule first.',+ );+ });++ it('sets the Language rule from the brand’s language', async () => {+ brandState.brands = [{ id: 'b1', language: 'tr' } as never, { id: 'b2' }];+ try {+ getContentDraft.mockResolvedValue(draft({ pageType: 'blog_post' }));+ window.innerWidth = 1024;+ await renderPage();+ const chip = container.querySelector<HTMLButtonElement>(+ 'header button[aria-label^="Rules "]',+ )!;+ await act(async () => chip.click());+ const values = [...panel()!.querySelectorAll<HTMLInputElement>('input')].map((i) => i.value);+ expect(values).toContain('Turkish');+ expect(values).not.toContain('English (US)');+ } finally {+ brandState.brands = [{ id: 'b1' }, { id: 'b2' }];+ }+ });+describe('Fix open rules with agent', () => {const traced = draft({pageType: 'blog_post',diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsxindex 542d6d3f2..8cdeba2df 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx@@ -3,13 +3,17 @@ 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 { ContentDraftListItem } from '@/lib/content/drafts';+import { libraryTabCounts, type ContentDraftListItem } from '@/lib/content/drafts';import ContentLibraryPage from './page';const getContentDrafts = vi.fn();const getContentStartOptions = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({- getContentDrafts: (...args: unknown[]) => getContentDrafts(...args),+ // A list stands for a brand under the cap: its tabs count its rows.+ getContentDrafts: async (...args: unknown[]) => {+ const read = await getContentDrafts(...args);+ return Array.isArray(read) ? { drafts: read, counts: libraryTabCounts(read) } : read;+ },getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),createContentDraft: vi.fn(),}));@@ -153,6 +157,22 @@ describe('the Content Library', () => {expect(link.getAttribute('href')).toBe('/dashboard/content/editor/d1');});+ it('counts each tab in all past the cap, and says the list holds the latest', async () => {+ getContentDrafts.mockResolvedValue({+ drafts: [row({}), row({ id: 'd2', status: 'published' })],+ counts: { all: 812, draft: 300, in_review: 12, ready: 0, published: 500 },+ });+ await renderPage();+ expect(tab('All').textContent).toBe('All812');+ expect(tab('Published').textContent).toBe('Published500');+ expect(container.textContent).toContain('Showing the 2 changed most recently of 812.');++ await act(async () => {+ tab('Ready').click();+ });+ expect(container.textContent).not.toContain('changed most recently');+ });+it('shows a tab’s drafts only, and keeps the tab in the URL', async () => {getContentDrafts.mockResolvedValue([row({}), row({ id: 'd2', status: 'published' })]);await renderPage();diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsxindex 56321b0e5..f5893824b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx@@ -12,7 +12,6 @@ import {AGENT_POLL_MS,LIBRARY_TABS,draftsInTab,- libraryTabCounts,type ContentDraftListItem,type LibraryTab,} from '@/lib/content/drafts';@@ -26,6 +25,8 @@ import { LibraryTable } from './_library-table';interface LibraryRead {brandId: string;drafts: ContentDraftListItem[] | null;+ /** Each tab's drafts in all: past the Library's cap, more than it lists. */+ counts: Record<LibraryTab, number> | null;failed: boolean;}@@ -52,12 +53,14 @@ export default function ContentLibraryPage() {if (!activeBrandId) return;let cancelled = false;getContentDrafts(activeBrandId)- .then((drafts) => {- if (!cancelled) setRead({ brandId: activeBrandId, drafts, failed: false });+ .then(({ drafts, counts }) => {+ if (!cancelled) setRead({ brandId: activeBrandId, drafts, counts, failed: false });}).catch((err) => {console.error('Failed to load the content library:', err);- if (!cancelled) setRead({ brandId: activeBrandId, drafts: null, failed: true });+ if (!cancelled) {+ setRead({ brandId: activeBrandId, drafts: null, counts: null, failed: true });+ }});return () => {cancelled = true;@@ -89,7 +92,8 @@ export default function ContentLibraryPage() {// A read for another brand (just switched) counts as still loading.const current = read?.brandId === activeBrandId ? read : null;const drafts = current?.drafts ?? null;- const counts = drafts ? libraryTabCounts(drafts) : null;+ const counts = current?.counts ?? null;+ const listed = drafts ? draftsInTab(drafts, tab) : [];return (<div className="space-y-6">@@ -143,10 +147,18 @@ export default function ContentLibraryPage() {<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>) : (- <LibraryTable drafts={draftsInTab(drafts, tab)} tab={tab} />+ <LibraryTable drafts={listed} tab={tab} />)}</CardContent></Card>+ {counts && listed.length < counts[tab] && (+ <p className="text-xs text-muted-foreground">+ {t('latestOnly', {+ shown: formatNumber(listed.length),+ count: formatNumber(counts[tab]),+ })}+ </p>+ )}</div>);}diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsxindex 415163c3a..03a77f779 100644--- a/web/src/components/content/new-content-dialog.tsx+++ b/web/src/components/content/new-content-dialog.tsx@@ -67,6 +67,7 @@ import {} from '@/lib/content/start';import { formatNumber } from '@/lib/format';import { cn } from '@/lib/utils';+import { useBrandStore } from '@/stores/use-brand-store';type SourceKind = 'opportunity' | 'prompt' | 'topic';const SOURCE_KINDS: SourceKind[] = ['opportunity', 'prompt', 'topic'];@@ -159,6 +160,8 @@ export function NewContentDialog({preset?: DialogPreset | null;}) {const t = useTranslations('contentEditor.newContent');+ // The Language rule's default for the agent: the brand's language.+ const brandLanguage = useBrandStore((s) => s.brands.find((b) => b.id === brandId)?.language);const tTypes = useTranslations('contentEditor.pageTypes');const router = useRouter();const describeRule = useRuleDescriber();@@ -500,6 +503,7 @@ export function NewContentDialog({sourceUrl: existing?.url ?? start?.sourceUrl ?? null,bodyHtml: bodyHtml ?? '',rules: NO_DRAFT_RULES,+ language: brandLanguage,},describeRule,);diff --git a/web/src/lib/actions/content-drafts-library.test.ts b/web/src/lib/actions/content-drafts-library.test.tsnew file mode 100644index 000000000..5092c6c49--- /dev/null+++ b/web/src/lib/actions/content-drafts-library.test.ts@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The Library's read (CE-002): the latest 500 drafts, and each tab counted+ * in all once a brand has more.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';++let rows: Record<string, unknown>[];+let counted: Record<string, number>;+let countReads: string[];++vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));+vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },+ from: () => {+ let head = false;+ let status = 'all';+ const chain: Record<string, unknown> = {+ select: (_cols: string, opts?: { head?: boolean }) => ((head = !!opts?.head), chain),+ eq: (col: string, v: string) => (col === 'status' && (status = v), chain),+ order: () => chain,+ limit: async () => ({ data: rows, error: null }),+ then: (resolve: (r: unknown) => void) => {+ countReads.push(status);+ resolve({ count: head ? counted[status] : null, error: null });+ },+ };+ return chain;+ },+ })),+}));++const { getContentDrafts } = await import('./content-drafts');++const row = (i: number, status = 'draft') => ({+ id: `d${i}`,+ title: `Draft ${i}`,+ page_type: null,+ method: 'create',+ status,+ author: 'user',+ created_by: 'u1',+ score_before: null,+ score_after: null,+ agent_state: null,+ agent_state_at: null,+ updated_at: '2026-10-21T10:00:00Z',+});++beforeEach(() => {+ countReads = [];+ counted = { all: 812, draft: 300, in_review: 12, ready: 0, published: 500 };+});++describe('getContentDrafts', () => {+ it('counts the tabs from the rows under the cap', async () => {+ rows = [row(1), row(2, 'published')];+ const { drafts, counts } = await getContentDrafts(BRAND);+ expect(drafts).toHaveLength(2);+ expect(counts).toEqual({ all: 2, draft: 1, in_review: 0, ready: 0, published: 1 });+ expect(countReads).toEqual([]);+ });++ it('counts each tab on its own at the cap', async () => {+ rows = Array.from({ length: 500 }, (_, i) => row(i));+ const { drafts, counts } = await getContentDrafts(BRAND);+ expect(drafts).toHaveLength(500);+ expect(counts).toEqual(counted);+ expect(countReads.sort()).toEqual(['all', 'draft', 'in_review', 'published', 'ready']);+ });+});diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.tsindex 2ac20adbe..116540ed7 100644--- a/web/src/lib/actions/content-drafts-start.test.ts+++ b/web/src/lib/actions/content-drafts-start.test.ts@@ -116,12 +116,13 @@ describe('getContentStartOptions', () => {{ id: 'o2', title: 'Refresh the pricing page', decision: 'refresh', brief: null },],prompts: [- { id: PROMPT, text: 'best crm for realtors', topic_id: TOPIC },- { id: 'p2', text: 'crm pricing', topic_id: null },+ { id: PROMPT, text: 'best crm for realtors' },+ { id: 'p2', text: 'crm pricing' },],+ // Counted in the database: a big brand's topics past the listed prompts too.topics: [- { id: TOPIC, name: 'Real estate' },- { id: 't2', name: 'Empty topic' },+ { id: TOPIC, name: 'Real estate', prompts: [{ count: 640 }] },+ { id: 't2', name: 'Empty topic', prompts: [{ count: 0 }] },],};await expect(getContentStartOptions(BRAND)).resolves.toEqual({@@ -138,7 +139,7 @@ describe('getContentStartOptions', () => {{ id: PROMPT, text: 'best crm for realtors' },{ id: 'p2', text: 'crm pricing' },],- topics: [{ id: TOPIC, name: 'Real estate', promptCount: 1 }],+ topics: [{ id: TOPIC, name: 'Real estate', promptCount: 640 }],});expect(calls.find((call) => call.table === 'content_opportunities')!.filters).toEqual([['eq', 'brand_id', BRAND],@@ -148,6 +149,11 @@ describe('getContentStartOptions', () => {['eq', 'prompt_sets.brand_id', BRAND],['eq', 'is_active', true],]);+ expect(calls.find((call) => call.table === 'topics')!.filters).toEqual([+ ['eq', 'brand_id', BRAND],+ ['eq', 'is_active', true],+ ['eq', 'prompts.is_active', true],+ ]);});});diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsindex 20016d2a5..baa06f0d4 100644--- a/web/src/lib/actions/content-drafts.test.ts+++ b/web/src/lib/actions/content-drafts.test.ts@@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';*/const DRAFT = '2f1d1c52-0f7a-4c1e-9b8a-5d6e7f8a9b0c';+const VERSION = '3a2e2d63-1f8b-4d2f-8c9b-6e7f8a9b0c1d';interface Call {op: string;@@ -150,6 +151,18 @@ describe('saveContentDraft', () => {expect(calls[2].filters).toContainEqual(['eq', 'updated_at', '2026-10-20T14:30:00Z']);});+ it('takes the page of its own save whose answer was lost as its own', async () => {+ // The lost save wrote "<h1>Mine</h1>"; the editor still holds the loaded base.+ updates = [null, { updated_at: '2026-10-20T15:01:00Z' }];+ row = { updated_at: '2026-10-20T14:30:00Z', body_html: '<h1>Mine</h1>' };+ const result = await saveContentDraft(DRAFT, {+ title: 'Mine',+ bodyHtml: '<h1>Mine</h1><p>More</p>',+ base: { ...(await base()), unconfirmedHash: await bodyHash('<h1>Mine</h1>') },+ });+ expect(result).toMatchObject({ ok: true, updatedAt: '2026-10-20T15:01:00Z' });+ });+it('doesn’t overwrite a page someone else changed', async () => {row = { updated_at: '2026-10-20T14:30:00Z', body_html: '<h1>Their version</h1>' };await expect(@@ -406,16 +419,41 @@ describe('History', () => {data: { title: 'Old', bodyHtml: '<h1>Old</h1>', updatedAt: '2026-10-21T10:00:00Z' },error: null,};- await expect(restoreDraftVersion(DRAFT)).resolves.toEqual({+ await expect(restoreDraftVersion(DRAFT, VERSION)).resolves.toEqual({title: 'Old',bodyHtml: '<h1>Old</h1>',updatedAt: '2026-10-21T10:00:00Z',});- expect(rpcCalls).toEqual([['content_draft_restore', { p_version_id: DRAFT }]]);+ expect(rpcCalls).toEqual([['content_draft_restore', { p_version_id: VERSION }]]);rpcResult = { data: null, error: null };- await expect(restoreDraftVersion(DRAFT)).rejects.toThrow('not_found');- await expect(restoreDraftVersion('../etc')).rejects.toThrow('invalid');+ await expect(restoreDraftVersion(DRAFT, VERSION)).rejects.toThrow('not_found');+ await expect(restoreDraftVersion(DRAFT, '../etc')).rejects.toThrow('invalid');+ });++ it('gives a draft whose type follows its page the restored page’s type', async () => {+ rpcResult = {+ data: { title: 'Acme vs HubSpot', bodyHtml: '<h1>Acme vs HubSpot</h1>', updatedAt: 't1' },+ error: null,+ };+ row = {+ page_type: 'blog_post',+ page_type_source: 'detected',+ body_html: '<h1>Acme vs HubSpot</h1>',+ brands: { site_type: 'b2b', industry: 'Software', shopping_mode_enabled: false },+ };+ updates = [{ updated_at: 't2' }];+ // The saves go on from the type write.+ await expect(restoreDraftVersion(DRAFT, VERSION)).resolves.toMatchObject({ updatedAt: 't2' });+ const typed = calls.find((call) => call.op === 'update')!;+ expect(typed.value).toEqual({ page_type: 'comparison' });+ expect(typed.filters).toContainEqual(['eq', 'page_type_source', 'detected']);++ // A type the person picked stays.+ calls = [];+ row = { ...row, page_type_source: 'user' };+ await expect(restoreDraftVersion(DRAFT, VERSION)).resolves.toMatchObject({ updatedAt: 't1' });+ expect(calls.some((call) => call.op === 'update')).toBe(false);});});diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 9dbded141..3bc2e43f5 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -6,9 +6,11 @@ import { createClient } from '@/lib/supabase/server';import { readAssignees } from '@/lib/action-center/assignees';import {DRAFT_STATUSES,+ LIBRARY_TABS,PAGE_TYPES,WRITING_STALE_MS,agentStateOf,+ libraryTabCounts,type ContentDraft,type ContentDraftListItem,type ContentOverlap,@@ -17,6 +19,7 @@ import {type DraftStartOptions,type DraftStatus,type ImportedPage,+ type LibraryTab,type PageImportError,type PageType,PAGE_IMPORT_ERRORS,@@ -33,7 +36,9 @@ import { detectPageType, siteTypeOf, type SiteType } from '@/lib/content/page-tyimport { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';import {NO_DRAFT_RULES,+ draftRulesFit,draftRulesSchema,+ ruleSetFits,savedRuleSetSchema,type DraftRulesInput,type SavedRuleSet,@@ -93,8 +98,40 @@ import {/** How many drafts the Library lists, the latest changed first. */const LIBRARY_LIMIT = 500;-/** The brand's drafts for the Library, with who started each. */-export async function getContentDrafts(brandId: string): Promise<ContentDraftListItem[]> {+/** The Library: the latest drafts, and how many each tab holds in all. */+export interface ContentLibrary {+ drafts: ContentDraftListItem[];+ counts: Record<LibraryTab, number>;+}++/**+ * Each tab's drafts counted on their own, for a brand past the Library's+ * cap: the listed rows would undercount them.+ */+async function countLibraryTabs(+ supabase: Awaited<ReturnType<typeof createClient>>,+ brandId: string,+): Promise<Record<LibraryTab, number>> {+ const counted = await Promise.all(+ LIBRARY_TABS.map(async (tab) => {+ let query = supabase+ .from('content_drafts')+ .select('id', { count: 'exact', head: true })+ .eq('brand_id', brandId);+ if (tab !== 'all') query = query.eq('status', tab);+ const { count, error } = await query;+ if (error) throw new Error(error.message);+ return [tab, count ?? 0] as const;+ }),+ );+ return Object.fromEntries(counted) as Record<LibraryTab, number>;+}++/**+ * The brand's drafts for the Library, the latest LIBRARY_LIMIT, with who+ * started each, and each tab's count of all its drafts.+ */+export async function getContentDrafts(brandId: string): Promise<ContentLibrary> {const supabase = await createClient();const [userRes, draftsRes] = await Promise.all([supabase.auth.getUser(),@@ -119,20 +156,28 @@ export async function getContentDrafts(brandId: string): Promise<ContentDraftLisrows.flatMap((row) => (row.created_by ? [row.created_by] : [])),);- return rows.map((row) => ({- id: row.id,- title: row.title,- pageType: row.page_type,- method: row.method as DraftMethod,- status: draftStatus(row.status),- author: row.author === 'agent' ? 'agent' : 'user',- createdBy: row.created_by ? (people.get(row.created_by) ?? null) : null,- isMine: me !== null && row.created_by === me,- scoreBefore: row.score_before,- scoreAfter: row.score_after,- agentState: agentStateOf(row.agent_state, row.agent_state_at),- updatedAt: row.updated_at,- }));+ const drafts = rows.map(+ (row): ContentDraftListItem => ({+ id: row.id,+ title: row.title,+ pageType: row.page_type,+ method: row.method as DraftMethod,+ status: draftStatus(row.status),+ author: row.author === 'agent' ? 'agent' : 'user',+ createdBy: row.created_by ? (people.get(row.created_by) ?? null) : null,+ isMine: me !== null && row.created_by === me,+ scoreBefore: row.score_before,+ scoreAfter: row.score_after,+ agentState: agentStateOf(row.agent_state, row.agent_state_at),+ updatedAt: row.updated_at,+ }),+ );+ // Under the cap the rows are every draft; at it, each tab is counted on its own.+ const counts =+ rows.length < LIBRARY_LIMIT+ ? libraryTabCounts(drafts)+ : await countLibraryTabs(supabase, brandId);+ return { drafts, counts };}function draftStatus(value: string): DraftStatus {@@ -215,25 +260,24 @@ export async function getContentStartOptions(brandId: string): Promise<DraftStar.limit(START_LIMIT),supabase.from('prompts')- .select('id, text, topic_id, prompt_sets!inner(brand_id)')+ .select('id, text, prompt_sets!inner(brand_id)').eq('prompt_sets.brand_id', brandId).eq('is_active', true).order('text').limit(START_LIMIT),+ // Each topic's active prompts counted in the database: the prompt list+ // above stops at START_LIMIT, and would undercount a big brand's topics.supabase.from('topics')- .select('id, name')+ .select('id, name, prompts(count)').eq('brand_id', brandId).eq('is_active', true)+ .eq('prompts.is_active', true).order('name'),]);const failed = opportunities.error ?? prompts.error ?? topics.error;if (failed) throw new Error(failed.message);- const perTopic = new Map<string, number>();- for (const p of prompts.data ?? []) {- if (p.topic_id) perTopic.set(p.topic_id, (perTopic.get(p.topic_id) ?? 0) + 1);- }return {opportunities: (opportunities.data ?? []).map((o) => {const suggested = (o.brief as { suggestedTitle?: unknown } | null)?.suggestedTitle;@@ -250,7 +294,9 @@ export async function getContentStartOptions(brandId: string): Promise<DraftStar.map((topic) => ({id: topic.id,name: topic.name,- promptCount: perTopic.get(topic.id) ?? 0,+ promptCount: Number(+ (topic.prompts as unknown as { count: number }[] | null)?.[0]?.count ?? 0,+ ),})).filter((topic) => topic.promptCount > 0),};@@ -773,6 +819,11 @@ const saveInput = z.object({base: z.object({updatedAt: z.string().min(1),bodyHash: z.string().regex(/^[0-9a-f]{64}$/),+ /** The page of a save whose answer never came back: it may be this editor's own write. */+ unconfirmedHash: z+ .string()+ .regex(/^[0-9a-f]{64}$/)+ .optional(),}),});@@ -786,8 +837,10 @@ const SAVE_ATTEMPTS = 3;* the page tells which kind: the same page means only the draft's other* columns changed (Mark ready, its type), and the save goes over them;* another page means someone else changed it (another tab, a teammate, the- * Content Agent), and nothing is overwritten. A save RLS refused, or of a- * draft that no longer exists, comes back not_found rather than saved.+ * Content Agent), and nothing is overwritten. A page that is the editor's+ * own last save whose answer was lost (`unconfirmedHash`) counts as the+ * same page. A save RLS refused, or of a draft that no longer exists, comes+ * back not_found rather than saved.** Until a person picks the page type, it follows the page (CE-023): detected* again from what was saved, and written only while it is still detected, so@@ -796,7 +849,11 @@ const SAVE_ATTEMPTS = 3;*/export async function saveContentDraft(id: string,- input: { title: string; bodyHtml: string; base: { updatedAt: string; bodyHash: string } },+ input: {+ title: string;+ bodyHtml: string;+ base: { updatedAt: string; bodyHash: string; unconfirmedHash?: string };+ },): Promise<SaveDraftResult> {if (typeof input?.bodyHtml === 'string' && input.bodyHtml.length > MAX_BODY_HTML_LENGTH) {return { ok: false, reason: 'too_large' };@@ -856,7 +913,8 @@ export async function saveContentDraft(if (agentStateOf(current.agent_state, current.agent_state_at) === 'writing') {return { ok: false, reason: 'conflict' };}- if ((await bodyHash(current.body_html)) !== base.bodyHash) {+ const currentHash = await bodyHash(current.body_html);+ if (currentHash !== base.bodyHash && currentHash !== base.unconfirmedHash) {return { ok: false, reason: 'conflict' };}expected = current.updated_at;@@ -975,11 +1033,15 @@ export async function getDraftVersions(id: string): Promise<DraftVersion[]> {/*** Restores a version (CE-018): the draft as it is now is kept in History* first, so nothing is lost, then takes the version's title and body- * (00215 content_draft_restore). Throws 'not_found' when the version is- * unknown, past its 90 days, or another organization's.+ * (00215 content_draft_restore). A draft whose type follows its page gets+ * the restored page's type, as a save would give it, so the Library shows+ * it. Throws 'not_found' when the version is unknown, past its 90 days, or+ * another organization's.*/-export async function restoreDraftVersion(versionId: string): Promise<RestoredDraft> {- if (!draftId.safeParse(versionId).success) throw new Error('invalid');+export async function restoreDraftVersion(id: string, versionId: string): Promise<RestoredDraft> {+ if (!draftId.safeParse(id).success || !draftId.safeParse(versionId).success) {+ throw new Error('invalid');+ }const supabase = await createClient();const { data, error } = await supabase.rpc('content_draft_restore', {p_version_id: versionId,@@ -987,11 +1049,36 @@ export async function restoreDraftVersion(versionId: string): Promise<RestoredDrif (error) throw new Error(error.message);if (!data) throw new Error('not_found');const restored = data as unknown as RestoredDraft;- return {- title: restored.title,- bodyHtml: restored.bodyHtml,- updatedAt: restored.updatedAt,- };+ let updatedAt = restored.updatedAt;++ // Read back, so the type is detected only on the draft the version restored.+ const { data: row, error: rowError } = await supabase+ .from('content_drafts')+ .select(`page_type, page_type_source, body_html, ${BRAND_SITE}`)+ .eq('id', id)+ .maybeSingle();+ if (rowError) {+ console.error('Failed to read the restored draft:', rowError.message);+ } else if (row?.page_type_source === 'detected' && row.body_html === restored.bodyHtml) {+ const detected = detectPageType(+ { title: restored.title, html: restored.bodyHtml },+ brandSiteType(row.brands),+ );+ // A page that shows no type keeps the one it had, as on a save.+ if (detected && detected !== row.page_type) {+ const { data: typed, error: typeError } = await supabase+ .from('content_drafts')+ .update({ page_type: detected })+ .eq('id', id)+ .eq('page_type_source', 'detected')+ .select('updated_at')+ .maybeSingle();+ // The page is restored; its type catches up on the next save.+ if (typeError) console.error('Failed to update the detected page type:', typeError.message);+ else if (typed) updatedAt = typed.updated_at;+ }+ }+ return { title: restored.title, bodyHtml: restored.bodyHtml, updatedAt };}/**@@ -1455,6 +1542,7 @@ export async function startAgentWriting(export async function saveDraftRules(id: string, rules: DraftRulesInput): Promise<void> {const parsed = draftRulesSchema.safeParse(rules);if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');+ if (!draftRulesFit(parsed.data)) throw new Error('too_large');const supabase = await createClient();const { data, error } = await supabase.from('content_drafts')@@ -1517,6 +1605,7 @@ export async function saveMyRuleSet() {throw new Error('invalid');}+ if (!ruleSetFits(parsed.data)) throw new Error('too_large');const supabase = await createClient();const [userRes, brandRes] = await Promise.all([supabase.auth.getUser(),diff --git a/web/src/lib/content/agent-write.ts b/web/src/lib/content/agent-write.tsindex 20eaffdf9..e7db0da8a 100644--- a/web/src/lib/content/agent-write.ts+++ b/web/src/lib/content/agent-write.ts@@ -72,6 +72,8 @@ export async function agentWriteRequest(sourceUrl: string | null;bodyHtml: string;rules: DraftRules;+ /** The brand's language, the Language rule's default. */+ language?: string | null;},describe: RuleDescriber,inEffect?: { rules: ActiveRule[]; textRules: string[] },@@ -89,7 +91,8 @@ export async function agentWriteRequest(]);const effective = effectiveRules(draft.rules, setType ? mine?.[setType] : undefined);const rules = (- inEffect?.rules ?? activeRules(ruleSet(setType), effective).filter((rule) => rule.on)+ inEffect?.rules ??+ activeRules(ruleSet(setType, { language: draft.language }), effective).filter((rule) => rule.on)).filter((rule) => rule.check !== 'feed');const textRules =inEffect?.textRules ?? effective.textRules.filter((rule) => rule.on).map((rule) => rule.text);diff --git a/web/src/lib/content/attachments.test.ts b/web/src/lib/content/attachments.test.tsindex 94def1dc1..499751d47 100644--- a/web/src/lib/content/attachments.test.ts+++ b/web/src/lib/content/attachments.test.ts@@ -57,22 +57,30 @@ describe('tableHtml', () => {});describe('rowsThatFit', () => {- // As the editor saves them: 350 for the table, 9 a row, 40 a cell plus its text.+ // As the editor saves them: 100 for the table and 29 a column, 9 a row,+ // 40 a cell plus its text. One column and its header: 179.const rows = [['a'], ['xx'], ['xx']];it('counts the data rows that fit after the header, as the editor saves a table', () => {expect(rowsThatFit(rows, 10_000)).toBe(2);- expect(rowsThatFit(rows, 400 + 51)).toBe(1);- expect(rowsThatFit(rows, 400 + 50)).toBe(0);+ expect(rowsThatFit(rows, 179 + 51)).toBe(1);+ expect(rowsThatFit(rows, 179 + 50)).toBe(0);});it('says when not even the header fits', () => {- expect(rowsThatFit(rows, 399)).toBe(-1);+ expect(rowsThatFit(rows, 178)).toBe(-1);});it('counts a cell’s text as it is escaped', () => {- expect(rowsThatFit([['a'], ['<<']], 400 + 9 + 40 + 8)).toBe(1);- expect(rowsThatFit([['a'], ['<<']], 400 + 9 + 40 + 7)).toBe(0);+ expect(rowsThatFit([['a'], ['<<']], 179 + 9 + 40 + 8)).toBe(1);+ expect(rowsThatFit([['a'], ['<<']], 179 + 9 + 40 + 7)).toBe(0);+ });++ it('allows for each column’s width on a wide sheet', () => {+ // 30 columns: 100 + 30 × 29 for the table, 9 + 30 × 41 for the header.+ const wide = [Array.from({ length: 30 }, () => 'a')];+ expect(rowsThatFit(wide, 100 + 870 + 9 + 1230)).toBe(0);+ expect(rowsThatFit(wide, 100 + 870 + 9 + 1229)).toBe(-1);});});diff --git a/web/src/lib/content/attachments.ts b/web/src/lib/content/attachments.tsindex f8c074370..def80bb45 100644--- a/web/src/lib/content/attachments.ts+++ b/web/src/lib/content/attachments.ts@@ -98,8 +98,13 @@ export function tableHtml(rows: string[][]): string {/** What the editor adds around each cell's text when it saves a table. */const SAVED_CELL_OVERHEAD = '<td colspan="1" rowspan="1"><p></p></td>'.length;const SAVED_ROW_OVERHEAD = '<tr></tr>'.length;-/** The table's own tags, its column widths included: a generous allowance. */-const SAVED_TABLE_OVERHEAD = 200 + MAX_TABLE_COLUMNS * '<col>'.length;+/**+ * The table's own tags as the editor saves them: one column width per+ * column (`<col style="min-width: 25px">`), and an allowance for+ * `<table style="min-width: …px"><colgroup>…</colgroup><tbody>…</tbody></table>`.+ */+const SAVED_COLUMN_OVERHEAD = '<col style="min-width: 25px">'.length;+const SAVED_TABLE_OVERHEAD = 100;/*** How many of a sheet's data rows fit in `room` characters of the saved@@ -112,7 +117,12 @@ export function rowsThatFit(rows: string[][], room: number): number {const rowLength = (row: string[]) =>SAVED_ROW_OVERHEAD +row.reduce((sum, cell) => sum + SAVED_CELL_OVERHEAD + escapeHtml(cell).length, 0);- let used = SAVED_TABLE_OVERHEAD + (rows[0] ? rowLength(rows[0]) : 0);+ const columns = Math.min(+ MAX_TABLE_COLUMNS,+ rows.reduce((most, row) => Math.max(most, row.length), 0),+ );+ let used =+ SAVED_TABLE_OVERHEAD + columns * SAVED_COLUMN_OVERHEAD + (rows[0] ? rowLength(rows[0]) : 0);if (used > room) return -1;let fit = 0;for (const row of rows.slice(1)) {diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.tsindex c6f9038fd..d185620e1 100644--- a/web/src/lib/content/rules.test.ts+++ b/web/src/lib/content/rules.test.ts@@ -13,6 +13,9 @@ import {rulesMet,type ActiveRule,type RuleContext,+ draftRulesFit,+ ruleSetFits,+ storedBytes,} from './rules';const ctx: RuleContext = {@@ -63,6 +66,41 @@ describe('rule sets', () => {).toBe('espresso, grinder');});+ it('checks the rules against the database’s size in bytes, not characters', () => {+ const rule = (text: string, i: number) => ({ id: `r${i}`, text, on: true });+ const latin = Array.from({ length: 40 }, (_, i) => rule('a'.repeat(300), i));+ const cjk = Array.from({ length: 40 }, (_, i) => rule('日'.repeat(300), i));+ const rules = (textRules: typeof latin) => ({+ set: null,+ source: 'default' as const,+ overrides: {},+ textRules,+ });+ expect(draftRulesFit(rules(latin))).toBe(true);+ expect(draftRulesFit(rules(cjk))).toBe(false);+ expect(ruleSetFits({ overrides: {}, textRules: latin })).toBe(true);+ expect(+ ruleSetFits({+ overrides: Object.fromEntries(+ Array.from({ length: 40 }, (_, i) => [`k${i}`, { value: 'ü'.repeat(300) }]),+ ),+ textRules: [],+ }),+ ).toBe(false);+ // jsonb writes a space after each ':' and ',': the count errs high, never low.+ expect(storedBytes({ a: [1, 2] })).toBeGreaterThanOrEqual('{"a": [1, 2]}'.length);+ });++ it('writes in the brand’s language by default, US English for English or none', () => {+ const language = (code?: string | null) =>+ ruleSet('guide', { language: code }).find((r) => r.key === 'language')?.value;+ expect(language('tr')).toBe('Turkish');+ expect(language('pt')).toBe('Portuguese');+ expect(language('en')).toBe('English (US)');+ expect(language(null)).toBe('English (US)');+ expect(language('xx')).toBe('English (US)');+ });+it('applies the draft’s choices', () => {const rules = activeRules(ruleSet('category_page'), {overrides: { length: { value: '1000' }, faq: { on: false } },diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.tsindex 5ffec0a29..4194472ac 100644--- a/web/src/lib/content/rules.ts+++ b/web/src/lib/content/rules.ts@@ -1,4 +1,5 @@import { z } from 'zod';+import { LANGUAGES } from '@/config/prompt-options';import { classifyDomain, normalizeDomain } from '@/lib/citations/classify';import { PAGE_TYPES, type PageType } from '@/lib/content/drafts';import { lengthTarget } from '@/lib/content/editor';@@ -240,15 +241,26 @@ const TYPE_RULES: Partial<Record<PageType, RuleDef[]>> = {};/** The rules of a set: the type's own, then the shared groups, with the type's length. */+/**+ * The Language rule's value for the brand's language (brands.language, as+ * the brief and the agent write in): its name, US English for English or+ * none.+ */+export function languageRuleValue(code: string | null | undefined): string {+ const label = code && code !== 'en' ? LANGUAGES.find((l) => l.code === code)?.label : undefined;+ return label ? label.replace(/\s*\([^)]*\)$/, '') : 'English (US)';+}+export function ruleSet(pageType: PageType | null,- defaults: { keywords?: string[] } = {},+ defaults: { keywords?: string[]; language?: string | null } = {},): RuleDef[] {const own = (pageType && TYPE_RULES[pageType]) || [];return [...own,...SHARED_RULES.map((rule) => {if (rule.key === 'length') return { ...rule, value: String(lengthTarget(pageType)) };+ if (rule.key === 'language') return { ...rule, value: languageRuleValue(defaults.language) };if (rule.key === 'keywords' && defaults.keywords?.length) {return { ...rule, value: defaults.keywords.join(', ') };}@@ -305,6 +317,39 @@ export const savedRuleSetSchema = z.object({});export type SavedRuleSet = z.infer<typeof savedRuleSetSchema>;+/**+ * The database's size checks, in bytes of the JSON as stored: a draft's+ * rules (00213), and a set's overrides and text rules (00214). The zod+ * limits count characters, and text outside Latin script takes 2–4 bytes+ * each, so a save is checked against these first.+ */+export const MAX_DRAFT_RULES_BYTES = 32_768;+export const MAX_SET_OVERRIDES_BYTES = 16_384;+export const MAX_SET_TEXT_RULES_BYTES = 32_768;++/**+ * At least the bytes a value takes as jsonb text: its UTF-8 JSON, plus the+ * space jsonb writes after each ':' and ',' (counted for every one, so the+ * size errs high).+ */+export function storedBytes(value: unknown): number {+ const json = JSON.stringify(value);+ return new TextEncoder().encode(json).length + (json.match(/[:,]/g)?.length ?? 0);+}++/** Whether a draft's rules fit the database's check. */+export function draftRulesFit(rules: DraftRules): boolean {+ return storedBytes(rules) <= MAX_DRAFT_RULES_BYTES;+}++/** Whether a set fits the database's checks. */+export function ruleSetFits(set: SavedRuleSet): boolean {+ return (+ storedBytes(set.overrides) <= MAX_SET_OVERRIDES_BYTES &&+ storedBytes(set.textRules) <= MAX_SET_TEXT_RULES_BYTES+ );+}+/*** The choices in effect: the draft's own; or, for a draft no one has set* rules on yet, the workspace's My rules for the set's type, as a template.