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: share hosted video preparation and queue handoff (#7110)
[._.]/ Adam Eivy61a66bf34813
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex af3918f9a1..8f78833ae8 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -804,6 +804,138 @@ describe('videoGen routes', () => {});});+ describe('POST / — hosted submission contracts', () => {+ const settings = {+ imageGen: { grok: { enabled: true, grokPath: '/example/grok', aspectRatio: '16:9' } },+ videoGen: { fal: { apiKey: 'example-fal-key' }, reactor: { apiKey: 'example-reactor-key' } },+ };+ const providers = [+ { backend: 'grok', input: { grokDuration: 10 },+ minimal: { grokPath: '/example/grok', aspectRatio: '16:9', width: undefined, height: undefined, duration: undefined },+ tagged: { grokPath: '/example/grok', aspectRatio: '9:16', width: 576, height: 1024, duration: 10 } },+ { backend: 'fal', input: { falModelId: 'example/model', falDuration: 6 },+ minimal: { modelId: undefined, aspectRatio: undefined, width: undefined, height: undefined, duration: undefined },+ tagged: { modelId: 'example/model', aspectRatio: '9:16', width: 576, height: 1024, duration: 6 } },+ { backend: 'reactor', input: { reactorClipId: 'example-clip', reactorSeconds: 6, reactorSeed: 0, reactorAspect: '9:16' },+ minimal: { continueFromClipId: undefined, seconds: undefined, seed: undefined, aspect: undefined },+ tagged: { continueFromClipId: 'example-clip', seconds: 6, seed: 0, aspect: '9:16' } },+ ];++ it.each(providers)('preserves $backend text defaults and exact optional-key presence', async ({ backend, minimal }) => {+ const { getSettings } = await import('../services/settings.js');+ getSettings.mockResolvedValueOnce(settings);+ const r = await request(app).post('/api/video-gen/').send({ backend, prompt: 'a fox' });+ expect(r.status).toBe(200);+ expect(r.body).toStrictEqual({+ jobId: 'mock-video-job', generationId: 'mock-video-job', filename: 'mock-video-job.mp4',+ model: backend, mode: backend, status: 'queued', position: 1,+ });+ expect(mediaJobQueue.enqueueJob.mock.calls[0][0]).toStrictEqual({+ kind: 'video', params: {+ mode: backend, videoMode: 'text', prompt: 'a fox', negativePrompt: '',+ sourceImagePath: null, uploadedTempPath: null, ...minimal,+ },+ });+ });++ it.each(providers)('preserves $backend image payload and all provenance tags', async ({ backend, input, tagged }) => {+ const { getSettings } = await import('../services/settings.js');+ getSettings.mockResolvedValueOnce(settings);+ getLoom.mockResolvedValueOnce({ renderSettings: { formatId: 'portrait-9-16' } });+ const musicVideo = { projectId: 'mv-example', sceneId: 'scene-example' };+ const fableLoom = { loomId: 'loom-example', episodeId: 'ep-example', nodeId: 'node-example' };+ const r = await request(app).post('/api/video-gen/').send({+ backend, prompt: 'a fox', negativePrompt: 'blur', sourceImageFile: 'frame.png',+ musicVideo, fableLoom, ...input,+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob.mock.calls[0][0]).toStrictEqual({+ kind: 'video', params: {+ mode: backend, videoMode: 'image', prompt: 'a fox', negativePrompt: 'blur',+ sourceImagePath: '/mock/images/frame.png', uploadedTempPath: null,+ musicVideo, fableLoom,+ visualConditioning: {+ ...compiledVisual, render: {+ provider: backend, modelId: backend + '-video', modelRevision: null,+ parameters: { width: 576, height: 1024, aspectRatio: '9:16' },+ },+ },+ ...tagged,+ },+ });+ expect(unlink).not.toHaveBeenCalledWith('/mock/images/frame.png');+ });++ it.each([+ ['grok', 'GROK_IMAGEGEN_DISABLED', 'Grok Imagegen is disabled — enable it in Settings → Image Gen first'],+ ['fal', 'FAL_NOT_CONFIGURED', 'No fal.ai API key configured — set it in Settings → Video Gen (or the FAL_KEY env var) first'],+ ['reactor', 'REACTOR_NOT_CONFIGURED', 'No reactor.inc API key configured — set it in Settings → Video Gen (or the REACTOR_API_KEY env var) first'],+ ])('preserves %s availability errors after staging a source', async (backend, code, message) => {+ const { getSettings } = await import('../services/settings.js');+ vi.stubEnv('FAL_KEY', '');+ vi.stubEnv('REACTOR_API_KEY', '');+ getSettings.mockResolvedValueOnce({});+ setPendingUpload({ fieldname: 'sourceImage', path: '/tmp/hosted-frame.png', originalname: 'frame.png' });+ const r = await request(app).post('/api/video-gen/').send({ backend, prompt: 'a fox' });+ vi.unstubAllEnvs();+ expect(r.status).toBe(400);+ expect(r.body).toMatchObject({ code, error: message });+ expect(copyFile).toHaveBeenCalledTimes(1);+ expect(unlink).toHaveBeenCalledWith(copyFile.mock.calls[0][1]);+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });++ it.each(['enqueue', 'conditioning'])('rolls back a hosted durable source on %s failure', async (failureStage) => {+ const { getSettings } = await import('../services/settings.js');+ getSettings.mockResolvedValueOnce(settings);+ const failure = new Error('example hosted rejection');+ if (failureStage === 'enqueue') mediaJobQueue.enqueueJob.mockImplementationOnce(() => { throw failure; });+ else compileFableLoomVisualRequest.mockRejectedValueOnce(failure);+ setPendingUpload({ fieldname: 'sourceImage', path: '/tmp/hosted-frame.png', originalname: 'frame.png' });+ const r = await request(app).post('/api/video-gen/').send({+ backend: 'fal', prompt: 'a fox',+ fableLoom: { loomId: 'loom-example', episodeId: 'ep-example', nodeId: 'node-example' },+ });+ expect(r.status).toBe(500);+ expect(r.body.error).toBe(failure.message);+ expect(copyFile).toHaveBeenCalledTimes(1);+ const durable = copyFile.mock.calls[0][1];+ expect(unlink.mock.calls.filter(([path]) => path === durable)).toHaveLength(1);+ expect(unlink).toHaveBeenCalledWith('/tmp/hosted-frame.png');+ if (failureStage === 'conditioning') expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });++ it('hands a successful hosted upload to the worker and discards it on conditioning downgrade', async () => {+ const { getSettings } = await import('../services/settings.js');+ getSettings.mockResolvedValueOnce(settings);+ const source = { fieldname: 'sourceImage', path: '/tmp/hosted-frame.png', originalname: 'frame.png' };+ setPendingUpload(source);+ const r = await request(app).post('/api/video-gen/').send({ backend: 'reactor', prompt: 'a fox' });+ expect(r.status).toBe(200);+ const durable = copyFile.mock.calls[0][1];+ expect(mediaJobQueue.enqueueJob.mock.calls[0][0].params).toMatchObject({+ videoMode: 'image', sourceImagePath: durable, uploadedTempPath: durable,+ });+ expect(unlink).not.toHaveBeenCalledWith(durable);+ expect(unlink).toHaveBeenCalledWith(source.path);++ getSettings.mockResolvedValueOnce(settings);+ compileFableLoomVisualRequest.mockResolvedValueOnce({+ prompt: 'a fox', negativePrompt: '', sourceImagePath: null, visualConditioning: compiledVisual,+ });+ setPendingUpload(source);+ const downgraded = await request(app).post('/api/video-gen/').send({+ backend: 'reactor', prompt: 'a fox',+ fableLoom: { loomId: 'loom-example', episodeId: 'ep-example', nodeId: 'node-example' },+ });+ expect(downgraded.status).toBe(200);+ expect(mediaJobQueue.enqueueJob.mock.calls[1][0].params).toMatchObject({+ videoMode: 'text', sourceImagePath: null, uploadedTempPath: null,+ });+ expect(unlink).toHaveBeenCalledWith(copyFile.mock.calls[1][1]);+ });+ });+describe('POST / — grok backend (#2859 phase 2)', () => {it('enqueues a grok video job with the saved grok config and no local-python dependency', async () => {const { getSettings } = await import('../services/settings.js');diff --git a/server/services/videoGen/hostedSubmission.js b/server/services/videoGen/hostedSubmission.jsnew file mode 100644index 0000000000..88b2e3c470--- /dev/null+++ b/server/services/videoGen/hostedSubmission.js@@ -0,0 +1,53 @@+/**+ * Hosted preparation policy and provider-specific queue fields. Configuration+ * is read from this submission's live settings; fal/Reactor credentials never+ * enter prepared output or persisted params (their workers resolve them).+ */+import { VIDEO_GEN_MODE, isVideoModeUsable } from './modes.js';++export const HOSTED_VIDEO_SUBMISSIONS = {+ [VIDEO_GEN_MODE.GROK]: {+ prepare: (settings) => {+ const grok = settings.imageGen?.grok || {};+ return { usable: grok.enabled, extras: { grok } };+ },+ errorCode: 'GROK_IMAGEGEN_DISABLED',+ errorMessage: 'Grok Imagegen is disabled — enable it in Settings → Image Gen first',+ buildParams: (body, prepared) => ({+ grokPath: prepared.grok.grokPath,+ aspectRatio: body.visualConditioning?.render?.parameters?.aspectRatio || prepared.grok.aspectRatio,+ width: body.width,+ height: body.height,+ duration: body.grokDuration,+ }),+ },+ [VIDEO_GEN_MODE.FAL]: {+ prepare: (settings) => ({+ usable: isVideoModeUsable(settings, VIDEO_GEN_MODE.FAL),+ extras: {},+ }),+ errorCode: 'FAL_NOT_CONFIGURED',+ errorMessage: 'No fal.ai API key configured — set it in Settings → Video Gen (or the FAL_KEY env var) first',+ buildParams: (body) => ({+ modelId: body.falModelId,+ aspectRatio: body.visualConditioning?.render?.parameters?.aspectRatio,+ width: body.width,+ height: body.height,+ duration: body.falDuration,+ }),+ },+ [VIDEO_GEN_MODE.REACTOR]: {+ prepare: (settings) => ({+ usable: isVideoModeUsable(settings, VIDEO_GEN_MODE.REACTOR),+ extras: {},+ }),+ errorCode: 'REACTOR_NOT_CONFIGURED',+ errorMessage: 'No reactor.inc API key configured — set it in Settings → Video Gen (or the REACTOR_API_KEY env var) first',+ buildParams: (body) => ({+ continueFromClipId: body.reactorClipId,+ seconds: body.reactorSeconds,+ seed: body.reactorSeed,+ aspect: body.reactorAspect,+ }),+ },+};diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.jsindex e2b1200011..87e3ba0ff2 100644--- a/server/services/videoGen/prepareParams.js+++ b/server/services/videoGen/prepareParams.js@@ -11,7 +11,7 @@* - validate modelId + local-python configuration* - a2v / IC-LoRA mode↔upload pairing and reference-count bounds* - stage multipart uploads into PATHS.uploads with rollback bookkeeping- * - grok short-circuit (grok reads only prompt/dims/source image/duration)+ * - hosted backend short-circuit after source-image staging* - keyframe resolution + range checks* - render-history resolution for native extend and IC references* - LoRA-array normalization and chunk-count resolution@@ -51,7 +51,8 @@ import {import { getSettings } from '../settings.js';import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';import { getTrack } from '../tracks/index.js';-import { VIDEO_GEN_MODE, resolveVideoMode, isVideoModeUsable } from './modes.js';+import { VIDEO_GEN_MODE, resolveVideoMode } from './modes.js';+import { HOSTED_VIDEO_SUBMISSIONS } from './hostedSubmission.js';import { isDefaultI2vReferenceMode } from '../../lib/videoReferenceModes.js';import {listVideoModels,@@ -727,74 +728,20 @@ async function resolvePreparedParams({}if (uploads.sourceImage?.path) await unlinkGuarded(uploads.sourceImage.path).catch(() => {});};- // Grok backend short-circuit (#2859 phase 2): everything past this point —- // last-frame/keyframe staging, extend resolution, LoRA gating — is- // local-runtime machinery grok doesn't use. sourceImagePath (upload or- // gallery pick) is already resolved above, so an i2v render animates that- // frame and a plain prompt runs the image-first image_gen → image_to_video- // flow inside the provider. `backend` (not `body.backend`) so the #3231- // pin ladder routes an unpinned-request grok default through here too.- if (backend === 'grok') {- const grok = settings.imageGen?.grok || {};- if (!grok.enabled) {+ // Hosted workers consume the already-staged source frame, but none of the+ // local last-frame/audio/IC machinery below. Keep availability checking here+ // so failures retain source validation precedence and staged-file ownership.+ const hosted = HOSTED_VIDEO_SUBMISSIONS[backend];+ if (hosted) {+ const { usable, extras } = hosted.prepare(settings);+ if (!usable) {await cleanupStaged();- throw new ServerError(- 'Grok Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'GROK_IMAGEGEN_DISABLED' },- );- }- return {- backend,- grok,- effectiveModel: { id: 'grok', supportedModes: ['text', 'image'] },- sourceImagePath,- uploadedTempPath,- discardSourceImage,- cleanupStaged,- };- }-- // fal.ai short-circuit (#6213): mirrors the grok branch above — the queue- // REST provider reads only prompt/dims/source-image/duration, so every- // local-runtime knob past this point is irrelevant to it.- if (backend === VIDEO_GEN_MODE.FAL) {- if (!isVideoModeUsable(settings, VIDEO_GEN_MODE.FAL)) {- await cleanupStaged();- throw new ServerError(- 'No fal.ai API key configured — set it in Settings → Video Gen (or the FAL_KEY env var) first',- { status: 400, code: 'FAL_NOT_CONFIGURED' },- );- }- return {- backend,- // No CLI-config sibling to grok's `grok` field: fal.js re-resolves the- // API key from live settings itself (see its generateVideo comment) so- // the secret never rides through job.params/media-jobs.json.- effectiveModel: { id: 'fal', supportedModes: ['text', 'image'] },- sourceImagePath,- uploadedTempPath,- discardSourceImage,- cleanupStaged,- };- }-- // reactor.inc short-circuit (#6214): mirrors the fal branch above — the- // fast-h3 API reads only prompt/source-image/continue_from_clip_id/seconds,- // so every local-runtime knob past this point is irrelevant to it.- if (backend === VIDEO_GEN_MODE.REACTOR) {- if (!isVideoModeUsable(settings, VIDEO_GEN_MODE.REACTOR)) {- await cleanupStaged();- throw new ServerError(- 'No reactor.inc API key configured — set it in Settings → Video Gen (or the REACTOR_API_KEY env var) first',- { status: 400, code: 'REACTOR_NOT_CONFIGURED' },- );+ throw new ServerError(hosted.errorMessage, { status: 400, code: hosted.errorCode });}return {backend,- // No CLI-config sibling to grok's `grok` field: reactor.js re-resolves- // the API key from live settings itself (see its generateVideo- // comment) so the secret never rides through job.params/media-jobs.json.- effectiveModel: { id: 'reactor', supportedModes: ['text', 'image'] },+ ...extras,+ effectiveModel: { id: backend, supportedModes: ['text', 'image'] },sourceImagePath,uploadedTempPath,discardSourceImage,diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.jsindex 8ab3788f3f..fb02e763b8 100644--- a/server/services/videoGen/prepareParams.test.js+++ b/server/services/videoGen/prepareParams.test.js@@ -232,6 +232,19 @@ describe('prepareVideoGenParams', () => {expect(prepared.loras).toBeUndefined();});+ it.each(['fal', 'reactor'])('returns the complete %s prepared contract without credentials', async (backend) => {+ getSettings.mockResolvedValueOnce({ videoGen: { [backend]: { apiKey: 'example-secret' } } });+ const prepared = await prepare({ backend, sourceImageFile: 'still.png' });+ expect(prepared).toStrictEqual({+ backend,+ effectiveModel: { id: backend, supportedModes: ['text', 'image'] },+ sourceImagePath: '/mock/images/still.png',+ uploadedTempPath: null,+ discardSourceImage: expect.any(Function),+ cleanupStaged: expect.any(Function),+ });+ });+it('normalizes the parallel lora arrays and defaults a missing scale', async () => {const prepared = await prepare({ loraFilenames: ['a.safetensors', 'b.safetensors'], loraScales: [0.4] });expect(prepared.loras).toEqual([diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex ec300328e5..fd6b568ae3 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -1,5 +1,5 @@/**- * Submit a validated video-generation request to its federated, Grok, or local+ * Submit a validated video-generation request to its federated, hosted, or local* dispatch lane. HTTP parsing and validation stay in the route; this service* owns every subsequent orchestration and rollback decision.*/@@ -20,6 +20,7 @@ import {fableLoomVideoCapabilities,} from '../fableLoom/visualConditioning.js';import { VIDEO_GEN_MODE } from './modes.js';+import { HOSTED_VIDEO_SUBMISSIONS } from './hostedSubmission.js';import { enqueueJob } from '../mediaJobQueue/index.js';import {cleanupMultipartTemp,@@ -164,89 +165,28 @@ const submitValidatedVideoGenJob = async (body, uploads) => {() => enqueueJob({ kind: 'video', params }),);- if (backend === VIDEO_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: VIDEO_GEN_MODE.GROK,- videoMode: sourceImagePath ? 'image' : 'text',- grokPath: g.grokPath,- aspectRatio: body.visualConditioning?.render?.parameters?.aspectRatio || g.aspectRatio,- prompt: body.prompt,- negativePrompt: body.negativePrompt || '',- width: body.width,- height: body.height,- duration: body.grokDuration,- sourceImagePath,- uploadedTempPath,- ...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),- ...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),- ...(body.visualConditioning ? { visualConditioning: body.visualConditioning } : {}),- });- return {- jobId,- generationId: jobId,- filename: `${jobId}.mp4`,- model: 'grok',- mode: 'grok',- status,- position,- };- }-- if (backend === VIDEO_GEN_MODE.FAL) {- const { sourceImagePath, uploadedTempPath } = prepared;- const { jobId, position, status } = await enqueue({- mode: VIDEO_GEN_MODE.FAL,- videoMode: sourceImagePath ? 'image' : 'text',- modelId: body.falModelId,- aspectRatio: body.visualConditioning?.render?.parameters?.aspectRatio,- prompt: body.prompt,- negativePrompt: body.negativePrompt || '',- width: body.width,- height: body.height,- duration: body.falDuration,- sourceImagePath,- uploadedTempPath,- ...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),- ...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),- ...(body.visualConditioning ? { visualConditioning: body.visualConditioning } : {}),- });- return {- jobId,- generationId: jobId,- filename: `${jobId}.mp4`,- model: 'fal',- mode: 'fal',- status,- position,- };- }-- if (backend === VIDEO_GEN_MODE.REACTOR) {+ const hosted = HOSTED_VIDEO_SUBMISSIONS[backend];+ if (hosted) {const { sourceImagePath, uploadedTempPath } = prepared;const { jobId, position, status } = await enqueue({- mode: VIDEO_GEN_MODE.REACTOR,+ // Hosted jobs use mode for queue dispatch and videoMode for text/image.+ mode: backend,videoMode: sourceImagePath ? 'image' : 'text',prompt: body.prompt,negativePrompt: body.negativePrompt || '',- continueFromClipId: body.reactorClipId,- seconds: body.reactorSeconds,- seed: body.reactorSeed,- aspect: body.reactorAspect,sourceImagePath,uploadedTempPath,...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),...(body.visualConditioning ? { visualConditioning: body.visualConditioning } : {}),+ ...hosted.buildParams(body, prepared),});return {jobId,generationId: jobId,filename: `${jobId}.mp4`,- model: 'reactor',- mode: 'reactor',+ model: backend,+ mode: backend,status,position,};