Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: auto-review keeps a paused run's verdict, refunds unqueued kickoffs, and pauses on failed generation (#8988)

[._.]/ Adam Eivy0c76887833ae
diff --git a/client/src/components/musicVideo/AutoReviewPanel.jsx b/client/src/components/musicVideo/AutoReviewPanel.jsx
index 6b05082571..18f8c51821 100644
--- a/client/src/components/musicVideo/AutoReviewPanel.jsx
+++ b/client/src/components/musicVideo/AutoReviewPanel.jsx
@@ -160,6 +160,10 @@ export default function AutoReviewPanel({ project, startSec, endSec, rangeValid,
</span>
{active && (
<div className="flex items-center gap-2">
+ {/* After a reload the board may have missed a hand-out: Continue re-derives the step. */}
+ {run.status === 'running' && !autoReview.action && (
+ <button type="button" disabled={busy} onClick={() => autoReview.resume(run.id)} className="flex items-center gap-1 text-port-accent disabled:opacity-50 min-h-[44px] sm:min-h-0"><Play size={12} /> Continue</button>
+ )}
{run.status === 'running'
? <button type="button" disabled={busy} onClick={() => autoReview.stop(run.id)} className="flex items-center gap-1 text-port-warning disabled:opacity-50 min-h-[44px] sm:min-h-0"><Pause size={12} /> Pause</button>
: <button type="button" disabled={busy} onClick={resume} className="flex items-center gap-1 text-port-accent disabled:opacity-50 min-h-[44px] sm:min-h-0"><Play size={12} /> Resume</button>}
diff --git a/server/routes/musicVideoAutoReview.test.js b/server/routes/musicVideoAutoReview.test.js
index 41e0a7d4b6..aebd3a8511 100644
--- a/server/routes/musicVideoAutoReview.test.js
+++ b/server/routes/musicVideoAutoReview.test.js
@@ -76,7 +76,8 @@ vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: v
vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'inst-test') }));
vi.mock('../lib/killWithEscalation.js', () => ({ killWithEscalation: vi.fn((proc) => proc.emit('close', null, 'SIGTERM')) }));
vi.mock('../services/htmlComposition/encode.js', () => ({ encodeFileContactSheetAtTimes: vi.fn(async () => {}) }));
-vi.mock('../services/mediaJobQueue/index.js', () => ({
+vi.mock('../services/mediaJobQueue/index.js', async () => ({
+ mediaJobEvents: new (await import('events')).EventEmitter(),
listJobs: vi.fn(({ kind } = {}) => h.jobs.filter((j) => !kind || j.kind === kind)),
enqueueJob: vi.fn(),
cancelJob: vi.fn(async () => {}),
@@ -102,6 +103,7 @@ const projects = await import('../services/musicVideo/projects.js');
const { assertRevisionOpen } = await import('../services/musicVideo/revisionService.js');
const { musicVideoEvents } = await import('../services/musicVideo/events.js');
const { runPromptThroughProvider } = await import('../services/promptRunner.js');
+const { mediaJobEvents } = await import('../services/mediaJobQueue/index.js');
const app = express();
app.use(express.json());
@@ -250,6 +252,33 @@ describe('opt-in automatic review/retries (#8988)', () => {
expect(h.procs).toHaveLength(2);
});
+ it('refunds a kickoff that never reached the queue, and pauses (not retries) when a revised generation fails', async () => {
+ const p = await project();
+ h.verdicts.push(FAIL_S2);
+ await start(p.id, { maxAttempts: 2, maxGenerations: 2 });
+ await finishDraft(p.id, 1);
+ let current = await settled(p.id, (x) => expect(run(x).attempts[0].revisionId).toBeTruthy());
+ const revisionId = run(current).attempts[0].revisionId;
+ const s2 = { sceneId: 's2', kind: 'video' };
+
+ // The board's kickoff was charged but failed before the queue: releasing
+ // the section returns the generation to the budget.
+ await assertRevisionOpen(p.id, revisionId, s2);
+ expect(run(await projects.getProject(p.id)).usage.generations).toBe(1);
+ await request(app).post(`${base(p.id)}/revisions/${revisionId}/release`).send({ sceneId: 's2' });
+ expect(run(await projects.getProject(p.id)).usage.generations).toBe(0);
+
+ // Resubmitted, queued, and the provider fails it: the run pauses for the
+ // director instead of paying for a retry on its own.
+ await assertRevisionOpen(p.id, revisionId, s2);
+ const job = { id: 'job-s2', kind: 'video', status: 'failed', error: 'provider error', queuedAt: new Date().toISOString(), params: { musicVideo: { projectId: p.id, sceneId: 's2', revisionId } } };
+ mediaJobEvents.emit('failed', job);
+ current = await settled(p.id, (x) => expect(run(x).status).toBe('stopped'));
+ expect(run(current).stopReason).toMatch(/generation failed: provider error/);
+ expect(run(current).usage.generations).toBe(1);
+ expect(current.revisions.find((rv) => rv.id === revisionId).sections.find((s) => s.sceneId === 's2').claimedAt).toBeNull();
+ });
+
it('stops before handing out a revision the remaining spend cannot cover', async () => {
const p = await project();
h.verdicts.push(FAIL_S2);
diff --git a/server/services/musicVideo/autoReview.js b/server/services/musicVideo/autoReview.js
index 09c52f55a5..a5c286e42b 100644
--- a/server/services/musicVideo/autoReview.js
+++ b/server/services/musicVideo/autoReview.js
@@ -54,6 +54,9 @@ export const AUTO_REVIEW_CHECKS = Object.freeze(['composition', 'continuity', 'm
// not loop forever: this many failed renders of one attempt fail the run.
const MAX_RENDER_FAILURES = 2;
const MAX_PROJECT_AUTO_REVIEWS = 10;
+// How long a charged submission reserves its section before the job must have
+// reached the queue (a kickoff takes seconds; the live-job check covers the rest).
+const RESERVATION_LEASE_MS = 30_000;
const MAX_FINDINGS = 20;
const MAX_FINDING_LEN = 500;
const NOTE_PREFIX = '[auto-review]';
@@ -68,6 +71,8 @@ export const projectAutoReviews = (project) => (Array.isArray(project?.autoRevie
const activeAutoReview = (project) => projectAutoReviews(project).find((r) => ACTIVE.has(r.status)) || null;
const currentAttempt = (run) => run.attempts[run.attempts.length - 1];
+const liveReservations = (run, nowMs) => (Array.isArray(run.reservations) ? run.reservations : [])
+ .filter((r) => Number.isFinite(nowMs) && nowMs - Date.parse(r.at) < RESERVATION_LEASE_MS);
function findRun(project, runId) {
const run = projectAutoReviews(project).find((r) => r.id === runId);
@@ -166,6 +171,11 @@ export function nextAutoReviewStep(project, run) {
}
return { type: 'review', excerptId: attempt.excerptId };
}
+ // A review recorded while the run was paused keeps its verdict for resume.
+ if (attempt.review.verdict === 'pass') return { type: 'halt', status: 'passed', reason: null };
+ if (attempt.review.verdict !== 'revise') {
+ return { type: 'halt', status: 'needs-human', reason: attempt.review.reason || 'The review could not verify every check — watch this draft yourself' };
+ }
if (!attempt.revisionId) return { type: 'revise', excerptId: attempt.excerptId };
const revision = projectRevisions(project).find((r) => r.id === attempt.revisionId);
if (!revision || revision.status === 'canceled') {
@@ -254,12 +264,15 @@ export function recordAttemptReview(project, runId, review, now = new Date().toI
const findings = (Array.isArray(review.findings) ? review.findings : []).map((f) => cleanFinding(f, spanSec)).filter(Boolean).slice(0, MAX_FINDINGS);
const stored = { ...review, findings, reviewedAt: now };
let next = project;
- if (review.verdict === 'revise' && excerpt) {
+ // A review that returns after the run was paused is still recorded (it was
+ // paid for, and resume continues from it); one that returns after a cancel
+ // is recorded but files nothing and moves no status.
+ if (review.verdict === 'revise' && excerpt && RESUMABLE.has(run.status)) {
for (const finding of findings.filter((f) => f.severity === 'blocking')) {
next = addExcerptNote(next, excerpt.id, { atSec: finding.atSec, note: `${NOTE_PREFIX} ${finding.note}`, verdict: 'flagged' }, now).project;
}
}
- const terminal = review.verdict === 'pass'
+ const terminal = run.status !== 'running' ? {} : review.verdict === 'pass'
? { status: 'passed', stopReason: null }
: review.verdict === 'inconclusive'
? { status: 'needs-human', stopReason: review.reason || 'The review could not verify every check — a director must watch this draft' }
@@ -297,8 +310,8 @@ export function resumeAutoReviewOnProject(project, runId, { limits } = {}, now =
return mutateRun(project, runId, (run) => {
if (!RESUMABLE.has(run.status)) throw autoReviewError(409, 'AUTO_REVIEW_CLOSED', `This run is ${run.status} — start a new run instead`);
const nextLimits = limits ? normalizeAutoReviewLimits({ ...run.limits, ...limits }) : run.limits;
- if (nextLimits.maxAttempts < run.usage.reviews || nextLimits.maxGenerations < run.usage.generations) {
- throw autoReviewError(422, 'VALIDATION_ERROR', 'A limit cannot be lowered below what this run already used');
+ if (nextLimits.maxAttempts < run.limits.maxAttempts || nextLimits.maxGenerations < run.limits.maxGenerations) {
+ throw autoReviewError(422, 'VALIDATION_ERROR', 'Resuming can only raise a limit, never lower it');
}
return { status: 'running', limits: nextLimits, stopReason: null, error: null };
}, now);
@@ -323,13 +336,42 @@ export function cancelAutoReviewOnProject(project, runId, now = new Date().toISO
* Returns `{ project, run }` — `run` null (and the project untouched) when no
* running run owns the revision.
*/
-export function chargeAutoReviewGeneration(project, revisionId, now = new Date().toISOString()) {
+export function chargeAutoReviewGeneration(project, revisionId, { sceneId = null, kind = null } = {}, now = new Date().toISOString()) {
const run = runOwningRevision(project, revisionId);
if (!run) return { project, run: null };
+ const nowMs = Date.parse(now);
+ const reservations = liveReservations(run, nowMs);
+ // A charge RESERVES its section until the job reaches the queue (where the
+ // caller's live-job check takes over), so two overlapping submissions of the
+ // same section can never both be paid for.
+ if (sceneId && reservations.some((r) => r.revisionId === revisionId && r.sceneId === sceneId && r.kind === kind)) {
+ throw autoReviewError(409, 'AUTO_REVIEW_SECTION_IN_FLIGHT', 'This section is already being submitted for the auto-review run', { sceneId });
+ }
if (run.usage.generations >= run.limits.maxGenerations) {
throw autoReviewError(409, 'AUTO_REVIEW_SPEND_LIMIT', `This auto-review run reached its ${run.limits.maxGenerations}-generation spend limit`, { runId: run.id });
}
- return mutateRun(project, run.id, (r) => ({ usage: { ...r.usage, generations: r.usage.generations + 1 } }), now);
+ return mutateRun(project, run.id, (r) => ({
+ usage: { ...r.usage, generations: r.usage.generations + 1 },
+ reservations: sceneId ? [...reservations, { revisionId, sceneId, kind, at: now }] : reservations,
+ }), now);
+}
+
+/**
+ * Refund a charge whose submission never reached the queue (the board reports
+ * a failed kickoff by releasing the section's claim): the reservation is
+ * dropped and its generation returned to the budget. A no-op when there is no
+ * live reservation for the section — a job that was queued stays charged.
+ */
+export function refundAutoReviewGeneration(project, revisionId, sceneId, now = new Date().toISOString()) {
+ const run = projectAutoReviews(project).find((r) => RESUMABLE.has(r.status) && currentAttempt(r).revisionId === revisionId);
+ if (!run) return { project, run: null };
+ const reservations = liveReservations(run, Date.parse(now));
+ const idx = reservations.findIndex((r) => r.revisionId === revisionId && r.sceneId === sceneId);
+ if (idx === -1) return { project, run: null };
+ return mutateRun(project, run.id, (r) => ({
+ usage: { ...r.usage, generations: Math.max(0, r.usage.generations - 1) },
+ reservations: reservations.filter((_, i) => i !== idx),
+ }), now);
}
/** Generations still affordable before the spend limit. */
diff --git a/server/services/musicVideo/autoReviewService.js b/server/services/musicVideo/autoReviewService.js
index 1990cee2c0..060a8e2aa6 100644
--- a/server/services/musicVideo/autoReviewService.js
+++ b/server/services/musicVideo/autoReviewService.js
@@ -37,7 +37,7 @@ import { musicVideoEvents } from './events.js';
import { startExcerptRender } from './excerptRender.js';
import { cancelRevision, resumeRevision } from './revisionService.js';
import { projectExcerpts } from './excerpt.js';
-import { projectRevisions, revisionSectionStates, startRevisionOnProject } from './revision.js';
+import { projectRevisions, releaseRevisionClaim, revisionSectionStates, startRevisionOnProject } from './revision.js';
import {
attachAttemptExcerpt,
attachAttemptRevision,
@@ -51,6 +51,7 @@ import {
remainingGenerations,
resumeAutoReviewOnProject,
runAwaitingExcerpt,
+ runOwningRevision,
startAutoReviewOnProject,
stopAutoReviewOnProject,
} from './autoReview.js';
@@ -279,6 +280,7 @@ async function takeSteps(projectId, runId) {
* Returns `{ project, run, action }`.
*/
function advanceAutoReview(projectId, runId) {
+ armJobEndListener();
const live = advancing.get(runId);
if (live) {
live.again = true;
@@ -354,6 +356,46 @@ export async function cancelAutoReview(projectId, runId) {
// ---- completion events of work a run put in flight ------------------------
+// A revised section's generation job that FAILS (or is cancelled by hand)
+// pauses its run rather than retrying on its own — a retry is more paid work,
+// so it waits for the director's Resume, which hands the section out again.
+// Armed on a run's first advance (never at boot); the queue module is deferred
+// because only this path needs it.
+let jobEndListenerArmed = false;
+function armJobEndListener() {
+ if (jobEndListenerArmed) return;
+ jobEndListenerArmed = true;
+ import('../mediaJobQueue/index.js').then(({ mediaJobEvents }) => {
+ const onJobEnded = (job) => {
+ const tag = job?.params?.musicVideo;
+ if (!tag?.projectId || !tag.revisionId || !tag.sceneId) return;
+ pauseOnEndedGeneration(tag, job).catch((err) => {
+ console.error(`❌ Music Video auto-review could not pause after a ${job.status} generation: ${err.message}`);
+ });
+ };
+ mediaJobEvents.on('failed', onJobEnded);
+ mediaJobEvents.on('canceled', onJobEnded);
+ }).catch((err) => {
+ jobEndListenerArmed = false;
+ console.error(`❌ Music Video auto-review could not watch generation jobs: ${err.message}`);
+ });
+}
+
+async function pauseOnEndedGeneration(tag, job) {
+ const project = await getProject(tag.projectId);
+ if (!project || !runOwningRevision(project, tag.revisionId)) return;
+ const out = await mutateProjectRecord(tag.projectId, (current) => {
+ const run = runOwningRevision(current, tag.revisionId);
+ if (!run) return { project: current, run: null };
+ const released = releaseRevisionClaim(current, tag.revisionId, tag.sceneId);
+ const detail = job.error ? `: ${String(job.error).slice(0, 200)}` : '';
+ return haltAutoReview(released.project, run.id, { status: 'stopped', reason: `A revised section's generation ${job.status}${detail} — resume to try it again` });
+ });
+ if (!out.run) return;
+ console.warn(`⏸️ Music Video auto-review ${short(out.run.id)} paused: a revised section's generation ${job.status}`);
+ publish(tag.projectId, out.project, out.run, { type: 'idle' });
+}
+
function continueFromEvent(projectId, pickRun, label) {
getProject(projectId)
.then((project) => {
diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.js
index 55675069d5..2b116f86ca 100644
--- a/server/services/musicVideo/revisionService.js
+++ b/server/services/musicVideo/revisionService.js
@@ -32,7 +32,7 @@ import {
revisionSectionStates,
startRevisionOnProject,
} from './revision.js';
-import { chargeAutoReviewGeneration, runOwningRevision } from './autoReview.js';
+import { chargeAutoReviewGeneration, refundAutoReviewGeneration, runOwningRevision } from './autoReview.js';
/** Open a revision from a reviewed excerpt. Returns `{ project, revision, skippedSceneIds }`. */
export async function startRevision(projectId, excerptId, input = {}) {
@@ -68,7 +68,7 @@ export async function assertRevisionOpen(projectId, revisionId, { sceneId = null
if (inFlight) {
throw new ServerError('This section is already generating for the auto-review run', { status: 409, code: 'AUTO_REVIEW_SECTION_IN_FLIGHT', context: { sceneId } });
}
- return chargeAutoReviewGeneration(current, revisionId);
+ return chargeAutoReviewGeneration(current, revisionId, { sceneId, kind });
});
}
@@ -78,7 +78,12 @@ export async function assertRevisionOpen(projectId, revisionId, { sceneId = null
* instead of waiting out the claim lease. Returns `{ project, revision }`.
*/
export async function releaseRevisionSection(projectId, revisionId, sceneId) {
- return mutateProjectRecord(projectId, (current) => releaseRevisionClaim(current, revisionId, sceneId));
+ // #8988: a kickoff that never reached the queue also returns its charge to
+ // the owning auto-review run's spend budget.
+ return mutateProjectRecord(projectId, (current) => {
+ const released = releaseRevisionClaim(current, revisionId, sceneId);
+ return { ...released, project: refundAutoReviewGeneration(released.project, revisionId, sceneId).project };
+ });
}
/**