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: reject invalid or stale media cancel targets before selecting jobs (#9932)

Adam Eivyeaa025880827
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 6249a00289..fbf1ff052f 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1740,6 +1740,19 @@ export function validateRequest(schema, data) {
});
}
+// Media cancellation bodies (#9932). An OMITTED jobId keeps the legacy
+// "newest/running job" selection; a SUPPLIED jobId must be a usable id — a
+// malformed one (array, object, null, blank) is a 400, never silently treated
+// as absent, because absent selects a different live render to cancel.
+export const mediaCancelJobIdSchema = z.string().trim().min(1).max(200);
+export const imageCancelBodySchema = z.object({
+ jobId: mediaCancelJobIdSchema.optional(),
+ all: z.boolean().optional(),
+});
+export const videoCancelBodySchema = z.object({
+ jobId: mediaCancelJobIdSchema.optional(),
+});
+
export const rapidReaderLibraryParamsSchema = z.object({ id: z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/) });
export const rapidReaderLibraryCreateSchema = z.object({ title: z.string().trim().min(1).max(200), author: z.string().trim().max(200).optional(), text: z.string().trim().min(1).max(2 * 1024 * 1024) });
export const rapidReaderLibraryFetchSchema = z.object({ url: z.string().trim().url().max(2000).refine((value) => /^https?:\/\//i.test(value), 'url must be http(s)'), title: z.string().trim().min(1).max(200).optional() });
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 1cf204bb67..e6a20debb3 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -14,7 +14,7 @@ import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import {
- validateRequest, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,
+ validateRequest, imageCancelBodySchema, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,
} from '../lib/validation.js';
import { optionalUploadFields, optionalUpload } from '../lib/multipart.js';
import * as imageGen from '../services/imageGen/index.js';
@@ -847,17 +847,16 @@ router.post('/cancel', asyncHandler(async (req, res) => {
// 1. body.all === true — cancel every queued/running image job. Used by
// the writers-room storyboard "Cancel renders" CTA, which can have
// 20+ scene renders in flight at once.
- // 2. Explicit body.jobId — cancel that queued/running local image job.
- // Required for users with multiple in-flight renders.
+ // 2. Explicit body.jobId — cancel exactly that job and NOTHING else. An id
+ // that is unknown (404) or already terminal (409) never falls through
+ // to another job or a bulk cancel (#9932). A malformed id is a 400.
// 3. No jobId — cancel the newest queued/running local image job (most
// recent activity wins, matching the user's last "submit" gesture).
// 4. No queue match — fall through to the codex-mode cancel.
- const requestedJobId = typeof req.body?.jobId === 'string' && req.body.jobId.trim()
- ? req.body.jobId.trim()
- : undefined;
- const cancellable = listJobs({ kind: 'image' })
- .filter((j) => j.status === 'queued' || j.status === 'running');
- if (req.body?.all === true) {
+ const { jobId: requestedJobId, all } = validateRequest(imageCancelBodySchema, req.body ?? {});
+ const imageJobs = listJobs({ kind: 'image' });
+ const cancellable = imageJobs.filter((j) => j.status === 'queued' || j.status === 'running');
+ if (all === true) {
// Cancel queued first so the running job's slot doesn't get refilled the
// moment we cancel it. Settle individually so one stale job doesn't
// block the rest. cancellable is already a fresh filter() result.
@@ -872,9 +871,21 @@ router.post('/cancel', asyncHandler(async (req, res) => {
return res.json({ ok: true, canceled: results.filter((r) => r?.ok).length, attempted: results.length });
}
if (requestedJobId) {
- const target = cancellable.find((j) => j.id === requestedJobId);
- if (target) return res.json(await cancelJob(target.id));
- // jobId not in our queue — fall through (could be a codex job).
+ const known = imageJobs.find((j) => j.id === requestedJobId);
+ if (known) {
+ if (!cancellable.includes(known)) {
+ throw new ServerError(`Job already ${known.status}`, { status: 409, code: 'ALREADY_TERMINAL' });
+ }
+ const result = await cancelJob(known.id);
+ if (!result?.ok && result?.code) {
+ throw new ServerError(result.error || 'Cancel failed', { status: result.code === 'ALREADY_TERMINAL' ? 409 : 404, code: result.code });
+ }
+ return res.json(result);
+ }
+ // Not in the queue — it may be a legacy provider job (sync codex/grok/agy/
+ // fal, local) the dispatcher owns. Exact-ID only; never the bulk path.
+ if (imageGen.cancelJob(requestedJobId)) return res.json({ ok: true });
+ throw new ServerError('Job not found or expired', { status: 404 });
} else if (cancellable.length) {
// "Most recent submit" — explicitly sort by queuedAt DESC instead of
// relying on listJobs() ordering (which puts gpuRunning before
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index f437e887c5..0efbb2b378 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -70,6 +70,7 @@ vi.mock('../services/imageGen/index.js', () => ({
generateAvatar: vi.fn(),
attachSseClient: vi.fn(() => false),
cancel: vi.fn(() => false),
+ cancelJob: vi.fn(() => false),
IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex', GROK: 'grok', AGY: 'agy' },
IMAGE_GEN_MODES: ['external', 'local', 'codex', 'grok', 'agy'],
CLOUD_IMAGE_GEN_MODES: ['codex', 'grok', 'agy'],
@@ -1380,6 +1381,75 @@ describe('Image Gen Routes', () => {
});
});
+ // Explicit-target contract (#9932): a named id cancels that job or nothing —
+ // it never degrades to bulk cancellation or to a different live job.
+ describe('POST /cancel explicit-target contract', () => {
+ it.each([
+ ['array', []],
+ ['object', {}],
+ ['null', null],
+ ['whitespace', ' '],
+ ['number', 7],
+ ])('rejects a %s jobId with 400 and cancels nothing', async (_label, jobId) => {
+ // Validation runs before any job lookup, so no queue state is needed.
+ const response = await request(app).post('/api/image-gen/cancel').send({ jobId });
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('VALIDATION_ERROR');
+ expect(mediaJobQueue.cancelJob).not.toHaveBeenCalled();
+ expect(imageGen.cancelJob).not.toHaveBeenCalled();
+ expect(imageGen.cancel).not.toHaveBeenCalled();
+ });
+
+ it('rejects a non-boolean all flag with 400', async () => {
+ const response = await request(app).post('/api/image-gen/cancel').send({ all: 'yes' });
+ expect(response.status).toBe(400);
+ expect(mediaJobQueue.cancelJob).not.toHaveBeenCalled();
+ expect(imageGen.cancel).not.toHaveBeenCalled();
+ });
+
+ it('409s for a known terminal job without touching live job B or any bulk method', async () => {
+ mediaJobQueue.listJobs.mockReturnValueOnce([
+ { id: 'running-b', kind: 'image', status: 'running' },
+ { id: 'finished-a', kind: 'image', status: 'completed' },
+ ]);
+ const response = await request(app).post('/api/image-gen/cancel').send({ jobId: 'finished-a' });
+ expect(response.status).toBe(409);
+ expect(response.body.code).toBe('ALREADY_TERMINAL');
+ expect(mediaJobQueue.cancelJob).not.toHaveBeenCalled();
+ expect(imageGen.cancelJob).not.toHaveBeenCalled();
+ expect(imageGen.cancel).not.toHaveBeenCalled();
+ });
+
+ it('404s for an unknown id after asking providers for that exact id only', async () => {
+ mediaJobQueue.listJobs.mockReturnValueOnce([{ id: 'running-b', kind: 'image', status: 'running' }]);
+ imageGen.cancelJob.mockReturnValueOnce(false);
+ const response = await request(app).post('/api/image-gen/cancel').send({ jobId: 'expired-a' });
+ expect(response.status).toBe(404);
+ expect(response.body.code).toBe('NOT_FOUND');
+ expect(imageGen.cancelJob).toHaveBeenCalledWith('expired-a');
+ expect(mediaJobQueue.cancelJob).not.toHaveBeenCalled();
+ expect(imageGen.cancel).not.toHaveBeenCalled();
+ });
+
+ it('cancels an exact legacy-provider job the queue does not know, never the bulk path', async () => {
+ mediaJobQueue.listJobs.mockReturnValueOnce([]);
+ imageGen.cancelJob.mockReturnValueOnce(true);
+ const response = await request(app).post('/api/image-gen/cancel').send({ jobId: ' codex-1 ' });
+ expect(response.status).toBe(200);
+ expect(response.body.ok).toBe(true);
+ expect(imageGen.cancelJob).toHaveBeenCalledWith('codex-1');
+ expect(imageGen.cancel).not.toHaveBeenCalled();
+ });
+
+ it('maps a queue-reported ALREADY_TERMINAL race (job finished mid-request) to 409', async () => {
+ mediaJobQueue.listJobs.mockReturnValueOnce([{ id: 'racing', kind: 'image', status: 'running' }]);
+ mediaJobQueue.cancelJob.mockResolvedValueOnce({ ok: false, code: 'ALREADY_TERMINAL', status: 'completed', error: 'Job is already finishing' });
+ const response = await request(app).post('/api/image-gen/cancel').send({ jobId: 'racing' });
+ expect(response.status).toBe(409);
+ expect(imageGen.cancel).not.toHaveBeenCalled();
+ });
+ });
+
describe('FLUX.2 installer contract', () => {
it('GET /setup/flux2-install reports status without starting an install', async () => {
const { installFlux2Venv, isFlux2InstallSatisfied } = await import('../lib/pythonSetup.js');
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index f5c4cb87f1..f6bf4a9fd0 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -15,7 +15,7 @@ import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.j
import { createVideoHistoryItemRead, historyRecordIdSchema } from './videoHistoryRead.js';
import { uploadFields, optionalUpload } from '../lib/multipart.js';
import {
- validateRequest, videoModelTermsSchema,
+ validateRequest, videoCancelBodySchema, videoModelTermsSchema,
} from '../lib/validation.js';
import { grokVideoDurationSchema } from '../lib/sharedSchemas.js';
import {
@@ -1094,9 +1094,9 @@ router.post('/cancel', asyncHandler(async (req, res) => {
// 2. No jobId — cancel the currently-running video job (legacy behavior).
// 3. No running job — cancel the newest queued video job so the user can
// take back a submission they regret while it's still in line.
- const requestedJobId = typeof req.body?.jobId === 'string' && req.body.jobId.trim()
- ? req.body.jobId.trim()
- : undefined;
+ // A supplied-but-malformed jobId is a 400, not "absent": absent selects the
+ // running job, which would cancel a different render than the one named (#9932).
+ const { jobId: requestedJobId } = validateRequest(videoCancelBodySchema, req.body ?? {});
if (requestedJobId) {
// Validate that the jobId is a video job before cancelling, so a stray
// image jobId from another tab doesn't accidentally cancel here.
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 80bc3130dc..76db7693c9 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -2821,6 +2821,32 @@ describe('videoGen routes', () => {
expect(mediaJobQueue.cancelJob).toHaveBeenCalledWith('queued-2');
});
+ // A supplied-but-malformed jobId must NOT degrade to "absent" (which cancels
+ // the running render) — it would kill a render the caller never named (#9932).
+ it.each([
+ ['array', []],
+ ['object', {}],
+ ['null', null],
+ ['whitespace', ' '],
+ ['number', 7],
+ ])('rejects a %s jobId with 400 and cancels nothing', async (_label, jobId) => {
+ mediaJobQueue.listJobs.mockReturnValue([{ id: 'running-b', kind: 'video', status: 'running' }]);
+ const r = await request(app).post('/api/video-gen/cancel').send({ jobId });
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('VALIDATION_ERROR');
+ expect(mediaJobQueue.cancelJob).not.toHaveBeenCalled();
+ });
+
+ it('does not fall back to the running job when the named id is stale', async () => {
+ mediaJobQueue.listJobs.mockImplementation(({ status, kind } = {}) => [
+ { id: 'finished-a', kind: 'video', status: 'completed' },
+ { id: 'running-b', kind: 'video', status: 'running' },
+ ].filter((j) => (!status || j.status === status) && (!kind || j.kind === kind)));
+ const r = await request(app).post('/api/video-gen/cancel').send({ jobId: 'finished-a' });
+ expect(r.body.ok).toBe(false);
+ expect(mediaJobQueue.cancelJob).not.toHaveBeenCalled();
+ });
+
// No running job and no jobId — fall back to newest queued so the user
// can pull back a recent submission before it starts.
it('falls back to newest queued video when no jobId and nothing is running', async () => {
diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.js
index 885ca55991..6fd33b90d9 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -273,6 +273,19 @@ export const cancel = () => {
return localCancelled || codexCancelled || grokCancelled || agyCancelled || falCancelled;
};
+// Exact-ID cancel (#9932). The explicit-target counterpart to cancel(): stops
+// ONLY the render that owns `jobId` and never reaches a bulk method, so a
+// request naming a finished/unknown job cancels nothing instead of nuking a
+// concurrent render. Local holds one anonymous process, so it is signalled only
+// when its active job IS the requested one; the cloud backends key by job id.
+// Returns whether a live render was signalled.
+export const cancelJob = (jobId) => {
+ if (!jobId) return false;
+ const localJob = local.getActiveJob();
+ if ((localJob?.id === jobId || localJob?.generationId === jobId) && local.cancel()) return true;
+ return codex.cancel(jobId) || grok.cancel(jobId) || agy.cancel(jobId) || fal.cancel(jobId);
+};
+
// Re-exports so routes can hit a specific backend directly when the request
// is shape-specific (gallery, LoRAs). The dispatcher is for the generic
// generate/status flow used by all modes.
diff --git a/server/services/imageGen/index.test.js b/server/services/imageGen/index.test.js
index 3fd5028c31..6429d856b3 100644
--- a/server/services/imageGen/index.test.js
+++ b/server/services/imageGen/index.test.js
@@ -4,22 +4,28 @@ const settings = vi.hoisted(() => ({ value: {} }));
const models = vi.hoisted(() => ({ value: [] }));
vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => settings.value) }));
+const localMock = vi.hoisted(() => ({ activeJob: null, cancel: vi.fn(() => true) }));
vi.mock('./local.js', () => ({
- getActiveJob: () => null,
+ getActiveJob: () => localMock.activeJob,
attachSseClient: () => false,
- cancel: () => false,
+ cancel: localMock.cancel,
}));
// The model registry moved behind the shared diagnosis in localRuntime.js, which
// reads it from the lib leaf rather than through the renderer.
vi.mock('../../lib/mediaModels.js', () => ({ getImageModels: vi.fn(() => models.value) }));
vi.mock('./external.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null }));
-vi.mock('./codex.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null, cancelAll: () => false }));
-vi.mock('./grok.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null, cancelAll: () => false }));
-vi.mock('./agy.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null, cancelAll: () => false }));
+const codexMock = vi.hoisted(() => ({ cancel: vi.fn(() => false), cancelAll: vi.fn(() => false) }));
+vi.mock('./codex.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null, cancel: codexMock.cancel, cancelAll: codexMock.cancelAll }));
+const grokMock = vi.hoisted(() => ({ cancel: vi.fn(() => false), cancelAll: vi.fn(() => false) }));
+vi.mock('./grok.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null, cancel: grokMock.cancel, cancelAll: grokMock.cancelAll }));
+const agyMock = vi.hoisted(() => ({ cancel: vi.fn(() => false), cancelAll: vi.fn(() => false) }));
+vi.mock('./agy.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null, cancel: agyMock.cancel, cancelAll: agyMock.cancelAll }));
+const falMock = vi.hoisted(() => ({ cancel: vi.fn(() => false), cancelAll: vi.fn(() => false) }));
+vi.mock('./fal.js', async (importOriginal) => ({ ...(await importOriginal()), cancel: falMock.cancel, cancelAll: falMock.cancelAll }));
vi.mock('./setup.js', () => ({ getSetupCheck: vi.fn() }));
vi.mock('../../lib/pythonSetup.js', () => ({ isFlux2VenvHealthy: vi.fn(), FLUX2_VENV_DEFAULT: '/test/venv-flux2/bin/python3' }));
-import { checkConnection } from './index.js';
+import { checkConnection, cancelJob } from './index.js';
import { getSetupCheck } from './setup.js';
import { isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
@@ -32,6 +38,9 @@ const mfluxModel = {
beforeEach(() => {
vi.clearAllMocks();
+ localMock.activeJob = null;
+ localMock.cancel.mockReturnValue(true);
+ for (const m of [codexMock, grokMock, agyMock, falMock]) m.cancel.mockReset().mockReturnValue(false);
models.value = [mfluxModel];
settings.value = { imageGen: { mode: 'local', local: { modelId: 'dev', pythonPath: '/test/python3' } } };
});
@@ -128,3 +137,41 @@ describe('local image connection readiness', () => {
});
});
});
+
+// Exact-ID cancel (#9932): signals only the owning backend; never a bulk method.
+describe('cancelJob exact-ID dispatch', () => {
+ const bulk = () => [localMock.cancel, codexMock.cancelAll, grokMock.cancelAll, agyMock.cancelAll, falMock.cancelAll];
+
+ it('refuses an empty id without touching any backend', () => {
+ expect(cancelJob('')).toBe(false);
+ expect(localMock.cancel).not.toHaveBeenCalled();
+ expect(codexMock.cancel).not.toHaveBeenCalled();
+ });
+
+ it('signals local only when its active job IS the requested id', () => {
+ localMock.activeJob = { id: 'local-b', generationId: 'local-b' };
+ expect(cancelJob('local-a')).toBe(false);
+ expect(localMock.cancel).not.toHaveBeenCalled();
+ expect(cancelJob('local-b')).toBe(true);
+ expect(localMock.cancel).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ ['codex', codexMock],
+ ['grok', grokMock],
+ ['agy', agyMock],
+ ['fal', falMock],
+ ])('routes an exact %s id to that backend only, leaving the others and bulk cancels alone', (_name, owner) => {
+ owner.cancel.mockImplementation((id) => id === 'job-1');
+ localMock.activeJob = { id: 'local-b', generationId: 'local-b' };
+ expect(cancelJob('job-1')).toBe(true);
+ expect(owner.cancel).toHaveBeenCalledWith('job-1');
+ expect(localMock.cancel).not.toHaveBeenCalled();
+ for (const fn of bulk()) expect(fn).not.toHaveBeenCalled();
+ });
+
+ it('returns false for an id no backend owns', () => {
+ expect(cancelJob('gone')).toBe(false);
+ for (const fn of bulk()) expect(fn).not.toHaveBeenCalled();
+ });
+});