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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: harden video submission contracts (#5707)
Adam Eivyd88390420906
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 3556b288cf..7601121cd2 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -22306,7 +22306,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 930+ "line": 931}]},@@ -22317,7 +22317,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1060+ "line": 1063}]},@@ -22328,7 +22328,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1036+ "line": 1039}]},@@ -22339,7 +22339,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1065+ "line": 1068}]},@@ -22350,7 +22350,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1094+ "line": 1097}]},@@ -22361,7 +22361,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1142+ "line": 1145}]},@@ -22372,7 +22372,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1114+ "line": 1117}]},@@ -22383,7 +22383,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1150+ "line": 1153}]},@@ -22394,7 +22394,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1146+ "line": 1149}]},@@ -22405,7 +22405,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 809+ "line": 810}]},@@ -22416,7 +22416,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 828+ "line": 829}]},@@ -22427,7 +22427,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1167+ "line": 1170}]},@@ -22438,7 +22438,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 447+ "line": 448}]},@@ -22449,7 +22449,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 451+ "line": 452}]},@@ -22460,7 +22460,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 519+ "line": 520}]},@@ -22471,7 +22471,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 772+ "line": 773}]},@@ -22482,7 +22482,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 757+ "line": 758}]},@@ -22493,7 +22493,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 660+ "line": 661}]},@@ -22504,7 +22504,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 740+ "line": 741}]},@@ -22515,7 +22515,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 489+ "line": 490}]},@@ -22526,7 +22526,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 491+ "line": 492}]},@@ -22537,7 +22537,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 485+ "line": 486}]},@@ -22548,7 +22548,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 397+ "line": 398}]},@@ -22559,7 +22559,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1184+ "line": 1187}]},@@ -22570,7 +22570,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 917+ "line": 918}]},@@ -22581,7 +22581,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 903+ "line": 904}]},@@ -22592,7 +22592,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 873+ "line": 874}]},@@ -22603,7 +22603,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 883+ "line": 884}]},@@ -22614,7 +22614,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1135+ "line": 1138}]},@@ -22625,7 +22625,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1173+ "line": 1176}]},diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 5e790faf36..6bfa1e2ad5 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -42,6 +42,7 @@ import {} from '../services/videoGen/local.js';import { cleanupMultipartTemp } from '../services/videoGen/prepareParams.js';import { submitVideoGenJob } from '../services/videoGen/submitJob.js';+import { VIDEO_GEN_LOCAL_ONLY_FIELDS } from '../services/videoGen/requestFields.js';import { attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';import { repoForModel, getTextEncoderRepo, isHfRepoId } from '../lib/mediaModels.js';import {@@ -174,35 +175,35 @@ const listPreprocess = (v) => {// together so Grok eligibility and request validation cannot drift when a new// local-only knob is added.export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({- numFrames: optionalInt(1, FEDERATED_MEDIA_MAX_VIDEO_FRAMES, 'numFrames'),- fps: optionalNum(1, 60, 'fps'),- steps: optionalNum(1, 200, 'steps'),- guidanceScale: optionalNum(0, 30, 'guidanceScale'),- seed: optionalNum(0, Number.MAX_SAFE_INTEGER, 'seed'),- imageStrength: optionalNum(0, 1, 'imageStrength'),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.NUM_FRAMES]: optionalInt(1, FEDERATED_MEDIA_MAX_VIDEO_FRAMES, 'numFrames'),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.FPS]: optionalNum(1, 60, 'fps'),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.STEPS]: optionalNum(1, 200, 'steps'),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.GUIDANCE_SCALE]: optionalNum(0, 30, 'guidanceScale'),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.SEED]: optionalNum(0, Number.MAX_SAFE_INTEGER, 'seed'),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.IMAGE_STRENGTH]: optionalNum(0, 1, 'imageStrength'),// What the conditioning image PROMISES (#4874) — 'anchor' (default) pins it as// frame one, 'inspire' conditions loosely for subject/style. Local-only by// construction: grok's image_to_video always anchors, so a request that names a// mode is not grok-deliverable and must stay on the local lane rather than be// rerouted into a render that silently ignores it. Preprocessed like the numeric// knobs because a multipart body sends an unset select as ''.- i2vReferenceMode: z.preprocess(+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.I2V_REFERENCE_MODE]: z.preprocess((v) => (v == null || v === '' ? undefined : v),z.enum(I2V_REFERENCE_MODES).optional(),),- tiling: z.enum(['auto', 'none', 'spatial', 'temporal']).optional(),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.TILING]: z.enum(['auto', 'none', 'spatial', 'temporal']).optional(),// Which prompt conditioner reads the prompt (lib/videoTextEncoders.js).// Validated loosely here and resolved against the MODEL's own option list in// the service — the set is per-runtime, so a route-level enum would either// have to enumerate every runtime's options or reject a legitimate one.- textEncoderId: z.string().min(1).max(64).optional(),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.TEXT_ENCODER_ID]: z.string().min(1).max(64).optional(),// Named sampler schedule to render with (lib/videoSpeedProfiles.js). Loosely// validated here for the same reason as textEncoderId — the option list is// per-MODEL. Deliberately never rejected downstream either: an id this model// doesn't offer (or a mode the profile isn't validated for) falls back to the// model's own sampler with the reason logged, because a knob that only makes// a render faster must degrade rather than 400 a submitted job.- speedProfileId: z.string().min(1).max(64).optional(),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.SPEED_PROFILE_ID]: z.string().min(1).max(64).optional(),// Decode this render's latents on the model's own decoder or on its declared// preview-fidelity one (lib/videoDraftDecoders.js). A closed enum, unlike the// two ids above, because there is at most ONE draft decoder per model — the@@ -210,7 +211,7 @@ export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({// model declares", not from a per-model list. Never rejected downstream// either: an unsupported model, an old runner checkout, a missing download or// a delivery render all fall back to the full decoder with the reason logged.- draftDecode: z.enum(DRAFT_DECODE_IDS).optional(),+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.DRAFT_DECODE]: z.enum(DRAFT_DECODE_IDS).optional(),});const generateBodySchema = z.object({@@ -928,6 +929,8 @@ router.get('/text-encoder/download', asyncHandler(async (req, res) => {}));router.post('/', frameImageUpload, asyncHandler(async (req, res) => {+ // The route owns cleanup before validation succeeds; the submit service owns+ // every failure after it receives parsed data.const uploads = req.files || {};const parsed = generateBodySchema.safeParse(req.body);if (!parsed.success) {diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.jsindex 7a8c3fcb77..c0c0b2b428 100644--- a/server/services/videoGen/prepareParams.js+++ b/server/services/videoGen/prepareParams.js@@ -188,7 +188,13 @@ export async function validateVideoRetryParams(params = {}) {** @param {object} uploads - `req.files` keyed by fieldname (may be empty)*/+const cleanedMultipartUploads = new WeakSet();+export const cleanupMultipartTemp = async (uploads) => {+ if (uploads && typeof uploads === 'object') {+ if (cleanedMultipartUploads.has(uploads)) return;+ cleanedMultipartUploads.add(uploads);+ }for (const f of Object.values(uploads || {})) {if (f?.path) await unlink(f.path).catch(() => {});}diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.jsindex e2f243b6f1..be013a4fa6 100644--- a/server/services/videoGen/prepareParams.test.js+++ b/server/services/videoGen/prepareParams.test.js@@ -130,9 +130,12 @@ describe('withStagedRollback', () => {describe('cleanupMultipartTemp', () => {it('unlinks every multipart temp path and tolerates an empty/absent map', async () => {- await cleanupMultipartTemp({ sourceImage: upload('sourceImage'), lastImage: upload('lastImage', 'end.png') });+ const uploads = { sourceImage: upload('sourceImage'), lastImage: upload('lastImage', 'end.png') };+ await cleanupMultipartTemp(uploads);expect(unlink).toHaveBeenCalledWith('/tmp/multipart-sourceImage-frame.png');expect(unlink).toHaveBeenCalledWith('/tmp/multipart-lastImage-end.png');+ await cleanupMultipartTemp(uploads);+ expect(unlink).toHaveBeenCalledTimes(2);await expect(cleanupMultipartTemp(undefined)).resolves.toBeUndefined();});});diff --git a/server/services/videoGen/requestFields.js b/server/services/videoGen/requestFields.jsnew file mode 100644index 0000000000..ef8acb395c--- /dev/null+++ b/server/services/videoGen/requestFields.js@@ -0,0 +1,20 @@+// Request fields that only local video runtimes understand. Their Zod schemas+// stay at the HTTP boundary, while this domain-level list lets submission logic+// decide whether a request can be routed to a Grok pin without duplicating names.+export const VIDEO_GEN_LOCAL_ONLY_FIELDS = Object.freeze({+ NUM_FRAMES: 'numFrames',+ FPS: 'fps',+ STEPS: 'steps',+ GUIDANCE_SCALE: 'guidanceScale',+ SEED: 'seed',+ IMAGE_STRENGTH: 'imageStrength',+ I2V_REFERENCE_MODE: 'i2vReferenceMode',+ TILING: 'tiling',+ TEXT_ENCODER_ID: 'textEncoderId',+ SPEED_PROFILE_ID: 'speedProfileId',+ DRAFT_DECODE: 'draftDecode',+});++export const VIDEO_GEN_LOCAL_ONLY_FIELD_NAMES = Object.freeze(+ Object.values(VIDEO_GEN_LOCAL_ONLY_FIELDS),+);diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex 455f732b97..2082d05643 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -25,23 +25,7 @@ import {prepareVideoGenParams,withStagedRollback,} from './prepareParams.js';--// These names mirror the route-owned Zod schema. The service needs only their-// names to decide whether a request can honor a Grok pin; it deliberately does-// not import HTTP validation back into the service layer.-const LOCAL_ONLY_VIDEO_PARAM_KEYS = [- 'numFrames',- 'fps',- 'steps',- 'guidanceScale',- 'seed',- 'imageStrength',- 'i2vReferenceMode',- 'tiling',- 'textEncoderId',- 'speedProfileId',- 'draftDecode',-];+import { VIDEO_GEN_LOCAL_ONLY_FIELD_NAMES } from './requestFields.js';const submitValidatedVideoGenJob = async (body, uploads) => {let fableLoomRenderSettings = null;@@ -58,6 +42,10 @@ const submitValidatedVideoGenJob = async (body, uploads) => {// locally. Handled before local preparation, which resolves this machine's// backend and stages uploads a remote render can never use.if (body.mediaProviderPeerId) {+ // Start/end gallery frames may cross to an allowlisted peer, but multipart+ // files, model weights, and multi-step chain state stay local under the+ // federated-input contract in ADR 2026-08-22. Each entry here is a deliberate+ // refusal, not a missing transport implementation.const unsupported = [['uploaded files', Object.keys(uploads).length],['keyframes', body.keyframes?.length],@@ -67,6 +55,8 @@ const submitValidatedVideoGenJob = async (body, uploads) => {['chained chunks', body.chunks > 1],['the Grok backend', body.backend === 'grok'],['a FableLoom scene tag', body.fableLoom],+ // Inspire is a per-runtime capability the caller cannot prove for a peer.+ // Refuse it instead of returning an anchored clip under an Inspire label.['a loose reference mode', !isDefaultI2vReferenceMode(body.i2vReferenceMode)],['a music-video scene tag', body.musicVideo],].filter(([, present]) => present).map(([label]) => label);@@ -118,7 +108,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {const prepared = await prepareVideoGenParams({body,uploads,- localOnlyParamKeys: LOCAL_ONLY_VIDEO_PARAM_KEYS,+ localOnlyParamKeys: VIDEO_GEN_LOCAL_ONLY_FIELD_NAMES,});const { backend, cleanupStaged } = prepared;@@ -171,6 +161,8 @@ const submitValidatedVideoGenJob = async (body, uploads) => {if (backend === IMAGE_GEN_MODE.GROK) {const { grok: g, sourceImagePath, uploadedTempPath } = prepared;const { jobId, position, status } = await enqueue({+ // This literal is the queue discriminator. Local jobs use mode for their+ // t2v/i2v semantic, while the Grok lane stores that as videoMode.mode: IMAGE_GEN_MODE.GROK,videoMode: sourceImagePath ? 'image' : 'text',grokPath: g.grokPath,@@ -220,6 +212,8 @@ const submitValidatedVideoGenJob = async (body, uploads) => {guidanceScale: body.guidanceScale,seed: body.seed,tiling: body.tiling || 'auto',+ // Default-valued delivery controls stay absent from persisted params so a+ // resumed form cannot restore a knob that never changed the render....(isStockTextEncoder(body.textEncoderId) ? {} : { textEncoderId: body.textEncoderId }),...(isDefaultSpeedProfile(body.speedProfileId) ? {} : { speedProfileId: body.speedProfileId }),...(isFullDecode(body.draftDecode) ? {} : { draftDecode: body.draftDecode }),@@ -237,6 +231,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {...(isDefaultI2vReferenceMode(body.i2vReferenceMode) ? {} : { i2vReferenceMode: body.i2vReferenceMode }),chunks: effectiveChunks,...(effectiveChunkPrompts ? { chunkPrompts: effectiveChunkPrompts } : {}),+ // Zero is a real last-frame-chaining value; only nullish means absent....(effectiveContextFrames != null ? { contextFrames: effectiveContextFrames } : {}),loras,icReferencePaths,@@ -259,14 +254,18 @@ const submitValidatedVideoGenJob = async (body, uploads) => {};/**- * @param {object} body - validated and coerced request body+ * @param {object} body - validated/coerced request body, mutated with compiled+ * FableLoom dimensions, prompts, and visual conditioning when present* @param {object} uploads - multipart uploads keyed by field name*/export async function submitVideoGenJob(body, uploads) {try {return await submitValidatedVideoGenJob(body, uploads);} catch (err) {- await cleanupMultipartTemp(uploads);+ // Preparation may already have released these request-scoped files. The+ // cleanup helper is idempotent, so this remains the one submission-level+ // unwind path without issuing duplicate unlinks.+ await cleanupMultipartTemp(uploads).catch(() => {});throw err;}}diff --git a/server/services/videoGen/submitJob.test.js b/server/services/videoGen/submitJob.test.jsindex f1eb1f8127..6fe03bc287 100644--- a/server/services/videoGen/submitJob.test.js+++ b/server/services/videoGen/submitJob.test.js@@ -27,23 +27,38 @@ vi.mock('../fableLoom/visualConditioning.js', () => ({fableLoomVideoCapabilities: mocks.fableLoomVideoCapabilities,}));vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: mocks.enqueueJob }));-vi.mock('./prepareParams.js', () => ({+vi.mock('./prepareParams.js', async (importOriginal) => ({+ ...await importOriginal(),cleanupMultipartTemp: mocks.cleanupMultipartTemp,prepareVideoGenParams: mocks.prepareVideoGenParams,- withStagedRollback: async (cleanup, fn) => {- try {- return await fn();- } catch (error) {- await cleanup();- throw error;- }- },}));import { submitVideoGenJob } from './submitJob.js';const queued = { jobId: 'job-123', position: 2, status: 'queued' };+const localPrepared = (overrides = {}) => ({+ backend: 'local',+ cleanupStaged: vi.fn(async () => {}),+ pythonPath: '/example/python',+ effectiveModelId: 'local-model',+ effectiveNumFrames: 121,+ mode: 'text',+ sourceImagePath: null,+ lastImagePath: null,+ audioFilePath: null,+ icReferencePaths: [],+ resolvedKeyframes: [],+ extendFromVideoPath: null,+ uploadedTempPath: null,+ uploadedTempPaths: [],+ loras: [],+ effectiveChunks: 1,+ effectiveChunkPrompts: undefined,+ effectiveContextFrames: undefined,+ ...overrides,+});+describe('submitVideoGenJob', () => {beforeEach(() => {vi.clearAllMocks();@@ -108,27 +123,7 @@ describe('submitVideoGenJob', () => {});it('submits a local job with the effective model response contract', async () => {- const cleanupStaged = vi.fn(async () => {});- mocks.prepareVideoGenParams.mockResolvedValue({- backend: 'local',- cleanupStaged,- pythonPath: '/example/python',- effectiveModelId: 'local-model',- effectiveNumFrames: 121,- mode: 'text',- sourceImagePath: null,- lastImagePath: null,- audioFilePath: null,- icReferencePaths: [],- resolvedKeyframes: [],- extendFromVideoPath: null,- uploadedTempPath: null,- uploadedTempPaths: [],- loras: [],- effectiveChunks: 1,- effectiveChunkPrompts: undefined,- effectiveContextFrames: undefined,- });+ mocks.prepareVideoGenParams.mockResolvedValue(localPrepared({ effectiveContextFrames: 0 }));await expect(submitVideoGenJob({prompt: 'Example shot',@@ -147,8 +142,13 @@ describe('submitVideoGenJob', () => {pythonPath: '/example/python',numFrames: 121,mode: 'text',+ contextFrames: 0,}),}));+ const params = mocks.enqueueJob.mock.calls[0][0].params;+ for (const key of ['textEncoderId', 'speedProfileId', 'draftDecode', 'i2vReferenceMode', 'chunkPrompts']) {+ expect(params).not.toHaveProperty(key);+ }});it('cleans multipart uploads exactly once when submission fails', async () => {@@ -160,4 +160,29 @@ describe('submitVideoGenJob', () => {expect(mocks.cleanupMultipartTemp).toHaveBeenCalledTimes(1);expect(mocks.cleanupMultipartTemp).toHaveBeenCalledWith(uploads);});++ it('rolls staged assets back when enqueueing throws', async () => {+ const failure = new Error('queue full');+ const prepared = localPrepared();+ mocks.prepareVideoGenParams.mockResolvedValue(prepared);+ mocks.enqueueJob.mockImplementation(() => { throw failure; });++ await expect(submitVideoGenJob({ prompt: 'Example shot' }, {})).rejects.toBe(failure);+ expect(prepared.cleanupStaged).toHaveBeenCalledTimes(1);+ });++ it('rolls staged assets back when FableLoom compilation rejects', async () => {+ const failure = new Error('conditioning failed');+ const prepared = localPrepared();+ mocks.getLoom.mockResolvedValue({ renderSettings: {} });+ mocks.prepareVideoGenParams.mockResolvedValue(prepared);+ mocks.fableLoomVideoCapabilities.mockReturnValue({ modes: ['text'] });+ mocks.compileFableLoomVisualRequest.mockRejectedValue(failure);++ await expect(submitVideoGenJob({+ prompt: 'Example shot',+ fableLoom: { loomId: 'loom-example', sceneId: 'scene-example' },+ }, {})).rejects.toBe(failure);+ expect(prepared.cleanupStaged).toHaveBeenCalledTimes(1);+ });});