Skip to content

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

feat(web): open the plan dialog from the content area's actions, and keep the editor read-only, while the plan has ended (#1609)

Cihane73e5a913de7
diff --git a/web/messages/en.json b/web/messages/en.json
index bc600bd78..9c787cbd3 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -138,7 +138,48 @@
"addCompetitors": "Adding competitors needs a plan",
"deleteCompetitors": "Deleting competitors needs a plan",
"suggestCompetitors": "Suggesting competitors needs a plan",
- "pinCompetitors": "Pinning competitors needs a plan"
+ "pinCompetitors": "Pinning competitors needs a plan",
+ "generateOpportunities": "Generating opportunities needs a plan",
+ "sendToWorkflow": "Sending to your workflow needs a plan",
+ "saveWorkflow": "Saving the workflow settings needs a plan",
+ "testWorkflow": "Testing the workflow needs a plan",
+ "markOpportunitiesDone": "Marking opportunities done needs a plan",
+ "markOpportunityReviewed": "Marking an opportunity reviewed needs a plan",
+ "dismissOpportunities": "Dismissing opportunities needs a plan",
+ "deleteOpportunities": "Deleting opportunities needs a plan",
+ "restoreOpportunities": "Restoring opportunities needs a plan",
+ "generateBrief": "Generating a brief needs a plan",
+ "prioritizeContent": "Marking priorities needs a plan",
+ "assignContent": "Assigning content needs a plan",
+ "hidePlanRows": "Hiding rows needs a plan",
+ "showPlanRows": "Showing hidden rows needs a plan",
+ "importPage": "Importing a page needs a plan",
+ "changeContentStatus": "Changing a page's status needs a plan",
+ "markReady": "Marking a page ready needs a plan",
+ "markPublished": "Marking a page published needs a plan",
+ "sendToCms": "Sending to your CMS needs a plan",
+ "archiveContent": "Archiving content needs a plan",
+ "restoreContent": "Restoring content needs a plan",
+ "deleteContent": "Deleting content needs a plan",
+ "editContent": "Editing the page needs a plan",
+ "runAgent": "Running the Content Agent needs a plan",
+ "fixRules": "Fixing rules needs a plan",
+ "rewritePage": "Rewriting the page needs a plan",
+ "reviewSuggestions": "Reviewing suggestions needs a plan",
+ "restoreVersion": "Restoring a version needs a plan",
+ "setPageType": "Changing the page type needs a plan",
+ "setSiteType": "Changing the site type needs a plan",
+ "setAuthor": "Setting the author needs a plan",
+ "setReviewer": "Setting the reviewer needs a plan",
+ "confirmDetails": "Confirming page details needs a plan",
+ "keepSources": "Keeping sources needs a plan",
+ "addSources": "Adding sources needs a plan",
+ "changeSources": "Changing sources needs a plan",
+ "addImages": "Adding images needs a plan",
+ "buildBrief": "Building the brief needs a plan",
+ "editBrief": "Editing the brief needs a plan",
+ "editRules": "Changing rules needs a plan",
+ "saveInput": "Saving your input needs a plan"
}
},
"common": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx
index 75b9d0cb1..5f0f5149c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx
@@ -21,6 +21,7 @@ import {
testWebhook,
type WebhookTestResult,
} from '@/lib/actions/content';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { useUserRole } from '@/hooks/use-user-role';
import { toast } from 'sonner';
@@ -46,6 +47,10 @@ interface WebhookSettingsDialogProps {
export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSettingsDialogProps) {
const t = useTranslations('content.webhook');
const tFailure = useTranslations('apiFailure');
+ // A read-only workspace (plan not active): the settings show, and Test and
+ // Save open the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
// Only admins and managers save the webhook (RLS) and test it (the API):
// a member sees it, and why it can't be changed, before pressing anything.
const { canManage } = useUserRole();
@@ -263,7 +268,7 @@ export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSe
<Button
variant="outline"
size="sm"
- onClick={handleTest}
+ onClick={guard(handleTest, { action: tActions('testWorkflow') })}
disabled={readOnly || testing || !url.trim()}
className="gap-2"
>
@@ -272,7 +277,7 @@ export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSe
</Button>
<Button
size="sm"
- onClick={handleSave}
+ onClick={guard(handleSave, { action: tActions('saveWorkflow') })}
disabled={readOnly || saving || !url.trim()}
className="gap-2"
>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
index 5929f0056..0a2663ec3 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
@@ -15,6 +15,7 @@ import {
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { LoadingDots } from '@/components/ui/loading-dots';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { saveDraftBrief } from '@/lib/actions/content-drafts';
import type { InputsGiven } from '@/lib/content/draft-inputs';
import {
@@ -123,6 +124,10 @@ export function BriefTab({
const [confirming, setConfirming] = useState(false);
// The agent writes over the page (or suggests changes) only once the person says so.
const [confirmingRewrite, setConfirmingRewrite] = useState(false);
+ // A read-only workspace (plan not active): Run Agent, Rebuild, the rewrite
+ // and Edit open the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
if (state.status === 'loading') {
return (
@@ -160,7 +165,10 @@ export function BriefTab({
const typeLabel = pageType && (tTypes.has(pageType) ? tTypes(pageType) : pageType);
// Nothing written yet: Run Agent writes it. Once it is, Rebuild brief.
const empty = !brief || (!brief.goal && !brief.audience && brief.outline.length === 0);
- const rebuild = () => (brief?.origin === 'edit' && !empty ? setConfirming(true) : onRebuild());
+ const rebuild = guard(
+ () => (brief?.origin === 'edit' && !empty ? setConfirming(true) : onRebuild()),
+ { action: tActions('buildBrief') },
+ );
return (
<div className="space-y-4 text-sm">
@@ -382,7 +390,7 @@ export function BriefTab({
size="sm"
className="w-full"
disabled={rewrite.running || rewrite.blocked !== null || rebuilding}
- onClick={() => setConfirmingRewrite(true)}
+ onClick={guard(() => setConfirmingRewrite(true), { action: tActions('runAgent') })}
>
{rewrite.running ? <WorkingDots className="ml-0" /> : <Bot className="h-3.5 w-3.5" />}
{t(`rewrite.button.${method}`)}
@@ -395,7 +403,12 @@ export function BriefTab({
))}
<div className="flex flex-wrap gap-2">
- <Button size="sm" variant="ghost" disabled={rebuilding} onClick={() => setEditing(true)}>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={rebuilding}
+ onClick={guard(() => setEditing(true), { action: tActions('editBrief') })}
+ >
<Pencil className="h-3.5 w-3.5" />
{t('edit')}
</Button>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
index 763ce4709..d6055a7e1 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
@@ -411,7 +411,18 @@ export function DraftEditor({
const t = useTranslations('contentEditor.editor');
const tNext = useTranslations('contentEditor.editor.nextStep');
const tPublish = useTranslations('contentEditor.publish');
- const autosave = useDraftAutosave(draft.id, draft);
+ // A read-only workspace (plan not active): the page opens read-only and
+ // nothing is saved; each action opens the upgrade dialog instead, named.
+ // The reads the editor asks the API for by itself after a save (links,
+ // sources, claims, the page's proof) are left out; it shows what is stored.
+ const { guard, isLocked, openUpgrade } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
+ /** Read-only: the upgrade dialog, labeled with what was asked for; true when so. */
+ const lockedFor = (action: Parameters<typeof tActions>[0]) => {
+ if (isLocked) openUpgrade(tActions(action));
+ return isLocked;
+ };
+ const autosave = useDraftAutosave(draft.id, draft, { off: isLocked });
const [title, setTitle] = useState(draft.title);
// The page as written now, for the side panel's Sources.
const [pageHtml, setPageHtml] = useState(draft.bodyHtml);
@@ -622,6 +633,8 @@ export function DraftEditor({
ProofSpotsExtension,
],
content: draft.bodyHtml,
+ // Read-only: no typing, pasting or dropping into the page.
+ editable: !isLocked,
// Rendered on the client only, so the server's HTML can't disagree with it.
immediatelyRender: false,
editorProps: {
@@ -762,10 +775,6 @@ export function DraftEditor({
const language =
languageRule?.on && languageRule.current.trim() ? languageRule.current : brandLanguage;
const qualityOn = qualityPhase() >= 1;
- // A read-only workspace (plan not active): the reads the editor asks the
- // API for by itself after a save (links, sources, claims, the page's
- // proof) are left out; the page opens with what is stored.
- const { isLocked } = useUpgradeGate();
// Who the page is by (CE-038): page metadata, shown in the header and in a
// Page info strip outside the page; with Quality's first phase.
@@ -813,7 +822,7 @@ export function DraftEditor({
// One save at a time (the boxes wait): a failed one puts back the pair as saved.
const [confirming, setConfirming] = useState(false);
const confirmAuthor = (what: 'real' | 'profile', on: boolean) => {
- if (confirming) return;
+ if (lockedFor('confirmDetails') || confirming) return;
const before = authorConfirmed;
// Unticking the author unticks their profile too, as the database does.
setAuthorConfirmed(
@@ -1209,10 +1218,14 @@ export function DraftEditor({
);
// Confirm: only the person can tell their own image from stock.
const [confirmingImages, setConfirmingImages] = useState(false);
+ const openConfirmImages = guard(() => setConfirmingImages(true), {
+ action: tActions('confirmDetails'),
+ });
// Quality's Confirm on a category intro's facts (CE-054): the person's
// word that its counts and prices are right, the ones not confirmed yet in
// one row; put back if it can't be saved.
const confirmIntro = async () => {
+ if (lockedFor('confirmDetails')) return;
const keys = introConfirmKeys(introAll.filter((fact) => !introConfirmed.has(fact)));
if (!keys.length) return;
setIntroConfirms((prev) => new Set([...(prev ?? []), ...keys]));
@@ -1236,6 +1249,7 @@ export function DraftEditor({
// Quality's Confirm on a customer case (CE-052): the person's statement
// that the customer may be named; put back if it can't be saved.
const confirmCase = async (key: string) => {
+ if (lockedFor('confirmDetails')) return;
if (caseConfirms?.has(key)) return;
setCaseConfirms((prev) => new Set([...(prev ?? []), key]));
const takeBack = () =>
@@ -1252,6 +1266,7 @@ export function DraftEditor({
}
};
const confirmImage = async (src: string) => {
+ if (lockedFor('confirmDetails')) return;
// Already confirmed: nothing to take back if the save fails.
const had = ownImages?.has(src) ?? false;
setOwnImages((prev) => new Set([...(prev ?? []), src]));
@@ -1371,7 +1386,7 @@ export function DraftEditor({
// on them (its Apply links them and comes back to the page).
const [linkRequest, setLinkRequest] = useState(0);
const addSource = (mark: ClaimMark) => {
- if (!editor) return;
+ if (!editor || lockedFor('addSources')) return;
const [range] = textRanges(editor.state.doc, mark.text, mark.block);
if (!range) {
showInPage(mark.sentence);
@@ -1384,7 +1399,7 @@ export function DraftEditor({
// it too, and the paragraph (its list item) if that leaves it empty. Undo
// brings it back.
const removeClaim = (mark: ClaimMark) => {
- if (!editor) return;
+ if (!editor || lockedFor('editContent')) return;
const [range] = textRanges(editor.state.doc, mark.sentence, mark.block);
if (!range) {
showInPage(mark.sentence);
@@ -1410,6 +1425,7 @@ export function DraftEditor({
.run();
};
const keepSource = async (url: string) => {
+ if (lockedFor('keepSources')) return;
setKeptSources((kept) => (kept.includes(url) ? kept : [...kept, url]));
try {
setKeptSources(await keepDraftSource(draft.id, url));
@@ -1541,7 +1557,7 @@ export function DraftEditor({
const savedReviewer = useRef(draft.reviewerId);
const reviewerPick = useRef(0);
const pickReviewer = async (next: string | null) => {
- if (next === reviewerId) return;
+ if (next === reviewerId || lockedFor('setReviewer')) return;
const pick = ++reviewerPick.current;
setReviewerId(next);
try {
@@ -1648,7 +1664,7 @@ export function DraftEditor({
);
}, [editor, byline, bylineInContent, pageAuthor?.name, pageAuthor?.photoUrl, brandName, t]);
const pickAuthor = async (next: string | null) => {
- if (next === authorId) return;
+ if (next === authorId || lockedFor('setAuthor')) return;
const pick = ++authorPick.current;
setAuthorId(next);
try {
@@ -1939,7 +1955,7 @@ export function DraftEditor({
*/
const decide = async (ids: string[], decision: SuggestionDecision | 'undo_all') => {
// Never under a restore: it sets the open ones aside on the page it puts in.
- if (!editor || deciding || restoringNow.current) return;
+ if (!editor || deciding || restoringNow.current || lockedFor('reviewSuggestions')) return;
const all = suggestionsNow.current;
const next = all.map((s) => ({ ...s }));
const picked = next.filter((s) => ids.includes(s.id));
@@ -2204,7 +2220,7 @@ export function DraftEditor({
// reads, past an image, a byline or a date), else under the page's H1,
// else at the top; never twice. One undo takes it out.
const addLineUnderAnswer = (line: string) => {
- if (!editor || editor.isDestroyed) return;
+ if (!editor || editor.isDestroyed || lockedFor('editContent')) return;
const { doc } = editor.state;
if (squeeze(doc.textContent).includes(squeeze(line))) return;
let at = 0;
@@ -2241,7 +2257,7 @@ export function DraftEditor({
// the answer) stays theirs. One undo takes it back.
const addCheckDate = () => {
const line = checkDateText(language);
- if (!line || !editor || editor.isDestroyed) return;
+ if (!line || !editor || editor.isDestroyed || lockedFor('editContent')) return;
let found: { pos: number; size: number } | null = null;
editor.state.doc.forEach((node, pos) => {
if (!found && node.type.name === 'paragraph' && isCheckDateLine(node.textContent)) {
@@ -2323,7 +2339,7 @@ export function DraftEditor({
* isn't written over: the person runs the rewrite again.
*/
const decidePage = async (s: DraftSuggestion, to: SuggestionStatus) => {
- if (!editor || deciding || restoringNow.current) return;
+ if (!editor || deciding || restoringNow.current || lockedFor('reviewSuggestions')) return;
const undo = to === 'open' && s.status === 'accepted';
// What the page must still read as for the change to go in.
const expected = to === 'accepted' ? (s.beforeHtml ?? '') : undo ? s.afterText : null;
@@ -2391,6 +2407,7 @@ export function DraftEditor({
* batch of suggestions for review.
*/
const fixRules = async (only?: string[]) => {
+ if (lockedFor('fixRules')) return;
// One agent run at a time, never before the locked passages are read,
// nor while a restore replaces the page it would read.
if (!editor || fixing || starting || rewriting || !citedRead || restoringNow.current) return;
@@ -2620,6 +2637,8 @@ export function DraftEditor({
* workspace's AI usage).
*/
const handOff = async (origin: 'person' | 'auto' = 'person') => {
+ // Read-only, the automatic one isn't due: only the person's asks here.
+ if (lockedFor('runAgent')) return;
if (!editor || fixing || starting || rewriting || !citedRead || restoringNow.current) return;
if (openSuggestions > 0) {
toast(t('suggestions.decideFirst', { count: openSuggestions }));
@@ -2715,11 +2734,19 @@ export function DraftEditor({
const [spotFor, setSpotFor] = useState<ProofSpot | null>(null);
// Quality's Add image (CE-049, part d): the first spot still open.
const addImage = () => {
- if (!editor || !pageRead.read) return;
+ if (!editor || !pageRead.read || lockedFor('addImages')) return;
const [first] = openSpotPlaces(editor.state.doc, pageRead.read.spots);
if (first) setSpotFor(first.spot);
};
const spotList = sourcesOn && !agentBusy ? (pageRead.read?.spots ?? null) : null;
+ // A spot's Add, in the page's margin: read-only, the upgrade dialog instead.
+ const openSpot = useCallback(
+ (spot: ProofSpot) => {
+ if (isLocked) openUpgrade(tActions('addImages'));
+ else setSpotFor(spot);
+ },
+ [isLocked, openUpgrade, tActions],
+ );
useEffect(() => {
if (!editor || editor.isDestroyed) return;
editor.view.dispatch(
@@ -2734,13 +2761,13 @@ export function DraftEditor({
forPassage: (passage: string) => t('proofSpots.for', { passage }),
addFor: (passage: string) => t('proofSpots.addFor', { passage }),
marker: (image: string) => t('proofSpots.marker', { image }),
- onAdd: setSpotFor,
+ onAdd: openSpot,
}
: null,
)
.setMeta('addToHistory', false),
);
- }, [editor, spotList, t]);
+ }, [editor, spotList, t, openSpot]);
// Fix open rules and Hand off share the agent's fix run (fixing): each
// card runs its own, and the other's run is the agent at work.
const fixRunning = fixing && !handingOff;
@@ -2786,7 +2813,9 @@ export function DraftEditor({
useAutoHandOff({
draftId: draft.id,
brandId: draft.brandId,
+ // Read-only, nothing runs by itself.
due:
+ !isLocked &&
sourcesOn &&
draft.qualityHandoff &&
status !== 'published' &&
@@ -2835,6 +2864,7 @@ export function DraftEditor({
setDragging(false);
if (e.defaultPrevented || !withFiles(e)) return;
e.preventDefault();
+ if (lockedFor('editContent')) return;
void attachments.attach([...e.dataTransfer.files]);
},
};
@@ -2952,7 +2982,7 @@ export function DraftEditor({
* here, and the page waits for it.
*/
const startAgent = async () => {
- if (!editor || restoringNow.current) return;
+ if (!editor || restoringNow.current || lockedFor('runAgent')) return;
setStarting(true);
try {
await autosave.settle();
@@ -3027,7 +3057,9 @@ export function DraftEditor({
*/
const rewritePage = async ({ citedToo = false }: { citedToo?: boolean } = {}) => {
// Never before the locked passages are read: the rewrite would be told none are.
- if (!editor || agentBusy || !citedRead || restoringNow.current) return;
+ if (!editor || agentBusy || !citedRead || restoringNow.current || lockedFor('rewritePage')) {
+ return;
+ }
// Next's step as the person asked for it, before the waits below.
const stepAsked = nextStepNow.current;
setRewriting(true);
@@ -3158,7 +3190,7 @@ export function DraftEditor({
* History as published, as it stands in the database.
*/
const openPublish = async () => {
- if (preparingLive || draft.archivedAt) return;
+ if (preparingLive || draft.archivedAt || lockedFor('markPublished')) return;
if (htmlUnapplied) {
toast.error(t('send.applyHtml'));
return;
@@ -3176,6 +3208,7 @@ export function DraftEditor({
setAskLive(true);
};
const startSend = () => {
+ if (lockedFor('sendToCms')) return;
if (htmlUnapplied) {
toast.error(t('send.applyHtml'));
return;
@@ -3222,6 +3255,7 @@ export function DraftEditor({
}, [publishOpen, linkChecks, title]);
/** Marks it ready; past Before you publish's warning, logged with its facts. */
const markReady = async (anyway?: ReadyAnyway) => {
+ if (lockedFor('markReady')) return;
setMarking(true);
try {
// What's waiting goes out first, so the ready draft (and the version
@@ -3514,7 +3548,7 @@ export function DraftEditor({
*/
const [unmarking, setUnmarking] = useState(false);
const unmarkReady = async () => {
- if (unmarking) return;
+ if (unmarking || lockedFor('changeContentStatus')) return;
setUnmarking(true);
try {
const { status: now, tasksReopened } = await unmarkContentDraftReady(draft.id);
@@ -3538,7 +3572,7 @@ export function DraftEditor({
* heading, else the first block with words), to rename it there.
*/
const renameInPage = () => {
- if (!editor) return;
+ if (!editor || lockedFor('editContent')) return;
// The HTML view holds the page: the title is renamed in its text there.
if (htmlSource !== null) {
toast(t('header.renameInHtml'));
@@ -3566,7 +3600,7 @@ export function DraftEditor({
// as the server keeps the page it replaces, and the page can't change
// while the restore runs.
const restoreVersion = async (version: DraftVersion, label: string) => {
- if (!editor || restoringNow.current) return;
+ if (!editor || restoringNow.current || lockedFor('restoreVersion')) return;
restoringNow.current = true;
setRestoring(true);
editor.setEditable(false, false);
@@ -3639,7 +3673,7 @@ export function DraftEditor({
};
const pickPageType = async (type: PageType) => {
- if (type === picked) return;
+ if (type === picked || lockedFor('setPageType')) return;
const before = picked;
setPicked(type);
try {
@@ -3660,7 +3694,7 @@ export function DraftEditor({
const tSites = useTranslations('brands.siteTypes');
const [siteSaving, setSiteSaving] = useState(false);
const pickSite = async (next: SiteType) => {
- if (next === siteType || siteSaving) return;
+ if (next === siteType || siteSaving || lockedFor('setSiteType')) return;
// Taken once saved: My rules are read again for it, and one pick at a time.
setSiteSaving(true);
const saved = await updateBrand(draft.brandId, { siteType: next }).catch((err) => {
@@ -3879,7 +3913,10 @@ export function DraftEditor({
marking || autosave.state === 'conflict' || autosave.state === 'too_large'
}
aria-label={t('markReady')}
- onClick={() => (quality ? openBeforePublish('markReady') : void markReady())}
+ onClick={guard(
+ () => (quality ? openBeforePublish('markReady') : void markReady()),
+ { action: tActions('markReady') },
+ )}
>
{marking ? <LoadingDots /> : <Check className="h-3.5 w-3.5 lg:hidden" />}
<span className="hidden lg:inline">{t('markReady')}</span>
@@ -4179,6 +4216,8 @@ export function DraftEditor({
setHtmlEdited(true);
}}
spellCheck={false}
+ // Read-only: the source shows, and nothing in it changes.
+ readOnly={isLocked}
aria-label={t('html.label')}
className="block h-full min-h-[600px] w-full resize-none bg-muted/20 px-7 py-5 font-mono text-[12.5px] leading-relaxed outline-none"
/>
@@ -4205,7 +4244,7 @@ export function DraftEditor({
onConfirmIntro={() => void confirmIntro()}
onAddInput={addInput}
onAddSource={sourcesOn ? addSource : undefined}
- onConfirmImages={() => setConfirmingImages(true)}
+ onConfirmImages={openConfirmImages}
onAddImage={addImage}
onLater={nudge.later}
onAct={nudge.close}
@@ -4258,7 +4297,7 @@ export function DraftEditor({
onKeepSource={sourcesOn ? (url) => void keepSource(url) : undefined}
onAddSource={sourcesOn ? addSource : undefined}
onRemoveClaim={sourcesOn ? removeClaim : undefined}
- onConfirmImages={() => setConfirmingImages(true)}
+ onConfirmImages={openConfirmImages}
onAddImage={addImage}
onShoppingPathChange={shoppingCheck.reload}
/>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
index 2a46982ec..cb03747ea 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
@@ -26,6 +26,7 @@ import type { DraftInputsRead } from './_use-draft-inputs';
import type { DraftReads } from './_use-draft-reads';
import type { DraftRulesState } from './_use-draft-rules';
import { YourInput, type InputPrompt } from './_your-input';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
/** Remembers whether the panel is open, across drafts and visits. */
const PANEL_OPEN_KEY = 'aeo:content-editor-panel';
@@ -245,6 +246,10 @@ export function EditorSidePanel({
const [segment, setSegment] = useState<InstructionSegment>('rules');
const [opened, setOpened] = useState<Set<PanelTarget>>(() => new Set(['instructions', 'rules']));
const describeRule = useRuleDescriber();
+ // A read-only workspace (plan not active): Your input's changes open the
+ // upgrade dialog instead (the tabs gate their own actions).
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
// The rules as checked; described only when a rebuild asks for them, not on every keystroke.
const page = useRef({ title, html: bodyHtml, length: rules.length, checks: rules.rules });
const sourcesNow = useRef(reads.sources);
@@ -451,7 +456,7 @@ export function EditorSidePanel({
<YourInput
inputs={yourInput.inputs}
prompts={inputPrompts}
- onChange={yourInput.change}
+ onChange={guard(yourInput.change, { action: tActions('saveInput') })}
// Once Brief shows: a hidden block can't be scrolled to.
scrollRequest={tabRequest?.input && segment === 'brief' ? tabRequest.n : null}
/>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
index 5519244c6..dae400055 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
@@ -16,6 +16,7 @@ import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { LoadingDots } from '@/components/ui/loading-dots';
import { setDraftSourceIncluded } from '@/lib/actions/content-drafts';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { platformNames } from '@/lib/content/impact';
import {
buildSourceGroups,
@@ -85,6 +86,10 @@ export function SourcesTab({
const format = useFormatter();
const now = useNow({ updateInterval: 60_000 });
const [adding, setAdding] = useState(false);
+ // A read-only workspace (plan not active): a source's box, Add source and
+ // Rebuild open the upgrade dialog instead.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
// Where each source is used follows the page as it is written, a beat behind typing.
const html = useDeferredValue(bodyHtml);
@@ -200,7 +205,9 @@ export function SourcesTab({
key={`${row.kind}:${row.ref}`}
row={row}
used={usedIn(row, doc, { sourceUrl })}
- onToggle={(included) => void toggle(row, included)}
+ onToggle={guard((included: boolean) => void toggle(row, included), {
+ action: tActions('changeSources'),
+ })}
/>
))}
</ul>
@@ -218,7 +225,11 @@ export function SourcesTab({
{rebuilding ? <WorkingDots className="ml-0" /> : <RefreshCw className="h-3.5 w-3.5" />}
{t('rebuild')}
</Button>
- <Button variant="outline" size="sm" onClick={() => setAdding(true)}>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={guard(() => setAdding(true), { action: tActions('addSources') })}
+ >
<Plus className="h-3.5 w-3.5" />
{t('add.button')}
</Button>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
index 1e84ed607..209d815a0 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
@@ -27,6 +27,7 @@ import {
type LucideIcon,
} from 'lucide-react';
import { ImageUploadButton } from '@/components/content/image-upload-button';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -100,6 +101,11 @@ export function EditorToolbar({
productsBrandId?: string | null;
}) {
const t = useTranslations('contentEditor.editor.toolbar');
+ // A read-only workspace (plan not active): each tool that changes the page
+ // opens the upgrade dialog instead; </> HTML still shows the source.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
+ const edit = (run: () => void) => guard(run, { action: tActions('editContent') });
const [dialog, setDialog] = useState<'link' | 'image' | 'htmlBlock' | 'products' | null>(null);
// Only a new request opens it: not the toolbar showing again.
const [linkAsked, setLinkAsked] = useState(linkRequest);
@@ -236,7 +242,7 @@ export function EditorToolbar({
pressed={!htmlView && tool.on}
disabled={htmlView}
blocked={!!off[tool.key]}
- onClick={tool.run}
+ onClick={edit(tool.run)}
>
<tool.icon className="h-4 w-4" />
{tool.text && <span className="ml-1 text-xs font-medium">{tool.text}</span>}
@@ -257,7 +263,7 @@ export function EditorToolbar({
<div className="flex items-center gap-0.5">
<span aria-hidden="true" className="mx-1.5 h-5 w-px bg-border" />
{tableTools.map((tool) => (
- <ToolButton key={tool.key} label={t(tool.key)} onClick={tool.run}>
+ <ToolButton key={tool.key} label={t(tool.key)} onClick={edit(tool.run)}>
<tool.icon className="h-4 w-4" />
</ToolButton>
))}
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.tsx
index a951a579a..cc7374791 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
@@ -26,8 +26,8 @@ const REAL = '<p><a href="https://acme.example/" target="_blank" rel="noopener">
const BODIES = ['<p>a</p>', '<p>ab</p>', '<p>1</p>', '<p>12</p>', '<p>x</p>', '<p>last</p>'];
/** The hook behind buttons, as the editor drives it: one per text, Retry, and settle. */
-function Harness() {
- const autosave = useDraftAutosave('d1', LOADED);
+function Harness({ off = false }: { off?: boolean }) {
+ const autosave = useDraftAutosave('d1', LOADED, { off });
const [settled, setSettled] = useState('');
return (
<div>
@@ -270,3 +270,24 @@ describe('the editor’s autosave', () => {
root = createRoot(container);
});
});
+
+describe('the editor’s autosave on a read-only workspace (plan not active)', () => {
+ it('saves nothing, says nothing waits, and leaving the page asks nothing', async () => {
+ await act(async () => root.render(<Harness off />));
+ const leave = vi.spyOn(window, 'addEventListener');
+ edit('<p>a</p>');
+ expect(state()).toBe('saved');
+ await act(async () => vi.advanceTimersByTime(1500));
+ await retry();
+ await settle();
+ expect(settled()).toBe('saved');
+ expect(saveContentDraft).not.toHaveBeenCalled();
+ expect(leave).not.toHaveBeenCalledWith('beforeunload', expect.any(Function));
+ // Leaving the editor sends nothing either.
+ act(() => root.unmount());
+ root = createRoot(container);
+ await act(async () => vi.advanceTimersByTime(1500));
+ expect(saveContentDraft).not.toHaveBeenCalled();
+ leave.mockRestore();
+ });
+});
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.ts
index 31d7b9c0a..522e28066 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
@@ -38,8 +38,15 @@ interface DraftContent {
* save under way, and throws when the page isn't saved; discard() drops what
* is waiting once the server's page has replaced it, and saves go on from
* that version.
+ *
+ * `off` (a read-only workspace, plan not active): nothing is saved, so a
+ * change never waits to save, and leaving the page doesn't ask first.
*/
-export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; bodyHtml: string }) {
+export function useDraftAutosave(
+ draftId: string,
+ loaded: { updatedAt: string; bodyHtml: string },
+ { off = false }: { off?: boolean } = {},
+) {
const [state, setState] = useState<SaveState>('saved');
// When the page was last saved, from here or as loaded: the Page info strip's date.
const [savedAt, setSavedAt] = useState(loaded.updatedAt);
@@ -57,6 +64,10 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; b
const loadedBody = useRef(loaded.bodyHtml);
// The page of a save sent whose answer never came back.
const unconfirmed = useRef<string | null>(null);
+ const offNow = useRef(off);
+ useEffect(() => {
+ offNow.current = off;
+ });
const baseVersion = useCallback(async () => {
base.current.bodyHash ??= await bodyHash(loadedBody.current);
@@ -124,6 +135,7 @@ export function useDraftAutosave(draftId: string, loaded: { updatedAt: string; b
const schedule = useCallback(
(content: DraftContent) => {
+ if (offNow.current) return;
pending.current = content;
if (stopped.current) return;
clearTimeout(timer.current);
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.ts
index 90ca38b7b..c71f02281 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
@@ -3,6 +3,7 @@
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { addDraftPrompts, getDraftSources, rebuildDraftBrief } from '@/lib/actions/content-drafts';
import { builtFromCount, rebuildSources, type DraftBrief } from '@/lib/content/brief';
import type { AgentRule } from '@/lib/content/agent-write';
@@ -45,6 +46,10 @@ export function useBriefRebuild({
const t = useTranslations('contentEditor.editor.brief');
const tCard = useTranslations('contentEditor.editor.agentCard');
const [rebuilding, setRebuilding] = useState(false);
+ // A read-only workspace (plan not active): each way in (Brief, Sources,
+ // Impact, Next step's Build brief) opens the upgrade dialog instead.
+ const { isLocked, openUpgrade } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const rebuild = async (
options: {
@@ -52,6 +57,10 @@ export function useBriefRebuild({
addPrompts?: string[];
} = {},
): Promise<boolean> => {
+ if (isLocked) {
+ openUpgrade(tActions('buildBrief'));
+ return false;
+ }
setRebuilding(true);
try {
const added = !!options.addPrompts?.length;
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.ts
index bef5b618a..0aaba11d4 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
@@ -32,6 +32,7 @@ import {
} from '@/lib/content/rules';
import { buildSourceGroups } from '@/lib/content/sources';
import { useBrandStore } from '@/stores/use-brand-store';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import type { DraftReads } from './_use-draft-reads';
export interface DraftRulesState {
@@ -129,6 +130,14 @@ export function useDraftRules({
}): DraftRulesState {
const t = useTranslations('contentEditor.editor.rules');
const tTypes = useTranslations('contentEditor.pageTypes');
+ // A read-only workspace (plan not active): a rule changed, a set picked or
+ // saved as My rules opens the upgrade dialog instead, and nothing changes.
+ const { isLocked, openUpgrade } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
+ const locked = () => {
+ if (isLocked) openUpgrade(tActions('editRules'));
+ return isLocked;
+ };
const [choices, setChoices] = useState<DraftRules>(draft.rules);
// My rules as read, and for which site type: they are kept per type
// (00227), so after a switch they count as unread until read again.
@@ -256,6 +265,7 @@ export function useDraftRules({
});
};
const save = (next: DraftRules, message: string) => {
+ if (locked()) return;
// 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.
@@ -335,7 +345,7 @@ export function useDraftRules({
);
},
saveAsMine: () => {
- if (!setType) return;
+ if (!setType || locked()) return;
const set = setToSave(effective, mine[setType]);
if (!ruleSetFits(set)) {
toast.error(t('tooLongMine'));
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
index 46eb35bde..73b7f621c 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
@@ -7,6 +7,7 @@ import type { Editor } from '@tiptap/core';
import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';
import { PlanProvider } from '@/components/providers/plan-provider';
import { UpgradeDialogProvider } from '@/components/providers/upgrade-dialog-provider';
+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
import type { ContentDraft } from '@/lib/content/drafts';
import type { DraftSuggestion } from '@/lib/content/suggestions';
import { passageKey, type CitedPassage } from '@/lib/content/cited-passages';
@@ -8621,3 +8622,150 @@ describe('the side panel', () => {
expect(panel()).toBeNull();
});
});
+
+describe('the editor on a read-only workspace (plan not active)', () => {
+ const openUpgrade = vi.fn();
+ async function renderLocked(isLocked = true) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <RoleProvider role="admin">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <ContentEditorPage />
+ </UpgradeDialogContext.Provider>
+ </RoleProvider>
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+ }
+ const editorOf = () =>
+ (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor }).editor;
+
+ beforeEach(() => openUpgrade.mockReset());
+
+ it('opens the page read-only and saves nothing; the toolbar opens the upgrade dialog', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ getContentDraft.mockResolvedValue(draft());
+ await renderLocked();
+ expect(container.querySelector('.ProseMirror')!.getAttribute('contenteditable')).toBe(
+ 'false',
+ );
+ expect(editorOf().isEditable).toBe(false);
+ // A change that reaches the page all the same (a command) waits for no save.
+ await act(async () => void editorOf().commands.insertContentAt(2, 'x'));
+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));
+ expect(saveContentDraft).not.toHaveBeenCalled();
+ expect(container.querySelector('header')!.textContent).toContain('Saved');
+
+ const html = editorOf().getHTML();
+ await act(async () => button('Bold')!.click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Editing the page needs a plan');
+ expect(editorOf().getHTML()).toBe(html);
+ // The HTML view still shows the source, which can't be edited.
+ await act(async () => button('Edit as HTML')!.click());
+ expect(container.querySelector('textarea')!.readOnly).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('opens the upgrade dialog from Mark ready, Send to CMS, History and the title', async () => {
+ getContentDraft.mockResolvedValue(draft());
+ getDraftVersions.mockResolvedValue([
+ { id: 'v1', origin: 'import', title: 'Old title', createdAt: '2026-10-12T09:42:00Z' },
+ ]);
+ await renderLocked();
+ await act(async () => button('Mark ready')!.click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Marking a page ready needs a plan');
+ await act(async () => button('Send to CMS')!.click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Sending to your CMS needs a plan');
+ await act(async () => container.querySelector<HTMLButtonElement>('header h1 button')!.click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Editing the page needs a plan');
+
+ const trigger = button('History')!;
+ await act(async () => {
+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ trigger.click();
+ });
+ await act(async () => {});
+ const versions = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ await act(async () => versions[0].click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Restoring a version needs a plan');
+
+ expect(openUpgrade).toHaveBeenCalledTimes(4);
+ expect(markContentDraftReady).not.toHaveBeenCalled();
+ expect(restoreDraftVersion).not.toHaveBeenCalled();
+ expect(saveContentDraft).not.toHaveBeenCalled();
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ });
+
+ it('runs no agent and decides no suggestion', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ status: 'draft',
+ agentState: 'failed',
+ bodyHtml: '<h1>Pipeline forecasting</h1><p>Our forecasting is very accurate.</p>',
+ }),
+ );
+ getDraftSuggestions.mockResolvedValue([
+ {
+ id: 's1',
+ batchId: 'b1',
+ actionId: 'a1',
+ actionNo: 214,
+ kind: 'replace',
+ blockText: 'Our forecasting is very accurate.',
+ beforeText: 'Our forecasting is very accurate.',
+ afterText: 'Accuracy is shown per team, each week.',
+ reason: 'answer fan-out',
+ ruleKeys: [],
+ status: 'open',
+ },
+ ]);
+ await renderLocked();
+ await act(async () => button('Try again')!.click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Running the Content Agent needs a plan');
+ const bar = container.querySelector('[role="region"][aria-label="Agent suggestions"]')!;
+ await act(async () =>
+ [...bar.querySelectorAll('button')].find((b) => b.textContent === 'Accept all')!.click(),
+ );
+ expect(openUpgrade).toHaveBeenLastCalledWith('Reviewing suggestions needs a plan');
+ expect(startAgentWriting).not.toHaveBeenCalled();
+ expect(decideDraftSuggestions).not.toHaveBeenCalled();
+ expect(keepAgentBeforeVersion).not.toHaveBeenCalled();
+ });
+
+ it('changes no rule', async () => {
+ getContentDraft.mockResolvedValue(draft());
+ await renderLocked();
+ // The header's rules chip opens the panel on Rules: reading them stays open.
+ await act(async () =>
+ container.querySelector<HTMLButtonElement>('header button[aria-label^="Rules "]')!.click(),
+ );
+ const sentence = container.querySelector<HTMLElement>(
+ 'aside [role="switch"][aria-label="Max sentence length: on or off"]',
+ )!;
+ await act(async () => sentence.click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Changing rules needs a plan');
+ expect(saveDraftRules).not.toHaveBeenCalled();
+ });
+
+ it('is written and saved as before on an active plan', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ getContentDraft.mockResolvedValue(draft());
+ await renderLocked(false);
+ expect(editorOf().isEditable).toBe(true);
+ await act(async () => void editorOf().commands.insertContentAt(2, 'x'));
+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));
+ expect(saveContentDraft).toHaveBeenCalledTimes(1);
+ expect(openUpgrade).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
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.tsx
index 934e5c636..70ac597ad 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
@@ -67,12 +67,22 @@ vi.mock('@/lib/webflow-client', () => ({
}));
vi.mock('@/lib/actions/content-authors', () => ({ getContentAuthors: vi.fn(async () => null) }));
// The workspace's plan: active unless a test says it's read-only.
-const gate = vi.hoisted(() => ({ isLocked: false }));
+const gate = vi.hoisted(() => ({ isLocked: false, openUpgrade: vi.fn() }));
vi.mock('@/components/providers/upgrade-gate', () => ({
useUpgradeGate: () => ({
isLocked: gate.isLocked,
- openUpgrade: vi.fn(),
- guard: (fn: () => unknown) => fn,
+ openUpgrade: gate.openUpgrade,
+ // As the real one: read-only, the dialog with the action's label instead.
+ guard:
+ <Args extends unknown[], Result>(
+ fn: (...args: Args) => Result,
+ options: { action?: string } = {},
+ ) =>
+ (...args: Args) => {
+ if (!gate.isLocked) return fn(...args);
+ gate.openUpgrade(options.action);
+ return undefined;
+ },
}),
useUpgradeDialog: () => null,
}));
@@ -146,6 +156,7 @@ const tab = (name: string) =>
beforeEach(() => {
brandState.activeBrandId = 'brand-1';
gate.isLocked = false;
+ gate.openUpgrade.mockReset();
window.history.replaceState(null, '', '/dashboard/content/library');
container = document.createElement('div');
document.body.appendChild(container);
@@ -1204,6 +1215,81 @@ describe('the Library’s Export and Created filter (CE-002)', () => {
});
});
+describe('the Library on a read-only workspace (plan not active)', () => {
+ const pick = async (title: string, item: string) => {
+ const trigger = container.querySelector<HTMLElement>(`[aria-label="Actions for ${title}"]`)!;
+ await act(async () => trigger.click());
+ const found = [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (el) => el.textContent === item,
+ )!;
+ await act(async () => found.click());
+ };
+ const buttonNamed = (name: string) =>
+ [...container.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent === name,
+ )!;
+
+ beforeEach(() => {
+ gate.isLocked = true;
+ });
+
+ it('opens the upgrade dialog from New content, Send and the row menu, and changes nothing', async () => {
+ getContentDrafts.mockResolvedValue([row({}), row({ id: 'd2', title: 'Churn guide' })]);
+ await renderPage();
+
+ await act(async () => buttonNamed('New content').click());
+ expect(gate.openUpgrade).toHaveBeenLastCalledWith('Creating content needs a plan');
+ expect(getContentStartOptions).not.toHaveBeenCalled();
+
+ await pick('Pipeline forecasting', 'Ready');
+ expect(gate.openUpgrade).toHaveBeenLastCalledWith('Marking a page ready needs a plan');
+ await pick('Pipeline forecasting', 'Published');
+ expect(gate.openUpgrade).toHaveBeenLastCalledWith('Marking a page published needs a plan');
+ await pick('Pipeline forecasting', 'In progress');
+ expect(gate.openUpgrade).toHaveBeenLastCalledWith("Changing a page's status needs a plan");
+ await pick('Pipeline forecasting', 'Send to CMS');
+ expect(gate.openUpgrade).toHaveBeenLastCalledWith('Sending to your CMS needs a plan');
+ await pick('Pipeline forecasting', 'Send to Archive');
+ expect(gate.openUpgrade).toHaveBeenLastCalledWith('Archiving content needs a plan');
+ await pick('Pipeline forecasting', 'Delete');
+ expect(gate.openUpgrade).toHaveBeenLastCalledWith('Deleting content needs a plan');
+
+ // Picking rows is no action; sending them is.
+ const box = container.querySelector<HTMLButtonElement>(
+ '[role="checkbox"][aria-label="Select Churn guide"]',
+ )!;
+ await act(async () => box.click());
+ await act(async () => buttonNamed('Send to CMS').click());
+ expect(gate.openUpgrade).toHaveBeenLastCalledWith('Sending to your CMS needs a plan');
+
+ expect(gate.openUpgrade).toHaveBeenCalledTimes(8);
+ expect(markContentDraftReady).not.toHaveBeenCalled();
+ expect(setContentDraftStatus).not.toHaveBeenCalled();
+ expect(readPublishAddress).not.toHaveBeenCalled();
+ expect(archiveContentDraft).not.toHaveBeenCalled();
+ expect(getContentDraftPages).not.toHaveBeenCalled();
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ });
+
+ it('still exports a page', async () => {
+ getContentDrafts.mockResolvedValue([row({})]);
+ await renderPage();
+ await pick('Pipeline forecasting', 'Export Markdown');
+ await act(async () => {});
+ expect(saveBlob).toHaveBeenCalledTimes(1);
+ expect(gate.openUpgrade).not.toHaveBeenCalled();
+ });
+
+ it('doesn’t open New content by itself when the URL asks', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?new=1');
+ getContentDrafts.mockResolvedValue([]);
+ await renderPage();
+ expect(document.body.textContent).not.toContain('Pick how you want to start.');
+ expect(window.location.search).toBe('');
+ expect(gate.openUpgrade).not.toHaveBeenCalled();
+ });
+});
+
describe('the Library’s Shopping path column (00352)', () => {
const checked = (bad: { id: string; title: string; state: 'sold_out' | 'refused' | 'gone' }[]) =>
({
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
index db6aa65ce..4b1fd60a9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
@@ -108,8 +108,11 @@ export default function ContentLibraryPage() {
const [starting, setStarting] = useState(false);
const { canManage } = useUserRole();
// A read-only workspace (plan not active): the reads the Library asks for
- // by itself are left out, and it lists what is stored.
- const { isLocked } = useUpgradeGate();
+ // by itself are left out, and it lists what is stored. New content, Send
+ // and the row menu's changes open the upgrade dialog instead; tabs, the
+ // date filter and Export stay open.
+ const { guard, isLocked } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
// The draft whose Delete waits for a confirmation.
const [deleting, setDeleting] = useState<ContentDraftListItem | null>(null);
const [deletePending, setDeletePending] = useState(false);
@@ -141,12 +144,12 @@ export default function ContentLibraryPage() {
setCreated(readUrlChoice('created', CREATED_RANGES, 'all'));
setSent(readUrlChoice('sent', SEND_FILTERS, 'all'));
setShoppingFilter(readUrlChoice('shopping', SHOPPING_FILTERS, 'all'));
- // Once: closed, it doesn't open again on a reload.
+ // Once: closed, it doesn't open again on a reload. Read-only, it doesn't open.
if (readUrlParam('new') === '1') {
- setStarting(true);
+ if (!isLocked) setStarting(true);
writeUrlParams({ new: null });
}
- }, []);
+ }, [isLocked]);
const { exporting, exportList, exportDraft } = useLibraryExport(activeBrandId);
useEffect(() => {
@@ -274,25 +277,40 @@ export default function ContentLibraryPage() {
else toast.error(t('rowMenu.sendFailed'));
};
+ const changeStatus = (draft: ContentDraftListItem, status: DraftStatus) => {
+ // Published asks where the page is live (CE-013): tracking starts there.
+ if (status === 'published') {
+ setPublishing(draft.id);
+ return;
+ }
+ // Ready keeps a History version and completes the draft's task, as the editor's Mark ready.
+ const change =
+ status === 'ready'
+ ? markContentDraftReady(draft.id)
+ : setContentDraftStatus(draft.id, status);
+ change.then(reload, failed);
+ };
const rowActions: LibraryRowActions = {
canManage,
- onStatus: (draft: ContentDraftListItem, status: DraftStatus) => {
- // Published asks where the page is live (CE-013): tracking starts there.
- if (status === 'published') {
- setPublishing(draft.id);
- return;
- }
- // Ready keeps a History version and completes the draft's task, as the editor's Mark ready.
- const change =
- status === 'ready'
- ? markContentDraftReady(draft.id)
- : setContentDraftStatus(draft.id, status);
- change.then(reload, failed);
- },
- onArchive: (draft, archived) => void archive(draft, archived),
- onDelete: setDeleting,
+ onStatus: (draft, status) =>
+ guard(changeStatus, {
+ action: tActions(
+ status === 'published'
+ ? 'markPublished'
+ : status === 'ready'
+ ? 'markReady'
+ : 'changeContentStatus',
+ ),
+ })(draft, status),
+ onArchive: (draft, archived) =>
+ guard(() => void archive(draft, archived), {
+ action: tActions(archived ? 'archiveContent' : 'restoreContent'),
+ })(),
+ onDelete: guard(setDeleting, { action: tActions('deleteContent') }),
onExport: (draft, format) => void exportDraft(draft, format),
- onSend: (draft) => void openSend(draft),
+ onSend: guard((draft: ContentDraftListItem) => void openSend(draft), {
+ action: tActions('sendToCms'),
+ }),
};
const confirmDelete = async () => {
@@ -388,7 +406,10 @@ export default function ContentLibraryPage() {
exporting={exporting}
onExport={(format) => void exportList(listed, tab, format)}
/>
- <Button className="gap-2" onClick={() => setStarting(true)}>
+ <Button
+ className="gap-2"
+ onClick={guard(() => setStarting(true), { action: tActions('createContent') })}
+ >
<Plus className="h-4 w-4" />
{t('newContent')}
</Button>
@@ -498,14 +519,16 @@ export default function ContentLibraryPage() {
size="sm"
className="h-7 gap-1.5 text-xs"
disabled={tooMany}
- onClick={() =>
- setBulk({
- brandId: activeBrandId,
- brandName: activeBrand?.name ?? '',
- brandLanguage: activeBrand?.language,
- drafts: pickedDrafts,
- })
- }
+ onClick={guard(
+ () =>
+ setBulk({
+ brandId: activeBrandId,
+ brandName: activeBrand?.name ?? '',
+ brandLanguage: activeBrand?.language,
+ drafts: pickedDrafts,
+ }),
+ { action: tActions('sendToCms') },
+ )}
>
<Send className="h-3 w-3" />
{t('bulk.sendSelected')}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx
new file mode 100644
index 000000000..fe03a948d
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx
@@ -0,0 +1,237 @@
+import { act, type ReactNode } 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 { ContentOpportunity } from '@/types';
+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
+
+/**
+ * Content Opportunities on a read-only workspace (plan not active): New, the
+ * bulk bar, the rows' menu and the workflow settings open the upgrade dialog
+ * instead, named; on an active plan they run.
+ */
+
+const content = vi.hoisted(() => ({
+ generateOpportunitiesOnDemand: vi.fn(),
+ getGenerationJobStatus: vi.fn(),
+ getContentUsage: vi.fn(),
+ getOpportunities: vi.fn(),
+ getOpportunityPrompts: vi.fn(),
+ getOpportunityTopics: vi.fn(),
+ updateOpportunityStatus: vi.fn(),
+ sendToWebhook: vi.fn(),
+ bulkSendToWebhook: vi.fn(),
+ bulkUpdateStatus: vi.fn(),
+ bulkDeleteOpportunities: vi.fn(),
+ getWebhookConfig: vi.fn(),
+ saveWebhookConfig: vi.fn(),
+ testWebhook: vi.fn(),
+}));
+vi.mock('@/lib/actions/content', () => content);
+vi.mock('@/lib/actions/content-drafts', () => ({
+ getOpportunityDrafts: vi.fn(async () => ({})),
+}));
+const plan = vi.hoisted(() => ({
+ getPlanPriorities: vi.fn(async () => []),
+ setPlanRowPriority: vi.fn(async () => undefined),
+}));
+vi.mock('@/lib/actions/content-plan', () => plan);
+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => ({ canManage: true }) }));
+const brandState = vi.hoisted(() => ({
+ activeBrandId: 'b1',
+ brands: [{ id: 'b1', name: 'Acme', slug: 'acme', siteType: 'b2b' }],
+ getActiveBrand: () => ({ id: 'b1', slug: 'acme' }),
+}));
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: (select: (state: typeof brandState) => unknown) => select(brandState),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children }: { href: string; children: ReactNode }) => (
+ <a href={href}>{children}</a>
+ ),
+ useRouter: () => ({ push: vi.fn() }),
+}));
+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({
+ HeaderWithAiUsage: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+// The dialogs are their own tests'; here, whether the page opens them.
+const opened = vi.hoisted(() => ({ newOpportunities: false, newContent: false }));
+vi.mock('@/components/content/new-opportunities-dialog', () => ({
+ NewOpportunitiesDialog: ({ open }: { open: boolean }) => {
+ opened.newOpportunities = open;
+ return null;
+ },
+}));
+vi.mock('@/components/content/new-content-dialog', () => ({
+ NewContentDialog: ({ open }: { open: boolean }) => {
+ opened.newContent = open;
+ return null;
+ },
+}));
+vi.mock('@/components/content/opportunity-detail', () => ({ OpportunityDetail: () => null }));
+vi.mock('sonner', () => ({
+ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn() }),
+}));
+
+const { default: ContentPage } = await import('./page');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const OPPORTUNITY: ContentOpportunity = {
+ id: 'o1',
+ brandId: 'b1',
+ title: 'Office coffee subscriptions',
+ description: 'A page AI answers lack.',
+ type: 'owned',
+ impact: 'high',
+ opportunityScore: 74,
+ status: 'new',
+ source: 'system',
+ sourceData: {},
+ createdAt: '2026-10-20T10:00:00Z',
+ updatedAt: '2026-10-20T10:00:00Z',
+} as ContentOpportunity;
+
+let container: HTMLDivElement;
+let root: Root;
+const openUpgrade = vi.fn();
+
+async function render(isLocked: boolean) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <ContentPage />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+}
+
+const buttonNamed = (name: string) =>
+ [...document.body.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === name,
+ )!;
+const pickRow = async () => {
+ const box = container.querySelector<HTMLElement>('tbody [role="checkbox"]')!;
+ await act(async () => box.click());
+};
+const rowItem = async (item: string) => {
+ const trigger = container.querySelector<HTMLElement>(
+ '[aria-label="Actions for Office coffee subscriptions"]',
+ )!;
+ await act(async () => trigger.click());
+ const found = [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (el) => el.textContent === item,
+ )!;
+ await act(async () => found.click());
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ opened.newOpportunities = false;
+ opened.newContent = false;
+ window.history.replaceState(null, '', '/dashboard/content');
+ content.getOpportunities.mockResolvedValue({
+ opportunities: [OPPORTUNITY],
+ total: 1,
+ aggregates: { avgScore: 74, highImpactCount: 1, sentCount: 0, signalCount: 0 },
+ });
+ content.getOpportunityPrompts.mockResolvedValue([]);
+ content.getOpportunityTopics.mockResolvedValue([]);
+ content.getContentUsage.mockResolvedValue(null);
+ content.bulkUpdateStatus.mockResolvedValue({ updated: 1 });
+ content.getWebhookConfig.mockResolvedValue({
+ webhookUrl: 'https://hooks.example/acme',
+ webhookSecret: '',
+ isActive: true,
+ events: ['opportunity.sent'],
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('Content Opportunities on a read-only workspace', () => {
+ it('asks the AI for nothing: New opens the upgrade dialog, not its own', async () => {
+ await render(true);
+ await act(async () => buttonNamed('New').click());
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Generating opportunities needs a plan');
+ expect(opened.newOpportunities).toBe(false);
+ });
+
+ it('opens the upgrade dialog from the bulk bar, without asking first', async () => {
+ await render(true);
+ await pickRow();
+ await act(async () => buttonNamed('Send All').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Sending to your workflow needs a plan');
+ await act(async () => buttonNamed('Done').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Marking opportunities done needs a plan');
+ await act(async () => buttonNamed('Dismiss All').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Dismissing opportunities needs a plan');
+ await act(async () => buttonNamed('Delete').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Deleting opportunities needs a plan');
+ expect(openUpgrade).toHaveBeenCalledTimes(4);
+ // No confirmation opened, and nothing sent or changed.
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ expect(content.bulkSendToWebhook).not.toHaveBeenCalled();
+ expect(content.bulkUpdateStatus).not.toHaveBeenCalled();
+ expect(content.bulkDeleteOpportunities).not.toHaveBeenCalled();
+ });
+
+ it('opens the upgrade dialog from the row’s menu', async () => {
+ await render(true);
+ await rowItem('Send to Editor');
+ expect(openUpgrade).toHaveBeenLastCalledWith('Creating content needs a plan');
+ await rowItem('Send to Plan');
+ expect(openUpgrade).toHaveBeenLastCalledWith('Marking priorities needs a plan');
+ await rowItem('Send to Workflow');
+ expect(openUpgrade).toHaveBeenLastCalledWith('Sending to your workflow needs a plan');
+ await rowItem('Dismiss');
+ expect(openUpgrade).toHaveBeenLastCalledWith('Dismissing opportunities needs a plan');
+ expect(opened.newContent).toBe(false);
+ expect(plan.setPlanRowPriority).not.toHaveBeenCalled();
+ expect(content.sendToWebhook).not.toHaveBeenCalled();
+ expect(content.updateOpportunityStatus).not.toHaveBeenCalled();
+ });
+
+ it('shows the workflow settings, and saves or tests nothing', async () => {
+ await render(true);
+ await act(async () => buttonNamed('Webhook Settings').click());
+ await act(async () => {});
+ expect(content.getWebhookConfig).toHaveBeenCalledWith('b1');
+ await act(async () => buttonNamed('Save Webhook').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Saving the workflow settings needs a plan');
+ await act(async () => buttonNamed('Test Webhook').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Testing the workflow needs a plan');
+ expect(content.saveWebhookConfig).not.toHaveBeenCalled();
+ expect(content.testWebhook).not.toHaveBeenCalled();
+ });
+});
+
+describe('Content Opportunities on an active plan', () => {
+ it('runs the actions', async () => {
+ await render(false);
+ await act(async () => buttonNamed('New').click());
+ expect(opened.newOpportunities).toBe(true);
+ await pickRow();
+ await act(async () => buttonNamed('Done').click());
+ expect(content.bulkUpdateStatus).toHaveBeenCalledWith(['o1'], 'done');
+ await pickRow();
+ await act(async () => buttonNamed('Dismiss All').click());
+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain(
+ 'Dismiss opportunities?',
+ );
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index a01898180..91c4f37c5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -84,6 +84,7 @@ import { getOpportunityDrafts } from '@/lib/actions/content-drafts';
import { getPlanPriorities, setPlanRowPriority } from '@/lib/actions/content-plan';
import { OpportunityRowMenu } from '@/components/content/opportunity-row-menu';
import { useUserRole } from '@/hooks/use-user-role';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { bulkSendNotes } from '@/lib/content/bulk-send';
import { contentEditorPath } from '@/lib/content/drafts';
import { canWriteOpportunity, opportunityStart } from '@/lib/content/opportunity-start';
@@ -349,6 +350,17 @@ export default function ContentPage() {
const locale = useLocale();
const activeBrandId = useBrandStore((s) => s.activeBrandId);
const activeBrandSlug = useBrandStore((s) => s.getActiveBrand()?.slug);
+ // A read-only workspace (plan not active): New, the bulk bar and the rows'
+ // actions open the upgrade dialog instead; filters and Export stay open.
+ const { guard, isLocked, openUpgrade } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
+ // The bulk bar's Dismiss and Delete ask first: the upgrade dialog instead.
+ const confirmUnlessLocked =
+ (action: string) => (open: boolean, details: { cancel: () => void }) => {
+ if (!open || !isLocked) return;
+ details.cancel();
+ openUpgrade(action);
+ };
const [opportunities, setOpportunities] = useState<ContentOpportunity[]>([]);
const [total, setTotal] = useState(0);
@@ -868,7 +880,7 @@ export default function ContentPage() {
: '';
const newButton = (
<Button
- onClick={() => setNewOpen(true)}
+ onClick={guard(() => setNewOpen(true), { action: tActions('generateOpportunities') })}
disabled={generating || loading || limitReached}
size="sm"
className="gap-2"
@@ -1408,7 +1420,7 @@ export default function ContentPage() {
variant="outline"
size="sm"
className="h-7 text-xs gap-1.5"
- onClick={handleBulkSend}
+ onClick={guard(handleBulkSend, { action: tActions('sendToWorkflow') })}
disabled={bulkSending}
>
{bulkSending ? <LoadingDots /> : <Send className="h-3 w-3" />}
@@ -1419,14 +1431,14 @@ export default function ContentPage() {
variant="outline"
size="sm"
className="h-7 text-xs gap-1.5"
- onClick={handleBulkDone}
+ onClick={guard(handleBulkDone, { action: tActions('markOpportunitiesDone') })}
disabled={bulkSending}
>
<Check className="h-3 w-3" />
{t('status.done')}
</Button>
- <Dialog>
+ <Dialog onOpenChange={confirmUnlessLocked(tActions('dismissOpportunities'))}>
<DialogTrigger
render={
<Button
@@ -1462,7 +1474,7 @@ export default function ContentPage() {
{/* Last in the row, and the only destructive-styled trigger:
this one does not move a row, it removes it. */}
- <Dialog>
+ <Dialog onOpenChange={confirmUnlessLocked(tActions('deleteOpportunities'))}>
<DialogTrigger
render={
<Button
@@ -1690,7 +1702,9 @@ export default function ContentPage() {
lookupFailed: draftsShown?.failed ?? false,
onRetry: retryDrafts,
canStart: canWriteOpportunity(opp),
- onStart: () => setContentPreset(opportunityStart(opp)),
+ onStart: guard(() => setContentPreset(opportunityStart(opp)), {
+ action: tActions('createContent'),
+ }),
onOpenDraft: (draftId) => router.push(contentEditorPath(draftId)),
}}
// The Plan lists owned work still open; its marks are
@@ -1701,7 +1715,9 @@ export default function ContentPage() {
prioritized: prioritiesShown
? prioritiesShown.includes(opp.id)
: undefined,
- onSend: () => void handleSendToPlan(opp.id),
+ onSend: guard(() => void handleSendToPlan(opp.id), {
+ action: tActions('prioritizeContent'),
+ }),
onOpen: () => router.push('/dashboard/content/plan'),
}
: null
@@ -1710,13 +1726,19 @@ export default function ContentPage() {
opp.status === 'new'
? {
sending: sendingId === opp.id,
- onSend: () => void handleSendWebhook(opp.id),
+ onSend: guard(() => void handleSendWebhook(opp.id), {
+ action: tActions('sendToWorkflow'),
+ }),
}
: null
}
pageHref={`/dashboard/content/${opp.id}`}
onDismiss={
- opp.status === 'new' ? () => void handleDismiss(opp.id) : undefined
+ opp.status === 'new'
+ ? guard(() => void handleDismiss(opp.id), {
+ action: tActions('dismissOpportunities'),
+ })
+ : undefined
}
/>
</TableCell>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
index a3a0f7992..f1c4a58c3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
@@ -4,6 +4,7 @@ import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../../messages/en.json';
import type { PlanOpportunity, PlanPage } from '@/lib/content/plan';
+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
import ContentPlanPage from './page';
const getContentPlan = vi.fn();
@@ -793,3 +794,76 @@ describe('Getting started’s content steps (00234)', () => {
expect(push).not.toHaveBeenCalled();
});
});
+
+describe('the Content plan on a read-only workspace (plan not active)', () => {
+ const openUpgrade = vi.fn();
+ const render = async (isLocked: boolean) => {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <ContentPlanPage />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ );
+ });
+ };
+ const clickItem = async (title: string, item: string) => {
+ const trigger = container.querySelector<HTMLElement>(`[aria-label="Actions for ${title}"]`)!;
+ await act(async () => trigger.click());
+ const found = [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (el) => el.textContent === item,
+ )!;
+ await act(async () => found.click());
+ };
+
+ beforeEach(() => openUpgrade.mockReset());
+
+ it('opens the upgrade dialog from New content, Start and the row menu, and runs nothing', async () => {
+ await render(true);
+ await act(async () => button('New content').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Creating content needs a plan');
+ const rows = container.querySelectorAll('tbody tr');
+ await act(async () => rows[1].querySelector<HTMLButtonElement>(START)!.click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Optimizing content needs a plan');
+ expect(dialog.props).toMatchObject({ open: false, preset: null });
+
+ await clickItem('Espresso guide', 'Mark as priority');
+ expect(openUpgrade).toHaveBeenLastCalledWith('Marking priorities needs a plan');
+ await clickItem('Espresso guide', 'Hide from the plan');
+ expect(openUpgrade).toHaveBeenLastCalledWith('Hiding rows needs a plan');
+ await clickItem('Espresso guide', 'Assign to…');
+ expect(openUpgrade).toHaveBeenLastCalledWith('Assigning content needs a plan');
+ expect(openUpgrade).toHaveBeenCalledTimes(5);
+ expect(setPlanRowPriority).not.toHaveBeenCalled();
+ expect(hidePlanRow).not.toHaveBeenCalled();
+ expect(container.querySelector('[data-testid="assign-dialog"]')).toBeNull();
+ // Browsing stays open: a card still filters the list.
+ await act(async () => button('Protect').click());
+ expect(rowTexts().map((r) => r[1])).toEqual(['Protect']);
+ });
+
+ it('opens on Getting started’s card and starts nothing by itself', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/plan?start=create');
+ await render(true);
+ expect(button('Create').getAttribute('aria-pressed')).toBe('true');
+ expect(dialog.props).toMatchObject({ open: false });
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+
+ it('starts a row on an active plan', async () => {
+ await render(false);
+ const rows = container.querySelectorAll('tbody tr');
+ await act(async () => rows[0].querySelector<HTMLButtonElement>(START)!.click());
+ expect(dialog.props).toMatchObject({ open: true, preset: { kind: 'opportunity', id: 'o1' } });
+ await clickItem('Espresso guide', 'Mark as priority');
+ expect(setPlanRowPriority).toHaveBeenCalledWith(
+ 'brand-1',
+ 'page:acme.example/guides/espresso',
+ true,
+ );
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
index 9047e56b7..1b8852f34 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
@@ -17,6 +17,7 @@ import {
} from '@/lib/actions/content-plan';
import { listMembers, type TeamMember } from '@/lib/actions/team';
import { useUserRole } from '@/hooks/use-user-role';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { useRouter } from '@/i18n/navigation';
import { contentEditorPath, type PageType } from '@/lib/content/drafts';
import { pageTypeMix } from '@/lib/content/plan-mix';
@@ -108,6 +109,11 @@ export default function ContentPlanPage() {
const [starting, setStarting] = useState(false);
const [preset, setPreset] = useState<DialogPreset | null>(null);
const { canManage } = useUserRole();
+ // A read-only workspace (plan not active): New content, Start, Assign and
+ // the row menu open the upgrade dialog instead; the cards, the mix and the
+ // period still filter.
+ const { guard, isLocked } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const [members, setMembers] = useState<TeamMember[]>([]);
const [assigning, setAssigning] = useState<PlanRow | null>(null);
const [showHidden, setShowHidden] = useState(false);
@@ -230,14 +236,15 @@ export default function ContentPlanPage() {
// eslint-disable-next-line react-hooks/set-state-in-effect -- one start per visit from Getting started
setStartFrom(null);
setCard(startFrom);
- if (!row) return;
+ // Read-only: the plan opens on the step's card, and nothing starts by itself.
+ if (!row || isLocked) return;
if (row.draft) {
router.push(contentEditorPath(row.draft.id));
return;
}
setPreset(presetFor(row));
setStarting(true);
- }, [startFrom, plan, router]);
+ }, [startFrom, plan, router, isLocked]);
const reload = () => setAttempt((n) => n + 1);
@@ -321,10 +328,13 @@ export default function ContentPlanPage() {
</div>
<Button
className="gap-2"
- onClick={() => {
- setPreset(null);
- setStarting(true);
- }}
+ onClick={guard(
+ () => {
+ setPreset(null);
+ setStarting(true);
+ },
+ { action: tActions('createContent') },
+ )}
>
<Plus className="h-4 w-4" />
{t('newContent')}
@@ -449,10 +459,21 @@ export default function ContentPlanPage() {
rows={rows}
days={current?.days ?? 30}
canManage={canManage}
- onStart={startRow}
- onAssign={assignRow}
- onPriority={(row, priority) => void markRow(row, priority)}
- onHide={(row) => void hideRow(row)}
+ onStart={(row) =>
+ guard(startRow, {
+ action: tActions(
+ row.action === 'create' ? 'createContent' : 'optimizeContent',
+ ),
+ })(row)
+ }
+ onAssign={guard(assignRow, { action: tActions('assignContent') })}
+ onPriority={guard(
+ (row: PlanRow, priority: boolean) => void markRow(row, priority),
+ { action: tActions('prioritizeContent') },
+ )}
+ onHide={guard((row: PlanRow) => void hideRow(row), {
+ action: tActions('hidePlanRows'),
+ })}
/>
)}
</CardContent>
@@ -478,7 +499,13 @@ export default function ContentPlanPage() {
{row.title}
</span>
{canManage && (
- <Button size="sm" variant="outline" onClick={() => void showRow(row)}>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={guard(() => void showRow(row), {
+ action: tActions('showPlanRows'),
+ })}
+ >
{t('hidden.show')}
</Button>
)}
diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsx
index 7ce3685e4..a0c770b87 100644
--- a/web/src/components/content/new-content-dialog.tsx
+++ b/web/src/components/content/new-content-dialog.tsx
@@ -82,6 +82,7 @@ import {
import { formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import { useBrandStore } from '@/stores/use-brand-store';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
type SourceKind = 'opportunity' | 'prompt' | 'topic';
const SOURCE_KINDS: SourceKind[] = ['opportunity', 'prompt', 'topic'];
@@ -202,6 +203,11 @@ export function NewContentDialog({
const tTypes = useTranslations('contentEditor.pageTypes');
const router = useRouter();
const describeRule = useRuleDescriber();
+ // A read-only workspace (plan not active): what opens this dialog opens the
+ // upgrade dialog instead; should it be open, reading a page by its URL and
+ // Open editor do too.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const [options, setOptions] = useState<DraftStartOptions | null>(null);
const [optionsFailed, setOptionsFailed] = useState(false);
@@ -758,7 +764,14 @@ export function NewContentDialog({
<ArrowLeft className="h-4 w-4" />
{t('back')}
</Button>
- <Button onClick={() => void openEditor()} disabled={opening}>
+ <Button
+ onClick={guard(() => void openEditor(), {
+ action: tActions(
+ startMethod === 'optimize' ? 'optimizeContent' : 'createContent',
+ ),
+ })}
+ disabled={opening}
+ >
{opening && <LoadingDots />}
{t(
who === 'team'
@@ -939,7 +952,7 @@ export function NewContentDialog({
className="flex gap-2"
onSubmit={(e) => {
e.preventDefault();
- void readPage();
+ guard(() => void readPage(), { action: tActions('importPage') })();
}}
>
<Input
diff --git a/web/src/components/content/opportunity-detail.test.tsx b/web/src/components/content/opportunity-detail.test.tsx
new file mode 100644
index 000000000..c58e706c6
--- /dev/null
+++ b/web/src/components/content/opportunity-detail.test.tsx
@@ -0,0 +1,174 @@
+import { act, type ReactNode } 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 { ContentOpportunity } from '@/types';
+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';
+
+/**
+ * The opportunity panel on a read-only workspace (plan not active): its
+ * actions open the upgrade dialog instead, named; on an active plan they run.
+ */
+
+const content = vi.hoisted(() => ({
+ getOpportunity: vi.fn(),
+ getBriefQuota: vi.fn(),
+ generateBrief: vi.fn(),
+ updateOpportunityStatus: vi.fn(),
+ sendToWebhook: vi.fn(),
+ sendOpportunityToActionCenter: vi.fn(),
+ suggestAlternative: vi.fn(),
+ getGenerationJobStatus: vi.fn(),
+}));
+vi.mock('@/lib/actions/content', () => content);
+vi.mock('@/lib/actions/fanout', () => ({
+ getPromptFanout: vi.fn(async () => ({ subQueries: [] })),
+}));
+vi.mock('@/lib/actions/content-drafts', () => ({
+ getOpportunityDrafts: vi.fn(async () => ({})),
+}));
+const plan = vi.hoisted(() => ({
+ getPlanPriorities: vi.fn(async () => []),
+ setPlanRowPriority: vi.fn(async () => undefined),
+}));
+vi.mock('@/lib/actions/content-plan', () => plan);
+vi.mock('@/hooks/use-opportunity-volume', () => ({
+ useOpportunityVolume: () => ({ basket: null, basketFailed: false, volume: null }),
+}));
+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => ({ canManage: true }) }));
+const brandState = vi.hoisted(() => ({
+ activeBrandId: 'b1',
+ brands: [{ id: 'b1', name: 'Acme', siteType: 'b2b' }],
+}));
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: (select: (state: typeof brandState) => unknown) => select(brandState),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children }: { href: string; children: ReactNode }) => (
+ <a href={href}>{children}</a>
+ ),
+ useRouter: () => ({ push: vi.fn() }),
+}));
+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({
+ HeaderWithAiUsage: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.mock('@/components/ai-usage/ai-usage-banner', () => ({ AiUsageBanner: () => null }));
+const newContent = vi.hoisted(() => ({ open: false }));
+vi.mock('@/components/content/new-content-dialog', () => ({
+ NewContentDialog: ({ open }: { open: boolean }) => {
+ newContent.open = open;
+ return null;
+ },
+}));
+vi.mock('sonner', () => ({
+ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),
+}));
+
+const { OpportunityDetail } = await import('./opportunity-detail');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const OPPORTUNITY = {
+ id: 'o1',
+ brandId: 'b1',
+ title: 'Office coffee subscriptions',
+ type: 'owned',
+ impact: 'high',
+ opportunityScore: 74,
+ status: 'new',
+ source: 'system',
+ sourceData: {},
+ createdAt: '2026-10-20T10:00:00Z',
+ updatedAt: '2026-10-20T10:00:00Z',
+} as ContentOpportunity;
+
+let container: HTMLDivElement;
+let root: Root;
+const openUpgrade = vi.fn();
+
+async function render(isLocked: boolean) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <UpgradeDialogContext.Provider
+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}
+ >
+ <OpportunityDetail id="o1" inDrawer />
+ </UpgradeDialogContext.Provider>
+ </NextIntlClientProvider>,
+ );
+ });
+ await act(async () => {});
+}
+
+const buttonNamed = (name: string) =>
+ [...container.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === name,
+ )!;
+const moreItem = async (item: string) => {
+ await act(async () =>
+ container.querySelector<HTMLElement>('[aria-label="More actions"]')!.click(),
+ );
+ const found = [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (el) => el.textContent === item,
+ )!;
+ await act(async () => found.click());
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ newContent.open = false;
+ content.getOpportunity.mockResolvedValue(OPPORTUNITY);
+ content.getBriefQuota.mockResolvedValue({ limit: -1, remaining: -1 });
+ content.generateBrief.mockResolvedValue({
+ brief: {
+ suggestedTitle: 'Office coffee subscriptions',
+ contentType: 'how-to',
+ targetWordCount: 1200,
+ outline: [],
+ targetKeywords: [],
+ competitorInsights: '',
+ callToAction: '',
+ },
+ quota: null,
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('the opportunity panel on a read-only workspace', () => {
+ it('opens the upgrade dialog from its actions, and runs none', async () => {
+ await render(true);
+ await act(async () => buttonNamed('Send to Actions').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Sending actions needs a plan');
+ await act(async () => buttonNamed('Generate Brief').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Generating a brief needs a plan');
+ await act(async () => buttonNamed('Send to Editor').click());
+ expect(openUpgrade).toHaveBeenLastCalledWith('Creating content needs a plan');
+ await moreItem('Mark as reviewed');
+ expect(openUpgrade).toHaveBeenLastCalledWith('Marking an opportunity reviewed needs a plan');
+ await moreItem('Another angle');
+ expect(openUpgrade).toHaveBeenLastCalledWith('Generating opportunities needs a plan');
+ expect(openUpgrade).toHaveBeenCalledTimes(5);
+ expect(content.sendOpportunityToActionCenter).not.toHaveBeenCalled();
+ expect(content.generateBrief).not.toHaveBeenCalled();
+ expect(content.updateOpportunityStatus).not.toHaveBeenCalled();
+ expect(newContent.open).toBe(false);
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ });
+
+ it('generates the brief on an active plan', async () => {
+ await render(false);
+ await act(async () => buttonNamed('Generate Brief').click());
+ expect(content.generateBrief).toHaveBeenCalledWith('o1');
+ expect(openUpgrade).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsx
index 8b6df5a83..12dfbfa5f 100644
--- a/web/src/components/content/opportunity-detail.tsx
+++ b/web/src/components/content/opportunity-detail.tsx
@@ -70,6 +70,7 @@ import { siteTypeOf } from '@/lib/content/page-types';
import { getOpportunityDrafts } from '@/lib/actions/content-drafts';
import { getPlanPriorities, setPlanRowPriority } from '@/lib/actions/content-plan';
import { useUserRole } from '@/hooks/use-user-role';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { useBrandStore } from '@/stores/use-brand-store';
import { OpportunityActions } from '@/components/content/opportunity-actions';
import { NewContentDialog, type DialogPreset } from '@/components/content/new-content-dialog';
@@ -156,6 +157,10 @@ export function OpportunityDetail({
const failureToast = useFailureToast();
const assetTypeLabel = useAssetTypeLabel();
const locale = useLocale();
+ // A read-only workspace (plan not active): every action here opens the
+ // upgrade dialog instead; Copy, Export and Open draft stay open.
+ const { guard } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
const [opportunity, setOpportunity] = useState<ContentOpportunity | null>(null);
const [loading, setLoading] = useState(true);
@@ -559,7 +564,9 @@ export function OpportunityDetail({
? {
sending: sendingAction === 'all',
disabled: sendingAction !== null,
- onSend: () => void handleSendToActionCenter(),
+ onSend: guard(() => void handleSendToActionCenter(), {
+ action: tActions('sendAction'),
+ }),
}
: null
}
@@ -567,7 +574,9 @@ export function OpportunityDetail({
generated: !!brief,
generating: generatingBrief,
blockedReason: quotaExhausted ? t('briefLimitReached') : null,
- onGenerate: () => void handleGenerateBrief(),
+ onGenerate: guard(() => void handleGenerateBrief(), {
+ action: tActions('generateBrief'),
+ }),
}}
content={{
draftId:
@@ -575,14 +584,18 @@ export function OpportunityDetail({
lookupFailed: draft?.opportunityId === opportunity.id && draft.failed,
onRetry: retryDraft,
canStart: canWriteOpportunity(opportunity),
- onStart: () => setContentPreset(opportunityStart(opportunity)),
+ onStart: guard(() => setContentPreset(opportunityStart(opportunity)), {
+ action: tActions('createContent'),
+ }),
onOpenDraft: (draftId) => router.push(contentEditorPath(draftId)),
}}
plan={
canManage && canWriteOpportunity(opportunity)
? {
prioritized: priority?.opportunityId === opportunity.id ? priority.on : undefined,
- onSend: () => void handleSendToPlan(),
+ onSend: guard(() => void handleSendToPlan(), {
+ action: tActions('prioritizeContent'),
+ }),
onOpen: () => router.push('/dashboard/content/plan'),
}
: null
@@ -591,7 +604,12 @@ export function OpportunityDetail({
// from the Action Center (AC-004) has neither.
alternative={
opportunity.source !== 'action'
- ? { running: alternativeRunning, onOpen: () => setAlternativeOpen(true) }
+ ? {
+ running: alternativeRunning,
+ onOpen: guard(() => setAlternativeOpen(true), {
+ action: tActions('generateOpportunities'),
+ }),
+ }
: null
}
workflow={
@@ -599,15 +617,27 @@ export function OpportunityDetail({
? {
sending,
sentBefore: !!opportunity.webhookSentAt,
- onSend: () => void handleSend(),
+ onSend: guard(() => void handleSend(), { action: tActions('sendToWorkflow') }),
}
: null
}
onCopy={() => void handleCopy()}
onExport={(format) => void handleExport(format)}
- onReviewed={opportunity.status === 'new' ? () => void handleReviewed() : undefined}
- onRestore={opportunity.status === 'archived' ? () => void handleRestore() : undefined}
- onDismiss={opportunity.status === 'new' ? () => setDismissOpen(true) : undefined}
+ onReviewed={
+ opportunity.status === 'new'
+ ? guard(() => void handleReviewed(), { action: tActions('markOpportunityReviewed') })
+ : undefined
+ }
+ onRestore={
+ opportunity.status === 'archived'
+ ? guard(() => void handleRestore(), { action: tActions('restoreOpportunities') })
+ : undefined
+ }
+ onDismiss={
+ opportunity.status === 'new'
+ ? guard(() => setDismissOpen(true), { action: tActions('dismissOpportunities') })
+ : undefined
+ }
/>
</div>
<AiUsageBanner />
@@ -649,7 +679,11 @@ export function OpportunityDetail({
)}
<AssetsCard
sourceData={sd}
- onSend={canSendToActionCenter ? handleSendToActionCenter : undefined}
+ onSend={
+ canSendToActionCenter
+ ? guard(handleSendToActionCenter, { action: tActions('sendAction') })
+ : undefined
+ }
sendingKey={sendingAction}
/>
<OpportunityBasketCard basket={basket} failed={basketFailed} />
@@ -865,7 +899,7 @@ export function OpportunityDetail({
keywords, and competitor insights.
</p>
<Button
- onClick={handleGenerateBrief}
+ onClick={guard(handleGenerateBrief, { action: tActions('generateBrief') })}
disabled={generatingBrief}
className="gap-2"
>