From 89646b4eed79c4879c8569e75de1fd2ecb3ed81f Mon Sep 17 00:00:00 2001 From: snowopsdev Date: Tue, 10 Nov 2026 00:50:33 -0500 Subject: [PATCH 01/15] fix(cms): return reviewer-action refusals as values so production shows them Next redacts the message of an error thrown from a server action in a production build, so gate refusals reached the reviewer as a generic error. The actions in actions.ts, brandVoiceActions.ts and saveTemplateConfigAction now answer { ok: true, ... } | { ok: false, error }; the editors rethrow the message in the browser. Also narrows article reads in actions.ts to the fields they use, refuses resetting an article that is still at researched, and purges the public page when a published article is archived or unarchived. Co-Authored-By: Claude Sonnet 5.5 --- cms/src/components/ops/BrandVoiceEditor.tsx | 62 +- .../components/ops/TemplateConfigEditor.tsx | 27 +- cms/src/components/ops/actionResult.ts | 42 ++ cms/src/components/ops/actions.ts | 654 ++++++++++-------- cms/src/components/ops/articleReset.ts | 39 ++ cms/src/components/ops/brandVoiceActions.ts | 135 ++-- .../components/ops/review/SendBackAction.tsx | 5 +- .../ops/review/panels/RunNextStagePanel.tsx | 3 +- cms/src/components/ops/templateActions.ts | 73 +- cms/tests/int/articleActions.int.spec.ts | 207 +++++- cms/tests/int/brandVoiceEditor.int.spec.ts | 69 +- .../int/templateConfigEditor.int.spec.ts | 34 + cms/tests/int/tenantActions.int.spec.ts | 23 + 13 files changed, 919 insertions(+), 454 deletions(-) create mode 100644 cms/src/components/ops/actionResult.ts create mode 100644 cms/src/components/ops/articleReset.ts diff --git a/cms/src/components/ops/BrandVoiceEditor.tsx b/cms/src/components/ops/BrandVoiceEditor.tsx index aef9b79..d6e86be 100644 --- a/cms/src/components/ops/BrandVoiceEditor.tsx +++ b/cms/src/components/ops/BrandVoiceEditor.tsx @@ -9,6 +9,7 @@ import { brandVoiceActivationProblems, emptyBrandVoiceContent, } from '../../lib/brandVoice' +import { unwrap } from './actionResult' import { AssetStepper } from './AssetStepper' import { SaveButton } from './DirtyGuardUi' import { AuditTimeline } from './AuditTimeline' @@ -252,17 +253,49 @@ export function BrandVoiceEditor({ // safe choice is the one the keyboard lands on. const [confirmArchive, setConfirmArchive] = useState(false) const cancelArchiveRef = useRef(null) + const keepDeleteRef = useRef(null) + const archiveTriggerRef = useRef(null) + const deleteTriggerRef = useRef(null) + /** Which trigger should get focus back once its confirm has been backed out of. */ + const refocus = useRef<'archive' | 'delete' | null>(null) + + const cancelArchive = () => { + refocus.current = 'archive' + setConfirmArchive(false) + } + const cancelDelete = () => { + refocus.current = 'delete' + setConfirmDelete(false) + } useEffect(() => { if (!confirmArchive) return cancelArchiveRef.current?.focus() const onKey = (event: KeyboardEvent) => { - if (event.key === 'Escape') setConfirmArchive(false) + if (event.key === 'Escape') { + refocus.current = 'archive' + setConfirmArchive(false) + } } document.addEventListener('keydown', onKey) return () => document.removeEventListener('keydown', onKey) }, [confirmArchive]) + // Arming swaps the trigger for its confirm buttons, so focus would fall to + // : it goes to the safe choice (Cancel / Keep it), and back to the + // trigger when the confirm is backed out of. + useEffect(() => { + if (confirmDelete) keepDeleteRef.current?.focus() + }, [confirmDelete]) + + useEffect(() => { + if (confirmArchive || confirmDelete) return + const which = refocus.current + refocus.current = null + if (which === 'archive') archiveTriggerRef.current?.focus() + else if (which === 'delete') deleteTriggerRef.current?.focus() + }, [confirmArchive, confirmDelete]) + // Reload the working copy when the server picks a different record than the // one in hand. Saving a new voice also changes the selection — to the record // we just created — and that must not pull the form out from under the @@ -317,18 +350,18 @@ export function BrandVoiceEditor({ ): Promise<{ id: number; version: string; saved: BrandVoiceContent }> => { const onboardingStep = Math.max(record?.onboardingStep ?? 0, answeredThrough) if (workingId == null) { - const { id, updatedAt, saved } = await createBrandVoiceDraftAction({ - ...content, - onboardingStep, - }) + const { id, updatedAt, saved } = unwrap( + await createBrandVoiceDraftAction({ + ...content, + onboardingStep, + }), + ) setWorkingId(id) router.replace(`${VIEW_PATH}?id=${id}&mode=${modeOf(step)}`) return { id, version: updatedAt, saved } } - const { updatedAt, saved } = await saveBrandVoiceDraftAction( - workingId, - { ...content, onboardingStep }, - suggestion?.id, + const { updatedAt, saved } = unwrap( + await saveBrandVoiceDraftAction(workingId, { ...content, onboardingStep }, suggestion?.id), ) return { id: workingId, version: updatedAt, saved } } @@ -466,14 +499,14 @@ export function BrandVoiceEditor({ run(async () => { if (workingId == null) return setConfirmArchive(false) - await archiveBrandVoiceAction(workingId) + unwrap(await archiveBrandVoiceAction(workingId)) setMessage('Archived. Runs are blocked until you activate another voice.') }) const remove = () => run(async () => { if (workingId == null) return - await deleteDraftAction(workingId) + unwrap(await deleteDraftAction(workingId)) // Nothing of a deleted draft is worth keeping a copy of. guard.markSaved(content) setConfirmDelete(false) @@ -629,7 +662,7 @@ export function BrandVoiceEditor({ ref={cancelArchiveRef} type="button" className="datum-ops__btn" - onClick={() => setConfirmArchive(false)} + onClick={cancelArchive} disabled={pending} > Cancel @@ -640,6 +673,7 @@ export function BrandVoiceEditor({ ) : ( diff --git a/cms/src/components/ops/review/panels/ApprovedPanel.tsx b/cms/src/components/ops/review/panels/ApprovedPanel.tsx index 051a8d5..bcfca86 100644 --- a/cms/src/components/ops/review/panels/ApprovedPanel.tsx +++ b/cms/src/components/ops/review/panels/ApprovedPanel.tsx @@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from 'react' +import { unwrap } from '../../actionResult' import { publishArticleAction, scheduleArticleAction, unscheduleArticleAction } from '../../actions' import { formatAuditTimestamp } from '../../articleStatus' import { ArchiveAction, OpenInAdmin } from '../ArchiveAction' @@ -35,7 +36,7 @@ const isAhead = (iso: string) => new Date(iso).getTime() > Date.now() /** Signed off and waiting: publish it now, or pick a time. */ export function ApprovedPanel({ action, article, editHref, scheduleExpired }: PanelProps) { - const { pending, runAction, setNotice } = action + const { arm, armed, disarm, pending, runAction, setNotice } = action const [notes, setNotes] = useState(article.reviewNotes ?? '') /** * The scheduling input, in UTC. Seeded from whatever is already scheduled so @@ -72,7 +73,7 @@ export function ApprovedPanel({ action, article, editHref, scheduleExpired }: Pa disabled={pending} onClick={() => runAction(async () => { - const { previousPublishAt } = await unscheduleArticleAction(article.id) + const { previousPublishAt } = unwrap(await unscheduleArticleAction(article.id)) setScheduleAt('') // A time already past is not worth restoring: scheduling it // again is refused. Checked against the clock now and again on @@ -89,7 +90,7 @@ export function ApprovedPanel({ action, article, editHref, scheduleExpired }: Pa 'That time has passed — pick a new one to schedule it again.', ) } - await scheduleArticleAction(article.id, previousPublishAt) + unwrap(await scheduleArticleAction(article.id, previousPublishAt)) // The input was cleared on Unschedule and is seeded // only once, so put the restored time back in it. setScheduleAt(toUtcInputValue(previousPublishAt)) @@ -134,27 +135,46 @@ export function ApprovedPanel({ action, article, editHref, scheduleExpired }: Pa {scheduleError ? {scheduleError} : null}
- + {armed === 'publish' ? ( + <> + + + + ) : ( + + )}
+ {armed === 'publish' ? ( +

+ This puts the piece on the public site immediately. +

+ ) : null} ) diff --git a/cms/src/components/ops/review/panels/ArchivedPanel.tsx b/cms/src/components/ops/review/panels/ArchivedPanel.tsx index bfc448c..ff02bc3 100644 --- a/cms/src/components/ops/review/panels/ArchivedPanel.tsx +++ b/cms/src/components/ops/review/panels/ArchivedPanel.tsx @@ -3,6 +3,7 @@ import React from 'react' import { STATUS_META } from '../../../../lib/articleStatusMeta' +import { unwrap } from '../../actionResult' import { unarchiveArticleAction } from '../../actions' import { OpenInAdmin } from '../ArchiveAction' import type { PanelProps } from '../types' @@ -10,7 +11,7 @@ import type { PanelProps } from '../types' /** * The read-only panel every archived article gets, whatever its status. * - * Archived means off limits, not just off the board: `gateArchivedStatus` + * Archived means off limits, not just off the content list: `gateArchivedStatus` * refuses status changes and schedules, and `queueRunForArticles` refuses to * queue one, so the controls the status panel would offer are exactly the * ones the server would refuse. The only thing a person can do here is bring @@ -23,7 +24,7 @@ export function ArchivedPanel({ action, article, editHref }: PanelProps) {

Archived

- Off the content board and skipped by every run. It was {meta.label} ( + Off the content list and skipped by every run. It was {meta.label} ( {article.status}) when it was archived, and it goes back to that step if you unarchive it.

@@ -34,8 +35,8 @@ export function ArchivedPanel({ action, article, editHref }: PanelProps) { disabled={pending} onClick={() => runAction(async () => { - await unarchiveArticleAction(article.id) - setNotice('Unarchived — it is back on the content board.') + unwrap(await unarchiveArticleAction(article.id)) + setNotice('Unarchived — it is back on the content list.') }) } > diff --git a/cms/src/components/ops/review/panels/NeedsRevisionPanel.tsx b/cms/src/components/ops/review/panels/NeedsRevisionPanel.tsx index 8d11978..af791cd 100644 --- a/cms/src/components/ops/review/panels/NeedsRevisionPanel.tsx +++ b/cms/src/components/ops/review/panels/NeedsRevisionPanel.tsx @@ -2,6 +2,7 @@ import React, { useState } from 'react' +import { unwrap } from '../../actionResult' import { regenerateArticleAction, resetToDraftedAction } from '../../actions' import { announceRunQueued } from '../../runQueued' import { revisitBriefAction } from '../../briefActions' @@ -79,9 +80,11 @@ export function NeedsRevisionPanel({ runAction(async () => { const options = { confirmLiveCost } reportQueued( - which === 'reset' - ? await resetToDraftedAction(article.id, notes, options) - : await regenerateArticleAction(article.id, notes, options), + unwrap( + which === 'reset' + ? await resetToDraftedAction(article.id, notes, options) + : await regenerateArticleAction(article.id, notes, options), + ), ) }) } @@ -91,11 +94,14 @@ export function NeedsRevisionPanel({ else runReviewAction(which, false) } - const revisitBrief = () => + const confirmRevisit = armed === 'revisit' + const revisitBrief = () => { + disarm() runAction(async () => { const result = await revisitBriefAction(article.id) if (!result.ok) throw new Error(result.error) }) + } return ( <> @@ -160,15 +166,38 @@ export function NeedsRevisionPanel({ > Reset to drafted - + {confirmRevisit ? ( + <> + + + + ) : ( + + )} {confirmRegenerate ? ( <>
)} + {confirmRevisit ? ( +

+ This sends the article back to the brief. The current draft, its QA results and its + schedule are cleared, and a new draft is written once you approve the brief. +

+ ) : null} {confirmRegenerate && !pendingReviewAction ? (

This throws away the current body and sends the article back to researched, diff --git a/cms/src/components/ops/review/panels/PublishedPanel.tsx b/cms/src/components/ops/review/panels/PublishedPanel.tsx index b8d1449..85813eb 100644 --- a/cms/src/components/ops/review/panels/PublishedPanel.tsx +++ b/cms/src/components/ops/review/panels/PublishedPanel.tsx @@ -26,7 +26,12 @@ export function PublishedPanel({ action, article, editHref }: PanelProps) { > /articles/{article.slug || article.id} - + diff --git a/cms/src/components/ops/review/panels/ReviewDecisionPanel.tsx b/cms/src/components/ops/review/panels/ReviewDecisionPanel.tsx index 14d8c7d..3c4aa88 100644 --- a/cms/src/components/ops/review/panels/ReviewDecisionPanel.tsx +++ b/cms/src/components/ops/review/panels/ReviewDecisionPanel.tsx @@ -2,6 +2,7 @@ import React, { useState } from 'react' +import { unwrap } from '../../actionResult' import { overrideReviewAction } from '../../actions' import { revisitBriefAction } from '../../briefActions' import { ArchiveAction, OpenInAdmin } from '../ArchiveAction' @@ -18,7 +19,7 @@ import type { PanelProps } from '../types' * guaranteed to be refused. The reviewer types a fresh one, every time. */ export function ReviewDecisionPanel({ action, article, editHref, run }: PanelProps) { - const { pending, runAction } = action + const { arm, armed, disarm, pending, runAction } = action const [justification, setJustification] = useState('') return ( @@ -53,27 +54,56 @@ export function ReviewDecisionPanel({ action, article, editHref, run }: PanelPro type="button" className="datum-ops__btn datum-ops__btn--primary" disabled={pending || justification.trim().length === 0} - onClick={() => runAction(() => overrideReviewAction(article.id, justification))} - > - Override to verified - - + {armed === 'revisit' ? ( + <> + + + + ) : ( + + )} + {armed === 'revisit' ? ( +

+ This sends the article back to the brief. The current draft, its QA results and its + schedule are cleared, and a new draft is written once you approve the brief. +

+ ) : null} ) diff --git a/cms/src/components/ops/review/panels/VerifiedPanel.tsx b/cms/src/components/ops/review/panels/VerifiedPanel.tsx index 1cd3bd6..8a24867 100644 --- a/cms/src/components/ops/review/panels/VerifiedPanel.tsx +++ b/cms/src/components/ops/review/panels/VerifiedPanel.tsx @@ -2,6 +2,7 @@ import React, { useState } from 'react' +import { unwrap } from '../../actionResult' import { approveArticleAction, publishArticleAction } from '../../actions' import { ArchiveAction, OpenInAdmin } from '../ArchiveAction' import { SendBackAction } from '../SendBackAction' @@ -16,7 +17,7 @@ import { DECISION_LABEL, type PanelProps } from '../types' * write somewhere else, and the notice must not claim otherwise. */ export function VerifiedPanel({ action, article, editHref, run, runIsCurrent }: PanelProps) { - const { pending, runAction, setNotice } = action + const { arm, armed, disarm, pending, runAction, setNotice } = action const [notes, setNotes] = useState(article.reviewNotes ?? '') // An override moves the piece to `verified` and leaves the decision it // overrode on the article, so anything but PASS here means a person, not the @@ -49,7 +50,7 @@ export function VerifiedPanel({ action, article, editHref, run, runIsCurrent }: disabled={pending} onClick={() => runAction(async () => { - const { status } = await approveArticleAction(article.id, notes) + const { status } = unwrap(await approveArticleAction(article.id, notes)) setNotice( status === 'approved' ? 'Approved — publish when ready' : `Saved as ${status}.`, ) @@ -58,30 +59,54 @@ export function VerifiedPanel({ action, article, editHref, run, runIsCurrent }: > Approve - + {armed === 'publish' ? ( + <> + + + + ) : ( + + )} + {armed === 'publish' ? ( +

+ This approves the draft and puts it on the public site immediately. +

+ ) : null} ) diff --git a/cms/src/lib/findPublishedArticle.ts b/cms/src/lib/findPublishedArticle.ts index f3fd999..8a341fd 100644 --- a/cms/src/lib/findPublishedArticle.ts +++ b/cms/src/lib/findPublishedArticle.ts @@ -35,6 +35,15 @@ const publicFields = { contentUpdatedAt: true, } as const +/** + * What makes a piece public: published and not archived. Archiving a published + * article withdraws it from the site (`archiveArticleAction` purges the cache). + * `not_equals: true` rather than `equals: false` so a row with no value counts. + */ +export const PUBLIC: Where = { + and: [{ status: { equals: 'published' } }, { archived: { not_equals: true } }], +} + /** Resolve a published article by slug, or by numeric id when the path is an ID fallback. */ export const findPublishedArticle = cache(async function findPublishedArticle( payload: Payload, @@ -44,7 +53,7 @@ export const findPublishedArticle = cache(async function findPublishedArticle( collection: 'articles', select: publicFields, where: { - and: [{ slug: { equals: slugOrId } }, { status: { equals: 'published' } }], + and: [PUBLIC, { slug: { equals: slugOrId } }], }, limit: 1, depth: 0, @@ -54,9 +63,7 @@ export const findPublishedArticle = cache(async function findPublishedArticle( if (/^\d+$/.test(slugOrId)) { const id = Number(slugOrId) - const where: Where = { - and: [{ id: { equals: id } }, { status: { equals: 'published' } }], - } + const where: Where = { and: [PUBLIC, { id: { equals: id } }] } const byId = await payload.find({ collection: 'articles', select: publicFields, diff --git a/cms/tests/e2e/contentOps.e2e.spec.ts b/cms/tests/e2e/contentOps.e2e.spec.ts index 0ec29ea..27bd217 100644 --- a/cms/tests/e2e/contentOps.e2e.spec.ts +++ b/cms/tests/e2e/contentOps.e2e.spec.ts @@ -191,7 +191,9 @@ test.describe('Content ops', () => { seededIds.push(article.id) await page.goto(`/admin/ops/articles/${article.id}`) + // Publishing goes live at once, so the first click only asks. await page.getByRole('button', { name: 'Publish now' }).click() + await page.getByRole('button', { name: 'Confirm: publish now' }).click() // Publishing keeps the reviewer on the article: the page re-renders in // place and the panel for the new status replaces the one just used. await expect(page.getByText(/^Published ·/)).toBeVisible() @@ -258,7 +260,7 @@ test.describe('Content ops', () => { await page.goto(`/admin/ops/articles/${article.id}`) await page.getByRole('button', { name: 'Archive' }).click() - await expect(page.getByText('Archived — it is off the content board.')).toBeVisible() + await expect(page.getByText('Archived — it is off the content list.')).toBeVisible() const search = `?q=${encodeURIComponent(keyword)}&page=1` await page.goto(`/admin/ops/content${search}&filter=all`) diff --git a/cms/tests/e2e/reviewFeedback.e2e.spec.ts b/cms/tests/e2e/reviewFeedback.e2e.spec.ts index f2cf59d..db4c2fc 100644 --- a/cms/tests/e2e/reviewFeedback.e2e.spec.ts +++ b/cms/tests/e2e/reviewFeedback.e2e.spec.ts @@ -95,7 +95,7 @@ test.describe('Review feedback model', () => { ).toBeVisible() await page.keyboard.press('Enter') - await expect(page.getByText('Unarchived — it is back on the content board.')).toBeVisible() + await expect(page.getByText('Unarchived — it is back on the content list.')).toBeVisible() await expect(page.getByRole('button', { name: 'Archive' })).toBeVisible() const doc = await payload.findByID({ diff --git a/cms/tests/int/briefActions.int.spec.ts b/cms/tests/int/briefActions.int.spec.ts index 15a038b..35ab053 100644 --- a/cms/tests/int/briefActions.int.spec.ts +++ b/cms/tests/int/briefActions.int.spec.ts @@ -59,11 +59,15 @@ vi.mock('@/lib/loadWorkspaceReadiness', () => ({ const { approveBriefAction, revisitBriefAction, saveBriefAction } = await import('@/components/ops/briefActions') +/** The `updatedAt` the editor in these tests opened the brief at. */ +const LOADED = '2026-01-01T10:00:00.000Z' + const atBrief = (over: Record = {}) => ({ id: 1, status: 'brief_review', template: 3, + updatedAt: LOADED, brief: { angle: 'old', angleOptions: [{angle:'Option', rationale:'Pain', pain:null, gaps:[]}], sections: [{ heading: 'A', source: 'template' }], notes: '' }, ...over, }) as never @@ -97,7 +101,7 @@ beforeEach(() => { describe('saveBriefAction', () => { it('trims, drops blank sections, and writes the brief without changing status', async () => { findByIDMock.mockResolvedValue(atBrief()) - const result = await saveBriefAction(1, edits) + const result = await saveBriefAction(1, edits, LOADED) expect(result.ok).toBe(true) const call = updateMock.mock.calls[0]?.[0] as unknown as { data: { brief: Record; status?: string } @@ -113,20 +117,48 @@ describe('saveBriefAction', () => { it('refuses once the brief has been approved', async () => { findByIDMock.mockResolvedValue(atBrief({ status: 'researched' })) - const result = await saveBriefAction(1, edits) + const result = await saveBriefAction(1, edits, LOADED) expect(result.ok).toBe(false) expect(updateMock).not.toHaveBeenCalled() }) + // The save replaces the whole brief, so a colleague's save (or an accepted + // suggestion) after the page loaded would be silently overwritten. + describe('when someone else saved since the editor opened', () => { + const NEWER = '2026-01-01T10:05:00.000Z' + + it('refuses with a message that says to reload, and writes nothing', async () => { + findByIDMock.mockResolvedValue(atBrief({ updatedAt: NEWER })) + const result = await saveBriefAction(1, edits, LOADED) + expect(result).toEqual({ + ok: false, + error: 'Someone else saved this brief since you opened it. Reload to see their changes.', + }) + expect(updateMock).not.toHaveBeenCalled() + }) + + it('saves when the editor holds the stored version, which is how a second save goes through', async () => { + findByIDMock.mockResolvedValue(atBrief({ updatedAt: NEWER })) + const result = await saveBriefAction(1, edits, NEWER) + expect(result.ok).toBe(true) + expect(updateMock).toHaveBeenCalledTimes(1) + }) + + it('has nothing to compare when the editor sent no version', async () => { + findByIDMock.mockResolvedValue(atBrief({ updatedAt: NEWER })) + expect((await saveBriefAction(1, edits, null)).ok).toBe(true) + }) + }) + // Switching the audience is the one edit that rewrites another field, so the // rule that decides when it may is pinned from both sides. it('replaces the audience line when it is still the previous audience’s own', async () => { findByIDMock.mockResolvedValue(atBrief({ icp: 11 })) - const result = await saveBriefAction(1, { - ...edits, - audience: ICPS[0].audienceLine, - icpId: 12, - }) + const result = await saveBriefAction( + 1, + { ...edits, audience: ICPS[0].audienceLine, icpId: 12 }, + LOADED, + ) expect(result.ok).toBe(true) const call = updateMock.mock.calls[0]?.[0] as unknown as { data: { icp: number; brief: { audience: string } } @@ -137,7 +169,7 @@ describe('saveBriefAction', () => { it('leaves an edited audience line alone when the audience changes', async () => { findByIDMock.mockResolvedValue(atBrief({ icp: 11 })) - await saveBriefAction(1, { ...edits, audience: 'Whoever buys the thing', icpId: 12 }) + await saveBriefAction(1, { ...edits, audience: 'Whoever buys the thing', icpId: 12 }, LOADED) const call = updateMock.mock.calls[0]?.[0] as unknown as { data: { icp: number; brief: { audience: string } } } @@ -147,7 +179,7 @@ describe('saveBriefAction', () => { it('does not touch the relationship when the audience did not change', async () => { findByIDMock.mockResolvedValue(atBrief({ icp: 11 })) - await saveBriefAction(1, { ...edits, icpId: 11 }) + await saveBriefAction(1, { ...edits, icpId: 11 }, LOADED) const call = updateMock.mock.calls[0]?.[0] as unknown as { data: Record } expect('icp' in call.data).toBe(false) }) @@ -261,24 +293,72 @@ describe('approveBriefAction', () => { }) describe('revisitBriefAction', () => { - it('sends a draft back to its brief and clears the approval', async () => { - findByIDMock.mockResolvedValue( - atBrief({ status: 'needs_revision', brief: { approvedAt: 'x', approvedBy: 'y' } }), + const draftOf = (status: string, over: Record = {}) => + atBrief({ status, brief: { approvedAt: 'x', approvedBy: 'y' }, ...over }) + + const written = () => + updateMock.mock.calls[0]?.[0] as unknown as { + data: Record & { brief: { approvedAt: null; approvedBy: null } } + overrideAccess: boolean + } + + for (const status of ['needs_revision', 'needs_review', 'blocked'] as const) { + it(`sends ${status} back to its brief and clears the approval`, async () => { + findByIDMock.mockResolvedValue(draftOf(status)) + const result = await revisitBriefAction(1) + expect(result.ok).toBe(true) + const call = written() + expect(call.data.status).toBe('brief_review') + expect(call.data.brief.approvedAt).toBeNull() + }) + } + + // The draft is going to be rewritten, so everything that described it goes + // with it: otherwise a stale schedule, regeneration notes, QA verdict or + // information-gain decision sits next to a body nobody has written yet. + it('clears the schedule, revision notes, every QA group and the information-gain decision', async () => { + findByIDMock.mockResolvedValue(draftOf('needs_revision')) + await revisitBriefAction(1) + const { data, overrideAccess } = written() + expect(data.publishAt).toBeNull() + expect(data.revisionNotes).toBeNull() + const qa = data.qaResults as Record> + expect(Object.keys(qa).sort()).toEqual( + ['evidenceCheck', 'factCheck', 'qualitativeReview', 'structural'], ) + for (const group of Object.values(qa)) { + expect(Object.values(group).every((value) => value === null)).toBe(true) + } + const ig = data.informationGain as Record + expect(Object.keys(ig).length).toBeGreaterThan(0) + expect(Object.values(ig).every((value) => value === null)).toBe(true) + // `informationGain` is access-guarded, so only an unrestricted write can clear it. + expect(overrideAccess).toBe(true) + }) + + it('refuses while an active run lists the article, and writes nothing', async () => { + findByIDMock.mockResolvedValue(draftOf('needs_revision')) + findMock.mockResolvedValue({ docs: [{ runId: 'run-9' }] } as never) const result = await revisitBriefAction(1) - expect(result.ok).toBe(true) - const call = updateMock.mock.calls[0]?.[0] as unknown as { - data: { status: string; brief: { approvedAt: null } } + expect(result).toEqual({ + ok: false, + error: expect.stringContaining('active run'), + }) + expect(updateMock).not.toHaveBeenCalled() + }) + + it('refuses every status that is not waiting on a reviewer', async () => { + for (const status of ['published', 'topic_selected', 'researched', 'drafted', 'qa_passed', 'verified', 'approved']) { + updateMock.mockClear() + findByIDMock.mockResolvedValue(draftOf(status)) + expect((await revisitBriefAction(1)).ok, status).toBe(false) + expect(updateMock, status).not.toHaveBeenCalled() } - expect(call.data.status).toBe('brief_review') - expect(call.data.brief.approvedAt).toBeNull() }) - it('will not reopen a published piece, nor one research has not reached', async () => { - findByIDMock.mockResolvedValue(atBrief({ status: 'published' })) - expect((await revisitBriefAction(1)).ok).toBe(false) - findByIDMock.mockResolvedValue(atBrief({ status: 'topic_selected' })) - expect((await revisitBriefAction(1)).ok).toBe(false) + it('treats a piece already at its brief as nothing to do', async () => { + findByIDMock.mockResolvedValue(draftOf('brief_review')) + expect(await revisitBriefAction(1)).toEqual({ ok: true, message: 'Already at the brief.' }) expect(updateMock).not.toHaveBeenCalled() }) }) diff --git a/cms/tests/int/reviewActionsDb.int.spec.ts b/cms/tests/int/reviewActionsDb.int.spec.ts new file mode 100644 index 0000000..13247b0 --- /dev/null +++ b/cms/tests/int/reviewActionsDb.int.spec.ts @@ -0,0 +1,214 @@ +import { randomUUID } from 'node:crypto' + +import { renderToStaticMarkup } from 'react-dom/server' +import { getPayload, type Payload } from 'payload' +import { beforeAll, describe, expect, it, vi } from 'vitest' + +import config from '@/payload.config' + +/** + * The review actions and the public site, against a real database. + * + * What a mocked Payload cannot show: that the real `beforeChange` gates let the + * writes these actions make through (a brief revisit clears an access-guarded + * group), that a gate's own message comes back as a value, and that a lookup + * the public site makes really leaves out an archived article. + */ + +let payload: Payload +let user: { id: number; email: string } + +const authStub = vi.fn(async () => ({ user })) + +vi.mock('next/headers', () => ({ headers: vi.fn(async () => new Headers()) })) +vi.mock('next/headers.js', () => ({ headers: vi.fn(async () => new Headers()) })) +vi.mock('next/cache', () => ({ revalidatePath: vi.fn() })) +vi.mock('payload', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getPayload: async (args: Parameters[0]) => { + const instance = await actual.getPayload(args) + return new Proxy(instance, { + get(target, prop, receiver) { + if (prop === 'auth') return authStub + const value = Reflect.get(target, prop, receiver) + return typeof value === 'function' ? value.bind(target) : value + }, + }) + }, + } +}) + +const { revisitBriefAction } = await import('@/components/ops/briefActions') +const { + archiveArticleAction, + approveArticleAction, + overrideReviewAction, + resetToDraftedAction, + unarchiveArticleAction, +} = await import('@/components/ops/actions') +const { findPublishedArticle } = await import('@/lib/findPublishedArticle') +const { default: HomePage } = await import('@/app/(frontend)/page') + +const makeArticle = (data: Record) => + payload.create({ + collection: 'articles', + overrideAccess: true, + data: { keyword: `review actions ${randomUUID()}`, ...data } as never, + }) + +const reload = (id: number) => + payload.findByID({ collection: 'articles', id, depth: 0, overrideAccess: true }) + +beforeAll(async () => { + payload = await getPayload({ config: await config }) + const doc = await payload.create({ + collection: 'users', + data: { email: `review-actions-${randomUUID()}@example.com`, password: 'test' }, + overrideAccess: true, + }) + user = { id: doc.id, email: doc.email } +}) + +describe('archiving a published article withdraws it from the public site', () => { + it('findPublishedArticle skips it by slug and by id, and finds it again once unarchived', async () => { + const slug = `archive-public-${randomUUID()}` + const article = await makeArticle({ status: 'published', slug, title: 'Public piece' }) + + expect((await findPublishedArticle(payload, slug))?.id).toBe(article.id) + expect((await findPublishedArticle(payload, String(article.id)))?.id).toBe(article.id) + + expect(await archiveArticleAction(article.id)).toEqual({ ok: true }) + expect((await reload(article.id)).status).toBe('published') + expect(await findPublishedArticle(payload, slug)).toBeNull() + expect(await findPublishedArticle(payload, String(article.id))).toBeNull() + + expect(await unarchiveArticleAction(article.id)).toEqual({ ok: true }) + expect((await findPublishedArticle(payload, slug))?.id).toBe(article.id) + }) + + it('the home list leaves out an archived piece and keeps its neighbours', async () => { + const live = await makeArticle({ + status: 'published', + slug: `home-live-${randomUUID()}`, + title: `Home live ${randomUUID()}`, + publishedAt: new Date().toISOString(), + }) + const archived = await makeArticle({ + status: 'published', + slug: `home-archived-${randomUUID()}`, + title: `Home archived ${randomUUID()}`, + publishedAt: new Date().toISOString(), + archived: true, + }) + const html = renderToStaticMarkup(await HomePage()) + expect(html).toContain(live.title as string) + expect(html).not.toContain(archived.title as string) + }) +}) + +describe('revisitBriefAction through the real gates', () => { + it('reopens the brief and clears the schedule, notes, QA and decision it leaves behind', async () => { + const article = await makeArticle({ + status: 'needs_revision', + publishAt: new Date(Date.now() + 3_600_000).toISOString(), + revisionNotes: '- [noveltyFloor] thin', + brief: { angle: 'Old angle', approvedAt: '2026-01-01T00:00:00.000Z', approvedBy: 'x' }, + qaResults: { + structural: { passed: false, violations: ['BANNED_PHRASE'] }, + factCheck: { passed: true, notes: 'OK' }, + qualitativeReview: { passed: false, notes: 'too salesy' }, + evidenceCheck: { passed: false, notes: 'unsupported' }, + }, + informationGain: { decision: 'REVISE', verifiedGainUnits: 2 }, + }) + const before = await reload(article.id) + expect(before.informationGain?.decision).toBe('REVISE') + + const result = await revisitBriefAction(article.id) + expect(result.ok).toBe(true) + + const after = await reload(article.id) + expect(after.status).toBe('brief_review') + expect(after.brief?.approvedAt).toBeNull() + expect(after.brief?.angle).toBe('Old angle') + expect(after.publishAt).toBeNull() + expect(after.revisionNotes).toBeNull() + expect(after.qaResults?.structural?.passed).toBeNull() + expect(after.qaResults?.qualitativeReview?.notes).toBeNull() + expect(after.qaResults?.evidenceCheck?.passed).toBeNull() + expect(after.informationGain?.decision).toBeNull() + expect(after.informationGain?.verifiedGainUnits).toBeNull() + }) + + it('refuses while an active run lists the article', async () => { + const article = await makeArticle({ status: 'needs_revision' }) + const template = await payload.create({ + collection: 'templates', + data: { name: `Review actions ${randomUUID()}` }, + overrideAccess: true, + }) + const run = await payload.create({ + collection: 'pipeline-runs', + overrideAccess: true, + data: { + runId: `review-actions-${randomUUID()}`, + source: 'selected', + status: 'queued', + mode: 'mock', + template: template.id, + requestedCount: 1, + articles: [article.id], + configFingerprint: 'review-actions', + configSnapshot: {}, + requestedBy: user.email, + } as never, + }) + try { + const result = await revisitBriefAction(article.id) + expect(result).toEqual({ ok: false, error: expect.stringContaining('active run') }) + expect((await reload(article.id)).status).toBe('needs_revision') + } finally { + await payload.update({ + collection: 'pipeline-runs', + id: run.id, + overrideAccess: true, + data: { status: 'failed' } as never, + }) + } + }) +}) + +describe('resetToDraftedAction at researched', () => { + it('refuses and leaves the article where it was', async () => { + const article = await makeArticle({ status: 'researched' }) + const result = await resetToDraftedAction(article.id, 'again', { queueRun: false }) + expect(result).toEqual({ ok: false, error: expect.stringContaining('not been drafted') }) + expect((await reload(article.id)).status).toBe('researched') + }) +}) + +describe('a real gate refusal arrives as a value', () => { + it('overrideReviewAction returns the justification gate’s own message', async () => { + // A stale justification riding along is what the gate exists to refuse. + const article = await makeArticle({ + status: 'needs_review', + reviewJustification: 'same reason as last time', + }) + const result = await overrideReviewAction(article.id, 'same reason as last time') + expect(result).toEqual({ + ok: false, + error: expect.stringContaining('new reviewJustification'), + }) + expect((await reload(article.id)).status).toBe('needs_review') + }) + + it('approveArticleAction returns the publication-path gate’s message', async () => { + const article = await makeArticle({ status: 'drafted' }) + const result = await approveArticleAction(article.id) + expect(result.ok).toBe(false) + expect(result.ok === false && result.error).toMatch(/cannot move from drafted to approved/) + expect((await reload(article.id)).status).toBe('drafted') + }) +}) diff --git a/cms/tests/int/reviewFeedback.int.spec.ts b/cms/tests/int/reviewFeedback.int.spec.ts index ddb2c1a..568ae5a 100644 --- a/cms/tests/int/reviewFeedback.int.spec.ts +++ b/cms/tests/int/reviewFeedback.int.spec.ts @@ -7,6 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' * F4: the armed-confirm slot, Undo and the reasoned send-back, rendered with * the real `useReviewAction` so the slot is genuinely shared between panels. */ +type ActionOutcome = { ok: true; [key: string]: unknown } | { ok: false; error: string } + const { toastSuccess, toastDismiss, @@ -15,14 +17,28 @@ const { unarchiveMock, unscheduleMock, scheduleMock, + publishMock, + resetMock, + revisitMock, } = vi.hoisted(() => ({ toastSuccess: vi.fn(() => 'toast-1'), toastDismiss: vi.fn(), - sendBackMock: vi.fn(async () => undefined), - archiveMock: vi.fn(async () => undefined), - unarchiveMock: vi.fn(async () => undefined), - unscheduleMock: vi.fn(async () => ({ previousPublishAt: null as string | null })), - scheduleMock: vi.fn(async () => ({ publishAt: '' })), + sendBackMock: vi.fn(async (..._args: unknown[]): Promise => ({ ok: true })), + archiveMock: vi.fn(async (..._args: unknown[]): Promise => ({ ok: true })), + unarchiveMock: vi.fn(async (..._args: unknown[]): Promise => ({ ok: true })), + unscheduleMock: vi.fn(async () => ({ ok: true as const, previousPublishAt: null as string | null })), + scheduleMock: vi.fn(async (..._args: unknown[]) => ({ ok: true as const, publishAt: '' })), + publishMock: vi.fn( + async (..._args: unknown[]): Promise => ({ + ok: true, + status: 'published', + slug: 'cold-brew', + }), + ), + resetMock: vi.fn( + async (..._args: unknown[]): Promise => ({ ok: true, queued: false }), + ), + revisitMock: vi.fn(async (..._args: unknown[]) => ({ ok: true as const, message: '' })), })) vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: () => {} }) })) @@ -31,14 +47,15 @@ vi.mock('@/components/ops/actions', () => ({ archiveArticleAction: archiveMock, assignTemplateAction: vi.fn(), regenerateArticleAction: vi.fn(), - publishArticleAction: vi.fn(), - resetToDraftedAction: vi.fn(), + publishArticleAction: publishMock, + approveArticleAction: vi.fn(), + resetToDraftedAction: resetMock, scheduleArticleAction: scheduleMock, sendBackAction: sendBackMock, unarchiveArticleAction: unarchiveMock, unscheduleArticleAction: unscheduleMock, })) -vi.mock('@/components/ops/briefActions', () => ({ revisitBriefAction: vi.fn() })) +vi.mock('@/components/ops/briefActions', () => ({ revisitBriefAction: revisitMock })) vi.mock('@/components/ops/runQueued', () => ({ announceRunQueued: vi.fn() })) const { useReviewAction } = await import('@/components/ops/review/useReviewAction') @@ -46,6 +63,9 @@ const { ArchiveAction } = await import('@/components/ops/review/ArchiveAction') const { SendBackAction } = await import('@/components/ops/review/SendBackAction') const { NeedsRevisionPanel } = await import('@/components/ops/review/panels/NeedsRevisionPanel') const { ApprovedPanel } = await import('@/components/ops/review/panels/ApprovedPanel') +const { VerifiedPanel } = await import('@/components/ops/review/panels/VerifiedPanel') +const { PublishedPanel } = await import('@/components/ops/review/panels/PublishedPanel') +const { ReviewDecisionPanel } = await import('@/components/ops/review/panels/ReviewDecisionPanel') const article = { id: 1, @@ -97,7 +117,11 @@ function Page({ approvedPublishAt }: { approvedPublishAt?: string }) { ) } -beforeEach(() => vi.clearAllMocks()) +beforeEach(() => { + vi.clearAllMocks() + // `clearAllMocks` keeps implementations but drops queued `…Once` ones. + sendBackMock.mockResolvedValue({ ok: true }) +}) afterEach(cleanup) const confirms = () => screen.queryAllByRole('button', { name: /^Confirm/ }) @@ -120,9 +144,10 @@ it('any other action backs out of an armed confirm, so it cannot outlive the ref expect(confirms()).toHaveLength(1) await act(async () => { - fireEvent.click(screen.getByRole('button', { name: 'Revisit brief' })) + fireEvent.click(screen.getByRole('button', { name: 'Reset to drafted' })) }) expect(confirms()).toHaveLength(0) + expect(resetMock).toHaveBeenCalled() }) it('Escape disarms and focus returns to the trigger', () => { @@ -164,7 +189,7 @@ it('a failed Undo keeps the notice and its Undo, so it can be retried', async () fireEvent.click(screen.getByRole('button', { name: 'Undo' })) }) expect(screen.getByText('Network down')).toBeTruthy() - expect(screen.getByText('Archived — it is off the content board.')).toBeTruthy() + expect(screen.getByText('Archived — it is off the content list.')).toBeTruthy() await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Undo' })) @@ -179,7 +204,7 @@ describe('Unschedule Undo checks the clock, not the rendered page', () => { it('offers no Undo when the removed time has already passed', async () => { vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(new Date('2030-01-01T12:00:00Z')) - unscheduleMock.mockResolvedValueOnce({ previousPublishAt: '2030-01-01T11:00:00.000Z' }) + unscheduleMock.mockResolvedValueOnce({ ok: true, previousPublishAt: '2030-01-01T11:00:00.000Z' }) render(React.createElement(Page, { approvedPublishAt: '2030-01-01T11:00:00.000Z' })) await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Unschedule' })) @@ -191,7 +216,7 @@ describe('Unschedule Undo checks the clock, not the rendered page', () => { it('an Undo in time reschedules and puts the time back in the input', async () => { vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(new Date('2030-01-01T12:00:00Z')) - unscheduleMock.mockResolvedValueOnce({ previousPublishAt: '2030-01-01T12:05:00.000Z' }) + unscheduleMock.mockResolvedValueOnce({ ok: true, previousPublishAt: '2030-01-01T12:05:00.000Z' }) const { container } = render( React.createElement(Page, { approvedPublishAt: '2030-01-01T12:05:00.000Z' }), ) @@ -210,7 +235,7 @@ describe('Unschedule Undo checks the clock, not the rendered page', () => { it('refuses an Undo pressed after the time passed, and keeps it on screen', async () => { vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(new Date('2030-01-01T12:00:00Z')) - unscheduleMock.mockResolvedValueOnce({ previousPublishAt: '2030-01-01T12:05:00.000Z' }) + unscheduleMock.mockResolvedValueOnce({ ok: true, previousPublishAt: '2030-01-01T12:05:00.000Z' }) render(React.createElement(Page, { approvedPublishAt: '2030-01-01T12:05:00.000Z' })) await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Unschedule' })) @@ -255,5 +280,207 @@ it('renders ArchiveAction as archived once archived', () => { const Harness = () => React.createElement(ArchiveAction, { action: useReviewAction(), archived: true, articleId: 1 }) render(React.createElement(Harness)) - expect(screen.getByText(/Archived — hidden/)).toBeTruthy() + expect(screen.getByText('Archived — hidden from the content list.')).toBeTruthy() +}) + +/** Any panel, on the real `useReviewAction`, with the error and notice shown. */ +function PanelPage({ + Panel, + article: over, +}: { + Panel: React.ComponentType + article: Record +}) { + const action = useReviewAction() + const props = { + action, + activeRunIncludesArticle: false, + editHref: '/x', + mode: 'mock', + run: null, + runIsCurrent: false, + scheduleExpired: false, + scoreInvalidatedBy: null, + templates: [], + article: { ...article, ...over }, + } + return React.createElement( + React.Fragment, + null, + React.createElement(Panel, props as never), + action.error ? React.createElement('p', { role: 'alert' }, action.error) : null, + action.notice + ? React.createElement( + 'p', + { role: 'status' }, + typeof action.notice === 'string' ? action.notice : action.notice.text, + ) + : null, + ) +} + +// A thrown server-action error is redacted in a production build; the panels +// read { ok: false, error } and throw it themselves, in the browser. +describe('a refused action shows the server’s message', () => { + it('Send back', async () => { + sendBackMock.mockResolvedValueOnce({ ok: false, error: 'Say why this is going back.' }) + render(React.createElement(PanelPage, { Panel: ApprovedPanel, article: { status: 'approved' } })) + fireEvent.change(screen.getByLabelText(/Why is it going back/), { target: { value: 'x' } }) + fireEvent.click(screen.getByRole('button', { name: 'Send back' })) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Confirm: send back' })) + }) + expect(screen.getByRole('alert').textContent).toBe('Say why this is going back.') + }) + + it('Archive, with no success notice', async () => { + archiveMock.mockResolvedValueOnce({ + ok: false, + error: 'This article is in an active run. Wait for the run to finish before archiving it.', + }) + render(React.createElement(PanelPage, { Panel: NeedsRevisionPanel, article: {} })) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Archive' })) + }) + expect(screen.getByRole('alert').textContent).toMatch(/active run/) + expect(screen.queryByRole('status')).toBeNull() + expect(toastSuccess).not.toHaveBeenCalled() + }) + + it('Reset to drafted', async () => { + resetMock.mockResolvedValueOnce({ ok: false, error: 'This article has not been drafted yet.' }) + render(React.createElement(PanelPage, { Panel: NeedsRevisionPanel, article: {} })) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Reset to drafted' })) + }) + expect(screen.getByRole('alert').textContent).toBe('This article has not been drafted yet.') + }) +}) + +describe('publishing asks first, and says it goes live at once', () => { + const panels = [ + { name: 'Approved', Panel: ApprovedPanel, status: 'approved', trigger: 'Publish now', go: 'Confirm: publish now' }, + { + name: 'Verified', + Panel: VerifiedPanel, + status: 'verified', + trigger: 'Approve & publish', + go: 'Confirm: approve & publish', + }, + ] as const + + for (const { name, Panel, status, trigger, go } of panels) { + it(`${name}: the first click only arms; Confirm publishes with the notes`, async () => { + render(React.createElement(PanelPage, { Panel, article: { status, reviewNotes: 'reads well' } })) + + fireEvent.click(screen.getByRole('button', { name: trigger })) + expect(publishMock).not.toHaveBeenCalled() + expect(screen.getByText(/public site immediately/)).toBeTruthy() + expect(document.activeElement).toBe(screen.getByRole('button', { name: go })) + + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: go })) + }) + expect(publishMock).toHaveBeenCalledWith(1, 'reads well') + expect(screen.getByRole('status').textContent).toMatch(/^Published/) + }) + + it(`${name}: Cancel and Escape publish nothing and give the trigger its focus back`, () => { + render(React.createElement(PanelPage, { Panel, article: { status } })) + + fireEvent.click(screen.getByRole('button', { name: trigger })) + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + expect(document.activeElement).toBe(screen.getByRole('button', { name: trigger })) + + fireEvent.click(screen.getByRole('button', { name: trigger })) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('button', { name: trigger })) + expect(publishMock).not.toHaveBeenCalled() + }) + } + + it('a refused publish shows the gate’s message', async () => { + publishMock.mockResolvedValueOnce({ + ok: false, + error: 'An article cannot move from drafted to published.', + }) + render(React.createElement(PanelPage, { Panel: ApprovedPanel, article: { status: 'approved' } })) + fireEvent.click(screen.getByRole('button', { name: 'Publish now' })) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Confirm: publish now' })) + }) + expect(screen.getByRole('alert').textContent).toBe( + 'An article cannot move from drafted to published.', + ) + }) +}) + +describe('Revisit brief asks first, and says the draft will be rewritten', () => { + for (const [name, Panel, article] of [ + ['needs_revision', NeedsRevisionPanel, {}], + ['needs_review', ReviewDecisionPanel, { status: 'needs_review' }], + ] as const) { + it(`${name}: arms, explains, and only Confirm calls the action`, async () => { + render(React.createElement(PanelPage, { Panel, article })) + + fireEvent.click(screen.getByRole('button', { name: 'Revisit brief' })) + expect(revisitMock).not.toHaveBeenCalled() + expect(screen.getByText(/new draft is written once you approve the brief/)).toBeTruthy() + + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Confirm: revisit brief' })) + }) + expect(revisitMock).toHaveBeenCalledWith(1) + // `ok: true` is not an error: nothing is shown, and the confirm is gone. + expect(screen.queryByRole('alert')).toBeNull() + expect(confirms()).toHaveLength(0) + }) + } + + it('shows the action’s refusal, and Cancel calls nothing', async () => { + revisitMock.mockResolvedValueOnce({ ok: false, error: 'This article is in an active run.' } as never) + render(React.createElement(PanelPage, { Panel: NeedsRevisionPanel, article: {} })) + fireEvent.click(screen.getByRole('button', { name: 'Revisit brief' })) + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + expect(revisitMock).not.toHaveBeenCalled() + + fireEvent.click(screen.getByRole('button', { name: 'Revisit brief' })) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Confirm: revisit brief' })) + }) + expect(screen.getByRole('alert').textContent).toBe('This article is in an active run.') + }) +}) + +describe('archiving a live piece says it leaves the site', () => { + it('the published panel’s Archive is titled and announced accordingly, and Undo is kept', async () => { + render( + React.createElement(PanelPage, { + Panel: PublishedPanel, + article: { status: 'published', publishedAt: '2026-09-01T10:00:00.000Z' }, + }), + ) + expect(screen.getByRole('button', { name: 'Archive' }).getAttribute('title')).toMatch( + /off the public site/, + ) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Archive' })) + }) + expect(archiveMock).toHaveBeenCalledWith(1) + expect(screen.getByRole('status').textContent).toBe( + 'Archived — it is off the site and the content list.', + ) + expect(toastSuccess).toHaveBeenCalledWith( + 'Archived', + expect.objectContaining({ action: expect.objectContaining({ label: 'Undo' }) }), + ) + }) + + it('other panels still say only the content list', async () => { + render(React.createElement(PanelPage, { Panel: NeedsRevisionPanel, article: {} })) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Archive' })) + }) + expect(screen.getByRole('status').textContent).toBe('Archived — it is off the content list.') + }) }) From 80424fe3da05d74d0545dc303035691159fe827a Mon Sep 17 00:00:00 2001 From: snowopsdev Date: Tue, 10 Nov 2026 00:52:13 -0500 Subject: [PATCH 03/15] test(cms): cover narrowed article reads and brief concurrency against the real database Co-Authored-By: Claude Sonnet 5.5 --- cms/tests/int/reviewActionsDb.int.spec.ts | 66 ++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/cms/tests/int/reviewActionsDb.int.spec.ts b/cms/tests/int/reviewActionsDb.int.spec.ts index 13247b0..6a41618 100644 --- a/cms/tests/int/reviewActionsDb.int.spec.ts +++ b/cms/tests/int/reviewActionsDb.int.spec.ts @@ -40,13 +40,16 @@ vi.mock('payload', async (importOriginal) => { } }) -const { revisitBriefAction } = await import('@/components/ops/briefActions') +const { revisitBriefAction, saveBriefAction } = await import('@/components/ops/briefActions') const { archiveArticleAction, approveArticleAction, overrideReviewAction, + regenerateArticleAction, resetToDraftedAction, + scheduleArticleAction, unarchiveArticleAction, + unscheduleArticleAction, } = await import('@/components/ops/actions') const { findPublishedArticle } = await import('@/lib/findPublishedArticle') const { default: HomePage } = await import('@/app/(frontend)/page') @@ -212,3 +215,64 @@ describe('a real gate refusal arrives as a value', () => { expect((await reload(article.id)).status).toBe('drafted') }) }) + +// The actions read only the article fields they use (`select`); these run the +// real queries, which a mocked `findByID` cannot check. +describe('the narrowed article reads still see what the actions need', () => { + it('saveBriefAction saves a fresh brief and refuses one opened before another save', async () => { + const article = await makeArticle({ + status: 'brief_review', + brief: { angle: 'First', sections: [{ heading: 'A', source: 'template' }] }, + }) + const edits = { angle: 'Second', audience: '', sections: [], notes: '', icpId: null } + const opened = (await reload(article.id)).updatedAt + + const first = await saveBriefAction(article.id, edits, opened) + expect(first.ok).toBe(true) + expect((await reload(article.id)).brief?.angle).toBe('Second') + + // Someone else's save moved `updatedAt` on; this editor still holds `opened`. + const stale = await saveBriefAction(article.id, { ...edits, angle: 'Third' }, opened) + expect(stale).toEqual({ + ok: false, + error: 'Someone else saved this brief since you opened it. Reload to see their changes.', + }) + expect((await reload(article.id)).brief?.angle).toBe('Second') + + // Holding the version the first save returned, the next save goes through. + const stored = first.ok ? first.updatedAt : undefined + expect((await saveBriefAction(article.id, { ...edits, angle: 'Third' }, stored ?? null)).ok).toBe(true) + }) + + it('regenerate builds its notes from the stored QA failure and counts the revision', async () => { + const article = await makeArticle({ + status: 'needs_revision', + revisionCount: 1, + qaResults: { + structural: { passed: true, violations: [] }, + factCheck: { passed: false, notes: 'unsupported stat' }, + }, + }) + const result = await regenerateArticleAction(article.id, 'tighten it', { queueRun: false }) + expect(result).toEqual({ ok: true, queued: false }) + const after = await reload(article.id) + expect(after.status).toBe('researched') + expect(after.revisionCount).toBe(2) + expect(after.revisionNotes).toContain('unsupported stat') + expect(after.revisionNotes).toContain('Reviewer note: tighten it') + }) + + it('schedule and unschedule hand back the date they took off', async () => { + const article = await makeArticle({ status: 'approved' }) + const at = new Date(Date.now() + 86_400_000).toISOString() + expect(await scheduleArticleAction(article.id, at)).toEqual({ ok: true, publishAt: at }) + expect(await unscheduleArticleAction(article.id)).toEqual({ ok: true, previousPublishAt: at }) + expect((await reload(article.id)).publishAt).toBeNull() + + const draft = await makeArticle({ status: 'drafted' }) + expect(await scheduleArticleAction(draft.id, at)).toEqual({ + ok: false, + error: 'Only an approved article can be scheduled. Approve it first.', + }) + }) +}) From 69606c408abc9179bbe239dc7aaf89df4d9d3aa4 Mon Sep 17 00:00:00 2001 From: snowopsdev Date: Tue, 10 Nov 2026 01:08:09 -0500 Subject: [PATCH 04/15] fix(cms): log unexpected action failures and compare brief versions exactly `attempt()` now logs a failure that is not a gate's own refusal, since Next no longer logs an error the action did not throw. The brief save refuses any version but the stored one, not only an older one. The revisit audit row records what it clears, and the refusal tests assert the real messages for brand-voice delete and template save. Co-Authored-By: Claude Opus 5.5 --- cms/src/components/ops/actionResult.ts | 8 +++++++- cms/src/components/ops/briefActions.ts | 14 +++++++++++-- cms/tests/int/reviewActionsDb.int.spec.ts | 25 +++++++++++++++++++++++ cms/tests/int/tenantActions.int.spec.ts | 3 ++- 4 files changed, 46 insertions(+), 4 deletions(-) diff --git a/cms/src/components/ops/actionResult.ts b/cms/src/components/ops/actionResult.ts index c9e3ba8..b7fd4c3 100644 --- a/cms/src/components/ops/actionResult.ts +++ b/cms/src/components/ops/actionResult.ts @@ -1,3 +1,5 @@ +import { APIError } from 'payload' + import { errorMessage } from '../../lib/errorMessage' /** @@ -19,7 +21,9 @@ export type ActionResult = ({ ok: true } & T) | Actio * The body keeps throwing for its refusals — that reads best where the check * sits — and this is the one place they become data. An unexpected failure (a * database outage) is caught too, so the reviewer sees its message rather than - * a redacted one; `fallback` covers a thrown value that carries none. + * a redacted one, and it is logged, because Next no longer logs an error the + * action did not throw. A gate's own refusal (an `APIError` below 500) is not + * a fault and is not logged. `fallback` covers a thrown value with no message. */ export async function attempt( fallback: string, @@ -28,6 +32,8 @@ export async function attempt( try { return { ok: true, ...(await body()) } } catch (error) { + const refusal = error instanceof APIError && error.status < 500 + if (!refusal) console.error(`[server action] ${fallback}`, error) return { ok: false, error: errorMessage(error, fallback) } } } diff --git a/cms/src/components/ops/briefActions.ts b/cms/src/components/ops/briefActions.ts index 5712337..2d34ee0 100644 --- a/cms/src/components/ops/briefActions.ts +++ b/cms/src/components/ops/briefActions.ts @@ -119,7 +119,9 @@ export async function saveBriefAction( if (article.status !== 'brief_review') { return { ok: false, error: 'This brief has already been approved; the piece has moved on.' } } - if (loadedUpdatedAt && new Date(article.updatedAt).getTime() > new Date(loadedUpdatedAt).getTime()) { + // Any difference, not only a later one: two saves in the same millisecond, + // or one stamped by an instance with a slower clock, are still two saves. + if (loadedUpdatedAt && Date.parse(article.updatedAt) !== Date.parse(loadedUpdatedAt)) { return { ok: false, error: BRIEF_CHANGED_ELSEWHERE } } const next = cleanEdits(edits) @@ -335,7 +337,15 @@ export async function revisitBriefAction(articleId: number): Promise { expect((await reload(article.id)).status).toBe('needs_review') }) + it('deleteDraftAction returns its refusal for a voice that is not a draft', async () => { + const voice = await payload.create({ + collection: 'brand-voices', + overrideAccess: true, + data: { name: `Archived voice ${randomUUID()}`, status: 'archived' } as never, + }) + expect(await deleteDraftAction(voice.id)).toEqual({ + ok: false, + error: 'Only drafts can be deleted. Archive an active brand voice instead.', + }) + const still = await payload.findByID({ + collection: 'brand-voices', + id: voice.id, + depth: 0, + overrideAccess: true, + }) + expect(still.status).toBe('archived') + }) + it('approveArticleAction returns the publication-path gate’s message', async () => { const article = await makeArticle({ status: 'drafted' }) const result = await approveArticleAction(article.id) @@ -239,6 +259,11 @@ describe('the narrowed article reads still see what the actions need', () => { }) expect((await reload(article.id)).brief?.angle).toBe('Second') + // Any other version is refused too, not only an older one: a clock that + // runs ahead must not let a stale form through. + const ahead = await saveBriefAction(article.id, { ...edits, angle: 'Third' }, '2099-01-01T00:00:00.000Z') + expect(ahead.ok).toBe(false) + // Holding the version the first save returned, the next save goes through. const stored = first.ok ? first.updatedAt : undefined expect((await saveBriefAction(article.id, { ...edits, angle: 'Third' }, stored ?? null)).ok).toBe(true) diff --git a/cms/tests/int/tenantActions.int.spec.ts b/cms/tests/int/tenantActions.int.spec.ts index d844410..234f9c1 100644 --- a/cms/tests/int/tenantActions.int.spec.ts +++ b/cms/tests/int/tenantActions.int.spec.ts @@ -787,7 +787,8 @@ describe('saveTemplateConfigAction', () => { ogTagsRequired: true, }, }) - expect(result).toEqual({ ok: false, error: expect.any(String) }) + // Payload's own refusal (no such template), not a generic fallback. + expect(result).toEqual({ ok: false, error: expect.stringMatching(/not found/i) }) expect(result.ok === false && result.error.length).toBeGreaterThan(0) }) From 144169255851d51ac45ba2af89c89c174470fa50 Mon Sep 17 00:00:00 2001 From: snowopsdev Date: Tue, 10 Nov 2026 00:41:39 -0500 Subject: [PATCH 05/15] fix(cms): cap positioning core claims at three in the schema Matches the editor's limit and the completeness rule. Validation only: payload-types.ts and the database are unchanged. Co-Authored-By: Claude Sonnet 5.5 --- cms/src/globals/Positioning.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/cms/src/globals/Positioning.ts b/cms/src/globals/Positioning.ts index c2e311e..7715abb 100644 --- a/cms/src/globals/Positioning.ts +++ b/cms/src/globals/Positioning.ts @@ -91,6 +91,7 @@ export const Positioning: GlobalConfig = { { name: 'coreClaims', type: 'array', + maxRows: 3, admin: { description: 'Exactly three claims the position rests on. Three, because a position with a dozen claims has none.', From ef98d2e5fec00caa1d56c9733ce7c6b88cc0a885 Mon Sep 17 00:00:00 2001 From: snowopsdev Date: Tue, 10 Nov 2026 00:41:39 -0500 Subject: [PATCH 06/15] fix(cms): setup editors surface save failures, refuse stale saves and page the source queue - useDirtyGuard: onError for a rejected save, submit() returns the in-flight save, leave dialog disabled while saving - editors: transitions show a rejected server action instead of reaching the error boundary - ICP: step carried in ?step=, activation toast, activation error carried across the first-save remount - workspace: fetch site pages disabled while dirty, success names the domain - source review: pending, approved and dismissed queried separately with totals - tenantActions/suggestionActions: updatedAt checks on whole-document saves; demo workspace audit rows name the operator - accessibility: pressed tabs, aria-current step, TextRows names, fieldset for cleared surfaces Co-Authored-By: Claude Sonnet 5.5 --- cms/src/components/ops/AssetStepper.tsx | 65 +++--- cms/src/components/ops/DirtyGuardUi.tsx | 13 +- cms/src/components/ops/EvidenceBankEditor.tsx | 191 +++++++++-------- cms/src/components/ops/IcpEditor.tsx | 80 +++++-- cms/src/components/ops/IcpEditorView.tsx | 17 +- cms/src/components/ops/PositioningEditor.tsx | 5 +- cms/src/components/ops/SetupChecklist.tsx | 19 +- cms/src/components/ops/SetupSuggestions.tsx | 37 ++-- .../components/ops/SetupWorkspaceEditor.tsx | 46 ++-- cms/src/components/ops/SourceReviewQueue.tsx | 34 ++- cms/src/components/ops/SourceReviewView.tsx | 46 +--- .../components/ops/loadSourceReviewQueue.ts | 82 +++++++ cms/src/components/ops/settle.ts | 20 ++ cms/src/components/ops/setupActions.ts | 17 +- cms/src/components/ops/setupFields.tsx | 19 +- cms/src/components/ops/suggestionActions.ts | 86 +++++--- cms/src/components/ops/tenantActions.ts | 202 ++++++++++++++---- cms/src/components/ops/useDirtyGuard.ts | 63 ++++-- cms/tests/int/sitePages.int.spec.ts | 4 +- cms/tests/int/tenantActions.int.spec.ts | 2 +- 20 files changed, 725 insertions(+), 323 deletions(-) create mode 100644 cms/src/components/ops/loadSourceReviewQueue.ts create mode 100644 cms/src/components/ops/settle.ts diff --git a/cms/src/components/ops/AssetStepper.tsx b/cms/src/components/ops/AssetStepper.tsx index 6c71374..9d2325e 100644 --- a/cms/src/components/ops/AssetStepper.tsx +++ b/cms/src/components/ops/AssetStepper.tsx @@ -4,6 +4,7 @@ import React, { useState, useTransition } from 'react' import { type AnyGuard, LeaveDialog, RestoreNotice, UnsavedBar } from './DirtyGuardUi' import { assistAction, type AssistAsset } from './setupActions' +import { settle } from './settle' import { SitePagesHint } from './SitePagesHint' import './ops.css' @@ -160,33 +161,35 @@ export function AssetStepper({ setAssistError(null) setWarnings([]) setAssistNote(null) - startTransition(async () => { - const result = await assistAction({ - asset: stepAssist.asset, - section: stepAssist.section, - mode, - notes: notes[current.id] ?? '', - current: mode === 'refine' ? stepAssist.sectionValue(current.id) : null, - ...(stepAssist.icpId != null ? { icpId: stepAssist.icpId } : {}), - }) - if (!result.ok) { - setAssistError(result.error) - return - } - const value = asRecord(result.value) - if (!value) { - setAssistError('The assistant returned nothing usable for this step.') - return - } - stepAssist.onAssist(current.id, value) - setMock(result.mock) - setWarnings(result.warnings) - setAssistNote( - mode === 'draft' - ? 'Drafted into the fields above. Nothing is saved until you press Save.' - : 'Revised the fields above. Nothing is saved until you press Save.', - ) - }) + startTransition(() => + settle(async () => { + const result = await assistAction({ + asset: stepAssist.asset, + section: stepAssist.section, + mode, + notes: notes[current.id] ?? '', + current: mode === 'refine' ? stepAssist.sectionValue(current.id) : null, + ...(stepAssist.icpId != null ? { icpId: stepAssist.icpId } : {}), + }) + if (!result.ok) { + setAssistError(result.error) + return + } + const value = asRecord(result.value) + if (!value) { + setAssistError('The assistant returned nothing usable for this step.') + return + } + stepAssist.onAssist(current.id, value) + setMock(result.mock) + setWarnings(result.warnings) + setAssistNote( + mode === 'draft' + ? 'Drafted into the fields above. Nothing is saved until you press Save.' + : 'Revised the fields above. Nothing is saved until you press Save.', + ) + }, setAssistError), + ) } return ( @@ -208,7 +211,13 @@ export function AssetStepper({ i === step ? ' is-current' : '' }`} > - diff --git a/cms/src/components/ops/DirtyGuardUi.tsx b/cms/src/components/ops/DirtyGuardUi.tsx index 877360b..a8fe2be 100644 --- a/cms/src/components/ops/DirtyGuardUi.tsx +++ b/cms/src/components/ops/DirtyGuardUi.tsx @@ -141,6 +141,9 @@ const FOCUSABLE = 'button:not([disabled]), [href], input, select, textarea, [tab */ export function LeaveDialog({ guard, canSave = true }: { guard: AnyGuard; canSave?: boolean }) { const request = guard.leave + // A save started from the footer or the bar counts too: leaving mid-save would + // either lose it or submit it twice. + const busy = guard.leaveSaving || guard.saving const stayRef = useRef(null) const panelRef = useRef(null) @@ -155,7 +158,7 @@ export function LeaveDialog({ guard, canSave = true }: { guard: AnyGuard; canSav if (event.key === 'Escape') { event.preventDefault() event.stopPropagation() - if (!guard.leaveSaving) guard.stay() + if (!busy) guard.stay() return } if (event.key !== 'Tab') return @@ -191,16 +194,16 @@ export function LeaveDialog({ guard, canSave = true }: { guard: AnyGuard; canSav {canSave ? ( ) : null} @@ -323,6 +372,7 @@ export function IcpEditor({ className="datum-ops__link-btn" onClick={() => setConfirmDelete(true)} disabled={pending} + ref={deleteRef} > Delete draft diff --git a/cms/src/components/ops/IcpEditorView.tsx b/cms/src/components/ops/IcpEditorView.tsx index 1814c72..78f021c 100644 --- a/cms/src/components/ops/IcpEditorView.tsx +++ b/cms/src/components/ops/IcpEditorView.tsx @@ -7,7 +7,11 @@ import React from 'react' import { icpContentOf } from '../../lib/tenant/icp' import { formatAuditTimestamp } from './articleStatus' import { IcpEditor } from './IcpEditor' -import type { IcpDTO } from './icpTypes' +import { ICP_STEPS, type IcpDTO } from './icpTypes' + +function param(value: string | string[] | undefined): string | undefined { + return Array.isArray(value) ? value[0] : value +} /** * `/admin/ops/setup/audiences/:id`, and `/admin/ops/setup/audiences/new` for @@ -69,6 +73,15 @@ export async function IcpEditorView(props: AdminViewServerProps) { } : null + // The first save of a new audience moves to its own URL, which remounts the + // editor; the step and an activation error ride along so neither is lost. + const stepNumber = Number(param(searchParams?.step)) + const initialStep = + Number.isInteger(stepNumber) && stepNumber >= 0 && stepNumber < ICP_STEPS.length + ? stepNumber + : 0 + const initialError = param(searchParams?.activateError)?.slice(0, 500) || null + return ( 0} + initialStep={initialStep} + initialError={record ? initialError : null} /> diff --git a/cms/src/components/ops/PositioningEditor.tsx b/cms/src/components/ops/PositioningEditor.tsx index 1630628..9b90c02 100644 --- a/cms/src/components/ops/PositioningEditor.tsx +++ b/cms/src/components/ops/PositioningEditor.tsx @@ -85,10 +85,11 @@ export function PositioningEditor({ vocabularyAvoid: 'the words to avoid', openRulings: 'the open rulings', }, - save: async () => { + onError: setError, + save: async (_baseline, version) => { setError(null) setMessage(null) - const result = await savePositioningAction(content) + const result = await savePositioningAction(content, version) if (!result.ok) { setError(result.error) return null diff --git a/cms/src/components/ops/SetupChecklist.tsx b/cms/src/components/ops/SetupChecklist.tsx index cb9b1da..59a444f 100644 --- a/cms/src/components/ops/SetupChecklist.tsx +++ b/cms/src/components/ops/SetupChecklist.tsx @@ -4,6 +4,7 @@ import Link from 'next/link' import { useRouter } from 'next/navigation' import React, { useState, useTransition } from 'react' +import { settle } from './settle' import { activateDefaultTenantAction } from './tenantActions' import { SetupSuggestions } from './SetupSuggestions' import type { SetupSuggestionDTO } from './suggestionTypes' @@ -208,14 +209,16 @@ export function SetupChecklist(props: SetupChecklistData) { const useDemo = () => { setError(null) - startTransition(async () => { - const result = await activateDefaultTenantAction() - if (!result.ok) { - setError(result.error) - return - } - router.refresh() - }) + startTransition(() => + settle(async () => { + const result = await activateDefaultTenantAction() + if (!result.ok) { + setError(result.error) + return + } + router.refresh() + }, setError), + ) } return ( diff --git a/cms/src/components/ops/SetupSuggestions.tsx b/cms/src/components/ops/SetupSuggestions.tsx index 1ea13e9..96674e5 100644 --- a/cms/src/components/ops/SetupSuggestions.tsx +++ b/cms/src/components/ops/SetupSuggestions.tsx @@ -7,6 +7,7 @@ import { dismissSuggestionAction, scanSuggestionsAction, } from './suggestionActions' +import { settle } from './settle' import type { SetupSuggestionDTO } from './suggestionTypes' export function suggestionLabel(row: SetupSuggestionDTO): string { const p = row.proposal @@ -21,17 +22,19 @@ function SuggestionRow({ row }: { row: SetupSuggestionDTO }) { const [error, setError] = useState('') const [reason, setReason] = useState('') const act = (dismiss = false, evidenceAs: 'verified' | 'rejected' = 'verified') => - startTransition(async () => { - const result = dismiss - ? await dismissSuggestionAction(row.id, reason) - : await acceptSuggestionAction(row.id, { evidenceAs, reason }) - if (!result.ok) { - setError(result.error) - return - } - if (result.editorHref) router.push(result.editorHref) - else router.refresh() - }) + startTransition(() => + settle(async () => { + const result = dismiss + ? await dismissSuggestionAction(row.id, reason) + : await acceptSuggestionAction(row.id, { evidenceAs, reason }) + if (!result.ok) { + setError(result.error) + return + } + if (result.editorHref) router.push(result.editorHref) + else router.refresh() + }, setError), + ) return (
  • {suggestionLabel(row)}{' '} @@ -121,11 +124,13 @@ export function SetupSuggestions({ className="datum-ops__btn" disabled={pending} onClick={() => - startTransition(async () => { - const result = await scanSuggestionsAction() - if (!result.ok) setError(result.error) - else router.refresh() - }) + startTransition(() => + settle(async () => { + const result = await scanSuggestionsAction() + if (!result.ok) setError(result.error) + else router.refresh() + }, setError), + ) } > {pending ? 'Scanning…' : 'Scan now'} diff --git a/cms/src/components/ops/SetupWorkspaceEditor.tsx b/cms/src/components/ops/SetupWorkspaceEditor.tsx index 8f67628..1e552c3 100644 --- a/cms/src/components/ops/SetupWorkspaceEditor.tsx +++ b/cms/src/components/ops/SetupWorkspaceEditor.tsx @@ -9,6 +9,7 @@ import type { SitePage } from '../../lib/tenant/workspaceProfile' import { AssetStepper, hasSectionContent, type AssetStep } from './AssetStepper' import { SaveButton } from './DirtyGuardUi' import { workspaceSaveMessage } from './saveMessages' +import { settle } from './settle' import { Field, RowsEditor } from './setupFields' import { refreshSitePagesAction } from './setupActions' import { saveWorkspaceProfileAction } from './tenantActions' @@ -96,6 +97,7 @@ export function SetupWorkspaceEditor(props: WorkspaceEditorData) { siteNotes: 'the site notes', competitors: 'the competitors', }, + onError: setError, save: async () => { setError(null) setMessage(null) @@ -123,21 +125,25 @@ export function SetupWorkspaceEditor(props: WorkspaceEditorData) { }) const fetchPages = () => - startTransition(async () => { - setError(null) - setMessage(null) - setWarnings([]) - const result = await refreshSitePagesAction() - if (!result.ok) { - setError(result.error) - return - } - setWarnings(result.warnings) - setMessage(`Fetched ${result.pages} page${result.pages === 1 ? '' : 's'}.`) - // The action writes the pages to the global; the list below is rendered - // straight from the server's copy, so a refresh is what redraws it. - router.refresh() - }) + startTransition(() => + settle(async () => { + setError(null) + setMessage(null) + setWarnings([]) + const result = await refreshSitePagesAction() + if (!result.ok) { + setError(result.error) + return + } + setWarnings(result.warnings) + setMessage( + `Fetched ${result.pages} page${result.pages === 1 ? '' : 's'} from ${result.domain}.`, + ) + // The action writes the pages to the global; the list below is rendered + // straight from the server's copy, so a refresh is what redraws it. + router.refresh() + }, setError), + ) const applyAssist = (_step: StepId, value: Record) => { if (typeof value.companyName === 'string') setCompanyName(value.companyName) @@ -270,10 +276,18 @@ export function SetupWorkspaceEditor(props: WorkspaceEditorData) { type="button" className="datum-ops__btn" onClick={fetchPages} - disabled={pending} + disabled={pending || guard.dirty} + aria-describedby={guard.dirty ? 'ws-fetch-hint' : undefined} > {pending ? 'Fetching…' : 'Fetch site pages'} + {guard.dirty ? ( + + Save first: the pages are fetched from the saved domain + {guard.saved.targetDomain ? `, ${guard.saved.targetDomain}` : ''}, not the one in + the form. + + ) : null} {props.sitePagesFetchedLabel ? `Last fetched ${props.sitePagesFetchedLabel}` diff --git a/cms/src/components/ops/SourceReviewQueue.tsx b/cms/src/components/ops/SourceReviewQueue.tsx index d22c34c..b31efd6 100644 --- a/cms/src/components/ops/SourceReviewQueue.tsx +++ b/cms/src/components/ops/SourceReviewQueue.tsx @@ -10,6 +10,8 @@ import { dismissCandidateAction, reopenCandidateAction, } from './sourceReviewActions' +import { settle } from './settle' +import type { SourceReviewTotals } from './loadSourceReviewQueue' import { queueBucket, type CandidateDTO } from './sourceReviewTypes' import './ops.css' @@ -73,11 +75,13 @@ function CandidateCard({ candidate }: { candidate: CandidateDTO }) { const run = (action: () => Promise<{ ok: true } | { ok: false; error: string }>) => { setError(null) - startTransition(async () => { - const result = await action() - if (result.ok) router.refresh() - else setError(result.error) - }) + startTransition(() => + settle(async () => { + const result = await action() + if (result.ok) router.refresh() + else setError(result.error) + }, setError), + ) } const bucket = queueBucket(candidate) @@ -208,7 +212,14 @@ function CandidateCard({ candidate }: { candidate: CandidateDTO }) { ) } -export function SourceReviewQueue({ candidates }: { candidates: CandidateDTO[] }) { +export function SourceReviewQueue({ + candidates, + totals, +}: { + candidates: CandidateDTO[] + /** Each tab's size in the database, which is more than `candidates` once a tab is capped. */ + totals?: SourceReviewTotals +}) { const [tab, setTab] = useState('review') const buckets = useMemo(() => { @@ -218,6 +229,7 @@ export function SourceReviewQueue({ candidates }: { candidates: CandidateDTO[] } }, [candidates]) const shown = buckets[tab] + const totalOf = (key: Tab) => Math.max(totals?.[key] ?? 0, buckets[key].length) return (
    @@ -238,12 +250,13 @@ export function SourceReviewQueue({ candidates }: { candidates: CandidateDTO[] }
    {TABS.map((entry) => ( ))}
    @@ -259,6 +272,13 @@ export function SourceReviewQueue({ candidates }: { candidates: CandidateDTO[] } rewrite it first.

    + {shown.length < totalOf(tab) ? ( +

    + Showing {shown.length} of {totalOf(tab)}, most recently seen first. + {tab === 'review' ? ' Rate or dismiss some and the next ones appear.' : null} +

    + ) : null} + {shown.length === 0 ? (

    {tab === 'review' diff --git a/cms/src/components/ops/SourceReviewView.tsx b/cms/src/components/ops/SourceReviewView.tsx index 13e4466..e825234 100644 --- a/cms/src/components/ops/SourceReviewView.tsx +++ b/cms/src/components/ops/SourceReviewView.tsx @@ -1,4 +1,4 @@ -import { loadSourceReviewArticles } from './sourceReviewData' +import { loadSourceReviewQueue } from './loadSourceReviewQueue' import type { AdminViewServerProps } from 'payload' import { DefaultTemplate } from '@payloadcms/next/templates' import { Gutter } from '@payloadcms/ui' @@ -6,10 +6,6 @@ import { redirect } from 'next/navigation' import React from 'react' import { SourceReviewQueue } from './SourceReviewQueue' -import { toCandidateDTO } from './sourceReviewTypes' - -/** Cards past this are not work anybody is going to get through in one sitting. */ -const CANDIDATE_LIMIT = 200 export async function SourceReviewView(props: AdminViewServerProps) { const { initPageResult, params, searchParams } = props @@ -19,43 +15,7 @@ export async function SourceReviewView(props: AdminViewServerProps) { redirect('/admin/login') } - const [{ docs: candidateDocs }, { docs: ruleDocs }] = await Promise.all([ - req.payload.find({ - collection: 'evidence-source-candidates', - depth: 0, - limit: CANDIDATE_LIMIT, - sort: '-lastSeenAt', - user: req.user, - overrideAccess: false, - }), - // Include inactive rules: a card must know when a rule no longer covers it. - req.payload.find({ - collection: 'evidence-sources', - depth: 0, - pagination: false, - user: req.user, - overrideAccess: false, - }), - ]) - - // One lookup for every article named in a sighting, so a card can say which - // article is waiting on this domain rather than just showing an id. - const articleIds = [ - ...new Set( - candidateDocs.flatMap((doc) => - Array.isArray(doc.sightings) - ? doc.sightings - .map((s) => - s && typeof s === 'object' ? (s as { articleId?: unknown }).articleId : null, - ) - .filter((id): id is number => typeof id === 'number') - : [], - ), - ), - ] - const articles = await loadSourceReviewArticles(req.payload, req.user, articleIds) - - const candidates = candidateDocs.map((doc) => toCandidateDTO(doc, ruleDocs, articles)) + const { candidates, totals } = await loadSourceReviewQueue(req.payload, req.user) return ( - + ) diff --git a/cms/src/components/ops/loadSourceReviewQueue.ts b/cms/src/components/ops/loadSourceReviewQueue.ts new file mode 100644 index 0000000..6e7ce65 --- /dev/null +++ b/cms/src/components/ops/loadSourceReviewQueue.ts @@ -0,0 +1,82 @@ +import type { Payload, TypedUser } from 'payload' + +import { loadSourceReviewArticles } from './sourceReviewData' +import { type CandidateDTO, queueBucket, toCandidateDTO } from './sourceReviewTypes' + +/** Cards past this, per status, are not work anybody is going to get through in one sitting. */ +export const CANDIDATE_LIMIT = 200 + +export type SourceReviewTotals = { review: number; rated: number; dismissed: number } + +/** + * The review queue, one query per status. + * + * One query for every status, newest first, would let a long tail of rated and + * dismissed domains push older pending ones out of the page: past the cap they + * could not be reached at all, and the tab counts counted only what was loaded. + * So pending is read on its own, with its own cap, and each tab's total comes + * from the database. The "covered by a rule" check stays on the loaded rows: + * a rule is not a column on the candidate, so it can only be judged per row. + */ +export async function loadSourceReviewQueue( + payload: Payload, + user: TypedUser, +): Promise<{ candidates: CandidateDTO[]; totals: SourceReviewTotals }> { + const read = (status: 'pending' | 'approved' | 'dismissed') => + payload.find({ + collection: 'evidence-source-candidates', + where: { status: { equals: status } }, + depth: 0, + limit: CANDIDATE_LIMIT, + sort: '-lastSeenAt', + user, + overrideAccess: false, + }) + + const [pending, approved, dismissed, { docs: ruleDocs }] = await Promise.all([ + read('pending'), + read('approved'), + read('dismissed'), + // Include inactive rules: a card must know when a rule no longer covers it. + payload.find({ + collection: 'evidence-sources', + depth: 0, + pagination: false, + user, + overrideAccess: false, + }), + ]) + + const candidateDocs = [...pending.docs, ...approved.docs, ...dismissed.docs] + // One lookup for every article named in a sighting, so a card can say which + // article is waiting on this domain rather than just showing an id. + const articleIds = [ + ...new Set( + candidateDocs.flatMap((doc) => + Array.isArray(doc.sightings) + ? doc.sightings + .map((s) => + s && typeof s === 'object' ? (s as { articleId?: unknown }).articleId : null, + ) + .filter((id): id is number => typeof id === 'number') + : [], + ), + ), + ] + const articles = await loadSourceReviewArticles(payload, user, articleIds) + const candidates = candidateDocs.map((doc) => toCandidateDTO(doc, ruleDocs, articles)) + + // A pending row an active rule covers is settled work: it moves from the + // review total to the rated one. + const covered = candidates.filter( + (candidate) => candidate.status === 'pending' && queueBucket(candidate) === 'rated', + ).length + return { + candidates, + totals: { + review: pending.totalDocs - covered, + rated: approved.totalDocs + covered, + dismissed: dismissed.totalDocs, + }, + } +} diff --git a/cms/src/components/ops/settle.ts b/cms/src/components/ops/settle.ts new file mode 100644 index 0000000..743a8fe --- /dev/null +++ b/cms/src/components/ops/settle.ts @@ -0,0 +1,20 @@ +import { errorMessage } from '../../lib/errorMessage' + +/** + * Run an editor's server-action call from a transition, showing a failure + * where the editor shows its other errors. + * + * A server action that cannot be reached (offline, a 5xx, an action id gone + * stale after a deploy) rejects instead of returning `{ ok: false }`; inside a + * transition that rejection goes to the error boundary and blanks the page. + */ +export async function settle( + run: () => Promise, + onError: (message: string) => void, +): Promise { + try { + await run() + } catch (e) { + onError(errorMessage(e, 'Something went wrong. Check your connection and try again.')) + } +} diff --git a/cms/src/components/ops/setupActions.ts b/cms/src/components/ops/setupActions.ts index ba62444..e6268b8 100644 --- a/cms/src/components/ops/setupActions.ts +++ b/cms/src/components/ops/setupActions.ts @@ -1,6 +1,7 @@ 'use server' import { revalidatePath } from 'next/cache' +import { errorMessage } from '../../lib/errorMessage' import { governanceAuditContext } from '../../lib/governanceAudit' import { requireUser } from '../../lib/requireUser' @@ -60,13 +61,23 @@ const SITE_PAGE_CONCURRENCY = 3 const REFRESH_BUDGET_MS = 40_000 export type RefreshSitePagesResult = - { ok: true; pages: number; warnings: string[] } | { ok: false; error: string } + | { ok: true; pages: number; warnings: string[]; domain: string } + | { ok: false; error: string } /** What went wrong with one page, in the operator's words. */ function pageWarning(url: string, reason: string | null): string { return `${url}: ${reason ?? 'could not be read'}` } +/** A crawl that throws (a database or network fault) answers instead of rejecting. */ +export async function refreshSitePagesAction(): Promise { + try { + return await refreshSitePages() + } catch (e) { + return { ok: false, error: errorMessage(e, 'Could not fetch the site pages.') } + } +} + /** * Reads the workspace's own site so the setup assistant has something to work * from: the home page, plus up to seven marketing pages linked from it. @@ -82,7 +93,7 @@ function pageWarning(url: string, reason: string | null): string { * The crawl reuses `fetchPage`, so the SSRF guard, the redirect handling, the * byte ceiling, and the mock mode all come for free. */ -export async function refreshSitePagesAction(): Promise { +async function refreshSitePages(): Promise { const { payload, user } = await requireUser('Sign in to fetch the site pages.') const mode = modeFromEnv(process.env) const doc = (await payload.findGlobal({ @@ -192,7 +203,7 @@ export async function refreshSitePagesAction(): Promise }) revalidatePath(VIEW_PATH) - return { ok: true, pages: stored.length, warnings } + return { ok: true, pages: stored.length, warnings, domain } } // --------------------------------------------------------------------------- diff --git a/cms/src/components/ops/setupFields.tsx b/cms/src/components/ops/setupFields.tsx index 6924534..80ac1c6 100644 --- a/cms/src/components/ops/setupFields.tsx +++ b/cms/src/components/ops/setupFields.tsx @@ -108,6 +108,7 @@ export function RowsEditor({ className="datum-ops__link-btn" onClick={() => remove(index)} disabled={disabled} + aria-label={`Remove row ${index + 1}`} > Remove @@ -153,14 +154,27 @@ export function TextRows({ hint?: string }) { return ( -

    - +
    + {/* A group name, not a
    ) } diff --git a/cms/src/components/ops/DirtyGuardUi.tsx b/cms/src/components/ops/DirtyGuardUi.tsx index a8fe2be..ec05cd3 100644 --- a/cms/src/components/ops/DirtyGuardUi.tsx +++ b/cms/src/components/ops/DirtyGuardUi.tsx @@ -139,11 +139,20 @@ const FOCUSABLE = 'button:not([disabled]), [href], input, select, textarea, [tab * Escape is Stay. Without `save` there is no "Save and leave" — a guard that * cannot save should not offer it. */ -export function LeaveDialog({ guard, canSave = true }: { guard: AnyGuard; canSave?: boolean }) { +export function LeaveDialog({ + guard, + canSave = true, + pending = false, +}: { + guard: AnyGuard + canSave?: boolean + /** The editor's own write in flight outside the guard (e.g. save-and-activate). */ + pending?: boolean +}) { const request = guard.leave // A save started from the footer or the bar counts too: leaving mid-save would // either lose it or submit it twice. - const busy = guard.leaveSaving || guard.saving + const busy = guard.leaveSaving || guard.saving || pending const stayRef = useRef(null) const panelRef = useRef(null) diff --git a/cms/src/components/ops/SetupWorkspaceEditor.tsx b/cms/src/components/ops/SetupWorkspaceEditor.tsx index 1e552c3..4c19bfa 100644 --- a/cms/src/components/ops/SetupWorkspaceEditor.tsx +++ b/cms/src/components/ops/SetupWorkspaceEditor.tsx @@ -98,10 +98,10 @@ export function SetupWorkspaceEditor(props: WorkspaceEditorData) { competitors: 'the competitors', }, onError: setError, - save: async () => { + save: async (_baseline, version) => { setError(null) setMessage(null) - const result = await saveWorkspaceProfileAction(form) + const result = await saveWorkspaceProfileAction(form, version) if (!result.ok) { setError(result.error) return null diff --git a/cms/src/components/ops/tenantActions.ts b/cms/src/components/ops/tenantActions.ts index 2604b0f..bf215e7 100644 --- a/cms/src/components/ops/tenantActions.ts +++ b/cms/src/components/ops/tenantActions.ts @@ -161,9 +161,19 @@ const dateOrNull = (value: string | null | undefined): string | null => */ export async function saveWorkspaceProfileAction( input: WorkspaceProfileInput, + openedAt?: string | null, ): Promise { try { const { payload, user } = await requireUser('Sign in first.') + if (openedAt) { + const stored = await payload.findGlobal({ + slug: 'workspace-profile', + select: { updatedAt: true }, + depth: 0, + overrideAccess: true, + }) + if (movedOn(stored, openedAt)) return { ok: false, error: STALE_MESSAGE } + } const competitors = input.competitors .map((row) => ({ domain: normaliseDomain(row.domain), name: (row.name ?? '').trim() })) .filter((row): row is { domain: string; name: string } => row.domain !== null) diff --git a/cms/tests/int/dirtyGuardSave.int.spec.ts b/cms/tests/int/dirtyGuardSave.int.spec.ts index cab9deb..81b5f8a 100644 --- a/cms/tests/int/dirtyGuardSave.int.spec.ts +++ b/cms/tests/int/dirtyGuardSave.int.spec.ts @@ -19,9 +19,11 @@ type Form = { a: string } function Harness({ save, onError, + pending, }: { save: (baseline: Form, version: string | null) => Promise | null> onError?: (message: string) => void + pending?: boolean }) { const [value, setValue] = useState({ a: 'one' }) const guard = useDirtyGuard({ @@ -44,7 +46,7 @@ function Harness({ React.createElement('button', { onClick: () => void guard.submit(), type: 'button' }, 'Save'), React.createElement('span', { 'data-testid': 'saving' }, String(guard.saving)), React.createElement('a', { href: '/elsewhere' }, 'Elsewhere'), - React.createElement(LeaveDialog, { guard }), + React.createElement(LeaveDialog, { guard, pending }), ) } @@ -139,3 +141,16 @@ it('hands the save the version the form is based on', async () => { // After a save the next one is based on what that save returned. expect(save).toHaveBeenLastCalledWith({ a: 'edited' }, 'v2') }) + +it("keeps the leave dialog's buttons off while the editor's own write runs", async () => { + const save = vi.fn(async () => ({ saved: { a: 'edited' }, version: 'v2' })) + // `pending` is a write the guard does not run itself, such as save-and-activate. + render(React.createElement(Harness, { save, pending: true })) + edit() + fireEvent.click(screen.getByRole('link', { name: 'Elsewhere' })) + const dialog = await screen.findByRole('alertdialog') + for (const button of dialog.querySelectorAll('button')) { + expect((button as HTMLButtonElement).disabled).toBe(true) + } + expect(save).not.toHaveBeenCalled() +}) diff --git a/cms/tests/int/editorConcurrency.int.spec.ts b/cms/tests/int/editorConcurrency.int.spec.ts index d53ea2e..fade8a2 100644 --- a/cms/tests/int/editorConcurrency.int.spec.ts +++ b/cms/tests/int/editorConcurrency.int.spec.ts @@ -41,6 +41,7 @@ const { saveEvidenceBankAction, saveIcpAction, savePositioningAction, + saveWorkspaceProfileAction, } = await import('@/components/ops/tenantActions') const { emptyIcpContent, icpContentOf } = await import('@/lib/tenant/icp') const { emptyPositioningContent } = await import('@/lib/tenant/positioning') @@ -122,6 +123,31 @@ describe('positioning', () => { }) }) +describe('workspace profile', () => { + const profile = (companyName: string) => ({ + companyName, + targetDomain: 'acme.example.com', + siteNotes: '', + competitors: [], + }) + + it('refuses a save opened before someone else saved, and keeps their text', async () => { + const first = await saveWorkspaceProfileAction(profile('Theirs')) + if (!first.ok) throw new Error(first.error) + const theirs = await saveWorkspaceProfileAction(profile('Colleague edit'), first.updatedAt) + expect(theirs.ok).toBe(true) + + const stale = await saveWorkspaceProfileAction(profile('Stale edit'), before(first.updatedAt!)) + expect(stale).toEqual({ ok: false, error: STALE }) + const doc = (await payload.findGlobal({ + slug: 'workspace-profile', + depth: 0, + overrideAccess: true, + })) as { companyName?: string } + expect(doc.companyName).toBe('Colleague edit') + }) +}) + describe('positioning schema', () => { it('holds at most three core claims', async () => { const claims = (n: number) => Array.from({ length: n }, (_, i) => ({ claim: `Claim ${i + 1}` })) diff --git a/pipeline/src/report.ts b/pipeline/src/report.ts index f316ae3..67a2b32 100644 --- a/pipeline/src/report.ts +++ b/pipeline/src/report.ts @@ -6,7 +6,7 @@ import { decideQualitative, type NotTraitViolation } from './qa/verdicts' type ReportArticle = Pick< Article, - 'id' | 'keyword' | 'title' | 'status' | 'template' | 'qaResults' | 'informationGain' + 'id' | 'keyword' | 'title' | 'status' | 'template' | 'qaResults' | 'informationGain' | 'archived' > export type ReportPeriod = 'week' | 'month' @@ -137,6 +137,7 @@ export async function printReport(payload: Payload, period: ReportPeriod): Promi template: true, qaResults: true, informationGain: true, + archived: true, }, populate: { templates: { name: true } }, pagination: false, @@ -316,8 +317,10 @@ export async function printReport(payload: Payload, period: ReportPeriod): Promi // would only ever grow. The status is what says whether a human still owes // this article a decision; `ReportsPanel.tsx` reads the same queue off // status for the same reason. + // Archived pieces are set aside: nobody owes them a decision. const queue = scored.filter( (a) => + a.archived !== true && (a.status === 'needs_review' || a.status === 'blocked') && (a.informationGain?.decision === 'HUMAN_REVIEW' || a.informationGain?.decision === 'BLOCK'), ) @@ -360,7 +363,7 @@ export async function printReport(payload: Payload, period: ReportPeriod): Promi } // ---- Failure digest ---- - const needsRevision = articles.filter((a) => a.status === 'needs_revision') + const needsRevision = articles.filter((a) => a.status === 'needs_revision' && a.archived !== true) lines.push('') lines.push(`== Failure digest (${needsRevision.length} article(s) at needs_revision) ==`) const failureCodes = new Map() diff --git a/pipeline/test/report.test.ts b/pipeline/test/report.test.ts index ae8cfd8..c78ef68 100644 --- a/pipeline/test/report.test.ts +++ b/pipeline/test/report.test.ts @@ -10,6 +10,7 @@ interface FakeArticle { keyword: string status: string title?: string + archived?: boolean informationGain?: { run?: number | null; decision?: string | null } | null qaResults?: Record } @@ -206,6 +207,34 @@ test('the failure digest names an evidence-only failure', async () => { assert.match(report, /evidenceCheck \(failed\): Claim 1 has no backing in the bank\./) }) +test('archived articles stay out of the review queue and the failure digest', async () => { + const report = await reportOf( + [ + { + id: 3, + keyword: 'c', + title: 'Kettles', + status: 'needs_review', + archived: true, + informationGain: { run: 13, decision: 'HUMAN_REVIEW' }, + }, + { + id: 4, + keyword: 'd', + title: 'Scales', + status: 'needs_revision', + archived: true, + qaResults: qa({ evidenceCheck: { passed: false, notes: 'Archived failure.' } }), + }, + ], + [{ id: 13, reasons: [] }], + ) + assert.match(reviewQueue(report), /Review queue \(0 article\(s\)/) + assert.match(report, /Failure digest \(0 article\(s\) at needs_revision\)/) + assert.doesNotMatch(report, /Kettles/) + assert.doesNotMatch(report, /Archived failure\./) +}) + // QA fails a draft on a quoted "what we are NOT" breach even when the model // marked the review itself as passed (`decideQualitative`). The report has to // apply the same rule or it reports a pass rate QA never gave.