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({
>
) : (
-
- runAction(async () => {
- const { slug, status } = await publishArticleAction(article.id, notes)
- setNotice(
- status === 'published'
- ? {
- text: 'Published ·',
- href: `/articles/${slug || article.id}`,
- hrefLabel: 'view it',
- }
- : `Saved as ${status}.`,
- )
- })
- }
- >
- Approve & publish
-
+ {armed === 'publish' ? (
+ <>
+ {
+ disarm()
+ runAction(async () => {
+ const { slug, status } = unwrap(await publishArticleAction(article.id, notes))
+ setNotice(
+ status === 'published'
+ ? {
+ text: 'Published ·',
+ href: `/articles/${slug || article.id}`,
+ hrefLabel: 'view it',
+ }
+ : `Saved as ${status}.`,
+ )
+ })
+ }}
+ >
+ Confirm: approve & publish
+
+
+ Cancel
+
+ >
+ ) : (
+ arm('publish')}
+ >
+ Approve & 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' : ''
}`}
>
- onStep(i)} disabled={busy} title={s.title}>
+ onStep(i)}
+ title={s.title}
+ type="button"
+ >
{i + 1}{s.title}
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 ? (
void guard.saveAndLeave()}
type="button"
>
- {guard.leaveSaving ? 'Saving…' : 'Save and leave'}
+ {busy ? 'Saving…' : 'Save and leave'}
) : null}
@@ -208,7 +211,7 @@ export function LeaveDialog({ guard, canSave = true }: { guard: AnyGuard; canSav
{
+ onError: setError,
+ save: async (_baseline, version) => {
setError(null)
setMessage(null)
- const result = await saveEvidenceBankAction(draft, suggestion?.id)
+ const result = await saveEvidenceBankAction(draft, suggestion?.id, version)
if (!result.ok) {
setError(result.error)
return null
@@ -166,90 +168,92 @@ export function EvidenceBankEditor({
// Claims come from the operator's notes; with none, there is nothing to
// turn into a claim and the model would only echo the site back.
if (section === 'verifiedClaims' && needsNotes) return
- startTransition(async () => {
- setError(null)
- setMessage(null)
- setWarnings([])
- const result = await assistAction({
- asset: 'evidence',
- section,
- mode: 'draft',
- notes,
- current: null,
- })
- if (!result.ok) {
- setError(result.error)
- return
- }
- const value = (result.value ?? {}) as Record
- const proposed = Array.isArray(value[section]) ? (value[section] as unknown[]) : []
- if (proposed.length === 0) {
- setError('Datum found nothing to propose. Try adding more notes.')
- return
- }
- setMock(result.mock)
- setWarnings(result.warnings)
- if (section === 'facts') {
- setDraft((prev) => ({
- ...prev,
- facts: [
- ...prev.facts,
- ...proposed.map((row) => {
- const r = (row ?? {}) as Record
- return {
- fact: typeof r.fact === 'string' ? r.fact : '',
- source: typeof r.source === 'string' ? r.source : '',
- owner: typeof r.owner === 'string' ? r.owner : '',
- lastConfirmedAt: '',
- }
- }),
- ],
- }))
+ startTransition(() =>
+ settle(async () => {
+ setError(null)
+ setMessage(null)
+ setWarnings([])
+ const result = await assistAction({
+ asset: 'evidence',
+ section,
+ mode: 'draft',
+ notes,
+ current: null,
+ })
+ if (!result.ok) {
+ setError(result.error)
+ return
+ }
+ const value = (result.value ?? {}) as Record
+ const proposed = Array.isArray(value[section]) ? (value[section] as unknown[]) : []
+ if (proposed.length === 0) {
+ setError('Datum found nothing to propose. Try adding more notes.')
+ return
+ }
+ setMock(result.mock)
+ setWarnings(result.warnings)
+ if (section === 'facts') {
+ setDraft((prev) => ({
+ ...prev,
+ facts: [
+ ...prev.facts,
+ ...proposed.map((row) => {
+ const r = (row ?? {}) as Record
+ return {
+ fact: typeof r.fact === 'string' ? r.fact : '',
+ source: typeof r.source === 'string' ? r.source : '',
+ owner: typeof r.owner === 'string' ? r.owner : '',
+ lastConfirmedAt: '',
+ }
+ }),
+ ],
+ }))
+ setMessage(
+ 'Proposed rows added above. They are not saved yet. Add a source to each one, then press Save.',
+ )
+ return
+ }
+ // A claim the bank already holds, or one proposed twice in this batch,
+ // is dropped: it would only be a second row to reconcile by hand.
+ const seen = new Set(draft.verifiedClaims.map((row) => normaliseClaimKey(row.claim)))
+ let alreadyHere = 0
+ const fresh = proposed.flatMap((row) => {
+ const r = (row ?? {}) as Record
+ const claim = typeof r.claim === 'string' ? r.claim : ''
+ const key = normaliseClaimKey(claim)
+ if (seen.has(key)) {
+ alreadyHere += 1
+ return []
+ }
+ seen.add(key)
+ return [
+ {
+ claim,
+ primarySource: typeof r.primarySource === 'string' ? r.primarySource : '',
+ sourceUrl: typeof r.sourceUrl === 'string' ? r.sourceUrl : '',
+ sourceDate: '',
+ sampleOrMethod: typeof r.sampleOrMethod === 'string' ? r.sampleOrMethod : '',
+ // Never anything stronger: a model reading your own site back
+ // to you has checked nothing. A person raises this after they
+ // put a source next to it.
+ verificationDepth: 'self_reported' as const,
+ limits: typeof r.limits === 'string' ? r.limits : '',
+ clearedSurfaces: [] as ClearedSurface[],
+ recheckAt: '',
+ },
+ ]
+ })
+ const note = alreadyHere > 0 ? ` ${alreadyHere} already in your bank, left out.` : ''
+ if (fresh.length === 0) {
+ setMessage(`Nothing new to add: ${alreadyHere} already in your bank.`)
+ return
+ }
+ setDraft((prev) => ({ ...prev, verifiedClaims: [...prev.verifiedClaims, ...fresh] }))
setMessage(
- 'Proposed rows added above. They are not saved yet. Add a source to each one, then press Save.',
+ `Proposed rows added above. They are not saved yet. Add a source to each one, then press Save.${note}`,
)
- return
- }
- // A claim the bank already holds, or one proposed twice in this batch,
- // is dropped: it would only be a second row to reconcile by hand.
- const seen = new Set(draft.verifiedClaims.map((row) => normaliseClaimKey(row.claim)))
- let alreadyHere = 0
- const fresh = proposed.flatMap((row) => {
- const r = (row ?? {}) as Record
- const claim = typeof r.claim === 'string' ? r.claim : ''
- const key = normaliseClaimKey(claim)
- if (seen.has(key)) {
- alreadyHere += 1
- return []
- }
- seen.add(key)
- return [
- {
- claim,
- primarySource: typeof r.primarySource === 'string' ? r.primarySource : '',
- sourceUrl: typeof r.sourceUrl === 'string' ? r.sourceUrl : '',
- sourceDate: '',
- sampleOrMethod: typeof r.sampleOrMethod === 'string' ? r.sampleOrMethod : '',
- // Never anything stronger: a model reading your own site back
- // to you has checked nothing. A person raises this after they
- // put a source next to it.
- verificationDepth: 'self_reported' as const,
- limits: typeof r.limits === 'string' ? r.limits : '',
- clearedSurfaces: [] as ClearedSurface[],
- recheckAt: '',
- },
- ]
- })
- const note = alreadyHere > 0 ? ` ${alreadyHere} already in your bank, left out.` : ''
- if (fresh.length === 0) {
- setMessage(`Nothing new to add: ${alreadyHere} already in your bank.`)
- return
- }
- setDraft((prev) => ({ ...prev, verifiedClaims: [...prev.verifiedClaims, ...fresh] }))
- setMessage(
- `Proposed rows added above. They are not saved yet. Add a source to each one, then press Save.${note}`,
- )
- })
+ }, setError),
+ )
}
const isExpired = (row: (typeof draft.verifiedClaims)[number]) =>
@@ -276,11 +280,12 @@ export function EvidenceBankEditor({
if it is listed here, and it must cite the row. Put the proof next to every claim.
-
+
{TABS.map(([id, label]) => (
setTab(id)}
>
@@ -438,8 +443,19 @@ export function EvidenceBankEditor({
hint="QA rejects a draft that stretches the claim past this."
/>