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

feat: run federated image and video renders on a selected peer

[._.]/ Adam Eivy92891cf787b4
diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.md
index 42a1199231..baedbd4241 100644
--- a/docs/FEDERATED_MEDIA_PROVIDERS.md
+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md
@@ -1,15 +1,17 @@
# Federated Media Providers
-PortOS can opt in to serving local media-generation capacity to another registered PortOS peer. The first wire contract, `/api/federation/media/v1`, supports queued audio generation through the existing durable `mediaJobQueue` and local music engines.
+PortOS can opt in to serving local media-generation capacity to another registered PortOS peer. The wire contract, `/api/federation/media/v1`, carries queued **audio, image, and video** generation through the existing durable `mediaJobQueue` and this machine's local engines.
-Provider-side queued audio, consumer-side capacity discovery, and durable remote audio execution are available. Multi-provider scheduling, image/video transfer, and higher-level commission routing remain later slices of issue #4348.
+Provider-side queueing, consumer-side capacity discovery, and durable remote execution are available for all three kinds. Provider selection is exposed through the generation APIs; the picker UI, multi-provider scheduling, input-asset transfer, and higher-level commission routing remain later slices of issue #4348.
## Enable a provider
1. In **Settings → Security**, configure an instance password. The provider API remains closed when authentication is off, even though ordinary PortOS APIs normally trust the private network in that posture.
2. Register the consumer under **Instances**. The consumer must store this provider's Basic credential on its peer record and send its own registered instance id on every request.
3. Install and verify the desired music runtime and model under **Music**. A model must be locally ready before it can be advertised or accept work.
-4. In **Settings → Sharing → Federated media provider**, select the allowed audio models, choose the shared active-job limit, and enable the provider.
+4. In **Settings → Sharing → Federated media provider**, select the allowed models per kind, choose the shared active-job limit, and enable the provider.
+
+Audio models come from the Music engine registry (`engine` is the music engine id). Image and video models come from this install's local generator, so their `engine` is always `local` — the cloud-CLI image/video backends (codex/grok/agy) spend a *provider's own* account quota rather than sharing this machine's GPU, and are deliberately not federatable.
The default is disabled:
@@ -19,7 +21,9 @@ The default is disabled:
"mediaProvider": {
"enabled": false,
"maxQueuedJobs": 2,
- "audioModels": []
+ "audioModels": [],
+ "imageModels": [],
+ "videoModels": []
}
}
}
@@ -40,7 +44,9 @@ The consumer default is also disabled:
{
"mediaProvider": {
"enabled": false,
- "audioModels": []
+ "audioModels": [],
+ "imageModels": [],
+ "videoModels": []
}
}
```
@@ -69,6 +75,44 @@ An API caller deliberately selects remote execution on Music generation by sendi
`POST /api/music/generate` performs the fresh capacity preflight before returning the normal queued media-job response. Omitting `mediaProviderPeerId` keeps the existing local-engine behavior. The peer id and free-form `prompt` stay local. The worker renders the provider prompt only from the profile's enum values; non-empty remote lyrics are rejected so arbitrary personal text cannot cross the federation boundary.
+
+### Remote image and video renders
+
+`POST /api/image-gen/generate` and `POST /api/video-gen` take the same
+`mediaProviderPeerId` selection. `mediaProviderEngine` names the provider-side
+engine and defaults to `local`:
+
+```json
+{
+ "prompt": "a lighthouse at dusk",
+ "modelId": "dev",
+ "width": 1024,
+ "height": 1024,
+ "mediaProviderPeerId": "00000000-0000-4000-8000-000000000001"
+}
+```
+
+Both routes run the same fresh capacity preflight and then return the normal
+queued media-job response, with `mode: null` (no local backend is rendering
+it) and the peer id echoed back as `mediaProviderPeerId`. Omitting
+`mediaProviderPeerId` keeps the existing local/cloud behavior byte for byte.
+
+Wire v1 is **text-to-image and text-to-video only**. A federated request that
+carries an init image, reference images, keyframes, a clip to extend, IC-LoRA
+references, LoRA weights, a chained (multi-chunk) render, or a non-`text` render
+mode is rejected with `400 MEDIA_PROVIDER_INPUT_UNSUPPORTED` naming what has to
+go. That is deliberate: silently dropping the source image a user pinned would
+return a plausible render of the wrong thing. Input-asset transfer is a later
+slice.
+
+Unlike audio, image and video prompts cross as submitted rather than being
+re-rendered from a fixed vocabulary. There is no closed taxonomy for arbitrary
+visual content the way audio has a finite style/mood/instrument alphabet, and a
+federation peer is an authenticated, explicitly registered instance — typically
+the same user's other machine. The privacy line this project draws is that
+*status and capability payloads* never carry prompt or record content; a
+submitted job body is not a status payload.
+
## Authentication and identity
Every request requires both:
@@ -87,13 +131,15 @@ All successful JSON responses include `wireVersion: 1`. The version is also fixe
| Method | Endpoint | Purpose |
|--------|----------|---------|
| `GET` | `/api/federation/media/v1/status` | Fresh allowlisted capabilities, CUDA/runtime/model readiness, queue depth, and staleness window |
-| `POST` | `/api/federation/media/v1/jobs` | Submit an idempotent audio job; returns `202` for new work and `200` for a replay |
+| `POST` | `/api/federation/media/v1/jobs` | Submit an idempotent audio/image/video job; returns `202` for new work and `200` for a replay |
| `GET` | `/api/federation/media/v1/jobs/:id` | Read an owner-scoped sanitized job projection |
| `POST` | `/api/federation/media/v1/jobs/:id/cancel` | Cancel the caller's queued or running job |
-| `GET` | `/api/federation/media/v1/jobs/:id/result` | Download completed WAV bytes with integrity metadata |
+| `GET` | `/api/federation/media/v1/jobs/:id/result` | Download the completed WAV / PNG / MP4 bytes with integrity metadata |
### Capacity status
+`GET /status` reports **audio only** unless the caller opts in with `?kinds=audio,image,video`. That default is what keeps an already-deployed audio-only consumer working: its own copy of the wire schema validates `kinds`/`capabilities` against a literal `audio`, can never be patched retroactively, and would reject a capability naming a kind it has not heard of. A consumer asks for a kind only when it has models allowlisted for it.
+
`GET /status` is computed live and carries `generatedAt` plus `staleAfterMs`. Consumers must stop assigning new work after that window instead of treating stale capacity as available. A provider timestamp more than 30 seconds in the future is also rejected as unknown clock state rather than extending capacity indefinitely.
CUDA has three states: `available`, `absent`, and `unknown`. A CUDA model is ready only when the state is positively `available`; a failed or ambiguous probe blocks admission. Runtime, host-platform, exact fixed-checkpoint readiness, and queue capacity are similarly fail-closed.
@@ -130,12 +176,24 @@ Provider filesystem paths and original filenames never cross the API boundary.
### Consumer reconciliation
-Remote audio jobs use a dedicated non-GPU lane in the consumer's durable media queue. The local job UUID is also the stable provider `Idempotency-Key`. If the consumer restarts while the job is running, it requeues that same local record, replays the submission to recover the provider job id, and resumes status/progress polling. Temporary peer and provider outages remain queued rather than creating duplicate work.
+Remote jobs of every kind use a dedicated non-GPU lane in the consumer's durable media queue — work running on a peer must never occupy this machine's single GPU slot. The local job UUID is also the stable provider `Idempotency-Key`. If the consumer restarts while the job is running, it requeues that same local record, replays the submission to recover the provider job id, and resumes status/progress polling. Temporary peer and provider outages remain queued rather than creating duplicate work.
Cancellation intent is persisted before the consumer contacts the provider. After a restart it is replayed against the recovered provider job instead of resurrecting the render. A provider restart is handled by its own durable media queue; the consumer continues polling the owner-scoped wire job.
-On completion, the consumer ignores the advisory download URL and derives the fixed owner-scoped v1 result endpoint from the validated provider job id. It streams into a local partial file, verifies `Content-Length`, MIME type, both advertised digests, actual byte count, and SHA-256, then atomically promotes the WAV into the local Music library. Only that verified local filename is handed to the normal Music Studio completion hook.
+On completion, the consumer ignores the advisory download URL and derives the fixed owner-scoped v1 result endpoint from the validated provider job id. It streams into a local partial file, verifies `Content-Length`, MIME type, both advertised digests, actual byte count, and SHA-256, then atomically promotes the file into the local library. Only that verified local filename reaches the normal completion hooks.
+
+Each kind then registers the render exactly as a local one would, which is what makes it visible at all:
+
+| Kind | Lands at | Also registers |
+|------|----------|----------------|
+| audio | `data/music/music-gen-<jobId>.wav` | the Music Studio completion hook |
+| image | `data/images/<jobId>.png` | a `<jobId>.metadata.json` gallery sidecar the media index re-reads |
+| video | `data/videos/<jobId>.mp4` | a video-history row plus a thumbnail |
+
+The sidecar and history row record the render's provenance as `federatedPeerId` / `federatedJobId` — instance-level identifiers already shared across the federation, never a hostname, address, or credential.
+
+A remote job's conditioning prompt is persisted **only inside its versioned `remoteMedia` marker**, never in top-level job params. That is what makes a rolled-back install fail closed: an older build cannot route the marker, so it falls through to the local generator with an empty prompt and no configured runtime instead of quietly re-rendering the job on local hardware. The queue's public job projection rebuilds the prompt for display without exposing peer routing state.
## Current boundary
-Wire v1 currently provides instrumental audio only, and remote selection is exposed through the generation API rather than a Music-page peer picker. Still remaining from #4348 are that Music UI, a privacy-preserving design for remote lyrical conditioning, multi-provider fairness/failover, remote image/video jobs and input-asset transfer, Creative Commission routing/UX, and aggregate provider health on System Health.
+Wire v1 carries instrumental audio, text-to-image, and text-to-video. Remote selection is exposed through the generation APIs rather than a peer picker on the Image Gen / Video Gen pages. Still remaining from #4348: those pickers, a privacy-preserving design for remote lyrical conditioning, input-asset transfer (init/reference images, LoRAs, chained renders), multi-provider fairness/failover, Creative Commission routing/UX, and aggregate provider health on System Health.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index f503e61f61..1aa090df2b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -790,7 +790,7 @@ const federatedMediaAudioJobSubmissionSchema = federatedMediaJobRoutingSchema.ex
// carrying prompt or record content (see the acceptance criteria on #4348) —
// a submitted job body is not a status payload. Local input assets (init/
// reference images, LoRAs) stay out of scope for this slice; see the PR body.
-const federatedMediaImageJobSubmissionSchema = federatedMediaJobRoutingSchema.omit({
+export const federatedMediaImageJobSubmissionSchema = federatedMediaJobRoutingSchema.omit({
durationSec: true, durationMode: true,
}).extend({
kind: z.literal('image'),
@@ -803,7 +803,7 @@ const federatedMediaImageJobSubmissionSchema = federatedMediaJobRoutingSchema.om
seed: z.number().int().min(0).optional(),
}).strict().refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
-const federatedMediaVideoJobSubmissionSchema = federatedMediaJobRoutingSchema.omit({
+export const federatedMediaVideoJobSubmissionSchema = federatedMediaJobRoutingSchema.omit({
durationSec: true, durationMode: true,
}).extend({
kind: z.literal('video'),
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 65b25dc1ae..74d83f9e54 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -42,6 +42,8 @@ import * as characterService from '../services/character.js';
import { randomUUID } from 'crypto';
import { buildUniverseRunTag } from '../services/universeRunTag.js';
import { getSettings } from '../services/settings.js';
+import { federatedMediaImageJobSubmissionSchema } from '../lib/validation.js';
+import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';
const router = Router();
@@ -176,6 +178,14 @@ const generateSchema = z.object({
// path returns the filename to the client, which attaches it directly.
catalogIngredientId: z.string().min(1).max(200).optional(),
catalogMediaKind: z.enum(['portrait', 'reference']).optional(),
+ // Federated media provider (#4348). When set, the render is submitted to
+ // THIS registered peer instead of running on local hardware. Server-validated
+ // against the per-peer allowlist — an agent cannot route work to an arbitrary
+ // peer by naming one here. mediaProviderEngine names the provider-side
+ // engine within that allowlist; local image/video generation registers as
+ // 'local', which is the only engine a provider can currently advertise.
+ mediaProviderPeerId: z.string().uuid().optional(),
+ mediaProviderEngine: z.string().trim().min(1).max(80).optional(),
}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
// JSON callers (SDAPI bridge, avatar route, the Imagine page's old payload
@@ -336,7 +346,7 @@ router.get('/regen/availability', asyncHandler(async (req, res) => {
// Shape returned for any image-gen job that goes through the mediaJobQueue
// (local + codex). Kept in one place so the two enqueue branches below stay
// in sync — the client's polling/SSE hooks key off these fields.
-const queuedImageResponse = ({ jobId, position, status, mode, model }) => ({
+const queuedImageResponse = ({ jobId, position, status, mode, model, mediaProviderPeerId = null }) => ({
jobId,
generationId: jobId,
filename: `${jobId}.png`,
@@ -345,6 +355,10 @@ const queuedImageResponse = ({ jobId, position, status, mode, model }) => ({
model,
status,
position,
+ // Which peer is rendering this, or null for a local/cloud render. The client
+ // needs it to label the in-flight card honestly — `mode` is null for a
+ // federated render precisely because no local backend is running it.
+ mediaProviderPeerId,
});
router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
@@ -405,6 +419,81 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
// call with no local single-flight constraint to absorb. `settings` and
// `mode` were already resolved above (so the FLUX.2 + local-backend gate
// could fire before staging any uploads).
+
+ // Federated render (#4348): submit to the selected peer instead of running
+ // locally. Checked BEFORE the cloud/local dispatch below — those branches
+ // resolve this machine's backends, which a remote render never uses.
+ if (params.mediaProviderPeerId) {
+ // The federated wire is text-to-image only: it carries no init image,
+ // reference images, or LoRA weights, and cleaners run on the bytes this
+ // machine renders. Reject rather than silently dropping conditioning the
+ // user asked for — a render that quietly ignores its source image is worse
+ // than one that refuses.
+ const unsupported = [
+ ['an init image', params.initImagePath],
+ ['reference images', params.referenceImagePaths?.length],
+ ['LoRA weights', params.loraFilenames?.length || params.loraPaths?.length],
+ ].filter(([, present]) => present).map(([label]) => label);
+ if (unsupported.length) {
+ throw new ServerError(
+ `A federated media provider renders text-to-image only — this request uses ${unsupported.join(' and ')}. Render locally instead.`,
+ { status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },
+ );
+ }
+ // A peer advertises specific models; it has no notion of 'this caller's
+ // default'. Say so rather than letting the wire schema report a bare
+ // 'expected string, received undefined' for a field the local path defaults.
+ if (!params.modelId) {
+ throw new ServerError(
+ 'A federated render must name the provider model explicitly (modelId)',
+ { status: 400, code: 'MEDIA_PROVIDER_MODEL_REQUIRED' },
+ );
+ }
+ // Re-validate against the wire schema here rather than trusting the route
+ // schema's overlap with it: this object is what gets persisted and replayed
+ // on every reconcile, so it must already be a body the provider accepts.
+ const request = validateRequest(federatedMediaImageJobSubmissionSchema, {
+ kind: 'image',
+ engine: params.mediaProviderEngine || 'local',
+ modelId: params.modelId,
+ prompt: params.prompt,
+ ...(params.negativePrompt ? { negativePrompt: params.negativePrompt } : {}),
+ ...(params.width !== undefined ? { width: params.width } : {}),
+ ...(params.height !== undefined ? { height: params.height } : {}),
+ ...(params.steps !== undefined ? { steps: params.steps } : {}),
+ ...(params.guidance !== undefined ? { guidance: params.guidance } : {}),
+ ...(params.seed !== undefined ? { seed: params.seed } : {}),
+ });
+ const { peer, remoteMedia } = await prepareRemoteMediaJob({
+ peerId: params.mediaProviderPeerId,
+ kind: 'image',
+ request,
+ });
+ // Drop every field that only means something to a LOCAL dispatch: the
+ // routing inputs consumed above, plus the backend selectors this render
+ // never uses. The destination tags (universeRun, writersRoom, musicVideo,
+ // catalogAttach) deliberately stay — their completion hooks fire off the
+ // finished filename and work identically for a federated render.
+ const {
+ mediaProviderPeerId: _peerId, mediaProviderEngine: _engine,
+ mode: _mode, cloudModel: _cloudModel, ...jobParams
+ } = params;
+ // The conditioning prompt rides ONLY inside the versioned marker. An older
+ // build that cannot route `remoteMedia` therefore falls through to a local
+ // render with no prompt and no configured backend, rather than quietly
+ // re-rendering this job for real on local hardware.
+ const queued = enqueueJob({
+ kind: 'image',
+ params: { ...jobParams, prompt: '', remoteMedia },
+ });
+ return res.json(queuedImageResponse({
+ ...queued,
+ mode: null,
+ model: request.modelId,
+ mediaProviderPeerId: peer.id,
+ }));
+ }
+
// `cloudModel` is a dispatcher-level knob, not a provider param — the
// resolver folds it into the provider's own `model`, so drop the raw field
// before it rides into the persisted job params.
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 2d75a890ba..55970383a0 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -60,6 +60,18 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
// The /generate route resolves an optional universeRun collection target via
// findOrCreateUniverseCollection. Mock it so the universeRun test asserts the
// tag-resolution wiring without touching real collection storage.
+// The federated branch resolves the peer + capacity preflight through this
+// helper; mock it so the route test asserts its own validation and enqueue
+// wiring without standing up a peer registry.
+const federatedPeerId = '00000000-0000-4000-8000-0000000000f1';
+vi.mock('../services/federatedMedia/remoteSubmission.js', () => ({
+ prepareRemoteMediaJob: vi.fn(async ({ peerId, kind, request }) => ({
+ peer: { id: peerId },
+ capability: { kind, engine: request.engine, modelId: request.modelId },
+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },
+ })),
+}));
+
vi.mock('../services/mediaCollections.js', () => ({
findOrCreateUniverseCollection: vi.fn(async ({ universeId }) => ({ id: `col-${universeId}` })),
}));
@@ -109,6 +121,7 @@ import * as characterService from '../services/character.js';
import * as mediaJobQueue from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';
+import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';
describe('Image Gen Routes', () => {
let app;
@@ -1417,4 +1430,75 @@ describe('Image Gen Routes', () => {
resolveBackendSpy.mockRestore();
});
});
+
+ describe('POST /api/image-gen/generate — federated media provider', () => {
+ it('submits to the selected peer and keeps the prompt inside the versioned marker', async () => {
+ const response = await request(app).post('/api/image-gen/generate').send({
+ prompt: 'a lighthouse at dusk',
+ modelId: 'dev',
+ width: 512,
+ height: 512,
+ seed: 42,
+ mediaProviderPeerId: federatedPeerId,
+ });
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({
+ jobId: 'mock-image-job',
+ // No local backend renders this, so `mode` must not name one.
+ mode: null,
+ model: 'dev',
+ mediaProviderPeerId: federatedPeerId,
+ });
+ expect(prepareRemoteMediaJob).toHaveBeenCalledWith({
+ peerId: federatedPeerId,
+ kind: 'image',
+ request: {
+ kind: 'image',
+ engine: 'local',
+ modelId: 'dev',
+ prompt: 'a lighthouse at dusk',
+ width: 512,
+ height: 512,
+ seed: 42,
+ },
+ });
+
+ const [{ params }] = mediaJobQueue.enqueueJob.mock.calls[0];
+ // Blank top-level prompt + no routing fields: an older build that cannot
+ // read `remoteMedia` falls through to a local render with nothing to
+ // render, rather than quietly re-running this job on local hardware.
+ expect(params.prompt).toBe('');
+ expect(params.remoteMedia.request.prompt).toBe('a lighthouse at dusk');
+ expect(params).not.toHaveProperty('mediaProviderPeerId');
+ expect(params).not.toHaveProperty('mediaProviderEngine');
+ });
+
+ it('requires an explicit provider model instead of falling back to a local default', async () => {
+ const response = await request(app).post('/api/image-gen/generate').send({
+ prompt: 'a lighthouse at dusk',
+ mediaProviderPeerId: federatedPeerId,
+ });
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('MEDIA_PROVIDER_MODEL_REQUIRED');
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('refuses a federated render that carries conditioning the wire cannot take', async () => {
+ const response = await request(app).post('/api/image-gen/generate').send({
+ prompt: 'a lighthouse at dusk',
+ modelId: 'dev',
+ loraFilenames: ['style.safetensors'],
+ mediaProviderPeerId: federatedPeerId,
+ });
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('MEDIA_PROVIDER_INPUT_UNSUPPORTED');
+ expect(response.body.error).toMatch(/LoRA weights/);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ expect(prepareRemoteMediaJob).not.toHaveBeenCalled();
+ });
+ });
+
});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index d7ebd60a1a..3c52bd7716 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -13,7 +13,9 @@ import os from 'os';
import { z } from 'zod';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import { uploadFields } from '../lib/multipart.js';
-import { videoModelTermsSchema } from '../lib/validation.js';
+import {
+ validateRequest, videoModelTermsSchema, federatedMediaVideoJobSubmissionSchema,
+} from '../lib/validation.js';
import { grokVideoDurationSchema } from '../lib/sharedSchemas.js';
import { MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';
import {
@@ -66,6 +68,7 @@ import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import { saveUploadedGalleryVideo } from '../services/videoUpload.js';
import { JSON_BODY_LIMIT_BYTES } from '../lib/uploadLimits.js';
import { createInstallLogger } from '../lib/installLogger.js';
+import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';
const router = Router();
@@ -318,6 +321,13 @@ const generateBodySchema = z.object({
sceneId: z.string().min(1).max(200),
}).optional(),
),
+ // Federated media provider (#4348). When set, the render is submitted to
+ // THIS registered peer instead of local hardware. Server-validated against
+ // the per-peer allowlist, so naming a peer here cannot route work to one the
+ // local user never opted into. `mediaProviderEngine` names the provider-side
+ // engine inside that allowlist (local generation registers as 'local').
+ mediaProviderPeerId: z.string().guid().optional(),
+ mediaProviderEngine: z.string().trim().min(1).max(80).optional(),
});
// Probes required-package imports on each call so a half-installed Python
@@ -997,6 +1007,89 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
failValidation(parsed);
}
const body = parsed.data;
+ // Federated render (#4348): submit to the selected peer instead of running
+ // locally. Handled BEFORE prepareVideoGenParams, which resolves this
+ // machine's backend and stages uploads a remote render can never use.
+ if (body.mediaProviderPeerId) {
+ // The federated wire is text-to-video only. Every input below changes what
+ // the clip actually is, and none of it can cross — refuse rather than
+ // render something the user didn't ask for.
+ const unsupported = [
+ ['uploaded files', Object.keys(uploads).length],
+ ['a source image', body.sourceImageFile],
+ ['an end frame', body.lastImageFile],
+ ['keyframes', body.keyframes?.length],
+ ['a source video to extend', body.extendFromVideoId],
+ ['IC-LoRA references', body.icReferenceVideoIds?.length || body.icReferenceImageFiles?.length],
+ ['LoRA weights', body.loraFilenames?.length],
+ ['chained chunks', body.chunks > 1],
+ ['the Grok backend', body.backend === 'grok'],
+ ['a non-text render mode', body.mode !== undefined && body.mode !== 'text'],
+ // A director-board render is image-to-video by construction (its scene
+ // reference frame conditions the shot), and its project/scene ids are
+ // validated inside prepareVideoGenParams, which this branch bypasses.
+ ['a music-video scene tag', body.musicVideo],
+ ].filter(([, present]) => present).map(([label]) => label);
+ if (unsupported.length) {
+ await cleanupMultipartTemp(uploads);
+ throw new ServerError(
+ `A federated media provider renders text-to-video only — this request uses ${unsupported.join(' and ')}. Render locally instead.`,
+ { status: 400, code: 'MEDIA_PROVIDER_INPUT_UNSUPPORTED' },
+ );
+ }
+ // A peer advertises specific models; it has no notion of 'this caller's
+ // default'. Say so rather than letting the wire schema report a bare
+ // 'expected string, received undefined' for a field the local path defaults.
+ if (!body.modelId) {
+ throw new ServerError(
+ 'A federated render must name the provider model explicitly (modelId)',
+ { status: 400, code: 'MEDIA_PROVIDER_MODEL_REQUIRED' },
+ );
+ }
+ // Re-validate against the wire schema rather than trusting this route
+ // schema's overlap with it: this object is persisted and replayed on every
+ // reconcile, so it must already be a body the provider accepts.
+ const request = validateRequest(federatedMediaVideoJobSubmissionSchema, {
+ kind: 'video',
+ engine: body.mediaProviderEngine || 'local',
+ modelId: body.modelId,
+ prompt: body.prompt,
+ ...(body.negativePrompt ? { negativePrompt: body.negativePrompt } : {}),
+ ...(body.width !== undefined ? { width: body.width } : {}),
+ ...(body.height !== undefined ? { height: body.height } : {}),
+ ...(body.numFrames !== undefined ? { numFrames: body.numFrames } : {}),
+ ...(body.fps !== undefined ? { fps: body.fps } : {}),
+ ...(body.steps !== undefined ? { steps: body.steps } : {}),
+ ...(body.guidanceScale !== undefined ? { guidance: body.guidanceScale } : {}),
+ ...(body.seed !== undefined ? { seed: body.seed } : {}),
+ });
+ const { peer, remoteMedia } = await prepareRemoteMediaJob({
+ peerId: body.mediaProviderPeerId,
+ kind: 'video',
+ request,
+ });
+ // Prompt and dials ride ONLY inside the versioned marker, and the job
+ // carries no pythonPath. An older build that can't route `remoteMedia`
+ // therefore hits generateVideo's "Prompt is required" guard and fails
+ // closed instead of re-rendering this job locally.
+ const { jobId, position, status } = enqueueJob({
+ kind: 'video',
+ params: { prompt: '', modelId: request.modelId, remoteMedia },
+ });
+ return res.json({
+ jobId,
+ generationId: jobId,
+ filename: `${jobId}.mp4`,
+ model: request.modelId,
+ // No local backend is running this, so `mode` is null rather than a
+ // backend name the render never used.
+ mode: null,
+ mediaProviderPeerId: peer.id,
+ status,
+ position,
+ });
+ }
+
// Everything between validation and enqueue — backend resolution, upload
// staging with rollback, mode/reference validation, history lookups — lives
// in the service (#3288), mirroring imageGen's prepareGenerateParams. It
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 268522e01f..e7b7f906ce 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -149,6 +149,18 @@ vi.mock('../lib/sseDownload.js', () => ({
// Render submissions go through the mediaJobQueue. Mock its surface so the
// route tests stay synchronous and don't kick off the worker loop.
+// The federated branch resolves the peer + capacity preflight through this
+// helper; mock it so the route test asserts its own validation and enqueue
+// wiring without standing up a peer registry.
+const federatedPeerId = '00000000-0000-4000-8000-0000000000f2';
+vi.mock('../services/federatedMedia/remoteSubmission.js', () => ({
+ prepareRemoteMediaJob: vi.fn(async ({ peerId, kind, request }) => ({
+ peer: { id: peerId },
+ capability: { kind, engine: request.engine, modelId: request.modelId },
+ remoteMedia: { wireVersion: 1, peerId, reconcile: false, cancelRequested: false, request },
+ })),
+}));
+
vi.mock('../services/mediaJobQueue/index.js', () => ({
enqueueJob: vi.fn(({ kind, params }) => ({ jobId: `mock-${kind}-job`, position: 1, status: 'queued' })),
attachSseClient: vi.fn(() => false),
@@ -218,6 +230,7 @@ vi.mock('fs/promises', () => ({
import { copyFile, unlink } from 'fs/promises';
import * as videoGenService from '../services/videoGen/local.js';
import * as mediaJobQueue from '../services/mediaJobQueue/index.js';
+import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';
import { getProject as getMusicVideoProject } from '../services/musicVideo/projects.js';
import { getTrack } from '../services/tracks/index.js';
import { resolveGalleryImage } from '../lib/fileUtils.js';
@@ -2247,4 +2260,85 @@ describe('videoGen routes', () => {
expect(r.body.error).toMatch(/not found/i);
});
});
+
+ describe('POST / — federated media provider', () => {
+ it('submits to the selected peer and keeps the prompt inside the versioned marker', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a slow pan across a harbour',
+ modelId: 'ltx2',
+ numFrames: 121,
+ fps: 24,
+ mediaProviderPeerId: federatedPeerId,
+ });
+
+ expect(r.status).toBe(200);
+ expect(r.body).toMatchObject({
+ jobId: 'mock-video-job',
+ // No local backend renders this, so `mode` must not name one.
+ mode: null,
+ model: 'ltx2',
+ mediaProviderPeerId: federatedPeerId,
+ });
+ expect(prepareRemoteMediaJob).toHaveBeenCalledWith({
+ peerId: federatedPeerId,
+ kind: 'video',
+ request: {
+ kind: 'video',
+ engine: 'local',
+ modelId: 'ltx2',
+ prompt: 'a slow pan across a harbour',
+ numFrames: 121,
+ fps: 24,
+ },
+ });
+
+ const [{ params }] = mediaJobQueue.enqueueJob.mock.calls[0];
+ // Blank top-level prompt + no pythonPath: an older build that cannot read
+ // `remoteMedia` hits generateVideo's "Prompt is required" guard and fails
+ // closed instead of re-rendering this job on local hardware.
+ expect(params.prompt).toBe('');
+ expect(params).not.toHaveProperty('pythonPath');
+ expect(params.remoteMedia.request.prompt).toBe('a slow pan across a harbour');
+ });
+
+ it('requires an explicit provider model instead of falling back to a local default', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a slow pan across a harbour',
+ mediaProviderPeerId: federatedPeerId,
+ });
+
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('MEDIA_PROVIDER_MODEL_REQUIRED');
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('refuses a federated render that carries conditioning the wire cannot take', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a slow pan across a harbour',
+ modelId: 'ltx2',
+ sourceImageFile: 'frame.png',
+ mediaProviderPeerId: federatedPeerId,
+ });
+
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('MEDIA_PROVIDER_INPUT_UNSUPPORTED');
+ expect(r.body.error).toMatch(/source image/);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ expect(prepareRemoteMediaJob).not.toHaveBeenCalled();
+ });
+
+ it('refuses a federated chained render rather than shipping one unchained clip', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a slow pan across a harbour',
+ modelId: 'ltx2',
+ chunks: 3,
+ mediaProviderPeerId: federatedPeerId,
+ });
+
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/chained chunks/);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+ });
+
});
diff --git a/server/services/federatedMedia/remoteSubmission.js b/server/services/federatedMedia/remoteSubmission.js
new file mode 100644
index 0000000000..c82f4fcf97
--- /dev/null
+++ b/server/services/federatedMedia/remoteSubmission.js
@@ -0,0 +1,59 @@
+/**
+ * Route-side helper that turns "the user picked peer X" into the persisted
+ * remote-job marker the queue's remote adapters run from.
+ *
+ * It exists so every call site enforces the same three things in the same
+ * order — the peer is registered, the local user explicitly allowlisted this
+ * peer/model, and the provider has fresh capacity — before a job is enqueued.
+ * Skipping any of them is how an agent would end up routing arbitrary work to
+ * an arbitrary peer, which the provider contract exists to prevent.
+ *
+ * The preflight is advisory: the provider re-checks authorization and capacity
+ * on submit. Doing it here just keeps known-doomed work from being queued.
+ */
+
+import { ServerError } from '../../lib/errorHandler.js';
+import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';
+
+/**
+ * @param {object} args
+ * @param {string} args.peerId - Registered peer the user selected.
+ * @param {'audio'|'image'|'video'} args.kind
+ * @param {object} args.request - Validated wire submission (carries engine/modelId).
+ * @returns {Promise<{peer: object, capability: object, remoteMedia: object}>}
+ */
+export async function prepareRemoteMediaJob({ peerId, kind, request }) {
+ // Imported lazily, not statically: the image/video generate routes reach this
+ // module, and a static edge to the peer registry would drag it (and its
+ // settings/DB dependencies) into every route suite's module graph — where a
+ // partially-mocked fileUtils then fails to load it. Nothing here runs until a
+ // caller actually names a provider peer.
+ const [{ getPeers }, { resolveFederatedMediaProvider }] = await Promise.all([
+ import('../instances.js'),
+ import('../federatedMediaConsumer.js'),
+ ]);
+ const peers = await getPeers();
+ const peer = peers.find((candidate) => candidate.id === peerId);
+ if (!peer) {
+ throw new ServerError('Selected media provider peer was not found', {
+ status: 404,
+ code: 'MEDIA_PROVIDER_PEER_NOT_FOUND',
+ });
+ }
+ const { capability } = await resolveFederatedMediaProvider(peer, {
+ kind,
+ engine: request.engine,
+ modelId: request.modelId,
+ });
+ return {
+ peer,
+ capability,
+ remoteMedia: {
+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,
+ peerId: peer.id,
+ reconcile: false,
+ cancelRequested: false,
+ request,
+ },
+ };
+}
diff --git a/server/services/imageGen/remote.js b/server/services/imageGen/remote.js
new file mode 100644
index 0000000000..c5521d5bf9
--- /dev/null
+++ b/server/services/imageGen/remote.js
@@ -0,0 +1,80 @@
+/**
+ * Durable consumer-side adapter for federated image jobs.
+ *
+ * Mirrors audioGen/remote.js: the retry/idempotency/cancel/integrity machinery
+ * lives in the shared executor (services/federatedMedia/remoteExecutor.js) and
+ * this module supplies only the image-specific parts — the persisted marker
+ * shape, where the verified PNG lands, and the gallery sidecar a local render
+ * would have written.
+ *
+ * The sidecar matters as much as the pixels: mediaAssetIndex's `completed`
+ * hook re-reads it to build the gallery row, so a remote render with no
+ * sidecar would land on disk and never appear in the gallery.
+ */
+
+import { join } from 'node:path';
+import { z } from 'zod';
+import { PATHS, atomicWrite } from '../../lib/fileUtils.js';
+import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';
+import { federatedMediaImageJobSubmissionSchema } from '../../lib/validation.js';
+import { createRemoteMediaExecutor } from '../federatedMedia/remoteExecutor.js';
+import { imageGenEvents } from '../imageGenEvents.js';
+
+const remoteImageMarkerSchema = z.object({
+ wireVersion: z.literal(FEDERATED_MEDIA_WIRE_VERSION),
+ peerId: z.string().uuid(),
+ reconcile: z.boolean().optional(),
+ cancelRequested: z.boolean().optional(),
+ // The full wire submission, re-validated on every replay. Persisted queue
+ // state is user-editable, so the body that actually leaves this machine is
+ // the one this schema accepted — not whatever the file happens to contain.
+ request: federatedMediaImageJobSubmissionSchema,
+}).passthrough();
+
+const executor = createRemoteMediaExecutor({
+ kind: 'image',
+ label: 'image',
+ events: imageGenEvents,
+ markerSchema: remoteImageMarkerSchema,
+ buildRequest: (marker) => marker.request,
+ // PATHS is read per job (not captured at module load) so a test that swaps
+ // the gallery directory still sees its own temp root. The `<jobId>.png`
+ // filename is the same shape imageGen/local.js uses, which is what lets the
+ // gallery, the media index, and the provider-side result guard all agree.
+ resolveDestination: ({ jobId }) => ({ dir: PATHS.images, filename: `${jobId}.png` }),
+ async finalize({ jobId, dir, filename, request, remoteJob, peerId }) {
+ // Honest sidecar: only fields this render actually had. Seed is the
+ // requested one (wire-v1 results carry no rendered seed), so a render that
+ // did not pin one records null rather than inventing a number the peer
+ // never reported. `federatedPeer`/`federatedJob` are instance-level
+ // identifiers already shared across the federation — they are the result
+ // provenance, and carry no hostname, address, or credential.
+ const meta = {
+ id: jobId,
+ prompt: request.prompt,
+ negativePrompt: request.negativePrompt ?? '',
+ modelId: remoteJob.result.modelId ?? request.modelId,
+ seed: request.seed ?? null,
+ width: request.width,
+ height: request.height,
+ steps: request.steps ?? null,
+ guidance: request.guidance ?? null,
+ filename,
+ federatedPeerId: peerId,
+ federatedJobId: remoteJob.id,
+ createdAt: new Date().toISOString(),
+ };
+ await atomicWrite(join(dir, `${jobId}.metadata.json`), meta);
+ return {
+ filename,
+ path: `/data/images/${filename}`,
+ seed: meta.seed,
+ modelId: meta.modelId,
+ };
+ },
+});
+
+export const generateImage = executor.run;
+export const cancel = executor.cancel;
+export const __configureRemoteImageForTests = executor.configureForTests;
+export const __resetRemoteImageForTests = executor.resetForTests;
diff --git a/server/services/imageGen/remote.test.js b/server/services/imageGen/remote.test.js
new file mode 100644
index 0000000000..6ad817c551
--- /dev/null
+++ b/server/services/imageGen/remote.test.js
@@ -0,0 +1,238 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createHash } from 'node:crypto';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+let tempImageDir;
+const transport = vi.hoisted(() => ({ fetch: vi.fn() }));
+const federation = vi.hoisted(() => ({ resolve: vi.fn(), peers: [] }));
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: new Proxy(actual.PATHS, {
+ get(target, key) {
+ if (key === 'images') return tempImageDir;
+ return target[key];
+ },
+ }),
+ };
+});
+
+vi.mock('../../lib/peerHttpClient.js', () => ({
+ peerFetch: (...args) => transport.fetch(...args),
+}));
+
+vi.mock('../federatedMediaConsumer.js', () => ({
+ resolveFederatedMediaProvider: (...args) => federation.resolve(...args),
+}));
+
+vi.mock('../instances.js', () => ({
+ getPeers: vi.fn(async () => federation.peers),
+}));
+
+import { imageGenEvents } from '../imageGenEvents.js';
+import {
+ __configureRemoteImageForTests,
+ __resetRemoteImageForTests,
+ generateImage,
+} from './remote.js';
+
+const LOCAL_JOB_ID = '00000000-0000-4000-8000-000000000110';
+const REMOTE_JOB_ID = '00000000-0000-4000-8000-000000000120';
+const PEER_ID = '00000000-0000-4000-8000-000000000130';
+const peer = {
+ id: PEER_ID,
+ enabled: true,
+ address: '192.0.2.10',
+ port: 5555,
+ mediaProvider: { enabled: true, imageModels: [{ engine: 'local', modelId: 'dev' }] },
+};
+
+const sha256 = (value) => createHash('sha256').update(value).digest('hex');
+const jsonResponse = (body, status = 200) => new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+});
+
+const providerJob = (status, overrides = {}) => ({
+ wireVersion: 1,
+ id: REMOTE_JOB_ID,
+ kind: 'image',
+ status,
+ queuedAt: '2026-08-19T12:00:00.000Z',
+ startedAt: status === 'queued' ? null : '2026-08-19T12:00:01.000Z',
+ completedAt: ['completed', 'failed', 'canceled'].includes(status) ? '2026-08-19T12:00:02.000Z' : null,
+ position: status === 'queued' ? 1 : null,
+ progress: null,
+ etaMs: null,
+ ...overrides,
+});
+
+const params = (overrides = {}) => ({
+ jobId: LOCAL_JOB_ID,
+ prompt: '',
+ remoteMedia: {
+ wireVersion: 1,
+ peerId: PEER_ID,
+ request: {
+ kind: 'image',
+ engine: 'local',
+ modelId: 'dev',
+ prompt: 'a lighthouse at dusk',
+ width: 512,
+ height: 512,
+ seed: 42,
+ },
+ },
+ ...overrides,
+});
+
+function captureTerminal(jobId) {
+ return new Promise((resolve) => {
+ const cleanup = () => {
+ imageGenEvents.off('completed', onCompleted);
+ imageGenEvents.off('failed', onFailed);
+ };
+ const onCompleted = (event) => {
+ if (event.generationId !== jobId) return;
+ cleanup();
+ resolve({ type: 'completed', event });
+ };
+ const onFailed = (event) => {
+ if (event.generationId !== jobId) return;
+ cleanup();
+ resolve({ type: 'failed', event });
+ };
+ imageGenEvents.on('completed', onCompleted);
+ imageGenEvents.on('failed', onFailed);
+ });
+}
+
+beforeEach(() => {
+ tempImageDir = mkdtempSync(join(tmpdir(), 'remote-image-test-'));
+ federation.peers = [peer];
+ federation.resolve.mockReset().mockResolvedValue({
+ peer,
+ capability: { kind: 'image', engine: 'local', modelId: 'dev' },
+ });
+ transport.fetch.mockReset();
+ __configureRemoteImageForTests({ pollDelayMs: 0, retryDelayMs: 0, requestTimeoutMs: 1_000 });
+});
+
+afterEach(() => {
+ __resetRemoteImageForTests();
+ rmSync(tempImageDir, { recursive: true, force: true });
+});
+
+describe('federated image consumer adapter', () => {
+ it('imports a verified PNG and writes the gallery sidecar the local renderer would have', async () => {
+ const png = Buffer.from('\x89PNG-example-bytes');
+ const digest = sha256(png);
+ const metadata = {
+ available: true,
+ mimeType: 'image/png',
+ sizeBytes: png.length,
+ sha256: digest,
+ downloadUrl: `/api/federation/media/v1/jobs/${REMOTE_JOB_ID}/result`,
+ engine: 'local',
+ modelId: 'dev',
+ durationSec: null,
+ };
+ transport.fetch.mockImplementation(async (url, options) => {
+ if (url.endsWith('/jobs') && options.method === 'POST') return jsonResponse(providerJob('queued'), 202);
+ if (url.endsWith(`/jobs/${REMOTE_JOB_ID}`)) return jsonResponse(providerJob('completed', { result: metadata }));
+ if (url.endsWith(`/jobs/${REMOTE_JOB_ID}/result`)) {
+ return new Response(png, {
+ headers: {
+ 'Content-Length': String(png.length),
+ 'Content-Type': 'image/png',
+ 'X-Content-SHA256': digest,
+ },
+ });
+ }
+ throw new Error(`Unexpected test URL: ${url}`);
+ });
+
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateImage(params());
+ const outcome = await terminal;
+
+ expect(outcome).toMatchObject({
+ type: 'completed',
+ event: {
+ generationId: LOCAL_JOB_ID,
+ filename: `${LOCAL_JOB_ID}.png`,
+ path: `/data/images/${LOCAL_JOB_ID}.png`,
+ seed: 42,
+ modelId: 'dev',
+ federatedMedia: { wireVersion: 1, peerId: PEER_ID, remoteJobId: REMOTE_JOB_ID },
+ },
+ });
+ expect(readFileSync(join(tempImageDir, `${LOCAL_JOB_ID}.png`))).toEqual(png);
+
+ // The sidecar is what makes the render appear in the gallery at all — the
+ // media index re-reads it from disk on the `completed` event.
+ const sidecar = JSON.parse(readFileSync(join(tempImageDir, `${LOCAL_JOB_ID}.metadata.json`), 'utf8'));
+ expect(sidecar).toMatchObject({
+ id: LOCAL_JOB_ID,
+ prompt: 'a lighthouse at dusk',
+ modelId: 'dev',
+ seed: 42,
+ width: 512,
+ height: 512,
+ filename: `${LOCAL_JOB_ID}.png`,
+ federatedPeerId: PEER_ID,
+ federatedJobId: REMOTE_JOB_ID,
+ });
+
+ const submission = transport.fetch.mock.calls
+ .find(([url, options]) => url.endsWith('/jobs') && options.method === 'POST');
+ expect(JSON.parse(submission[1].body)).toEqual({
+ kind: 'image',
+ engine: 'local',
+ modelId: 'dev',
+ prompt: 'a lighthouse at dusk',
+ width: 512,
+ height: 512,
+ seed: 42,
+ });
+ expect(submission[1].headers['Idempotency-Key']).toBe(LOCAL_JOB_ID);
+ });
+
+ it('rejects a provider response whose kind is not image', async () => {
+ transport.fetch.mockImplementation(async (url, options) => {
+ if (url.endsWith('/jobs') && options.method === 'POST') {
+ return jsonResponse({ ...providerJob('queued'), kind: 'audio' }, 202);
+ }
+ throw new Error(`Unexpected test URL: ${url}`);
+ });
+
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateImage(params());
+ const outcome = await terminal;
+
+ expect(outcome.type).toBe('failed');
+ expect(outcome.event.error).toMatch(/invalid wire-v1 job projection/i);
+ expect(existsSync(join(tempImageDir, `${LOCAL_JOB_ID}.png`))).toBe(false);
+ });
+
+ it('fails closed on a marker whose persisted request is not a valid wire submission', async () => {
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateImage(params({
+ remoteMedia: {
+ wireVersion: 1,
+ peerId: PEER_ID,
+ // Hand-edited queue state: a video-shaped request under an image job.
+ request: { kind: 'video', engine: 'local', modelId: 'dev', prompt: 'x' },
+ },
+ }));
+ const outcome = await terminal;
+
+ expect(outcome.type).toBe('failed');
+ expect(outcome.event.error).toMatch(/invalid persisted routing metadata/i);
+ expect(transport.fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 2406802884..a29218bf39 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -9,8 +9,8 @@
* an immediate `queued` ack and watch progress via SSE.
*
* Lanes: GPU jobs drain serially through `running`; cloud CLI jobs use the
- * bounded `cloudRunning` lane; federated audio uses `remoteRunning` so work on
- * another machine never occupies this machine's GPU slot.
+ * bounded `cloudRunning` lane; federated audio/image/video use `remoteRunning`
+ * so work on another machine never occupies this machine's GPU slot.
*
* Scope: gates `videoGen/local#generateVideo` (always),
* `imageGen/local#generateImage` (when imageGen mode === 'local'), and
@@ -57,12 +57,23 @@ const isCloudImageJob = (j) =>
(j.kind === 'image' && CLOUD_IMAGE_GEN_MODES.includes(j.params?.mode))
|| (j.kind === 'video' && j.params?.mode === IMAGE_GEN_MODE.GROK);
+// The federatable kinds and the adapter each one dispatches to, in one map so
+// the two cannot drift apart. Kinds are listed explicitly rather than inferred
+// from the marker alone: a 'training' job has no federated contract, so a marker
+// on one is corrupt state that must keep taking the local path, not a routing
+// instruction.
+const REMOTE_MEDIA_MODULES = {
+ audio: () => import('../audioGen/remote.js'),
+ image: () => import('../imageGen/remote.js'),
+ video: () => import('../videoGen/remote.js'),
+};
+
// Presence, not truthiness of individual nested fields, selects the remote
// adapter. Persisted queue state is user-editable; a malformed marker must fail
-// closed in audioGen/remote rather than accidentally falling through to a local
-// engine with a remote-only model id.
+// closed in the kind's remote module rather than accidentally falling through to
+// a local engine with a remote-only model id.
export const isRemoteMediaJob = (job) =>
- job?.kind === 'audio' && job.params?.remoteMedia !== undefined;
+ Object.hasOwn(REMOTE_MEDIA_MODULES, job?.kind ?? '') && job.params?.remoteMedia !== undefined;
const jobLane = (job) => {
if (isRemoteMediaJob(job)) return 'remote';
@@ -144,10 +155,14 @@ export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'fa
// of provider-dispatch truth — used by the watchdog, runJob, and cancelJob
// so a new provider addition is one edit instead of three.
function getGenModuleForJob(job) {
+ // The remote check comes FIRST for every federatable kind: a remote job's
+ // params deliberately carry no local runtime fields (mode, pythonPath), so a
+ // later local branch would happily claim it and render a second time on this
+ // machine.
+ if (isRemoteMediaJob(job)) return REMOTE_MEDIA_MODULES[job.kind]();
if (job.kind === 'video' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../videoGen/grok.js');
if (job.kind === 'video') return import('../videoGen/local.js');
if (job.kind === 'training') return import('../loraTraining/index.js');
- if (isRemoteMediaJob(job)) return import('../audioGen/remote.js');
if (job.kind === 'audio') return import('../audioGen/local.js');
if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX) return import('../imageGen/codex.js');
if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../imageGen/grok.js');
@@ -173,6 +188,10 @@ async function jobHasSurvivingTrainer(runId) {
// here so the seam stays in one place instead of accreting into runJob.
// Mutates safeParams in place.
async function resolveLiveParams(job, safeParams) {
+ // A remote job renders on the peer's runtime, so this machine's pythonPath is
+ // neither used nor meaningful — resolving it would only emit a confusing
+ // re-resolution log line for a render that never touches local Python.
+ if (isRemoteMediaJob(job)) return;
// mflux training runs in the same venv as local image renders, so the
// live settings pythonPath wins there too. flux2 training resolves its
// own venv (resolveFlux2Python) inside runTraining — skip it here.
@@ -402,7 +421,7 @@ export async function initMediaJobQueue() {
},
},
});
- console.log(`🔁 media-job [${j.id.slice(0, 8)}] remote audio interrupted — re-enqueued for reconciliation`);
+ console.log(`🔁 media-job [${j.id.slice(0, 8)}] remote ${j.kind} interrupted — re-enqueued for reconciliation`);
continue;
}
// #1332: a LoRA trainer is a detached child (spawnDetached) that can
@@ -993,6 +1012,17 @@ async function runJob(job) {
try {
const mod = await getGenModuleForJob(job);
if (!mod) throw new Error(`Unknown job kind: ${job.kind}`);
+ // A cancel that arrived while this job was still queued lives on the
+ // persisted marker, not on any in-memory adapter state. Re-stamp it for
+ // every remote kind so the adapter starts already knowing it must recover
+ // the provider job and cancel it rather than import its result.
+ if (isRemoteMediaJob(job)) {
+ safeParams.remoteMedia = {
+ ...(safeParams.remoteMedia && typeof safeParams.remoteMedia === 'object'
+ ? safeParams.remoteMedia : {}),
+ cancelRequested: job.params?.remoteMedia?.cancelRequested === true,
+ };
+ }
if (job.kind === 'video' && safeParams.chunks > 1) {
await mod.generateChainedVideo({ ...safeParams, jobId: job.id });
} else if (job.kind === 'video') {
@@ -1000,13 +1030,6 @@ async function runJob(job) {
} else if (job.kind === 'training') {
await mod.runTraining({ ...safeParams, jobId: job.id });
} else if (job.kind === 'audio') {
- if (isRemoteMediaJob(job)) {
- safeParams.remoteMedia = {
- ...(safeParams.remoteMedia && typeof safeParams.remoteMedia === 'object'
- ? safeParams.remoteMedia : {}),
- cancelRequested: job.params?.remoteMedia?.cancelRequested === true,
- };
- }
await mod.generateAudio({ ...safeParams, jobId: job.id });
} else {
await mod.generateImage({ ...safeParams, jobId: job.id });
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index dfa94ddf04..39a5f33aa1 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -44,11 +44,15 @@ tryReadFile: vi.fn().mockResolvedValue(null), jobId: 'whatever' })),
generateImageCodex: vi.fn(async () => ({ jobId: 'whatever' })),
generateAudio: vi.fn(async () => ({ jobId: 'whatever' })),
generateAudioRemote: vi.fn(async () => ({ jobId: 'whatever' })),
+ generateImageRemote: vi.fn(async () => ({ jobId: 'whatever' })),
+ generateVideoRemote: vi.fn(async () => ({ jobId: 'whatever' })),
cancelVideo: vi.fn(),
cancelImage: vi.fn(),
cancelImageCodex: vi.fn(),
cancelAudio: vi.fn(),
cancelAudioRemote: vi.fn(),
+ cancelImageRemote: vi.fn(),
+ cancelVideoRemote: vi.fn(),
// #1332: loraTraining is dynamically imported by the queue for runTraining
// (worker) and hasSurvivingTrainer (boot reconcile). Stub both so the boot
// re-attach decision is testable without loading the real trainer module.
@@ -82,6 +86,17 @@ vi.mock('../audioGen/remote.js', () => ({
cancel: (...args) => stubs.cancelAudioRemote(...args),
}));
+vi.mock('../imageGen/remote.js', () => ({
+ generateImage: (...args) => stubs.generateImageRemote(...args),
+ cancel: (...args) => stubs.cancelImageRemote(...args),
+}));
+
+vi.mock('../videoGen/remote.js', () => ({
+ generateVideo: (...args) => stubs.generateVideoRemote(...args),
+ generateChainedVideo: (...args) => stubs.generateVideoRemote(...args),
+ cancel: (...args) => stubs.cancelVideoRemote(...args),
+}));
+
vi.mock('../loraTraining/index.js', () => ({
runTraining: (...args) => stubs.runTraining(...args),
hasSurvivingTrainer: (...args) => stubs.hasSurvivingTrainer(...args),
@@ -116,6 +131,22 @@ const remoteMediaParams = () => ({
request: { engine: 'remote-audio', modelId: 'example/model' },
});
+const remoteImageMediaParams = () => ({
+ wireVersion: 1,
+ peerId: '00000000-0000-4000-8000-000000000001',
+ request: {
+ kind: 'image', engine: 'local', modelId: 'dev', prompt: 'a harbour', width: 512, height: 512,
+ },
+});
+
+const remoteVideoMediaParams = () => ({
+ wireVersion: 1,
+ peerId: '00000000-0000-4000-8000-000000000001',
+ request: {
+ kind: 'video', engine: 'local', modelId: 'ltx2', prompt: 'a harbour', numFrames: 121, fps: 24,
+ },
+});
+
beforeEach(async () => {
tempDataDir = mkdtempSync(join(tmpdir(), 'mediaJobQueue-test-'));
Object.values(stubs).forEach((fn) => fn.mockReset());
@@ -899,6 +930,61 @@ describe('Audio kind (#1928)', () => {
await waitFor(() => mediaJobQueue.getJob(id)?.status === 'completed');
});
+
+ it('routes an image remote job to the remote adapter and the remote lane, not the GPU', async () => {
+ stubs.generateImage.mockImplementation(() => new Promise(() => {}));
+ stubs.generateImageRemote.mockImplementation(() => new Promise(() => {}));
+
+ // A local image render occupies the single GPU slot; the federated one must
+ // still start, because it renders on the peer's hardware.
+ const local = mediaJobQueue.enqueueJob({ kind: 'image', params: { prompt: 'local render' } });
+ const remote = mediaJobQueue.enqueueJob({
+ kind: 'image',
+ params: { prompt: '', modelId: 'dev', remoteMedia: remoteImageMediaParams() },
+ });
+
+ await waitFor(() => stubs.generateImage.mock.calls.length === 1
+ && stubs.generateImageRemote.mock.calls.length === 1);
+ expect(mediaJobQueue.getJob(local.jobId).status).toBe('running');
+ expect(mediaJobQueue.getJob(remote.jobId).status).toBe('running');
+ // The local adapter must never see the federated job — it would re-render
+ // it here and spend this machine's GPU on work already queued on the peer.
+ expect(stubs.generateImage).not.toHaveBeenCalledWith(
+ expect.objectContaining({ jobId: remote.jobId }),
+ );
+
+ imageGenEvents.emit('completed', { generationId: remote.jobId, filename: `${remote.jobId}.png` });
+ imageGenEvents.emit('failed', { generationId: local.jobId, error: 'cleanup' });
+ await waitFor(() => mediaJobQueue.getJob(remote.jobId)?.status === 'completed');
+ });
+
+ it('re-enqueues a persisted running remote VIDEO job with reconciliation enabled', async () => {
+ const id = '00000000-0000-4000-8000-000000000003';
+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({
+ jobs: [{
+ id,
+ kind: 'video',
+ owner: null,
+ status: 'running',
+ queuedAt: '2026-08-19T12:00:00.000Z',
+ startedAt: '2026-08-19T12:00:01.000Z',
+ params: { prompt: '', modelId: 'ltx2', remoteMedia: remoteVideoMediaParams() },
+ }],
+ }));
+ stubs.generateVideoRemote.mockImplementation(() => new Promise(() => {}));
+
+ await mediaJobQueue.initMediaJobQueue();
+ await waitFor(() => stubs.generateVideoRemote.mock.calls.length === 1);
+
+ expect(stubs.generateVideoRemote).toHaveBeenCalledWith(expect.objectContaining({
+ jobId: id,
+ remoteMedia: expect.objectContaining({ reconcile: true }),
+ }));
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+ videoGenEvents.emit('completed', { generationId: id, filename: `${id}.mp4` });
+ await waitFor(() => mediaJobQueue.getJob(id)?.status === 'completed');
+ });
+
// cancelJob's dispatch-by-kind (mod.cancel(jobId)) is exercised generically
// by the Codex lane's cancel test below via the same getGenModuleForJob
// mechanism; audioGen/local.js#cancel's own behavior (aborting the in-flight
diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.js
index b10d708acb..2300af3d4d 100644
--- a/server/services/mediaJobQueue/sanitizeJob.js
+++ b/server/services/mediaJobQueue/sanitizeJob.js
@@ -28,11 +28,16 @@ export function sanitizeJob(job) {
: value,
]))
: undefined;
- // Remote jobs keep only a fixed-vocabulary profile inside their versioned
- // marker so free-form personal text never reaches the provider. Rebuild the
- // actual conditioning prompt for the public projection without exposing
- // private peer routing state.
- const remotePrompt = renderFederatedMediaAudioPrompt(job.params?.remoteMedia?.profile);
+ // A remote job's conditioning text lives inside its versioned marker, never
+ // in top-level params — that is what makes an older build (which cannot route
+ // the marker) fail closed instead of quietly re-rendering the job locally.
+ // Rebuild the prompt for the public projection without exposing private peer
+ // routing state. Audio renders it from the fixed-vocabulary profile (free-form
+ // personal text never reaches an audio provider at all); image and video carry
+ // the submitted prompt itself.
+ const remotePrompt = renderFederatedMediaAudioPrompt(job.params?.remoteMedia?.profile)
+ ?? (typeof job.params?.remoteMedia?.request?.prompt === 'string'
+ ? job.params.remoteMedia.request.prompt : null);
if (safeParams && remotePrompt) {
safeParams.prompt = remotePrompt;
}
diff --git a/server/services/mediaJobQueue/sanitizeJob.test.js b/server/services/mediaJobQueue/sanitizeJob.test.js
index e072f0d1e9..c7e7e8ac0b 100644
--- a/server/services/mediaJobQueue/sanitizeJob.test.js
+++ b/server/services/mediaJobQueue/sanitizeJob.test.js
@@ -81,4 +81,40 @@ describe('sanitizeJob', () => {
});
expect(sanitized.params).not.toHaveProperty('remoteMedia');
});
+
+ it('restores an image/video remote job prompt from its marker, not from params', () => {
+ const sanitized = sanitizeJob({
+ id: 'job-image',
+ kind: 'image',
+ status: 'running',
+ params: {
+ // Blank on purpose: the prompt lives only inside the versioned marker so
+ // an older build that cannot route it fails closed instead of rendering.
+ prompt: '',
+ modelId: 'dev',
+ width: 512,
+ height: 512,
+ remoteMedia: {
+ wireVersion: 1,
+ peerId: '00000000-0000-4000-8000-000000000001',
+ request: {
+ kind: 'image',
+ engine: 'local',
+ modelId: 'dev',
+ prompt: 'a lighthouse at dusk',
+ width: 512,
+ height: 512,
+ },
+ },
+ },
+ });
+
+ expect(sanitized.params).toEqual({
+ prompt: 'a lighthouse at dusk',
+ modelId: 'dev',
+ width: 512,
+ height: 512,
+ });
+ expect(sanitized.params).not.toHaveProperty('remoteMedia');
+ });
});
diff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.js
new file mode 100644
index 0000000000..ff36171531
--- /dev/null
+++ b/server/services/videoGen/remote.js
@@ -0,0 +1,94 @@
+/**
+ * Durable consumer-side adapter for federated video jobs.
+ *
+ * Mirrors audioGen/remote.js and imageGen/remote.js: the shared executor
+ * (services/federatedMedia/remoteExecutor.js) owns retry, idempotent replay,
+ * cancellation, and hash-verified transfer; this module supplies the video
+ * specifics — the persisted marker shape, where the verified MP4 lands, and
+ * the history row + thumbnail a local render would have produced.
+ *
+ * The history row matters as much as the bytes: mediaAssetIndex's `completed`
+ * hook looks the render up by job id in video history, and the Video Gen UI
+ * lists from that same file — a remote render with no row would be invisible.
+ */
+
+import { join } from 'node:path';
+import { z } from 'zod';
+import { PATHS } from '../../lib/fileUtils.js';
+import { generateThumbnail, optimizeForStreaming } from '../../lib/ffmpeg.js';
+import { FEDERATED_MEDIA_WIRE_VERSION } from '../../lib/federatedMediaWire.js';
+import { federatedMediaVideoJobSubmissionSchema } from '../../lib/validation.js';
+import { createRemoteMediaExecutor } from '../federatedMedia/remoteExecutor.js';
+import { videoGenEvents } from './events.js';
+import { mutateVideoHistory } from './history.js';
+
+const remoteVideoMarkerSchema = z.object({
+ wireVersion: z.literal(FEDERATED_MEDIA_WIRE_VERSION),
+ peerId: z.string().uuid(),
+ reconcile: z.boolean().optional(),
+ cancelRequested: z.boolean().optional(),
+ // Re-validated on every replay — persisted queue state is user-editable, so
+ // the body that leaves this machine is the one this schema accepted.
+ request: federatedMediaVideoJobSubmissionSchema,
+}).passthrough();
+
+const executor = createRemoteMediaExecutor({
+ kind: 'video',
+ label: 'video',
+ events: videoGenEvents,
+ markerSchema: remoteVideoMarkerSchema,
+ buildRequest: (marker) => marker.request,
+ // `<jobId>.mp4` is videoGen/local.js's own filename shape, which is what the
+ // provider-side result guard and the local history row both key on.
+ resolveDestination: ({ jobId }) => ({ dir: PATHS.videos, filename: `${jobId}.mp4` }),
+ async finalize({ jobId, path, filename, request, remoteJob, peerId }) {
+ // Both ffmpeg passes are best-effort by construction (they no-op when
+ // ffmpeg is absent), exactly as the local finalize path treats them — a
+ // missing thumbnail must not fail a render that already landed verified.
+ await optimizeForStreaming(path);
+ const thumbnail = await generateThumbnail(path, jobId);
+ await mutateVideoHistory((history) => {
+ history.unshift({
+ id: jobId,
+ prompt: request.prompt,
+ negativePrompt: request.negativePrompt ?? '',
+ modelId: remoteJob.result.modelId ?? request.modelId,
+ seed: request.seed ?? null,
+ width: request.width ?? null,
+ height: request.height ?? null,
+ numFrames: request.numFrames ?? null,
+ fps: request.fps ?? null,
+ steps: request.steps ?? null,
+ guidanceScale: request.guidance ?? null,
+ filename,
+ thumbnail,
+ // Result provenance: instance-level identifiers already shared across
+ // the federation, never a hostname, address, or credential.
+ federatedPeerId: peerId,
+ federatedJobId: remoteJob.id,
+ createdAt: new Date().toISOString(),
+ });
+ return history;
+ });
+ return { filename, path: `/data/videos/${filename}`, thumbnail };
+ },
+});
+
+export const generateVideo = executor.run;
+export const cancel = executor.cancel;
+
+/**
+ * Chained renders condition each chunk on the previous chunk's tail frames,
+ * which the text-only federated wire cannot carry. The queue only reaches this
+ * when persisted params claim `chunks > 1` on a remote job, so fail loudly
+ * rather than silently rendering a single unchained clip.
+ */
+export function generateChainedVideo({ jobId }) {
+ videoGenEvents.emit('failed', {
+ generationId: jobId,
+ error: 'Chained video renders cannot run on a federated media provider',
+ });
+}
+
+export const __configureRemoteVideoForTests = executor.configureForTests;
+export const __resetRemoteVideoForTests = executor.resetForTests;
diff --git a/server/services/videoGen/remote.test.js b/server/services/videoGen/remote.test.js
new file mode 100644
index 0000000000..a705b8e58e
--- /dev/null
+++ b/server/services/videoGen/remote.test.js
@@ -0,0 +1,266 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createHash } from 'node:crypto';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+let tempVideoDir;
+const transport = vi.hoisted(() => ({ fetch: vi.fn() }));
+const federation = vi.hoisted(() => ({ resolve: vi.fn(), peers: [] }));
+const ffmpeg = vi.hoisted(() => ({ thumbnail: vi.fn(), faststart: vi.fn() }));
+const historyState = vi.hoisted(() => ({ rows: [] }));
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: new Proxy(actual.PATHS, {
+ get(target, key) {
+ if (key === 'videos') return tempVideoDir;
+ return target[key];
+ },
+ }),
+ };
+});
+
+vi.mock('../../lib/peerHttpClient.js', () => ({
+ peerFetch: (...args) => transport.fetch(...args),
+}));
+
+vi.mock('../../lib/ffmpeg.js', () => ({
+ generateThumbnail: (...args) => ffmpeg.thumbnail(...args),
+ optimizeForStreaming: (...args) => ffmpeg.faststart(...args),
+}));
+
+vi.mock('./history.js', () => ({
+ mutateVideoHistory: async (mutator) => { historyState.rows = await mutator(historyState.rows); },
+}));
+
+vi.mock('../federatedMediaConsumer.js', () => ({
+ resolveFederatedMediaProvider: (...args) => federation.resolve(...args),
+}));
+
+vi.mock('../instances.js', () => ({
+ getPeers: vi.fn(async () => federation.peers),
+}));
+
+import { videoGenEvents } from './events.js';
+import {
+ __configureRemoteVideoForTests,
+ __resetRemoteVideoForTests,
+ generateChainedVideo,
+ generateVideo,
+} from './remote.js';
+
+const LOCAL_JOB_ID = '00000000-0000-4000-8000-000000000210';
+const REMOTE_JOB_ID = '00000000-0000-4000-8000-000000000220';
+const PEER_ID = '00000000-0000-4000-8000-000000000230';
+const peer = {
+ id: PEER_ID,
+ enabled: true,
+ address: '192.0.2.10',
+ port: 5555,
+ mediaProvider: { enabled: true, videoModels: [{ engine: 'local', modelId: 'ltx2' }] },
+};
+
+const sha256 = (value) => createHash('sha256').update(value).digest('hex');
+const jsonResponse = (body, status = 200) => new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+});
+
+const providerJob = (status, overrides = {}) => ({
+ wireVersion: 1,
+ id: REMOTE_JOB_ID,
+ kind: 'video',
+ status,
+ queuedAt: '2026-08-19T12:00:00.000Z',
+ startedAt: status === 'queued' ? null : '2026-08-19T12:00:01.000Z',
+ completedAt: ['completed', 'failed', 'canceled'].includes(status) ? '2026-08-19T12:00:02.000Z' : null,
+ position: status === 'queued' ? 1 : null,
+ progress: null,
+ etaMs: null,
+ ...overrides,
+});
+
+const params = (overrides = {}) => ({
+ jobId: LOCAL_JOB_ID,
+ prompt: '',
+ remoteMedia: {
+ wireVersion: 1,
+ peerId: PEER_ID,
+ request: {
+ kind: 'video',
+ engine: 'local',
+ modelId: 'ltx2',
+ prompt: 'a slow pan across a harbour',
+ width: 704,
+ height: 480,
+ numFrames: 121,
+ fps: 24,
+ },
+ },
+ ...overrides,
+});
+
+function captureTerminal(jobId) {
+ return new Promise((resolve) => {
+ const cleanup = () => {
+ videoGenEvents.off('completed', onCompleted);
+ videoGenEvents.off('failed', onFailed);
+ };
+ const onCompleted = (event) => {
+ if (event.generationId !== jobId) return;
+ cleanup();
+ resolve({ type: 'completed', event });
+ };
+ const onFailed = (event) => {
+ if (event.generationId !== jobId) return;
+ cleanup();
+ resolve({ type: 'failed', event });
+ };
+ videoGenEvents.on('completed', onCompleted);
+ videoGenEvents.on('failed', onFailed);
+ });
+}
+
+beforeEach(() => {
+ tempVideoDir = mkdtempSync(join(tmpdir(), 'remote-video-test-'));
+ historyState.rows = [];
+ federation.peers = [peer];
+ federation.resolve.mockReset().mockResolvedValue({
+ peer,
+ capability: { kind: 'video', engine: 'local', modelId: 'ltx2' },
+ });
+ transport.fetch.mockReset();
+ ffmpeg.faststart.mockReset().mockResolvedValue(undefined);
+ ffmpeg.thumbnail.mockReset().mockResolvedValue(`${LOCAL_JOB_ID}.jpg`);
+ __configureRemoteVideoForTests({ pollDelayMs: 0, retryDelayMs: 0, requestTimeoutMs: 1_000 });
+});
+
+afterEach(() => {
+ __resetRemoteVideoForTests();
+ rmSync(tempVideoDir, { recursive: true, force: true });
+});
+
+describe('federated video consumer adapter', () => {
+ it('imports a verified MP4 and registers the history row the local renderer would have', async () => {
+ const mp4 = Buffer.from('ftyp-example-mp4-bytes');
+ const digest = sha256(mp4);
+ const metadata = {
+ available: true,
+ mimeType: 'video/mp4',
+ sizeBytes: mp4.length,
+ sha256: digest,
+ downloadUrl: `/api/federation/media/v1/jobs/${REMOTE_JOB_ID}/result`,
+ engine: 'local',
+ modelId: 'ltx2',
+ durationSec: 5,
+ };
+ transport.fetch.mockImplementation(async (url, options) => {
+ if (url.endsWith('/jobs') && options.method === 'POST') return jsonResponse(providerJob('queued'), 202);
+ if (url.endsWith(`/jobs/${REMOTE_JOB_ID}`)) return jsonResponse(providerJob('completed', { result: metadata }));
+ if (url.endsWith(`/jobs/${REMOTE_JOB_ID}/result`)) {
+ return new Response(mp4, {
+ headers: {
+ 'Content-Length': String(mp4.length),
+ 'Content-Type': 'video/mp4',
+ 'X-Content-SHA256': digest,
+ },
+ });
+ }
+ throw new Error(`Unexpected test URL: ${url}`);
+ });
+
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateVideo(params());
+ const outcome = await terminal;
+
+ expect(outcome).toMatchObject({
+ type: 'completed',
+ event: {
+ generationId: LOCAL_JOB_ID,
+ filename: `${LOCAL_JOB_ID}.mp4`,
+ path: `/data/videos/${LOCAL_JOB_ID}.mp4`,
+ thumbnail: `${LOCAL_JOB_ID}.jpg`,
+ federatedMedia: { wireVersion: 1, peerId: PEER_ID, remoteJobId: REMOTE_JOB_ID },
+ },
+ });
+ expect(readFileSync(join(tempVideoDir, `${LOCAL_JOB_ID}.mp4`))).toEqual(mp4);
+
+ // The history row is what makes the clip visible: the media index looks the
+ // render up by job id there, and the Video Gen page lists from it.
+ expect(historyState.rows).toHaveLength(1);
+ expect(historyState.rows[0]).toMatchObject({
+ id: LOCAL_JOB_ID,
+ prompt: 'a slow pan across a harbour',
+ modelId: 'ltx2',
+ filename: `${LOCAL_JOB_ID}.mp4`,
+ thumbnail: `${LOCAL_JOB_ID}.jpg`,
+ numFrames: 121,
+ fps: 24,
+ federatedPeerId: PEER_ID,
+ federatedJobId: REMOTE_JOB_ID,
+ });
+
+ const submission = transport.fetch.mock.calls
+ .find(([url, options]) => url.endsWith('/jobs') && options.method === 'POST');
+ expect(JSON.parse(submission[1].body)).toEqual({
+ kind: 'video',
+ engine: 'local',
+ modelId: 'ltx2',
+ prompt: 'a slow pan across a harbour',
+ width: 704,
+ height: 480,
+ numFrames: 121,
+ fps: 24,
+ });
+ });
+
+ it('still registers the render when ffmpeg is unavailable for a thumbnail', async () => {
+ ffmpeg.thumbnail.mockResolvedValue(null);
+ const mp4 = Buffer.from('ftyp-no-ffmpeg');
+ const digest = sha256(mp4);
+ transport.fetch.mockImplementation(async (url, options) => {
+ if (url.endsWith('/jobs') && options.method === 'POST') {
+ return jsonResponse(providerJob('completed', {
+ result: {
+ available: true,
+ mimeType: 'video/mp4',
+ sizeBytes: mp4.length,
+ sha256: digest,
+ downloadUrl: '/ignored/provider/url',
+ engine: 'local',
+ modelId: 'ltx2',
+ durationSec: 5,
+ },
+ }), 202);
+ }
+ return new Response(mp4, {
+ headers: {
+ 'Content-Length': String(mp4.length),
+ 'Content-Type': 'video/mp4',
+ 'X-Content-SHA256': digest,
+ },
+ });
+ });
+
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateVideo(params());
+ const outcome = await terminal;
+
+ expect(outcome.type).toBe('completed');
+ expect(outcome.event.thumbnail).toBeNull();
+ expect(historyState.rows[0].thumbnail).toBeNull();
+ });
+
+ it('fails a chained render instead of silently producing one unchained clip', async () => {
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ generateChainedVideo({ jobId: LOCAL_JOB_ID });
+ const outcome = await terminal;
+
+ expect(outcome.type).toBe('failed');
+ expect(outcome.event.error).toMatch(/chained video renders cannot run on a federated media provider/i);
+ expect(transport.fetch).not.toHaveBeenCalled();
+ });
+});