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: preserve Reactor videos when cancellation arrives during finalization (#7169)

[._.]/ Adam Eivyd6b8a0b360ef
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 83da113ef8..9efabb1612 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -1335,13 +1335,15 @@ export async function cancelJob(jobId) {
if (runningJob.terminating) {
return { ok: false, code: 'ALREADY_TERMINAL', status: runningJob.status, error: 'Job is already finishing' };
}
+ const mod = await getGenModuleForJob(runningJob);
+ if (runningJob.terminating || runningJob.status !== 'running') {
+ return { ok: false, code: 'ALREADY_TERMINAL', status: runningJob.status, error: 'Job is already finishing' };
+ }
+ const previousCancelRequested = runningJob.cancelRequested;
+ const previousRemoteMedia = runningJob.params?.remoteMedia;
// cancelRequested flips the dispatcher's `failed` handler into the
// `canceled` branch instead of marking it failed.
runningJob.cancelRequested = true;
- if (runningJob.params?.videoProduction && ['reactor', 'fal', 'grok'].includes(runningJob.params.mode)) {
- runningJob.params.videoProduction = { ...runningJob.params.videoProduction, submissionUncertain: true };
- await persist();
- }
if (isRemoteMediaJob(runningJob)) {
// Remote cancellation can outlive this process when the peer is down.
// Persist the intent before signaling the adapter so boot reconciliation
@@ -1354,8 +1356,19 @@ export async function cancelJob(jobId) {
};
await persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on remote cancel failed: ${e.message}`));
}
- const mod = await getGenModuleForJob(runningJob);
- if (mod?.cancel) mod.cancel(jobId);
+ if (mod?.cancel && mod.cancel(jobId) === false) {
+ // A provider may have crossed its durable finalization boundary before
+ // its completed event reaches the queue. Refusal must not turn a later
+ // finalization failure into a cancellation or leave retry markers set.
+ runningJob.cancelRequested = previousCancelRequested;
+ if (isRemoteMediaJob(runningJob)) runningJob.params.remoteMedia = previousRemoteMedia;
+ if (isRemoteMediaJob(runningJob)) await persist();
+ return { ok: false, code: 'ALREADY_TERMINAL', status: runningJob.status, error: 'Job is already finishing' };
+ }
+ if (runningJob.params?.videoProduction && ['reactor', 'fal', 'grok'].includes(runningJob.params.mode)) {
+ runningJob.params.videoProduction = { ...runningJob.params.videoProduction, submissionUncertain: true };
+ await persist();
+ }
console.log(`🛑 media-job [${jobId.slice(0, 8)}] cancel signal sent (was running)`);
return { ok: true, status: 'canceling' };
}
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 2dbc9ea556..20f9a1bc7d 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -82,6 +82,11 @@ tryReadFile: vi.fn().mockResolvedValue(null), jobId: 'whatever' })),
cancelVideoUpscale: vi.fn(),
};
+vi.mock('../creativeDirector/videoExecution.js', () => ({
+ assertVideoAttemptDispatch: vi.fn().mockResolvedValue(undefined),
+ settleVideoAttempt: vi.fn().mockResolvedValue(undefined),
+}));
+
vi.mock('../videoGen/local.js', () => ({
generateVideo: (...args) => stubs.generateVideo(...args),
generateChainedVideo: (...args) => stubs.generateChainedVideo(...args),
@@ -709,6 +714,34 @@ describe('mediaJobQueue', () => {
await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');
});
+ it('restores cancellation bookkeeping when a provider refuses during finalization', async () => {
+ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: {
+ mode: 'grok', prompt: 'finishing render', videoProduction: { submissionUncertain: false },
+ } });
+ await waitFor(() => stubs.generateVideoGrok.mock.calls.length === 1);
+ stubs.cancelVideo.mockReturnValueOnce(false);
+ const result = await mediaJobQueue.cancelJob(job.jobId);
+ expect(result).toMatchObject({ ok: false, code: 'ALREADY_TERMINAL', error: 'Job is already finishing' });
+ expect(mediaJobQueue.getJob(job.jobId).cancelRequested).toBeFalsy();
+ expect(mediaJobQueue.getJob(job.jobId).params.videoProduction.submissionUncertain).toBe(false);
+ const persisted = JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf8'));
+ expect(JSON.stringify(persisted)).not.toContain('"submissionUncertain":true');
+ videoGenEvents.emit('failed', { generationId: job.jobId, error: 'History write failed' });
+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'failed');
+ expect(mediaJobQueue.getJob(job.jobId).error).toBe('History write failed');
+ });
+
+ it.each([true, undefined])('preserves accepted or legacy cancellation results (%s)', async (accepted) => {
+ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'cancel render' } });
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
+ stubs.cancelVideo.mockImplementationOnce(() => {
+ videoGenEvents.emit('failed', { generationId: job.jobId, error: 'Stopped' });
+ return accepted;
+ });
+ await expect(mediaJobQueue.cancelJob(job.jobId)).resolves.toMatchObject({ ok: true, status: 'canceling' });
+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'canceled');
+ });
+
it('cancel during the terminal drain window is refused, not "canceling"', async () => {
const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'finishing race' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.js
index ed2775ee2e..e74298d2af 100644
--- a/server/services/videoGen/reactor.js
+++ b/server/services/videoGen/reactor.js
@@ -84,7 +84,7 @@ export const cancel = (jobId) => {
throw new Error("videoGen/reactor.cancel requires a jobId — use cancelAll() to terminate every in-flight render");
}
const entry = activeRequests.get(jobId);
- if (!entry) return false;
+ if (!entry || entry.finalizing) return false;
entry.aborted = true;
entry.stop?.('Canceled');
return true;
@@ -271,7 +271,7 @@ export async function generateVideo({
async function runReactorVideo(job, jobId, {
apiKey, prompt, seconds, seed, aspect, continueFromClipId, sourceImagePath, outputPath, filename, meta,
}) {
- const entry = { aborted: false, stop: null };
+ const entry = { aborted: false, finalizing: false, stop: null };
activeRequests.set(jobId, entry);
// Declared outside the try so the finally can still delete a fitted frame
// whose render failed after it was written.
@@ -309,6 +309,9 @@ async function runReactorVideo(job, jobId, {
await Promise.all(samples.map((name) => rm(join(PATHS.videoThumbnails, name), { force: true }).catch(() => {})));
}
if (entry.aborted) return finalizeCanceled(job, jobId);
+ // Durable publication owns the output from this point until it settles.
+ // No await may separate the last cancellation check from this boundary.
+ entry.finalizing = true;
await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, aspect: frame.aspect, width: frame.canvas.width, height: frame.canvas.height, clipId: result.clipId, seconds: result.seconds }, actualSeed: seed ?? null, mutateHistory: mutateVideoHistory });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
diff --git a/server/services/videoGen/reactor.test.js b/server/services/videoGen/reactor.test.js
index 09b34830b3..4dfaf0dba3 100644
--- a/server/services/videoGen/reactor.test.js
+++ b/server/services/videoGen/reactor.test.js
@@ -1,14 +1,15 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter, once } from 'events';
-import { mkdir, rm, stat, writeFile } from 'fs/promises';
+import { mkdir, readFile, rm, stat, writeFile } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
const root = join(tmpdir(), `reactor-test-${process.pid}`);
-const mocks = vi.hoisted(() => ({ spawn: vi.fn(), finalize: vi.fn(), settings: vi.fn(), samples: vi.fn(), runtime: vi.fn() }));
+const mocks = vi.hoisted(() => ({ spawn: vi.fn(), finalize: vi.fn(), settings: vi.fn(), samples: vi.fn(), runtime: vi.fn(), optimize: vi.fn(), thumbnail: vi.fn(), history: vi.fn() }));
vi.mock('../../lib/childProcess.js', async (importOriginal) => ({ ...await importOriginal(), spawn: mocks.spawn }));
vi.mock('./reactorRuntime.js', () => ({ ensureReactorRuntime: mocks.runtime }));
-vi.mock('../../lib/ffmpeg.js', () => ({ extractEvaluationFrames: mocks.samples }));
+vi.mock('../../lib/ffmpeg.js', () => ({ extractEvaluationFrames: mocks.samples, optimizeForStreaming: mocks.optimize, generateThumbnail: mocks.thumbnail }));
+vi.mock('./history.js', () => ({ mutateVideoHistory: mocks.history }));
// Partial: only the finalize is stubbed. emitCloudRenderStatus is real, so the
// status/phase frames the Video Gen page reads stay covered by these tests.
vi.mock('./generateVideoHelpers.js', async (importOriginal) => ({
@@ -72,6 +73,55 @@ describe('Reactor SDK adapter', () => {
await vi.waitFor(() => expect(mocks.finalize).toHaveBeenCalledWith(expect.objectContaining({ jobId: job.jobId, meta: expect.objectContaining({ clipId: 'clip-example', seconds: 6 }) })));
});
+ it.each(['optimize', 'thumbnail', 'history'])('refuses late cancellation during %s and retains the published video', async (stage) => {
+ const { finalizeGeneratedVideo } = await vi.importActual('./generateVideoHelpers.js');
+ mocks.finalize.mockImplementationOnce(finalizeGeneratedVideo);
+ const records = [];
+ mocks.optimize.mockResolvedValue(undefined);
+ mocks.thumbnail.mockResolvedValue('example-thumb.jpg');
+ mocks.history.mockImplementation(async (mutate) => mutate(records));
+ let release;
+ const deferred = new Promise((resolve) => { release = resolve; });
+ const original = mocks[stage].getMockImplementation();
+ mocks[stage].mockImplementationOnce(async (...args) => { await deferred; return original(...args); });
+ const completed = vi.fn();
+ const failed = vi.fn();
+ videoGenEvents.on('completed', completed);
+ videoGenEvents.on('failed', failed);
+ const job = await started();
+ await writeFile(input.outputPath, 'example-video');
+ child.stdout.emit('data', Buffer.from('{"type":"complete","clipId":"clip-example","seconds":6}\n'));
+ child.emit('close', 0);
+ await vi.waitFor(() => expect(mocks[stage]).toHaveBeenCalledOnce());
+ expect(reactor.cancel(job.jobId)).toBe(false);
+ expect(reactor.getActiveJob()?.generationId).toBe(job.jobId);
+ release();
+ await vi.waitFor(() => expect(reactor.getActiveJob()).toBeNull());
+ expect(completed).toHaveBeenCalledOnce();
+ expect(failed).not.toHaveBeenCalled();
+ expect(records).toHaveLength(1);
+ expect(records[0].id).toBe(job.jobId);
+ expect(await readFile(input.outputPath, 'utf8')).toBe('example-video');
+ expect(reactor.cancel(job.jobId)).toBe(false);
+ });
+
+ it('releases finalization ownership and reports one failure when publication fails', async () => {
+ mocks.finalize.mockRejectedValueOnce(new Error('History write failed'));
+ const failed = vi.fn();
+ const completed = vi.fn();
+ videoGenEvents.on('failed', failed);
+ videoGenEvents.on('completed', completed);
+ const job = await started();
+ await writeFile(input.outputPath, 'example-video');
+ child.stdout.emit('data', Buffer.from('{"type":"complete","clipId":"clip-example","seconds":6}\n'));
+ child.emit('close', 0);
+ await vi.waitFor(() => expect(reactor.getActiveJob()).toBeNull());
+ expect(failed).toHaveBeenCalledOnce();
+ expect(completed).not.toHaveBeenCalled();
+ expect(reactor.cancel(job.jobId)).toBe(false);
+ await expect(stat(input.outputPath)).rejects.toBeTruthy();
+ });
+
it('identifies connection timeouts before submission without exposing SDK diagnostics', async () => {
await started();
const failed = once(videoGenEvents, 'failed');