diff --git a/cms/src/app/(frontend)/page.tsx b/cms/src/app/(frontend)/page.tsx
index 2bc70cd..d7171b2 100644
--- a/cms/src/app/(frontend)/page.tsx
+++ b/cms/src/app/(frontend)/page.tsx
@@ -5,6 +5,7 @@ import React from 'react'
import config from '@/payload.config'
import { formatArticleDate } from '@/lib/articleReader'
+import { PUBLIC } from '@/lib/findPublishedArticle'
export default async function HomePage() {
const headers = await getHeaders()
@@ -21,7 +22,7 @@ export default async function HomePage() {
metaDescription: true,
publishedAt: true,
},
- where: { status: { equals: 'published' } },
+ where: PUBLIC,
limit: 12,
depth: 0,
sort: '-publishedAt',
diff --git a/cms/src/components/ops/AssetStepper.tsx b/cms/src/components/ops/AssetStepper.tsx
index 6c71374..af161a1 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' : ''
}`}
>
-
-
+
{TABS.map(([id, label]) => (
setTab(id)}
>
@@ -438,8 +443,19 @@ export function EvidenceBankEditor({
hint="QA rejects a draft that stretches the claim past this."
/>
- These kept their place on the board, so starting another run retries them. A research
+ These kept their place on the content list, so starting another run retries them. A research
failure usually means the keyword has no search results to compare against — try a
broader one.
diff --git a/cms/src/components/ops/RuntimeBanner.tsx b/cms/src/components/ops/RuntimeBanner.tsx
index bb8dd94..7857894 100644
--- a/cms/src/components/ops/RuntimeBanner.tsx
+++ b/cms/src/components/ops/RuntimeBanner.tsx
@@ -1,5 +1,6 @@
'use client'
+import { useAuth } from '@payloadcms/ui'
import React, { useEffect, useState } from 'react'
import { runtimeStatusAction } from './tenantActions'
@@ -27,12 +28,34 @@ export function RuntimeBanner() {
problems: string[]
} | null>(null)
+ // Mounted on every admin route, the login page included, and Payload's login
+ // navigates client-side, so a mount-only check would run before sign-in and
+ // never again. Keyed on the user instead; signed out there is nothing to ask.
+ const { user } = useAuth()
+ const userId = user?.id ?? null
+
useEffect(() => {
- const id = setTimeout(() => void runtimeStatusAction().then(setStatus), 0)
- return () => clearTimeout(id)
- }, [])
+ if (userId === null) return
+ let current = true
+ const id = setTimeout(
+ () =>
+ void runtimeStatusAction()
+ .then((next) => {
+ if (current) setStatus(next)
+ })
+ .catch(() => {
+ /* Keep the last status; the banner is advisory. */
+ }),
+ 0,
+ )
+ return () => {
+ current = false
+ clearTimeout(id)
+ }
+ }, [userId])
- if (!status || status.mode !== 'live' || status.ready) return null
+ // A status read for a user who has since signed out is not shown.
+ if (userId === null || !status || status.mode !== 'live' || status.ready) return null
// `missing` holds environment variable names; `problems` holds sentences the
// evaluator already phrased as instructions. Kept apart by readiness, so
// neither list has to be reconstructed by subtracting the other.
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..4c19bfa 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,10 +97,11 @@ export function SetupWorkspaceEditor(props: WorkspaceEditorData) {
siteNotes: 'the site notes',
competitors: 'the competitors',
},
- save: async () => {
+ onError: setError,
+ 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
@@ -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 (
+ 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/TemplateConfigEditor.tsx b/cms/src/components/ops/TemplateConfigEditor.tsx
index a67a327..2c1a7b1 100644
--- a/cms/src/components/ops/TemplateConfigEditor.tsx
+++ b/cms/src/components/ops/TemplateConfigEditor.tsx
@@ -10,6 +10,7 @@ import {
DEFAULT_COMPANY_MENTIONS,
} from '../../lib/tenant/companyMentions'
import { LeaveDialog, RestoreNotice, SaveButton, UnsavedBar } from './DirtyGuardUi'
+import { unwrap } from './actionResult'
import { createTemplateAction, saveTemplateConfigAction } from './templateActions'
import type { TemplateConfigDTO } from './templateTypes'
import { useDirtyGuard } from './useDirtyGuard'
@@ -127,17 +128,19 @@ export function TemplateConfigEditor({ templates, initialId }: Props) {
if (!selected) return null
setError(null)
try {
- const result = await saveTemplateConfigAction(selected.id, {
- // The outline and example go through a lossy plain-to-Lexical
- // conversion, so they are only sent when they actually changed.
- ...(form.outline !== baseline.outline ? { outline } : {}),
- ...(form.example !== baseline.example ? { example } : {}),
- companyMentions,
- dos: dos.split('\n'),
- donts: donts.split('\n'),
- requiredSections: requiredSections.split('\n'),
- seoSpec: seo,
- })
+ const result = unwrap(
+ await saveTemplateConfigAction(selected.id, {
+ // The outline and example go through a lossy plain-to-Lexical
+ // conversion, so they are only sent when they actually changed.
+ ...(form.outline !== baseline.outline ? { outline } : {}),
+ ...(form.example !== baseline.example ? { example } : {}),
+ companyMentions,
+ dos: dos.split('\n'),
+ donts: donts.split('\n'),
+ requiredSections: requiredSections.split('\n'),
+ seoSpec: seo,
+ }),
+ )
// The textareas show what was stored, through the same mapping the
// page reads it with: a blank line or padded outline is gone.
const saved = formOf(result.template)
@@ -281,6 +284,7 @@ export function TemplateConfigEditor({ templates, initialId }: Props) {
key={t.id}
type="button"
className={t.id === selected.id ? 'is-active' : undefined}
+ aria-current={t.id === selected.id ? 'true' : undefined}
// A save in flight resolves into whichever template is open, so
// switching mid-save would load one template's result into another.
disabled={pending}
@@ -327,6 +331,7 @@ export function TemplateConfigEditor({ templates, initialId }: Props) {
key={id}
type="button"
className={tab === id ? 'is-active' : undefined}
+ aria-pressed={tab === id}
onClick={() => setTab(id)}
>
{label}
diff --git a/cms/src/components/ops/actionResult.ts b/cms/src/components/ops/actionResult.ts
new file mode 100644
index 0000000..b7fd4c3
--- /dev/null
+++ b/cms/src/components/ops/actionResult.ts
@@ -0,0 +1,48 @@
+import { APIError } from 'payload'
+
+import { errorMessage } from '../../lib/errorMessage'
+
+/**
+ * How a reviewer-facing server action answers.
+ *
+ * Next replaces the message of an error thrown from a server action with a
+ * generic one in a production build, so a refusal that is *expected* — a gate
+ * saying why a write was refused, a missing justification, an article in an
+ * active run — has to travel as a return value to reach the person who needs
+ * to read it. `briefActions`, `boardActions` and `tenantActions` already do
+ * this; this is the same shape for the actions that used to throw.
+ */
+export type ActionFailure = { ok: false; error: string }
+export type ActionResult = ({ ok: true } & T) | ActionFailure
+
+/**
+ * Runs a server action's body and turns whatever it throws into `{ ok: false }`.
+ *
+ * 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, 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,
+ body: () => Promise,
+): Promise> {
+ 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) }
+ }
+}
+
+/**
+ * The client half: the success value, or a thrown `Error` carrying the
+ * server's message. The throw happens in the browser, so it is not redacted.
+ */
+export function unwrap(result: T | ActionFailure): T {
+ if (!result.ok) throw new Error(result.error)
+ return result
+}
diff --git a/cms/src/components/ops/actions.ts b/cms/src/components/ops/actions.ts
index 1905b88..870f4d8 100644
--- a/cms/src/components/ops/actions.ts
+++ b/cms/src/components/ops/actions.ts
@@ -12,6 +12,8 @@ import { gateRunReadiness, queueRunForArticles } from '@/lib/queueRunForArticles
import { revalidatePublishedArticle } from '@/lib/revalidatePublishedArticle'
import type { Article } from '@/payload-types'
+import { attempt, type ActionResult } from './actionResult'
+import { CLEARED_SCHEDULE, NULL_QA_RESULTS } from './articleReset'
import { buildRegenerateRevisionNotes, type ArticleStatus } from './articleStatus'
import { isSendBackReasonCode, type SendBackReasonCode } from './sendBackReasons'
@@ -38,38 +40,6 @@ import { isSendBackReasonCode, type SendBackReasonCode } from './sendBackReasons
*/
const NULL_INFORMATION_GAIN = CLEARED_INFORMATION_GAIN
-const NULL_QA_RESULTS = {
- structural: { passed: null, violations: null },
- factCheck: { passed: null, notes: null, sources: null },
- qualitativeReview: {
- passed: null,
- notes: null,
- voiceScore: null,
- voiceNotes: null,
- notTraitViolations: null,
- },
- // Without this the evidence verdict of the draft being thrown away stays on
- // the article, and the review page shows it against text QA has not seen.
- evidenceCheck: { passed: null, notes: null, claims: null },
-} as const
-
-/**
- * What every action that moves an article off `approved` writes to `publishAt`.
- *
- * A schedule is inert on any other status, which made leaving it in place look
- * free — and it is, right up to the moment the piece is approved a second
- * time. Then the five-minute `publish-due` tick finds a date that passed days
- * ago, publishes immediately, and the reviewer who had not finished looking at
- * the draft gets no say and no explanation. Taking the date back at the moment
- * it stops applying is the only point where the intent is unambiguous: the
- * person sending this piece back has just said it is not ready to go out.
- *
- * The audit details record the write (`publishAt: null`) the same way they
- * already record `reviewNotes` — what the action wrote, not a claim about what
- * was there before.
- */
-const CLEARED_SCHEDULE = { publishAt: null } as const
-
/**
* Statuses where no brief has been approved, so there is no draft to redo.
*
@@ -83,11 +53,18 @@ const NO_APPROVED_BRIEF: readonly ArticleStatus[] = ['topic_selected', 'brief_re
const noApprovedBrief = (verb: string) =>
`This article has no approved brief yet, so it cannot be ${verb}. Approve the brief first.`
-async function requireApprovedBrief(
+/**
+ * Reset also has nothing to act on at `researched`: the brief is approved but
+ * no draft exists yet, so writing `drafted` would queue QA over an empty body.
+ * Regenerate is fine there (it writes `researched`), which is why this is not
+ * part of `NO_APPROVED_BRIEF`.
+ */
+const NOT_DRAFTED_YET = 'researched' satisfies ArticleStatus
+
+async function requireDraftToReset(
payload: Awaited>['payload'],
user: Awaited>['user'],
articleId: number,
- verb: string,
): Promise {
const { status } = await payload.findByID({
collection: 'articles',
@@ -97,7 +74,12 @@ async function requireApprovedBrief(
overrideAccess: false,
user,
})
- if (NO_APPROVED_BRIEF.includes(status)) throw new Error(noApprovedBrief(verb))
+ if (NO_APPROVED_BRIEF.includes(status)) throw new Error(noApprovedBrief('reset'))
+ if (status === NOT_DRAFTED_YET) {
+ throw new Error(
+ 'This article has not been drafted yet, so there is nothing to reset. Run the next stage to write it.',
+ )
+ }
}
function revalidateOps(articleId?: number | string) {
@@ -240,95 +222,113 @@ async function currentInformationGainRun(
return docs[0] ?? null
}
-export async function assignTemplateAction(articleId: number, templateId: number) {
- const { payload, user } = await requireUser('Unauthorized')
- await payload.update({
- collection: 'articles',
- id: articleId,
- data: { template: templateId },
- context: auditContext(user, 'template_assigned', 'Template assigned', { templateId }),
- user,
- overrideAccess: false,
+/**
+ * Every action below answers `{ ok: true, ... } | { ok: false, error }` (see
+ * `actionResult.ts`): a thrown server-action error is redacted in a production
+ * build, and the refusals here — a gate's explanation, an active run, a missing
+ * justification — are exactly what the reviewer has to read.
+ */
+export async function assignTemplateAction(
+ articleId: number,
+ templateId: number,
+): Promise {
+ return attempt('Could not assign the template.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: { template: templateId },
+ context: auditContext(user, 'template_assigned', 'Template assigned', { templateId }),
+ user,
+ overrideAccess: false,
+ })
+ revalidateOps(articleId)
+ return {}
})
- revalidateOps(articleId)
}
export async function resetToDraftedAction(
articleId: number,
reviewNotes?: string,
options?: ReviewActionOptions,
-): Promise {
- const { payload, user } = await requireUser('Unauthorized')
- await requireApprovedBrief(payload, user, articleId, 'reset')
- const updated = await payload.update({
- collection: 'articles',
- id: articleId,
- data: {
- status: 'drafted' satisfies ArticleStatus,
- reviewNotes: reviewNotes?.trim() || null,
- reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
- qaResults: NULL_QA_RESULTS,
- informationGain: NULL_INFORMATION_GAIN,
- ...CLEARED_SCHEDULE,
- },
- context: auditContext(user, 'revision_reset', 'Article reset to drafted', {
- reviewNotes: reviewNotes?.trim() || null,
- ...CLEARED_SCHEDULE,
- }),
- user,
- // See NULL_INFORMATION_GAIN above — required to clear the informationGain group.
- overrideAccess: true,
+): Promise> {
+ return attempt('Could not reset the article.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ await requireDraftToReset(payload, user, articleId)
+ const updated = await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: {
+ status: 'drafted' satisfies ArticleStatus,
+ reviewNotes: reviewNotes?.trim() || null,
+ reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
+ qaResults: NULL_QA_RESULTS,
+ informationGain: NULL_INFORMATION_GAIN,
+ ...CLEARED_SCHEDULE,
+ },
+ context: auditContext(user, 'revision_reset', 'Article reset to drafted', {
+ reviewNotes: reviewNotes?.trim() || null,
+ ...CLEARED_SCHEDULE,
+ }),
+ user,
+ // See NULL_INFORMATION_GAIN above — required to clear the informationGain group.
+ overrideAccess: true,
+ })
+ revalidateOps(articleId)
+ return queueRunAfterRework(payload, user, updated, options)
})
- revalidateOps(articleId)
- return queueRunAfterRework(payload, user, updated, options)
}
export async function approveArticleAction(
articleId: number,
reviewNotes?: string,
-): Promise {
- const { payload, user } = await requireUser('Unauthorized')
- const approved = await payload.update({
- collection: 'articles',
- id: articleId,
- data: {
- status: 'approved' satisfies ArticleStatus,
- reviewNotes: reviewNotes?.trim() || null,
- reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
- },
- context: auditContext(user, 'article_approved', 'Article approved', {
- reviewNotes: reviewNotes?.trim() || null,
- }),
- user,
- overrideAccess: false,
+): Promise> {
+ return attempt('Could not approve the article.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const approved = await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: {
+ status: 'approved' satisfies ArticleStatus,
+ reviewNotes: reviewNotes?.trim() || null,
+ reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
+ },
+ context: auditContext(user, 'article_approved', 'Article approved', {
+ reviewNotes: reviewNotes?.trim() || null,
+ }),
+ user,
+ overrideAccess: false,
+ })
+ revalidateOps(articleId)
+ return { status: approved.status }
})
- revalidateOps(articleId)
- return { status: approved.status }
}
export async function publishArticleAction(
articleId: number,
reviewNotes?: string,
-): Promise {
- const { payload, user } = await requireUser('Unauthorized')
- const published = await payload.update({
- collection: 'articles',
- id: articleId,
- data: {
- status: 'published' satisfies ArticleStatus,
- publishedAt: new Date().toISOString(),
- reviewNotes: reviewNotes?.trim() || null,
- reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
- },
- context: auditContext(user, 'article_published', 'Article published', {
- reviewNotes: reviewNotes?.trim() || null,
- }),
- user,
- overrideAccess: false,
+): Promise> {
+ return attempt('Could not publish the article.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const published = await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: {
+ status: 'published' satisfies ArticleStatus,
+ publishedAt: new Date().toISOString(),
+ reviewNotes: reviewNotes?.trim() || null,
+ reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
+ },
+ context: auditContext(user, 'article_published', 'Article published', {
+ reviewNotes: reviewNotes?.trim() || null,
+ }),
+ user,
+ overrideAccess: false,
+ })
+ revalidatePublishedArticle(published)
+ revalidateOps(articleId)
+ return { status: published.status, slug: published.slug ?? null }
})
- revalidatePublishedArticle(published)
- revalidateOps(articleId)
- return { status: published.status, slug: published.slug ?? null }
}
/**
@@ -351,36 +351,42 @@ export async function publishArticleAction(
* it as UTC and sends an explicit `Z` — the same zone every other timestamp on
* that page is shown in, rather than a zone the reviewer has to infer.
*/
-export async function scheduleArticleAction(articleId: number, publishAt: string) {
- const { payload, user } = await requireUser('Unauthorized')
- const when = new Date(publishAt)
- if (Number.isNaN(when.getTime())) {
- throw new Error('Pick a date and time to schedule this article.')
- }
- if (when.getTime() <= Date.now()) {
- throw new Error('Pick a time in the future to schedule this article.')
- }
- const article = await payload.findByID({
- collection: 'articles',
- id: articleId,
- depth: 0,
- overrideAccess: false,
- user,
- })
- if (article.status !== 'approved') {
- throw new Error('Only an approved article can be scheduled. Approve it first.')
- }
- const iso = when.toISOString()
- await payload.update({
- collection: 'articles',
- id: articleId,
- data: { publishAt: iso },
- context: auditContext(user, 'publish_scheduled', 'Publish scheduled', { publishAt: iso }),
- user,
- overrideAccess: false,
+export async function scheduleArticleAction(
+ articleId: number,
+ publishAt: string,
+): Promise> {
+ return attempt('Could not schedule the article.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const when = new Date(publishAt)
+ if (Number.isNaN(when.getTime())) {
+ throw new Error('Pick a date and time to schedule this article.')
+ }
+ if (when.getTime() <= Date.now()) {
+ throw new Error('Pick a time in the future to schedule this article.')
+ }
+ const article = await payload.findByID({
+ collection: 'articles',
+ id: articleId,
+ depth: 0,
+ select: { status: true },
+ overrideAccess: false,
+ user,
+ })
+ if (article.status !== 'approved') {
+ throw new Error('Only an approved article can be scheduled. Approve it first.')
+ }
+ const iso = when.toISOString()
+ await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: { publishAt: iso },
+ context: auditContext(user, 'publish_scheduled', 'Publish scheduled', { publishAt: iso }),
+ user,
+ overrideAccess: false,
+ })
+ revalidateOps(articleId)
+ return { publishAt: iso }
})
- revalidateOps(articleId)
- return { publishAt: iso }
}
/**
@@ -389,80 +395,98 @@ export async function scheduleArticleAction(articleId: number, publishAt: string
* Answers with the date it took off so the page can offer Undo: the inverse is
* `scheduleArticleAction` with that instant, and nothing else remembers it.
*/
-export async function unscheduleArticleAction(articleId: number) {
- const { payload, user } = await requireUser('Unauthorized')
- const before = await payload.findByID({
- collection: 'articles',
- id: articleId,
- depth: 0,
- overrideAccess: false,
- user,
- })
- await payload.update({
- collection: 'articles',
- id: articleId,
- data: { publishAt: null },
- context: auditContext(user, 'publish_unscheduled', 'Publish schedule cleared'),
- user,
- overrideAccess: false,
+export async function unscheduleArticleAction(
+ articleId: number,
+): Promise> {
+ return attempt('Could not clear the schedule.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const before = await payload.findByID({
+ collection: 'articles',
+ id: articleId,
+ depth: 0,
+ select: { publishAt: true },
+ overrideAccess: false,
+ user,
+ })
+ await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: { publishAt: null },
+ context: auditContext(user, 'publish_unscheduled', 'Publish schedule cleared'),
+ user,
+ overrideAccess: false,
+ })
+ revalidateOps(articleId)
+ return { previousPublishAt: before?.publishAt ?? null }
})
- revalidateOps(articleId)
- return { previousPublishAt: before?.publishAt ?? null }
}
/**
- * Takes a piece off the board without destroying it — see the `archived` field
- * on `Articles.ts` for why a hard delete is not on offer.
+ * Takes a piece off the content list without destroying it — see the `archived`
+ * field on `Articles.ts` for why a hard delete is not on offer.
*
* Refused while a `queued`/`running` run lists the article, through the same
* `activeRunIncludesArticle` the review page and the content list resolve
* "Datum is working on this" with. A run mid-flight writes a status, a body
* and cost rows onto an article the reviewer has just declared dead, and the
* pipeline's own skip (`archived` articles are passed over at selection) does
- * not help a run that already picked this one up. Throwing is right here where
- * the queue helpers merely report: nothing was written, so there is no half of
- * the action to be honest about.
+ * not help a run that already picked this one up. Nothing is written when it
+ * refuses, so there is no half of the action to be honest about.
*
- * No reason is taken. The archive control is a two-click confirm in a row of
- * buttons with nowhere to type one, and a parameter no caller can reach is an
- * audit field that is always null pretending to be a field somebody fills in.
- * Who archived it and when is recorded either way.
+ * Archiving a *published* piece also withdraws it from the public site
+ * (`findPublishedArticle` and the home list skip archived rows), so the cached
+ * page is purged here: ISR would otherwise keep serving it for up to five
+ * minutes. `unarchiveArticleAction` purges it again on the way back.
+ *
+ * No reason is taken. The archive control is a one-click action with an Undo,
+ * and a parameter no caller can reach is an audit field that is always null
+ * pretending to be a field somebody fills in. Who archived it and when is
+ * recorded either way.
*/
-export async function archiveArticleAction(articleId: number) {
- const { payload, user } = await requireUser('Unauthorized')
- if (await activeRunIncludesArticle(payload, user, articleId)) {
- throw new Error(
- 'This article is in an active run. Wait for the run to finish before archiving it.',
- )
- }
- await payload.update({
- collection: 'articles',
- id: articleId,
- data: { archived: true },
- context: auditContext(user, 'article_archived', 'Article archived'),
- user,
- overrideAccess: false,
+export async function archiveArticleAction(articleId: number): Promise {
+ return attempt('Could not archive the article.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ if (await activeRunIncludesArticle(payload, user, articleId)) {
+ throw new Error(
+ 'This article is in an active run. Wait for the run to finish before archiving it.',
+ )
+ }
+ const updated = await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: { archived: true },
+ context: auditContext(user, 'article_archived', 'Article archived'),
+ user,
+ overrideAccess: false,
+ })
+ if (updated.status === 'published') revalidatePublishedArticle(updated)
+ revalidateOps(articleId)
+ return {}
})
- revalidateOps(articleId)
}
/**
- * Puts an archived piece back on the board, at the status it had when it was
- * archived. `gateArchivedStatus` refuses every status change and schedule
- * while a piece is archived, so this is the one door out of that state; the
- * status panel for wherever it lands takes over from there.
+ * Puts an archived piece back on the content list, at the status it had when
+ * it was archived (a published one is public again). `gateArchivedStatus`
+ * refuses every status change and schedule while a piece is archived, so this
+ * is the one door out of that state; the status panel for wherever it lands
+ * takes over from there.
*/
-export async function unarchiveArticleAction(articleId: number) {
- const { payload, user } = await requireUser('Unauthorized')
- await payload.update({
- collection: 'articles',
- id: articleId,
- data: { archived: false },
- context: auditContext(user, 'article_unarchived', 'Article unarchived'),
- user,
- overrideAccess: false,
+export async function unarchiveArticleAction(articleId: number): Promise {
+ return attempt('Could not unarchive the article.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const updated = await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: { archived: false },
+ context: auditContext(user, 'article_unarchived', 'Article unarchived'),
+ user,
+ overrideAccess: false,
+ })
+ if (updated.status === 'published') revalidatePublishedArticle(updated)
+ revalidateOps(articleId)
+ return {}
})
- revalidateOps(articleId)
}
/**
@@ -481,49 +505,52 @@ export async function sendBackAction(
articleId: number,
reviewNotes: string,
reasonCode?: SendBackReasonCode,
-) {
- const { payload, user } = await requireUser('Unauthorized')
- const note = reviewNotes.trim()
- if (!note) {
- throw new Error('Say why this is going back — the writer reads it.')
- }
- if (reasonCode !== undefined && !isSendBackReasonCode(reasonCode)) {
- throw new Error('Unknown send-back reason.')
- }
- await payload.update({
- collection: 'articles',
- id: articleId,
- data: {
- status: 'needs_revision' satisfies ArticleStatus,
- reviewNotes: note,
- reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
- qaResults: {
- structural: { passed: true, violations: [] },
- factCheck: { passed: true, notes: 'OK' },
- qualitativeReview: {
- passed: false,
- notes: note,
- voiceScore: null,
- voiceNotes: null,
- notTraitViolations: [],
+): Promise {
+ return attempt('Could not send the article back.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const note = reviewNotes.trim()
+ if (!note) {
+ throw new Error('Say why this is going back — the writer reads it.')
+ }
+ if (reasonCode !== undefined && !isSendBackReasonCode(reasonCode)) {
+ throw new Error('Unknown send-back reason.')
+ }
+ await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: {
+ status: 'needs_revision' satisfies ArticleStatus,
+ reviewNotes: note,
+ reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
+ qaResults: {
+ structural: { passed: true, violations: [] },
+ factCheck: { passed: true, notes: 'OK' },
+ qualitativeReview: {
+ passed: false,
+ notes: note,
+ voiceScore: null,
+ voiceNotes: null,
+ notTraitViolations: [],
+ },
+ // An omitted group is refilled from the stored document, so the old
+ // draft's evidence verdict has to be cleared by name.
+ evidenceCheck: NULL_QA_RESULTS.evidenceCheck,
},
- // An omitted group is refilled from the stored document, so the old
- // draft's evidence verdict has to be cleared by name.
- evidenceCheck: NULL_QA_RESULTS.evidenceCheck,
+ informationGain: NULL_INFORMATION_GAIN,
+ ...CLEARED_SCHEDULE,
},
- informationGain: NULL_INFORMATION_GAIN,
- ...CLEARED_SCHEDULE,
- },
- context: auditContext(user, 'article_sent_back', 'Article sent back for revision', {
- reviewNotes: note,
- reasonCode: reasonCode ?? null,
- ...CLEARED_SCHEDULE,
- }),
- user,
- // See NULL_INFORMATION_GAIN above — required to clear the informationGain group.
- overrideAccess: true,
+ context: auditContext(user, 'article_sent_back', 'Article sent back for revision', {
+ reviewNotes: note,
+ reasonCode: reasonCode ?? null,
+ ...CLEARED_SCHEDULE,
+ }),
+ user,
+ // See NULL_INFORMATION_GAIN above — required to clear the informationGain group.
+ overrideAccess: true,
+ })
+ revalidateOps(articleId)
+ return {}
})
- revalidateOps(articleId)
}
/**
@@ -535,52 +562,60 @@ export async function sendBackAction(
* `gateVerifiedStatus` requires that same freshness before it will allow
* `verified` for an article that never earned a `PASS`. Neither hook is
* bypassed by anything here: this call uses `overrideAccess: false`, same as
- * every other reviewer action, and simply lets the hooks' `APIError` propagate
- * to the caller — catching and re-wrapping it would strip the message the
- * gate wrote explaining *why* the override was refused (e.g. a stale or
- * missing justification), which is the one thing the reviewer needs to see.
+ * every other reviewer action. The hooks' `APIError` is returned as
+ * `{ ok: false, error }` with its message intact — re-wording it would strip
+ * the explanation of *why* the override was refused (e.g. a stale or missing
+ * justification), which is the one thing the reviewer needs to see.
*/
-export async function overrideReviewAction(articleId: number, justification: string) {
- const { payload, user } = await requireUser('Unauthorized')
- const trimmed = justification.trim()
- if (!trimmed) {
- throw new Error('A justification is required to override this decision')
- }
- const article = await payload.findByID({
- collection: 'articles',
- id: articleId,
- overrideAccess: false,
- user,
- })
- const from = article.status
- // The gates only judge a move out of these two statuses. From anywhere else
- // (a stale page on an article someone already overrode, say) they let the
- // write through, and the audit row below would record an override that did
- // not happen.
- if (!OVERRIDABLE_STATUSES.includes(from as (typeof OVERRIDABLE_STATUSES)[number])) {
- throw new Error('Only an article in Needs review or Blocked can be overridden.')
- }
- const runId = (await currentInformationGainRun(payload, article, user))?.id ?? null
- await payload.update({
- collection: 'articles',
- id: articleId,
- data: {
- status: 'verified' satisfies ArticleStatus,
- reviewJustification: trimmed,
- reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
- },
- context: auditContext(
+export async function overrideReviewAction(
+ articleId: number,
+ justification: string,
+): Promise {
+ return attempt('Could not override this decision.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const trimmed = justification.trim()
+ if (!trimmed) {
+ throw new Error('A justification is required to override this decision')
+ }
+ const article = await payload.findByID({
+ collection: 'articles',
+ id: articleId,
+ depth: 0,
+ select: { status: true, informationGain: { run: true } },
+ overrideAccess: false,
user,
- from === 'blocked' ? 'block_overridden' : 'review_overridden',
- from === 'blocked'
- ? 'Reviewer overrode blocked to verified'
- : 'Reviewer overrode needs_review to verified',
- { justification: trimmed, runId },
- ),
- user,
- overrideAccess: false,
+ })
+ const from = article.status
+ // The gates only judge a move out of these two statuses. From anywhere else
+ // (a stale page on an article someone already overrode, say) they let the
+ // write through, and the audit row below would record an override that did
+ // not happen.
+ if (!OVERRIDABLE_STATUSES.includes(from as (typeof OVERRIDABLE_STATUSES)[number])) {
+ throw new Error('Only an article in Needs review or Blocked can be overridden.')
+ }
+ const runId = (await currentInformationGainRun(payload, article, user))?.id ?? null
+ await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: {
+ status: 'verified' satisfies ArticleStatus,
+ reviewJustification: trimmed,
+ reviewedBy: typeof user.email === 'string' ? user.email : String(user.id),
+ },
+ context: auditContext(
+ user,
+ from === 'blocked' ? 'block_overridden' : 'review_overridden',
+ from === 'blocked'
+ ? 'Reviewer overrode blocked to verified'
+ : 'Reviewer overrode needs_review to verified',
+ { justification: trimmed, runId },
+ ),
+ user,
+ overrideAccess: false,
+ })
+ revalidateOps(articleId)
+ return {}
})
- revalidateOps(articleId)
}
/**
@@ -596,38 +631,49 @@ export async function regenerateArticleAction(
articleId: number,
note?: string,
options?: ReviewActionOptions,
-): Promise {
- const { payload, user } = await requireUser('Unauthorized')
- const article = await payload.findByID({
- collection: 'articles',
- id: articleId,
- overrideAccess: false,
- user,
- })
- if (NO_APPROVED_BRIEF.includes(article.status)) throw new Error(noApprovedBrief('regenerated'))
- const run = await currentInformationGainRun(payload, article, user)
- const revisionNotes = buildRegenerateRevisionNotes(run, article, note)
- const updated = await payload.update({
- collection: 'articles',
- id: articleId,
- data: {
- status: 'researched' satisfies ArticleStatus,
- revisionNotes,
- revisionCount: (article.revisionCount ?? 0) + 1,
- qaResults: NULL_QA_RESULTS,
- informationGain: NULL_INFORMATION_GAIN,
- ...CLEARED_SCHEDULE,
- },
- context: auditContext(
+): Promise> {
+ return attempt('Could not regenerate the article.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const article = await payload.findByID({
+ collection: 'articles',
+ id: articleId,
+ depth: 0,
+ select: {
+ status: true,
+ qaResults: true,
+ revisionCount: true,
+ informationGain: { run: true },
+ },
+ overrideAccess: false,
user,
- 'article_regenerate_requested',
- 'Article sent back for regeneration',
- { note: note?.trim() || null, runId: run?.id ?? null, ...CLEARED_SCHEDULE },
- ),
- user,
- // See NULL_INFORMATION_GAIN above — required to clear the informationGain group.
- overrideAccess: true,
+ })
+ if (NO_APPROVED_BRIEF.includes(article.status)) {
+ throw new Error(noApprovedBrief('regenerated'))
+ }
+ const run = await currentInformationGainRun(payload, article, user)
+ const revisionNotes = buildRegenerateRevisionNotes(run, article, note)
+ const updated = await payload.update({
+ collection: 'articles',
+ id: articleId,
+ data: {
+ status: 'researched' satisfies ArticleStatus,
+ revisionNotes,
+ revisionCount: (article.revisionCount ?? 0) + 1,
+ qaResults: NULL_QA_RESULTS,
+ informationGain: NULL_INFORMATION_GAIN,
+ ...CLEARED_SCHEDULE,
+ },
+ context: auditContext(
+ user,
+ 'article_regenerate_requested',
+ 'Article sent back for regeneration',
+ { note: note?.trim() || null, runId: run?.id ?? null, ...CLEARED_SCHEDULE },
+ ),
+ user,
+ // See NULL_INFORMATION_GAIN above — required to clear the informationGain group.
+ overrideAccess: true,
+ })
+ revalidateOps(articleId)
+ return queueRunAfterRework(payload, user, updated, options)
})
- revalidateOps(articleId)
- return queueRunAfterRework(payload, user, updated, options)
}
diff --git a/cms/src/components/ops/articleReset.ts b/cms/src/components/ops/articleReset.ts
new file mode 100644
index 0000000..fd0364e
--- /dev/null
+++ b/cms/src/components/ops/articleReset.ts
@@ -0,0 +1,39 @@
+/**
+ * What the actions that throw a draft away write to the article.
+ *
+ * Here rather than in `actions.ts` because a `'use server'` module may export
+ * only async functions, and `briefActions.ts` (revisiting a brief) clears the
+ * same fields as reset and regenerate do.
+ */
+
+export const NULL_QA_RESULTS = {
+ structural: { passed: null, violations: null },
+ factCheck: { passed: null, notes: null, sources: null },
+ qualitativeReview: {
+ passed: null,
+ notes: null,
+ voiceScore: null,
+ voiceNotes: null,
+ notTraitViolations: null,
+ },
+ // Without this the evidence verdict of the draft being thrown away stays on
+ // the article, and the review page shows it against text QA has not seen.
+ evidenceCheck: { passed: null, notes: null, claims: null },
+} as const
+
+/**
+ * What every action that moves an article off `approved` writes to `publishAt`.
+ *
+ * A schedule is inert on any other status, which made leaving it in place look
+ * free — and it is, right up to the moment the piece is approved a second
+ * time. Then the five-minute `publish-due` tick finds a date that passed days
+ * ago, publishes immediately, and the reviewer who had not finished looking at
+ * the draft gets no say and no explanation. Taking the date back at the moment
+ * it stops applying is the only point where the intent is unambiguous: the
+ * person sending this piece back has just said it is not ready to go out.
+ *
+ * The audit details record the write (`publishAt: null`) the same way they
+ * already record `reviewNotes` — what the action wrote, not a claim about what
+ * was there before.
+ */
+export const CLEARED_SCHEDULE = { publishAt: null } as const
diff --git a/cms/src/components/ops/boardActions.ts b/cms/src/components/ops/boardActions.ts
index e58688a..dffdf74 100644
--- a/cms/src/components/ops/boardActions.ts
+++ b/cms/src/components/ops/boardActions.ts
@@ -1,15 +1,17 @@
'use server'
import { revalidatePath } from 'next/cache'
+import { createLocalReq } from 'payload'
import { optionalUser, requireUser } from '../../lib/requireUser'
-import { activeRunIdForArticles } from '../../lib/activeRuns'
+import { ACTIVE_RUN_STATUSES, activeRunIdForArticles } from '../../lib/activeRuns'
import { ActivePipelineRunError } from '../../lib/createPipelineRun'
import { errorMessage } from '../../lib/errorMessage'
import { loadWorkspaceSetup } from '../../lib/loadWorkspaceReadiness'
-import { stageKpis } from '../../lib/opsKpis'
+import { loadReportCosts } from '../../lib/reportQueries'
import { gateRunReadiness, queueRunForArticles } from '../../lib/queueRunForArticles'
+import type { Article } from '../../payload-types'
import { type RunActivityDTO, type RunStatusDTO, toRunFailures } from './boardTypes'
const BOARD_PATH = '/admin/ops/content'
@@ -34,7 +36,7 @@ export async function runSelectedArticlesAction(input: {
confirmLiveCost?: boolean
}): Promise {
try {
- const { payload, user } = await requireUser('Sign in to manage the board.')
+ const { payload, user } = await requireUser('Sign in to manage the content list.')
const ids = [...new Set(input.articleIds)].filter((id) => Number.isFinite(id) && id > 0)
if (ids.length === 0) return { ok: false, error: 'Pick at least one article to run.' }
@@ -49,8 +51,11 @@ export async function runSelectedArticlesAction(input: {
pagination: false,
limit: ids.length,
depth: 0,
+ // Exactly what `queueRunForArticles` reads from each article; keep the two
+ // in step. The rest of an article (research, draft, scorecards) is large.
+ select: { status: true, archived: true, template: true },
})
- const { runId } = await queueRunForArticles(payload, user, docs, readiness)
+ const { runId } = await queueRunForArticles(payload, user, docs as Article[], readiness)
return {
ok: true,
message: `Started a run for ${plural(docs.length, 'article')}. Progress shows in the run bar.`,
@@ -81,7 +86,7 @@ export async function runSelectedArticlesAction(input: {
*/
export async function removeTopicsAction(articleIds: number[]): Promise {
try {
- const { payload, user } = await requireUser('Sign in to manage the board.')
+ const { payload, user } = await requireUser('Sign in to manage the content list.')
const ids = [...new Set(articleIds)].filter((id) => Number.isFinite(id) && id > 0)
if (ids.length === 0) return { ok: false, error: 'Pick at least one topic to remove.' }
@@ -91,6 +96,7 @@ export async function removeTopicsAction(articleIds: number[]): Promise doc.status !== 'topic_selected')
if (started.length > 0) {
@@ -141,15 +147,41 @@ export async function removeTopicsAction(articleIds: number[]): Promise {
// and polls this. Signed out there is simply no run to show.
const { payload, user } = await optionalUser()
if (!user) return null
- const { docs } = await payload.find({
+ const { docs: activeRuns } = await payload.find({
collection: 'pipeline-runs',
+ where: { status: { in: [...ACTIVE_RUN_STATUSES] } },
user,
overrideAccess: false,
- select: {
- runId: true,
- status: true,
- mode: true,
- source: true,
- startedAt: true,
- createdAt: true,
- completedAt: true,
- articles: true,
- finalStatuses: true,
- warnings: true,
- errorSummary: true,
- },
- sort: '-createdAt',
- limit: 1,
+ select: RUN_SELECT,
+ sort: 'createdAt',
+ limit: ACTIVE_RUNS_READ,
+ pagination: false,
depth: 0,
})
- const run = docs[0]
+ const run =
+ activeRuns.find((r) => r.status === 'running') ??
+ activeRuns[0] ??
+ (
+ await payload.find({
+ collection: 'pipeline-runs',
+ user,
+ overrideAccess: false,
+ select: RUN_SELECT,
+ sort: '-createdAt',
+ limit: 1,
+ depth: 0,
+ })
+ ).docs[0]
if (!run) return null
const started = run.startedAt ?? run.createdAt
- // Only while it matters: a settled run's articles are already on the board,
- // and this action is polled from every admin page.
+ // Only while it matters: a settled run's articles are already on the
+ // content list, and this action is polled from every admin page.
const active = run.status === 'queued' || run.status === 'running'
const ids = Array.isArray(run.articles)
? run.articles.flatMap((a) => (typeof a === 'number' ? [a] : a?.id ? [a.id] : []))
: []
- const [found, calls] = await Promise.all([
+ const [found, totals, latest] = await Promise.all([
active && ids.length > 0
? payload.find({
collection: 'articles',
@@ -205,15 +240,19 @@ export async function latestRunAction(): Promise {
overrideAccess: false,
})
: null,
+ // Totals come from SQL: a long run writes more cost rows than any read
+ // limit, and a capped sum quietly stops rising.
+ active
+ ? loadReportCosts(await createLocalReq({ user }, payload), { pipelineRunId: run.runId })
+ : null,
active
? payload.find({
collection: 'cost-log',
where: { pipelineRunId: { equals: run.runId } },
sort: '-createdAt',
- pagination: false,
- limit: 500,
+ limit: 1,
depth: 0,
- select: { stage: true, costUsd: true, createdAt: true },
+ select: { stage: true, createdAt: true },
user,
overrideAccess: false,
})
@@ -223,16 +262,14 @@ export async function latestRunAction(): Promise {
found?.docs.map((d) => ({ id: d.id, keyword: d.keyword, status: d.status })) ?? []
let activity: RunActivityDTO | null = null
- if (calls) {
- const perStage = stageKpis(calls.docs)
- const totalCostUsd = perStage.reduce((sum, s) => sum + s.costUsd, 0)
- const latest = calls.docs[0]
+ if (totals) {
+ const last = latest?.docs[0]
activity = {
- totalCalls: calls.docs.length,
- totalCostUsd,
- byStage: perStage.map(({ stage, calls: n, costUsd }) => ({ stage, calls: n, costUsd })),
- lastCallStage: latest?.stage ?? null,
- lastCallAtIso: latest?.createdAt ? new Date(latest.createdAt).toISOString() : null,
+ totalCalls: totals.aggregate.rowCount,
+ totalCostUsd: totals.aggregate.totalUsd,
+ byStage: totals.stages.map(({ stage, calls, costUsd }) => ({ stage, calls, costUsd })),
+ lastCallStage: last?.stage ?? null,
+ lastCallAtIso: last?.createdAt ? new Date(last.createdAt).toISOString() : null,
}
}
return {
@@ -247,6 +284,7 @@ export async function latestRunAction(): Promise {
articles,
completedAtIso: run.completedAt ? new Date(run.completedAt).toISOString() : null,
activity,
+ activeRunIds: activeRuns.map((r) => r.runId),
finalStatuses:
run.finalStatuses &&
typeof run.finalStatuses === 'object' &&
diff --git a/cms/src/components/ops/boardTypes.ts b/cms/src/components/ops/boardTypes.ts
index 01085a3..43078e6 100644
--- a/cms/src/components/ops/boardTypes.ts
+++ b/cms/src/components/ops/boardTypes.ts
@@ -54,6 +54,9 @@ export const CALL_LABELS: Record = {
evidenceVerification: 'Hunting evidence for new claims',
evidenceCheck: 'Checking company claims against the evidence bank',
briefAngle: 'Proposing angles for the brief',
+ brandVoiceExtract: 'Extracting a brand voice from your samples',
+ setupAssist: 'Suggesting workspace setup',
+ topicRelevance: 'Judging whether a topic fits your workspace',
}
/** `claimExtraction` means different work depending on where the article is. */
@@ -66,6 +69,14 @@ export function callLabel(stage: string, articleStatus: string | null): string {
return CALL_LABELS[stage] ?? stage
}
+/**
+ * A cost-log stage for a report that adds up a whole workspace: there is no
+ * article status to tell the two `claimExtraction` jobs apart, so it names both.
+ */
+export function costStageLabel(stage: string): string {
+ return stage === 'claimExtraction' ? 'Extracting claims' : callLabel(stage, null)
+}
+
/** LLM work recorded against a run so far — the "is it stuck?" answer. */
export type RunActivityDTO = {
totalCalls: number
@@ -75,6 +86,11 @@ export type RunActivityDTO = {
lastCallAtIso: string | null
}
+/** Runs queued or running besides the one the bar is showing. */
+export function otherActiveRuns(run: Pick): number {
+ return run.activeRunIds.filter((id) => id !== run.runId).length
+}
+
/** Mean completion across a run's articles, 0–1. Settled articles count as done. */
export function runProgress(articles: RunArticleDTO[]): number {
if (articles.length === 0) return 0
@@ -102,6 +118,12 @@ export type RunStatusDTO = {
completedAtIso: string | null
/** Populated while in flight, so the bar can say what the model is doing. */
activity: RunActivityDTO | null
+ /**
+ * Every queued or running run, oldest first. This run is one of them while it
+ * is active; the rest are waiting behind it, and the bar says so and refreshes
+ * the page when any of them settles.
+ */
+ activeRunIds: string[]
/** `{ verified: 2, needs_revision: 1 }` — what the run actually achieved. */
finalStatuses: Record
failures: RunFailureDTO[]
diff --git a/cms/src/components/ops/brandVoiceActions.ts b/cms/src/components/ops/brandVoiceActions.ts
index b76ddcb..041e2d9 100644
--- a/cms/src/components/ops/brandVoiceActions.ts
+++ b/cms/src/components/ops/brandVoiceActions.ts
@@ -17,6 +17,7 @@ import {
} from '../../lib/brandVoiceExtract'
import { detectKind, extractText, UnsupportedUploadError } from '../../lib/extractText'
import type { LlmSettingsDoc } from '../../lib/llmSettings'
+import { attempt, type ActionResult } from './actionResult'
import type { BrandVoiceInput } from './brandVoiceTypes'
const VIEW_PATH = '/admin/ops/setup/brand-voice'
@@ -32,54 +33,63 @@ function toData(input: BrandVoiceInput) {
}
}
+/**
+ * Create, save, archive and delete answer `{ ok: true, ... } | { ok: false,
+ * error }` (see `actionResult.ts`): a thrown server-action error is redacted
+ * in a production build, and the editor has to show why a write was refused.
+ */
export async function createBrandVoiceDraftAction(
input: BrandVoiceInput,
-): Promise<{ id: number; updatedAt: string; saved: BrandVoiceContent }> {
- const { payload, user } = await requireUser('Unauthorized')
- const doc = await payload.create({
- collection: 'brand-voices',
- data: { ...toData(input), status: 'draft', source: 'onboarding' },
- context: governanceAuditContext(user, 'brand_voice_created', 'Onboarding started', {
- step: input.onboardingStep ?? 0,
- }),
- user,
- overrideAccess: false,
+): Promise> {
+ return attempt('Could not start the brand voice.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const doc = await payload.create({
+ collection: 'brand-voices',
+ data: { ...toData(input), status: 'draft', source: 'onboarding' },
+ context: governanceAuditContext(user, 'brand_voice_created', 'Onboarding started', {
+ step: input.onboardingStep ?? 0,
+ }),
+ user,
+ overrideAccess: false,
+ })
+ revalidatePath(VIEW_PATH)
+ return { id: doc.id, updatedAt: doc.updatedAt, saved: brandVoiceContentOf(doc) }
})
- revalidatePath(VIEW_PATH)
- return { id: doc.id, updatedAt: doc.updatedAt, saved: brandVoiceContentOf(doc) }
}
export async function saveBrandVoiceDraftAction(
id: number,
input: BrandVoiceInput,
suggestionId?: number,
-): Promise<{ updatedAt: string; saved: BrandVoiceContent }> {
- const { payload, user } = await requireUser('Unauthorized')
- const doc = await payload.update({
- collection: 'brand-voices',
- id,
- data: toData(input),
- context: governanceAuditContext(user, 'brand_voice_updated', 'Brand voice saved', {
- step: input.onboardingStep ?? null,
- }),
- user,
- overrideAccess: false,
+): Promise> {
+ return attempt('Could not save the brand voice.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const doc = await payload.update({
+ collection: 'brand-voices',
+ id,
+ data: toData(input),
+ context: governanceAuditContext(user, 'brand_voice_updated', 'Brand voice saved', {
+ step: input.onboardingStep ?? null,
+ }),
+ user,
+ overrideAccess: false,
+ })
+ await completeSuggestionAfterEdit(payload, user, suggestionId, 'brand-voice')
+ revalidatePath(VIEW_PATH)
+ revalidatePath('/admin/ops/setup')
+ // The editor tags its local copy with this, so an edit made after this
+ // save is not mistaken for one made before someone else's. `saved` is the
+ // content as stored (a blank name is "Untitled brand voice"), the same
+ // reading the page takes of it.
+ return { updatedAt: doc.updatedAt, saved: brandVoiceContentOf(doc) }
})
- await completeSuggestionAfterEdit(payload, user, suggestionId, 'brand-voice')
- revalidatePath(VIEW_PATH)
- revalidatePath('/admin/ops/setup')
- // The editor tags its local copy with this, so an edit made after this
- // save is not mistaken for one made before someone else's. `saved` is the
- // content as stored (a blank name is "Untitled brand voice"), the same
- // reading the page takes of it.
- return { updatedAt: doc.updatedAt, saved: brandVoiceContentOf(doc) }
}
export async function activateBrandVoiceAction(
id: number,
): Promise<{ ok: true } | { ok: false; error: string }> {
- const { payload, user } = await requireUser('Unauthorized')
try {
+ const { payload, user } = await requireUser('Unauthorized')
await payload.update({
collection: 'brand-voices',
id,
@@ -95,17 +105,20 @@ export async function activateBrandVoiceAction(
return { ok: true }
}
-export async function archiveBrandVoiceAction(id: number): Promise {
- const { payload, user } = await requireUser('Unauthorized')
- await payload.update({
- collection: 'brand-voices',
- id,
- data: { status: 'archived' },
- context: governanceAuditContext(user, 'brand_voice_archived', 'Brand voice archived'),
- user,
- overrideAccess: false,
+export async function archiveBrandVoiceAction(id: number): Promise {
+ return attempt('Could not archive the brand voice.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ await payload.update({
+ collection: 'brand-voices',
+ id,
+ data: { status: 'archived' },
+ context: governanceAuditContext(user, 'brand_voice_archived', 'Brand voice archived'),
+ user,
+ overrideAccess: false,
+ })
+ revalidatePath(VIEW_PATH)
+ return {}
})
- revalidatePath(VIEW_PATH)
}
/** Canonical mimetypes accepted by the `brand-voice-files` upload collection. */
@@ -126,6 +139,14 @@ export type UploadExtractResult =
export async function extractBrandVoiceFromUploadAction(
formData: FormData,
): Promise {
+ try {
+ return await extractFromUpload(formData)
+ } catch (e) {
+ return { ok: false, error: errorMessage(e, 'Brand voice extraction failed') }
+ }
+}
+
+async function extractFromUpload(formData: FormData): Promise {
const { payload, user } = await requireUser('Unauthorized')
const file = formData.get('file')
if (!(file instanceof File) || file.size === 0) {
@@ -214,18 +235,22 @@ export async function extractBrandVoiceFromUploadAction(
return { ok: true, id: doc.id, warnings }
}
-export async function deleteDraftAction(id: number): Promise {
- const { payload, user } = await requireUser('Unauthorized')
- const doc = await payload.findByID({
- collection: 'brand-voices',
- id,
- depth: 0,
- user,
- overrideAccess: false,
+export async function deleteDraftAction(id: number): Promise {
+ return attempt('Could not delete the draft.', async () => {
+ const { payload, user } = await requireUser('Unauthorized')
+ const doc = await payload.findByID({
+ collection: 'brand-voices',
+ id,
+ depth: 0,
+ select: { status: true },
+ user,
+ overrideAccess: false,
+ })
+ if (doc.status !== 'draft') {
+ throw new Error('Only drafts can be deleted. Archive an active brand voice instead.')
+ }
+ await payload.delete({ collection: 'brand-voices', id, user, overrideAccess: false })
+ revalidatePath(VIEW_PATH)
+ return {}
})
- if (doc.status !== 'draft') {
- throw new Error('Only drafts can be deleted. Archive an active brand voice instead.')
- }
- await payload.delete({ collection: 'brand-voices', id, user, overrideAccess: false })
- revalidatePath(VIEW_PATH)
}
diff --git a/cms/src/components/ops/briefActions.ts b/cms/src/components/ops/briefActions.ts
index 24ce4ce..2d34ee0 100644
--- a/cms/src/components/ops/briefActions.ts
+++ b/cms/src/components/ops/briefActions.ts
@@ -4,6 +4,8 @@ import { revalidatePath } from 'next/cache'
import { errorMessage } from '../../lib/errorMessage'
import { requireUser } from '../../lib/requireUser'
+import { activeRunIdForArticles } from '../../lib/activeRuns'
+import { CLEARED_INFORMATION_GAIN } from '../../lib/articleReviewGate'
import { ActivePipelineRunError, ArticleInActiveRunError } from '../../lib/createPipelineRun'
import {
type IcpOption,
@@ -11,6 +13,7 @@ import {
loadWorkspaceSetup,
} from '../../lib/loadWorkspaceReadiness'
import { gateRunReadiness, queueRunForArticles } from '../../lib/queueRunForArticles'
+import { CLEARED_SCHEDULE, NULL_QA_RESULTS } from './articleReset'
export type BriefActionResult =
| {
@@ -89,17 +92,38 @@ function resolveAudience(
return untouched && nextLine ? nextLine : edits.audience
}
-/** Save edits to a brief that is waiting for approval. */
+const BRIEF_CHANGED_ELSEWHERE =
+ 'Someone else saved this brief since you opened it. Reload to see their changes.'
+
+/**
+ * Save edits to a brief that is waiting for approval.
+ *
+ * `loadedUpdatedAt` is the article's `updatedAt` as the editor last saw it.
+ * The save replaces the whole brief, so without this check a colleague's
+ * edit (or an accepted suggestion) made after the page loaded is silently
+ * overwritten. `null` means the caller has no version to compare.
+ */
export async function saveBriefAction(
articleId: number,
edits: BriefEdits,
+ loadedUpdatedAt: string | null,
): Promise {
try {
const { payload, user } = await requireUser('Sign in to work on a brief.')
- const article = await payload.findByID({ collection: 'articles', id: articleId, depth: 0 })
+ const article = await payload.findByID({
+ collection: 'articles',
+ id: articleId,
+ depth: 0,
+ select: { status: true, brief: true, icp: true, updatedAt: true },
+ })
if (article.status !== 'brief_review') {
return { ok: false, error: 'This brief has already been approved; the piece has moved on.' }
}
+ // 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)
const icps = await loadActiveAudienceOptions(payload, user)
const previousIcpId = icpIdOf(article.icp)
@@ -165,7 +189,12 @@ export async function approveBriefAction(
): Promise {
try {
const { payload, user } = await requireUser('Sign in to work on a brief.')
- const article = await payload.findByID({ collection: 'articles', id: articleId, depth: 0 })
+ const article = await payload.findByID({
+ collection: 'articles',
+ id: articleId,
+ depth: 0,
+ select: { status: true, template: true, brief: true, icp: true },
+ })
if (article.status !== 'brief_review') {
return { ok: false, error: 'This brief has already been approved.' }
}
@@ -246,14 +275,30 @@ export async function approveBriefAction(
}
}
+/** Where a draft can be sent back to its brief from: a reviewer is already the one acting. */
+const REVISITABLE_STATUSES = ['needs_revision', 'needs_review', 'blocked'] as const
+
/**
* Send a piece back to its brief. For when the draft is wrong because the
* *angle* was wrong — rewriting against the same brief would repeat it.
+ *
+ * Only from the three statuses that wait on a reviewer, and never while a run
+ * is carrying the piece (it would write over the reopened brief). The draft is
+ * going to be rewritten after the brief is approved, so everything that
+ * described it goes too: the schedule, the regeneration notes, the QA
+ * verdicts and the information-gain decision. `informationGain` is an
+ * access-guarded group, hence `overrideAccess: true` — the same fixed all-null
+ * payload `actions.ts` writes, and the status gates still run.
*/
export async function revisitBriefAction(articleId: number): Promise {
try {
const { payload, user } = await requireUser('Sign in to work on a brief.')
- const article = await payload.findByID({ collection: 'articles', id: articleId, depth: 0 })
+ const article = await payload.findByID({
+ collection: 'articles',
+ id: articleId,
+ depth: 0,
+ select: { status: true, brief: true },
+ })
if (article.status === 'brief_review') return { ok: true, message: 'Already at the brief.' }
if (article.status === 'topic_selected') {
return { ok: false, error: 'Research has not run yet, so there is no brief to revisit.' }
@@ -261,22 +306,46 @@ export async function revisitBriefAction(articleId: number): Promise {
+ 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/review/ArchiveAction.tsx b/cms/src/components/ops/review/ArchiveAction.tsx
index 71cff44..6d17178 100644
--- a/cms/src/components/ops/review/ArchiveAction.tsx
+++ b/cms/src/components/ops/review/ArchiveAction.tsx
@@ -2,6 +2,7 @@
import React from 'react'
+import { unwrap } from '../actionResult'
import { archiveArticleAction, unarchiveArticleAction } from '../actions'
import type { ReviewAction } from './useReviewAction'
@@ -17,20 +18,26 @@ import type { ReviewAction } from './useReviewAction'
* the notice (inline chip and toast) carries an Undo that unarchives, and the
* archived panel keeps Unarchive after that. Pressing it also backs out of any
* confirm armed elsewhere on the page.
+ *
+ * A published piece is the exception to "nothing changes": archiving it takes
+ * it off the public site too, so `published` makes the title and notice say
+ * so. Undo still puts it back, on the site as well.
*/
export function ArchiveAction({
action,
archived,
articleId,
+ published = false,
}: {
action: ReviewAction
archived: boolean
articleId: number
+ published?: boolean
}) {
const { armed, disarm, pending, runAction, setNotice } = action
if (archived) {
- return Archived — hidden from the content board.
+ return Archived — hidden from the content list.
}
return (
{
if (armed) disarm()
runAction(async () => {
- await archiveArticleAction(articleId)
- setNotice('Archived — it is off the content board.', {
- label: 'Undo',
- toast: 'Archived',
- run: () => unarchiveArticleAction(articleId),
- done: 'Unarchived — it is back on the content board.',
- })
+ unwrap(await archiveArticleAction(articleId))
+ setNotice(
+ published
+ ? 'Archived — it is off the site and the content list.'
+ : 'Archived — it is off the content list.',
+ {
+ label: 'Undo',
+ toast: 'Archived',
+ run: async () => {
+ unwrap(await unarchiveArticleAction(articleId))
+ },
+ done: published
+ ? 'Unarchived — it is back on the site and the content list.'
+ : 'Unarchived — it is back on the content list.',
+ },
+ )
})
}}
- title="Take this piece off the content board. Nothing is deleted, the audit trail is kept, and Undo puts it back."
+ title={
+ published
+ ? 'Take this piece off the public site and the content list. Nothing is deleted, the audit trail is kept, and Undo puts it back.'
+ : 'Take this piece off the content list. Nothing is deleted, the audit trail is kept, and Undo puts it back.'
+ }
>
Archive
diff --git a/cms/src/components/ops/review/SendBackAction.tsx b/cms/src/components/ops/review/SendBackAction.tsx
index 594c8f9..37210a1 100644
--- a/cms/src/components/ops/review/SendBackAction.tsx
+++ b/cms/src/components/ops/review/SendBackAction.tsx
@@ -2,6 +2,7 @@
import React, { useRef, useState } from 'react'
+import { unwrap } from '../actionResult'
import { sendBackAction } from '../actions'
import { SEND_BACK_REASONS, type SendBackReasonCode } from '../sendBackReasons'
import type { ReviewAction } from './useReviewAction'
@@ -73,7 +74,9 @@ export function SendBackAction({ action, articleId }: { action: ReviewAction; ar
disabled={pending || !ready}
onClick={() => {
disarm()
- runAction(() => sendBackAction(articleId, reason, code ?? undefined))
+ runAction(async () => {
+ unwrap(await sendBackAction(articleId, reason, code ?? undefined))
+ })
}}
>
Confirm: send back
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}
+ 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
-
- Revisit brief
-
+ {confirmRevisit ? (
+ <>
+
+ Confirm: revisit brief
+
+
+ Cancel
+
+ >
+ ) : (
+ arm('revisit')}
+ title="Go back to the brief and change the angle or sections before rewriting"
+ type="button"
+ >
+ Revisit brief
+
+ )}
{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.
+
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
-
-
runAction(async () => {
- const result = await revisitBriefAction(article.id)
- if (!result.ok) throw new Error(result.error)
+ unwrap(await overrideReviewAction(article.id, justification))
})
}
- title="Go back to the brief and change the angle or sections before rewriting"
- type="button"
>
- Revisit brief
+ Override to verified
+ {armed === 'revisit' ? (
+ <>
+ {
+ disarm()
+ runAction(async () => {
+ const result = await revisitBriefAction(article.id)
+ if (!result.ok) throw new Error(result.error)
+ })
+ }}
+ >
+ Confirm: revisit brief
+
+
+ Cancel
+
+ >
+ ) : (
+ arm('revisit')}
+ title="Go back to the brief and change the angle or sections before rewriting"
+ type="button"
+ >
+ Revisit brief
+
+ )}
+ {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/RunNextStagePanel.tsx b/cms/src/components/ops/review/panels/RunNextStagePanel.tsx
index 43074dd..008df01 100644
--- a/cms/src/components/ops/review/panels/RunNextStagePanel.tsx
+++ b/cms/src/components/ops/review/panels/RunNextStagePanel.tsx
@@ -2,6 +2,7 @@
import React, { useState } from 'react'
+import { unwrap } from '../../actionResult'
import { assignTemplateAction } from '../../actions'
import { runSelectedArticlesAction } from '../../boardActions'
import { announceRunQueued } from '../../runQueued'
@@ -94,7 +95,7 @@ export function RunNextStagePanel({
// Skipped when the piece already has this template: each call is a
// second write and a `template_assigned` audit row for no change.
if (status === 'topic_selected' && templateId && Number(templateId) !== article.templateId) {
- await assignTemplateAction(article.id, Number(templateId))
+ unwrap(await assignTemplateAction(article.id, Number(templateId)))
}
const result = await runSelectedArticlesAction({
articleIds: [article.id],
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
-
- 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/components/ops/runQueued.ts b/cms/src/components/ops/runQueued.ts
index d6431e2..ab5e7a4 100644
--- a/cms/src/components/ops/runQueued.ts
+++ b/cms/src/components/ops/runQueued.ts
@@ -33,11 +33,18 @@ const CLOCK_SKEW_MS = 2000
* A polled run that predates the announced action, so it cannot be the run the
* operator just asked for. Matching on the id is exact; the creation time is
* the fallback for call sites whose result does not carry one.
+ *
+ * The bar follows the run that is executing, not the newest one, so a run
+ * queued behind it is announced while an older run is on screen. The
+ * announcement is met as soon as the announced run is among the active ones:
+ * the older run shown is then current, not stale.
*/
export function isStaleRun(
- run: { runId: string; createdAtIso: string },
+ run: { runId: string; createdAtIso: string; activeRunIds?: string[] },
announced: RunQueuedDetail,
): boolean {
- if (announced.runId !== undefined) return run.runId !== announced.runId
+ if (announced.runId !== undefined) {
+ return run.runId !== announced.runId && !(run.activeRunIds ?? []).includes(announced.runId)
+ }
return new Date(run.createdAtIso).getTime() < announced.queuedAt - CLOCK_SKEW_MS
}
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 (
-