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
feat: add Reactor.inc fast-h3 video generation API provider to MediaGen and FableLoom (#6214)
[._.]/ Adam Eivy648682285f49
diff --git a/.env.example b/.env.exampleindex 9f2ba7e57d..421c41b9f9 100644--- a/.env.example+++ b/.env.example@@ -115,6 +115,11 @@ PGPASSWORD=portos# jobs before it starts, so this bounds the whole submit→poll→download run.# FAL_VIDEO_TIMEOUT_MS=1200000+# Maximum reactor.inc fast-h3 video-generation runtime in milliseconds+# (videoGen/reactor.js; default: 1200000 / 20 minutes) — same reasoning as+# FAL_VIDEO_TIMEOUT_MS above.+# REACTOR_VIDEO_TIMEOUT_MS=1200000+# Maximum Antigravity image-generation runtime in milliseconds (default: 1200000 / 20 minutes)# AGY_IMAGEGEN_TIMEOUT_MS=1200000@@ -159,6 +164,10 @@ PGPASSWORD=portos# Settings > Video Gen's stored key wins when both are set.# FAL_KEY=your_fal_api_key_here+# reactor.inc API key for the reactor.inc fast-h3 video backend (Video Gen+# page, FableLoom). Settings > Video Gen's stored key wins when both are set.+# REACTOR_API_KEY=your_reactor_api_key_here+# Absolute path to the bash binary used to run PortOS's bundled *.sh scripts# (e.g. scripts/db.sh). Auto-detected if unset; on Windows it prefers Git Bash,# because a bare `bash` often resolves to WSL, which can't see drive paths.diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsxindex 69cdf3d544..196b951a2f 100644--- a/client/src/components/fableloom/LoomSettingsDrawer.jsx+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx@@ -52,6 +52,7 @@ const VIDEO_RENDER_BACKENDS = [{ id: 'local', label: 'Local', icon: Cpu },{ id: 'grok', label: 'Grok', icon: Cloud },{ id: 'fal', label: 'fal.ai', icon: Cloud },+ { id: 'reactor', label: 'Reactor.inc', icon: Cloud },];const modelOptions = (models, selected) => {diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex 7bdb525f55..96133e244f 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -116,6 +116,8 @@ export function ImageGenTab() {// (settings, or the FAL_KEY env var server-side). No enabled toggle: the// key's presence IS the opt-in, same shape as loras.js's Civitai key.const [falApiKey, setFalApiKey] = useState('');+ // reactor.inc fast-h3 API key (#6214) — same usability-gate shape as fal above.+ const [reactorApiKey, setReactorApiKey] = useState('');const videoGenSliceRef = useRef({});const [sdapiUrl, setSdapiUrl] = useState('');const [pythonPath, setPythonPath] = useState('');@@ -182,6 +184,7 @@ export function ImageGenTab() {videoGenMode: '',videoGenDisplaySleep: true,falApiKey: '',+ reactorApiKey: '',});const [status, setStatus] = useState(null);@@ -255,6 +258,7 @@ export function ImageGenTab() {const vgMode = normalizeRenderPinValue(vg.mode) || '';const vgDisplaySleep = vg.displaySleep !== false;const vgFalApiKey = vg.fal?.apiKey || '';+ const vgReactorApiKey = vg.reactor?.apiKey || '';const m = ig.mode || IMAGE_GEN_MODE.EXTERNAL;const url = normalizeUrl(ig.external?.sdapiUrl || ig.sdapiUrl);const py = ig.local?.pythonPath || '';@@ -291,6 +295,7 @@ export function ImageGenTab() {setVideoGenMode(vgMode);setVideoGenDisplaySleep(vgDisplaySleep);setFalApiKey(vgFalApiKey);+ setReactorApiKey(vgReactorApiKey);videoGenSliceRef.current = vg;setSdapiUrl(url);setPythonPath(py);@@ -320,6 +325,7 @@ export function ImageGenTab() {videoGenMode: vgMode,videoGenDisplaySleep: vgDisplaySleep,falApiKey: vgFalApiKey,+ reactorApiKey: vgReactorApiKey,});setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));@@ -412,7 +418,8 @@ export function ImageGenTab() {|| JSON.stringify(renderDefaults) !== saved.renderDefaultsJson|| videoGenMode !== saved.videoGenMode|| videoGenDisplaySleep !== saved.videoGenDisplaySleep- || falApiKey !== saved.falApiKey;+ || falApiKey !== saved.falApiKey+ || reactorApiKey !== saved.reactorApiKey;const handleSave = async () => {setSaving(true);@@ -462,6 +469,7 @@ export function ImageGenTab() {mode: videoGenMode || null,displaySleep: videoGenDisplaySleep,fal: { ...videoGenSliceRef.current.fal, apiKey: falApiKey.trim() || undefined },+ reactor: { ...videoGenSliceRef.current.reactor, apiKey: reactorApiKey.trim() || undefined },},};try {@@ -481,6 +489,7 @@ export function ImageGenTab() {videoGenMode,videoGenDisplaySleep,falApiKey: falApiKey.trim(),+ reactorApiKey: reactorApiKey.trim(),});// Reflect the pruned no-op entries back into the editor state so the// dirty check compares like against like after a save.@@ -799,6 +808,20 @@ export function ImageGenTab() {className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"/></FormField>+ <FormField+ label={<>reactor.inc API key<span className="block text-xs text-gray-500 mt-0.5">Enables the reactor.inc fast-h3 video backend on the Video Gen page and in FableLoom, or set the REACTOR_API_KEY environment variable instead.</span></>}+ labelClassName="text-sm text-gray-300"+ >+ <input+ id="reactor-api-key"+ type="password"+ autoComplete="off"+ value={reactorApiKey}+ onChange={(e) => setReactorApiKey(e.target.value)}+ placeholder="reactor-key-..."+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ />+ </FormField><div className="space-y-3">{RENDER_TARGET_OPTIONS.map(({ id, label, video }) => {const entry = renderDefaults[id] || {};diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsxindex 225ab8a52f..1df16390bb 100644--- a/client/src/components/settings/ImageGenTab.test.jsx+++ b/client/src/components/settings/ImageGenTab.test.jsx@@ -245,7 +245,7 @@ describe('ImageGenTab grouped tabs', () => {await waitFor(() => expect(updateSettings).toHaveBeenCalled());const patch = updateSettings.mock.calls[0][0];expect(patch.videoGen).toEqual({- mode: 'local', defaultModelId: 'ltx23_distilled_q4', displaySleep: true, fal: {},+ mode: 'local', defaultModelId: 'ltx23_distilled_q4', displaySleep: true, fal: {}, reactor: {},});});});diff --git a/client/src/hooks/useVideoGenFieldState.js b/client/src/hooks/useVideoGenFieldState.jsindex c8922517da..a22048c3c0 100644--- a/client/src/hooks/useVideoGenFieldState.js+++ b/client/src/hooks/useVideoGenFieldState.js@@ -23,6 +23,9 @@ export function useVideoGenFieldState({const [grokDuration, setGrokDuration] = useState(GROK_VIDEO_DEFAULT_DURATION);const [falDuration, setFalDuration] = useState('');const [falModelId, setFalModelId] = useState('');+ const [reactorClipId, setReactorClipId] = useState('');+ const [reactorSeconds, setReactorSeconds] = useState('');+ const [reactorSeed, setReactorSeed] = useState('');const [mode, setMode] = useState(incomingAudioFilename ? 'a2v' : (incomingSourceImage ? 'image' : 'text'));const [prompt, setPrompt] = useState(incomingPrompt || '');const [negativePrompt, setNegativePrompt] = useState(incomingNegativePrompt || '');@@ -86,6 +89,9 @@ export function useVideoGenFieldState({grokDuration, setGrokDuration,falDuration, setFalDuration,falModelId, setFalModelId,+ reactorClipId, setReactorClipId,+ reactorSeconds, setReactorSeconds,+ reactorSeed, setReactorSeed,guidanceScale, setGuidanceScale,height, setHeight,i2vReferenceMode, setI2vReferenceMode,diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex 3d13904e8f..8255ed553f 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -72,7 +72,8 @@ const editableRemixModel = (models, defaultModelId) => {* one builder for what `server/routes/videoGen.js` validates.*/export function useVideoGenForm({- models, modelContext, availableLoras, grokEnabled, falEnabled = false, remoteSubmissionFields = null,+ models, modelContext, availableLoras, grokEnabled, falEnabled = false, reactorEnabled = false,+ remoteSubmissionFields = null,}) {const [searchParams, setSearchParams] = useSearchParams();const incomingSourceImage = searchParams.get('sourceImageFile');@@ -96,6 +97,9 @@ export function useVideoGenForm({grokDuration, setGrokDuration,falDuration, setFalDuration,falModelId, setFalModelId,+ reactorClipId, setReactorClipId,+ reactorSeconds, setReactorSeconds,+ reactorSeed, setReactorSeed,guidanceScale, setGuidanceScale,height, setHeight,i2vReferenceMode, setI2vReferenceMode,@@ -595,7 +599,11 @@ export function useVideoGenForm({// toggle — same short-circuit shape as grok: only prompt/dims/source-image// and a duration reach the provider.const isFal = falEnabled && backend === 'fal';- const referenceModeApplies = mode === 'image' && !isGrok && !isFal;+ // reactor.inc fast-h3 is likewise usability-gated on a configured API key+ // (`reactorEnabled`) — same short-circuit shape as fal, plus native+ // clip-to-clip chaining via continue_from_clip_id.+ const isReactor = reactorEnabled && backend === 'reactor';+ const referenceModeApplies = mode === 'image' && !isGrok && !isFal && !isReactor;// The strength the render will actually use, for the slider readout — an// untouched slider under Inspire still resolves to the contract's low default// rather than the pipeline's 1.0, and the panel must say so.@@ -879,7 +887,7 @@ export function useVideoGenForm({// clip survives the switch and reappears if the user flips back.const handleBackendChange = (id) => {setBackend(id);- if ((id === 'grok' || id === 'fal') && mode !== 'text' && mode !== 'image') {+ if ((id === 'grok' || id === 'fal' || id === 'reactor') && mode !== 'text' && mode !== 'image') {handleModeChange((sourceImageFile || sourceImageUpload) ? 'image' : 'text');}};@@ -1175,6 +1183,13 @@ export function useVideoGenForm({setMode(p.videoMode === 'image' ? 'image' : 'text');if (p.duration) setFalDuration(p.duration);if (p.modelId) setFalModelId(p.modelId);+ } else if (p.mode === 'reactor') {+ // reactor.inc job: same discriminator shape as grok/fal above.+ setBackend('reactor');+ setMode(p.videoMode === 'image' ? 'image' : 'text');+ if (p.continueFromClipId) setReactorClipId(p.continueFromClipId);+ if (p.seconds) setReactorSeconds(p.seconds);+ if (p.seed !== undefined && p.seed !== null) setReactorSeed(p.seed);} else if (p.mode) setMode(p.mode);if (p.chunks && p.chunks > 1) setChunks(p.chunks);// 0 is a real restored value ("last frame only"), so this can't gate on@@ -1247,7 +1262,8 @@ export function useVideoGenForm({// Snapshot the current validated state into a wire payload. The submit flow// stays pure so all three backend contracts can be tested independently.const submissionState = {- isGrok, grokDuration, isFal, falDuration, falModelId, remoteSubmissionFields,+ isGrok, grokDuration, isFal, falDuration, falModelId,+ isReactor, reactorClipId, reactorSeconds, reactorSeed, remoteSubmissionFields,prompt, negativePrompt, stylePreset, selectedUniverse,width, height, mode, sourceImageFile, sourceImageUpload,numFrames, fps, steps, guidanceScale, seed,@@ -1263,10 +1279,13 @@ export function useVideoGenForm({return {// Backend + mode- backend, isGrok, isFal, handleBackendChange,+ backend, isGrok, isFal, isReactor, handleBackendChange,grokDuration, setGrokDuration,falDuration, setFalDuration,falModelId, setFalModelId,+ reactorClipId, setReactorClipId,+ reactorSeconds, setReactorSeconds,+ reactorSeed, setReactorSeed,mode, handleModeChange,// Prompt + styleprompt, setPrompt,diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.jsindex 6a87d0bd4b..2f8811e51f 100644--- a/client/src/lib/imageGenModes.js+++ b/client/src/lib/imageGenModes.js@@ -71,7 +71,7 @@ export const RENDER_TARGET_OPTIONS = Object.freeze([// Client mirror of the server's VIDEO_GEN_MODES (services/videoGen/modes.js) —// the backend alphabet for the video pin controls above and the install-wide// `settings.videoGen.mode` pin.-export const VIDEO_RENDER_MODES = Object.freeze(['local', 'grok', 'fal']);+export const VIDEO_RENDER_MODES = Object.freeze(['local', 'grok', 'fal', 'reactor']);// Client mirror of the server's normalizeRenderPinValue// (server/lib/renderTargets.js) — THE one render-pin normalization rule: trim;@@ -95,6 +95,7 @@ export const MODE_LABELS = Object.freeze({[IMAGE_GEN_MODE.AGY]: 'Agy',[IMAGE_GEN_MODE.EXTERNAL]: 'External',fal: 'fal.ai',+ reactor: 'Reactor.inc',});// Client mirror of the server's CLOUD_IMAGE_GEN_MODES (imageGen/modes.js) —diff --git a/client/src/lib/videoGenSubmission.js b/client/src/lib/videoGenSubmission.jsindex e454c778ab..60c03045e3 100644--- a/client/src/lib/videoGenSubmission.js+++ b/client/src/lib/videoGenSubmission.js@@ -34,7 +34,8 @@ export function envelopVideoPrompt(text, {}export function buildVideoGenSubmission({- isGrok, grokDuration, isFal, falDuration, falModelId, remoteSubmissionFields,+ isGrok, grokDuration, isFal, falDuration, falModelId,+ isReactor, reactorClipId, reactorSeconds, reactorSeed, remoteSubmissionFields,prompt, negativePrompt, stylePreset, selectedUniverse,width, height, mode, sourceImageFile, sourceImageUpload,numFrames, fps, steps, guidanceScale, seed,@@ -86,6 +87,26 @@ export function buildVideoGenSubmission({};}+ if (isReactor) {+ return {+ backend: 'reactor',+ prompt: composed.prompt,+ negativePrompt: composed.negativePrompt,+ reactorClipId: reactorClipId || undefined,+ reactorSeconds: reactorSeconds || undefined,+ // Unlike falDuration/falModelId, a seed of 0 is a real, meaningful+ // value — `|| undefined` would silently drop it (the reactor route+ // and reactor.js's own buildRequestBody already preserve 0 correctly,+ // so only the client-side send needs the nullish check).+ reactorSeed: reactorSeed === '' || reactorSeed === null || reactorSeed === undefined ? undefined : reactorSeed,+ // No width/height: unlike grok/fal, reactor.js reads no dimension+ // field — submitJob's reactor lane never forwards them.+ mode: mode === 'image' ? 'image' : 'text',+ sourceImageFile: mode === 'image' ? (sourceImageFile || '') : '',+ sourceImage: mode === 'image' ? (sourceImageUpload || '') : '',+ };+ }+if (remoteSubmissionFields) {return {backend: 'local',diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex b3054d6b28..e53c59e69e 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -137,6 +137,9 @@ export default function VideoGen() {// fal.ai queue REST video backend (#6213) — surfaced only when an API key is// configured (Settings → Video Gen, or the FAL_KEY env var).const [falEnabled, setFalEnabled] = useState(false);+ // reactor.inc fast-h3 video backend (#6214) — same usability gate shape as+ // fal.ai above.+ const [reactorEnabled, setReactorEnabled] = useState(false);// The jobId of the render this tab's Generate button currently owns —// threaded into cancelVideoGen so cancellation is job-scoped.const activeJobIdRef = useRef(null);@@ -146,6 +149,7 @@ export default function VideoGen() {.then((sv) => {setGrokEnabled(sv?.imageGen?.grok?.enabled === true);setFalEnabled(Boolean(sv?.videoGen?.fal?.apiKey));+ setReactorEnabled(Boolean(sv?.videoGen?.reactor?.apiKey));}).catch(() => {});}, []);@@ -163,8 +167,9 @@ export default function VideoGen() {// Every field the form submits, plus the payload builder both submit paths// share. See client/src/hooks/useVideoGenForm.js.const {- backend, isGrok, isFal, handleBackendChange, grokDuration, setGrokDuration,+ backend, isGrok, isFal, isReactor, handleBackendChange, grokDuration, setGrokDuration,falDuration, setFalDuration, falModelId, setFalModelId,+ reactorClipId, setReactorClipId, reactorSeconds, setReactorSeconds, reactorSeed, setReactorSeed,mode, handleModeChange,prompt, setPrompt, envelopedPrompt, negativePrompt, setNegativePrompt, stylePreset, setStylePreset,selectedUniverse, setSelectedUniverse, remixModelFallback,@@ -199,7 +204,7 @@ export default function VideoGen() {icStrength, setIcStrength, icSkipStage2, setIcSkipStage2,applyRemix, applyFinish, applyResumedParams, buildGeneratePayload,} = useVideoGenForm({- models, modelContext, availableLoras, grokEnabled, falEnabled,+ models, modelContext, availableLoras, grokEnabled, falEnabled, reactorEnabled,remoteSubmissionFields: remoteTarget.isRemote ? remoteTarget.submissionFields : null,});@@ -224,6 +229,7 @@ export default function VideoGen() {const present = [['the Grok backend', isGrok],['the fal.ai backend', isFal],+ ['the reactor.inc backend', isReactor],// Each remaining pipeline semantic has its own input listed below, but the// mode can be set before that input is filled — so gate the mode too// rather than letting an a2v render reach the peer as plain text-to-video.@@ -250,7 +256,7 @@ export default function VideoGen() {return `${model?.modelName || 'The selected peer model'} renders only from a source image — add a start frame, or pick a text-to-video model.`;}return null;- }, [remoteTarget.isRemote, remoteTarget.model, remoteTarget.acceptsInput, isGrok, isFal, mode, sourceImageFile, sourceImageUpload,+ }, [remoteTarget.isRemote, remoteTarget.model, remoteTarget.acceptsInput, isGrok, isFal, isReactor, mode, sourceImageFile, sourceImageUpload,lastImageFile, lastImageUpload, keyframesActive, extendFromVideoId, audioFile, icReferenceFile,icReferenceVideoId, icReferenceImageFiles, selectedLoras, chunks]);// One reading for the Generate button, the enqueue guard and the caption.@@ -614,14 +620,14 @@ export default function VideoGen() {startEncoderWhenIdle(option && !option.builtIn ? textEncoderDownloadId(id) : null);}, [setTextEncoderId, textEncoderOptions, startEncoderWhenIdle]);const icWeightStatus = icSpec ? modelDownload.getStatus(icSpec.mode) : null;- const modelWeightsBlocked = !isGrok && !isFal+ const modelWeightsBlocked = !isGrok && !isFal && !isReactor&& (statusLoading || !modelId || !currentModel || modelDownload.loading|| modelStatus === null || modelStatus?.cached === false);- const textEncoderWeightsBlocked = !isGrok && !isFal && usesSharedTextEncoder+ const textEncoderWeightsBlocked = !isGrok && !isFal && !isReactor && usesSharedTextEncoder&& (modelDownload.loading || textEncoderStatus === null || textEncoderStatus?.cached === false);- const icWeightsBlocked = !isGrok && !isFal && icModeActive+ const icWeightsBlocked = !isGrok && !isFal && !isReactor && icModeActive&& (modelDownload.loading || icWeightStatus === null || icWeightStatus?.cached === false);- const textEncoderOptionBlocked = !isGrok && !isFal && !!textEncoderOptionDownloadId+ const textEncoderOptionBlocked = !isGrok && !isFal && !isReactor && !!textEncoderOptionDownloadId&& (modelDownload.loading || textEncoderOptionStatus === null || textEncoderOptionStatus?.cached === false);const weightsGateBlocked = modelWeightsBlocked || textEncoderWeightsBlocked|| textEncoderOptionBlocked || icWeightsBlocked;@@ -694,7 +700,7 @@ export default function VideoGen() {// actually apply it (macOS, and the user hasn't opted out).const rendersSleepDisplay = !!status?.displaySleepOnRender&& !!currentModel?.sleepsDisplayDuringRender- && !remoteTarget.isRemote && !isGrok && !isFal;+ && !remoteTarget.isRemote && !isGrok && !isFal && !isReactor;// Run a single payload through the SSE pipeline. Returns a promise that// resolves when the job completes (or rejects on error / cancel). The@@ -844,7 +850,7 @@ export default function VideoGen() {// will actually run on.const canEnqueue = prompt.trim() && (remoteTarget.isRemote? remoteBlocked === null- : (isGrok || isFal || (!notConnected && !extendModeBlocked+ : (isGrok || isFal || isReactor || (!notConnected && !extendModeBlocked&& !a2vModeBlocked && !icLoraModeBlocked && !byovGateBlocked&& !weightsGateBlocked && !keyframesBlocked)));@@ -919,15 +925,17 @@ export default function VideoGen() {})()}{/* Backend switch — shown only when the user enabled Grok in Settings →- Image Gen and/or configured a fal.ai API key. Both cloud backends'- image-to-video only supports text (image-first) and image modes, so- switching to either snaps an unsupported mode back to the nearest one. */}- {(grokEnabled || falEnabled) && (+ Image Gen and/or configured a fal.ai or reactor.inc API key. Every+ cloud backend's image-to-video only supports text (image-first) and+ image modes, so switching to one snaps an unsupported mode back to+ the nearest one. */}+ {(grokEnabled || falEnabled || reactorEnabled) && (<div className="bg-port-card border border-port-border rounded-xl p-1 flex gap-1" role="group" aria-label="Video generation backend">{[{ id: 'local', label: 'Local' },...(grokEnabled ? [{ id: 'grok', label: 'Grok' }] : []),...(falEnabled ? [{ id: 'fal', label: 'fal.ai' }] : []),+ ...(reactorEnabled ? [{ id: 'reactor', label: 'Reactor.inc' }] : []),].map(({ id, label }) => (<buttonkey={id}@@ -941,7 +949,9 @@ export default function VideoGen() {? 'Render via the Grok Build CLI (image_gen → image_to_video). Counts against your Grok plan.': id === 'fal'? 'Render via the fal.ai queue API. Counts against your fal.ai balance.'- : 'Render on this machine with the local runtimes.'}+ : id === 'reactor'+ ? 'Render via the reactor.inc fast-h3 API. Counts against your reactor.inc balance.'+ : 'Render on this machine with the local runtimes.'}>{label}</button>@@ -955,7 +965,7 @@ export default function VideoGen() {WAI-ARIA Tabs, since the mode-specific inputs aren't structured astabpanels and we don't implement roving-tabindex/arrow-key focus. */}<div className="bg-port-card border border-port-border rounded-xl p-1 flex flex-wrap gap-1" role="group" aria-label="Video generation mode">- {((isGrok || isFal) ? MODES.filter((m) => m.id === 'text' || m.id === 'image') : MODES).map(({ id, label, icon: Icon, desc }) => {+ {((isGrok || isFal || isReactor) ? MODES.filter((m) => m.id === 'text' || m.id === 'image') : MODES).map(({ id, label, icon: Icon, desc }) => {const active = mode === id;return (<button@@ -979,7 +989,7 @@ export default function VideoGen() {<form onSubmit={handleGenerate} className="grid grid-cols-1 lg:grid-cols-[3fr_2fr] gap-4"><div className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">- {!isGrok && !isFal && byovRuntimeMissing && (+ {!isGrok && !isFal && !isReactor && byovRuntimeMissing && (<div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2"><div><strong className="font-semibold">{byovStatus.label}</strong> {byovStatus.upgradeAvailable ? 'has an update available.' : "isn't installed yet."}@@ -1080,10 +1090,10 @@ export default function VideoGen() {<AutoSizeTextareavalue={negativePrompt}onChange={(e) => setNegativePrompt(e.target.value)}- disabled={!isGrok && !isFal && currentModel?.supportsNegativePrompt === false}+ disabled={!isGrok && !isFal && !isReactor && currentModel?.supportsNegativePrompt === false}rows={3}className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 min-h-[80px]"- placeholder={!isGrok && !isFal && currentModel?.supportsNegativePrompt === false+ placeholder={!isGrok && !isFal && !isReactor && currentModel?.supportsNegativePrompt === false? 'This CFG-distilled model does not use a negative prompt.': 'What to avoid...'}/>@@ -1293,6 +1303,42 @@ export default function VideoGen() {Renders on fal.ai's queue API — leave the model blank to use PortOS's default (text-to-video, or image-to-video in Image mode). Counts against your fal.ai balance.</p></div>+ ) : isReactor ? (+ <div className="grid grid-cols-2 gap-3">+ <FormField label="Continue from clip" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ <input+ type="text"+ value={reactorClipId}+ onChange={(e) => setReactorClipId(e.target.value)}+ placeholder="clip id (optional)"+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ />+ </FormField>+ <FormField label="Clip length (sec)" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ <input+ type="number"+ min={1}+ max={60}+ value={reactorSeconds}+ onChange={(e) => setReactorSeconds(e.target.value)}+ placeholder="model default"+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ />+ </FormField>+ <FormField label="Seed" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ <input+ type="number"+ min={0}+ value={reactorSeed}+ onChange={(e) => setReactorSeed(e.target.value)}+ placeholder="random"+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ />+ </FormField>+ <p className="col-span-2 text-[11px] text-gray-500 leading-snug">+ Renders on reactor.inc's fast-h3 API — near-realtime with native frame-accurate chaining via "Continue from clip". Counts against your reactor.inc balance.+ </p>+ </div>) : (<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">{/* The peer advertises its own models; the local list would name@@ -1442,11 +1488,11 @@ export default function VideoGen() {<ModelDisclosurebackend={backend}backendDisclosures={status?.backendDisclosures}- model={(isGrok || isFal) ? null : currentModel}+ model={(isGrok || isFal || isReactor) ? null : currentModel}systemMemoryGb={modelContext?.systemMemoryGb}/>- {!isGrok && !isFal && (+ {!isGrok && !isFal && !isReactor && (<AdvancedParamsPanelmode={mode}currentModel={currentModel}diff --git a/server/lib/generationModes.js b/server/lib/generationModes.jsindex 92b3ec1ef6..788ed02204 100644--- a/server/lib/generationModes.js+++ b/server/lib/generationModes.js@@ -33,13 +33,17 @@ export const QUEUEABLE_IMAGE_MODES = Object.freeze([// Video deliberately shares the image backend discriminator namespace. Local// video's text/image/fflf modes are a separate semantic value carried elsewhere.-// FAL has no image-gen counterpart (issue #6213 is video-only), so it is a-// video-only literal rather than a re-export of an IMAGE_GEN_MODE entry.+// FAL and REACTOR have no image-gen counterpart (issues #6213/#6214 are+// video-only), so they are video-only literals rather than re-exports of an+// IMAGE_GEN_MODE entry.export const VIDEO_GEN_MODE = Object.freeze({LOCAL: IMAGE_GEN_MODE.LOCAL,GROK: IMAGE_GEN_MODE.GROK,FAL: 'fal',+ REACTOR: 'reactor',});export const VIDEO_GEN_MODES = Object.freeze(Object.values(VIDEO_GEN_MODE));-export const CLOUD_VIDEO_GEN_MODES = Object.freeze([VIDEO_GEN_MODE.GROK, VIDEO_GEN_MODE.FAL]);+export const CLOUD_VIDEO_GEN_MODES = Object.freeze([+ VIDEO_GEN_MODE.GROK, VIDEO_GEN_MODE.FAL, VIDEO_GEN_MODE.REACTOR,+]);diff --git a/server/lib/generationModes.test.js b/server/lib/generationModes.test.jsindex 7f44009b95..5f89eee241 100644--- a/server/lib/generationModes.test.js+++ b/server/lib/generationModes.test.js@@ -22,10 +22,12 @@ describe('generation mode alphabets', () => {].every(Object.isFrozen)).toBe(true);});- it('keeps the video backend alphabet in the image discriminator namespace, plus fal as a video-only extra', () => {- expect(VIDEO_GEN_MODE).toEqual({ LOCAL: IMAGE_GEN_MODE.LOCAL, GROK: IMAGE_GEN_MODE.GROK, FAL: 'fal' });- expect(VIDEO_GEN_MODES).toEqual(['local', 'grok', 'fal']);- expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok', 'fal']);+ it('keeps the video backend alphabet in the image discriminator namespace, plus fal/reactor as video-only extras', () => {+ expect(VIDEO_GEN_MODE).toEqual({+ LOCAL: IMAGE_GEN_MODE.LOCAL, GROK: IMAGE_GEN_MODE.GROK, FAL: 'fal', REACTOR: 'reactor',+ });+ expect(VIDEO_GEN_MODES).toEqual(['local', 'grok', 'fal', 'reactor']);+ expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok', 'fal', 'reactor']);expect([VIDEO_GEN_MODE, VIDEO_GEN_MODES, CLOUD_VIDEO_GEN_MODES].every(Object.isFrozen)).toBe(true);});});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 555a1a32a1..2abe2af928 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1649,6 +1649,11 @@ export const videoGenSettingsSchema = z.object({fal: z.object({apiKey: z.preprocess((v) => (v === '' ? undefined : v), z.string().trim().max(200).optional()),}).optional(),+ // reactor.inc fast-h3 provider (#6214) — same settings-wins-over-env+ // precedence as `fal` above.+ reactor: z.object({+ apiKey: z.preprocess((v) => (v === '' ? undefined : v), z.string().trim().max(200).optional()),+ }).optional(),});// POST /api/video-gen/model-terms — record (or withdraw) the acknowledgement ofdiff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 321d442882..4b2443fbd5 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -43,6 +43,7 @@ import {} from '../services/videoGen/local.js';import { cleanupMultipartTemp } from '../services/videoGen/prepareParams.js';import { submitVideoGenJob } from '../services/videoGen/submitJob.js';+import { resolveReactorApiKey, mintReactorToken } from '../services/videoGen/reactor.js';import { VIDEO_GEN_LOCAL_ONLY_FIELDS } from '../services/videoGen/requestFields.js';import { attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';import { getTextEncoderRepo, isHfRepoId } from '../lib/mediaModels.js';@@ -244,11 +245,12 @@ export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({const generateBodySchema = z.object({// Render backend: the local runtimes (default), the Grok Build CLI's- // image-first image_to_video flow (#2859 phase 2), or fal.ai's queue REST- // API (#6213). Grok and fal both ignore the local-only knobs below; they- // read prompt/negativePrompt, width/height (mapped to an aspect ratio),- // sourceImageFile/sourceImage, and their own duration field.- backend: z.enum(['local', 'grok', 'fal']).optional(),+ // image-first image_to_video flow (#2859 phase 2), fal.ai's queue REST API+ // (#6213), or reactor.inc's fast-h3 API (#6214). Grok, fal, and reactor all+ // ignore the local-only knobs below; they read prompt/negativePrompt,+ // width/height (mapped to an aspect ratio), sourceImageFile/sourceImage,+ // and their own duration field.+ backend: z.enum(['local', 'grok', 'fal', 'reactor']).optional(),// Grok image_to_video clip length in seconds — the shared schema (see// lib/grokVideoClip.js for which lengths grok actually delivers). Multipart// bodies arrive as strings, so coerce first.@@ -264,6 +266,18 @@ const generateBodySchema = z.object({(v) => (v == null || v === '' ? undefined : Number(v)),optionalNum(1, 60, 'falDuration'),),+ // reactor.inc fast-h3 (#6214): the clip id to chain from+ // (continue_from_clip_id — frame-accurate continuation, unlike fal/grok+ // which start a fresh render each time) and clip length in seconds.+ reactorClipId: z.string().min(1).max(200).optional(),+ reactorSeconds: z.preprocess(+ (v) => (v == null || v === '' ? undefined : Number(v)),+ optionalNum(1, 60, 'reactorSeconds'),+ ),+ reactorSeed: z.preprocess(+ (v) => (v == null || v === '' ? undefined : Number(v)),+ optionalNum(0, 2 ** 32 - 1, 'reactorSeed'),+ ),prompt: z.string().min(1).max(8000),negativePrompt: z.string().max(8000).optional(),modelId: z.string().max(64).optional(),@@ -505,6 +519,18 @@ router.post('/model-terms', asyncHandler(async (req, res) => {res.json({ accepted: acceptedVideoModelTerms(next) });}));+// Mints a short-lived reactor.inc session JWT scoped to `reactor/fast-h3`+// (#6214) — the raw REACTOR_API_KEY never reaches the client. Load-bearing+// security pattern: never cached, and the scope/session bound is set by+// reactor.js#mintReactorToken, not by the caller.+router.get('/reactor/token', asyncHandler(async (_req, res) => {+ res.set('Cache-Control', 'private, no-store');+ const settings = await getSettings();+ const apiKey = resolveReactorApiKey(settings);+ const { jwt, expiresAt } = await mintReactorToken(apiKey);+ res.json({ jwt, expires_at: expiresAt });+}));+// `installed` here means "fully ready to render" — both the venv binary// exists AND its python packages are importable. The sync existsSync gate// alone is too permissive: a partial install (clone done, `uv pip install`@@ -874,6 +900,10 @@ const ACTIVE_JOB_PARAM_FIELDS = [// 'grok' discriminator for them) and the clip duration — both plain// values, safe to echo for the reloading page's form restore.'videoMode', 'duration',+ // reactor.inc jobs (#6214): the clip to chain from and the clip length —+ // both plain scalars (no filesystem path), safe to echo for the reloading+ // page's form restore. `seed` above already covers reactor's seed field.+ 'continueFromClipId', 'seconds',// loras are { filename, scale } basenames (no server filesystem paths), so// they're safe to echo back for the resuming picker to repopulate.'loras',diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 61bd9bba9a..f1838f7225 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -163,6 +163,7 @@ function getGenModuleForJob(job) {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' && job.params?.mode === VIDEO_GEN_MODE.FAL) return import('../videoGen/fal.js');+ if (job.kind === 'video' && job.params?.mode === VIDEO_GEN_MODE.REACTOR) return import('../videoGen/reactor.js');if (job.kind === 'video') return import('../videoGen/local.js');if (job.kind === 'training') return import('../loraTraining/index.js');if (job.kind === 'audio') return import('../audioGen/local.js');diff --git a/server/services/videoGen/modes.js b/server/services/videoGen/modes.jsindex 3afc388c35..32e85184dd 100644--- a/server/services/videoGen/modes.js+++ b/server/services/videoGen/modes.js@@ -47,6 +47,11 @@ export function isVideoModeUsable(settings, mode) {if (mode === VIDEO_GEN_MODE.FAL) {return Boolean((settings?.videoGen?.fal?.apiKey || '').trim() || (process.env.FAL_KEY || '').trim());}+ // reactor.inc is likewise a metered REST API — usability gated on a+ // configured API key (settings or REACTOR_API_KEY env), same shape as fal.+ if (mode === VIDEO_GEN_MODE.REACTOR) {+ return Boolean((settings?.videoGen?.reactor?.apiKey || '').trim() || (process.env.REACTOR_API_KEY || '').trim());+ }return mode === VIDEO_GEN_MODE.LOCAL;}diff --git a/server/services/videoGen/modes.test.js b/server/services/videoGen/modes.test.jsindex 74427aba50..73e7125cca 100644--- a/server/services/videoGen/modes.test.js+++ b/server/services/videoGen/modes.test.js@@ -11,8 +11,8 @@ describe('VIDEO_GEN_MODE', () => {// rather than re-typing is what keeps a schema from drifting from dispatch.expect(VIDEO_GEN_MODE.LOCAL).toBe(IMAGE_GEN_MODE.LOCAL);expect(VIDEO_GEN_MODE.GROK).toBe(IMAGE_GEN_MODE.GROK);- expect(VIDEO_GEN_MODES).toEqual(['local', 'grok', 'fal']);- expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok', 'fal']);+ expect(VIDEO_GEN_MODES).toEqual(['local', 'grok', 'fal', 'reactor']);+ expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok', 'fal', 'reactor']);expect(Object.isFrozen(VIDEO_GEN_MODE)).toBe(true);});});@@ -43,6 +43,16 @@ describe('isVideoModeUsable', () => {expect(isVideoModeUsable({}, 'fal')).toBe(true);if (prevEnv === undefined) delete process.env.FAL_KEY; else process.env.FAL_KEY = prevEnv;});++ it('gates reactor on a configured API key, settings or env', () => {+ expect(isVideoModeUsable({ videoGen: { reactor: { apiKey: 'key' } } }, 'reactor')).toBe(true);+ expect(isVideoModeUsable({ videoGen: { reactor: { apiKey: ' ' } } }, 'reactor')).toBe(false);+ expect(isVideoModeUsable({}, 'reactor')).toBe(false);+ const prevEnv = process.env.REACTOR_API_KEY;+ process.env.REACTOR_API_KEY = 'env-key';+ expect(isVideoModeUsable({}, 'reactor')).toBe(true);+ if (prevEnv === undefined) delete process.env.REACTOR_API_KEY; else process.env.REACTOR_API_KEY = prevEnv;+ });});describe('resolveVideoMode', () => {diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.jsindex de243b1970..e96350a5c1 100644--- a/server/services/videoGen/prepareParams.js+++ b/server/services/videoGen/prepareParams.js@@ -350,7 +350,8 @@ export async function prepareVideoGenParams({ body, uploads, localOnlyParamKeys// shared with services/videoGen/local.js so the route and worker stay// in sync.const runtimeBringsOwnVenv = effectiveModel && BYOV_VIDEO_RUNTIMES.has(effectiveModel.runtime);- if (!pythonPath && !runtimeBringsOwnVenv && backend !== VIDEO_GEN_MODE.GROK && backend !== VIDEO_GEN_MODE.FAL) {+ if (!pythonPath && !runtimeBringsOwnVenv+ && backend !== VIDEO_GEN_MODE.GROK && backend !== VIDEO_GEN_MODE.FAL && backend !== VIDEO_GEN_MODE.REACTOR) {await cleanupMultipartTemp(uploads);throw new ServerError('Local video generation is not configured (settings.imageGen.local.pythonPath is missing).',@@ -472,7 +473,7 @@ async function resolvePreparedParams({// plain grok render with the reference clip silently dropped. The client's// mode bar snaps grok back to text/image, but reject explicitly so a direct// caller gets an error instead of a wrong-looking clip.- if (body.backend === VIDEO_GEN_MODE.GROK || body.backend === VIDEO_GEN_MODE.FAL) {+ if (body.backend === VIDEO_GEN_MODE.GROK || body.backend === VIDEO_GEN_MODE.FAL || body.backend === VIDEO_GEN_MODE.REACTOR) {await cleanupStaged();throw new ServerError(`${icSpec.label} mode runs on the local ltx2 runtime — it isn't available on the ${body.backend} backend.`,@@ -784,6 +785,30 @@ async function resolvePreparedParams({};}+ // 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' },+ );+ }+ 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'] },+ sourceImagePath,+ uploadedTempPath,+ discardSourceImage,+ cleanupStaged,+ };+ }+if (uploads.lastImage) {lastImagePath = await stageUploadDurable(uploads.lastImage, 'last');extraUploadedTempPaths.push(lastImagePath);diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.jsnew file mode 100644index 0000000000..43f91687fd--- /dev/null+++ b/server/services/videoGen/reactor.js@@ -0,0 +1,312 @@+/**+ * Video Gen — Reactor.inc `fast-h3` video generation API provider (#6214).+ *+ * A cloud-only, near-realtime (~1.0x) video backend with native+ * clip-to-clip chaining (`continue_from_clip_id`), unlike the local+ * runtimes or the fal.ai/grok queue backends. Mirrors `videoGen/fal.js`'s+ * job-map/SSE contract (cloud lane, no local child process) so+ * `mediaJobQueue` can dispatch to it the same way.+ *+ * Auth flow: PortOS never hands the caller the raw `REACTOR_API_KEY` — it+ * mints a short-lived, scoped session JWT server-side (`mintReactorToken`,+ * also exposed at `GET /api/video-gen/reactor/token`) and uses that JWT to+ * submit/poll/cancel. Flow: POST the prompt (plus optional+ * `continue_from_clip_id` and a base64-encoded starting frame) to+ * `api.reactor.inc/v1/fast-h3/generate`, poll the returned status URL until+ * COMPLETED, then download the resulting MP4 and hand it to the shared+ * `finalizeGeneratedVideo` helper — same streaming optimization, thumbnail,+ * and history entry as every other video backend.+ */++import { randomUUID } from 'crypto';+import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { ensureDir, PATHS } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';+import { detectImageFormat } from '../../lib/mimeTypes.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';+import { videoGenEvents } from './events.js';+import { finalizeGeneratedVideo } from './generateVideoHelpers.js';+import { mutateVideoHistory } from './history.js';+import { getSettings } from '../settings.js';++export const REACTOR_API_BASE = 'https://api.reactor.inc';+export const REACTOR_MODEL_ID = 'fast-h3';+export const REACTOR_MAX_PROMPT_LENGTH = 800;++const REACTOR_TOKEN_TIMEOUT_MS = 15_000;+const REACTOR_SUBMIT_TIMEOUT_MS = 30_000;+const REACTOR_POLL_TIMEOUT_MS = 15_000;+const REACTOR_POLL_INTERVAL_MS = 3000;+const REACTOR_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;+// A cloud render can queue behind other tenants before it starts — generously+// bounded, same order of magnitude as fal's and grok's render caps.+const REACTOR_RENDER_TIMEOUT_MS = (() => {+ const n = Number(process.env.REACTOR_VIDEO_TIMEOUT_MS);+ return Number.isFinite(n) && n > 0 ? n : 20 * 60 * 1000;+})();++// Per-job state — keyed by jobId (cloud lane allows parallel renders). Same+// client shape as videoGen/fal.js so attachSseClient/broadcastSse work.+const jobs = new Map();+// Tracks the reactor.inc request so cancel() can both stop our poll loop and+// ask reactor.inc to cancel the queued/running render.+const activeRequests = new Map();+const activeJobs = new Map();++export const getActiveJob = () => {+ const entries = [...activeJobs.values()];+ return entries.length ? entries[entries.length - 1] : null;+};++export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);++/**+ * Resolve the reactor.inc API key: settings override, else the+ * `REACTOR_API_KEY` env var (same settings-wins-over-env precedence as+ * `videoGen/fal.js`'s `resolveFalApiKey`).+ */+export function resolveReactorApiKey(settings) {+ const fromSettings = (settings?.videoGen?.reactor?.apiKey || '').trim();+ if (fromSettings) return fromSettings;+ const fromEnv = (process.env.REACTOR_API_KEY || '').trim();+ return fromEnv || null;+}++/**+ * Mint a short-lived session JWT scoped to `reactor/fast-h3`, bounded to one+ * concurrent session. Called by the `/api/video-gen/reactor/token` route AND+ * internally before every submit — the raw API key never leaves this module.+ */+export async function mintReactorToken(apiKey) {+ if (!apiKey) {+ throw new ServerError('No reactor.inc API key configured — set it in Settings > Video Gen or the REACTOR_API_KEY env var', { status: 400, code: 'REACTOR_NOT_CONFIGURED' });+ }+ const res = await fetchWithTimeout(`${REACTOR_API_BASE}/tokens`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ authorization_details: [{ type: `reactor/${REACTOR_MODEL_ID}`, max_sessions: 1 }],+ }),+ }, REACTOR_TOKEN_TIMEOUT_MS);+ const payload = await res.json().catch(() => null);+ if (!res.ok || !payload?.jwt) {+ const reason = payload?.detail ? JSON.stringify(payload.detail) : `HTTP ${res.status}`;+ throw new ServerError(`reactor.inc token minting failed: ${reason}`, { status: 502, code: 'REACTOR_TOKEN_FAILED' });+ }+ return { jwt: payload.jwt, expiresAt: payload.expires_at || null };+}++export const cancel = (jobId) => {+ if (!jobId) {+ throw new Error("videoGen/reactor.cancel requires a jobId — use cancelAll() to terminate every in-flight render");+ }+ const entry = activeRequests.get(jobId);+ if (!entry) return false;+ entry.aborted = true;+ if (entry.cancelUrl && entry.jwt) {+ fetchWithTimeout(entry.cancelUrl, {+ method: 'PUT',+ headers: { Authorization: `Bearer ${entry.jwt}` },+ }, REACTOR_POLL_TIMEOUT_MS).catch(() => {});+ }+ return true;+};++export const cancelAll = () => {+ const ids = [...activeRequests.keys()];+ if (ids.length === 0) return false;+ for (const id of ids) cancel(id);+ return true;+};++async function toDataUri(imagePath) {+ const buf = await readFile(imagePath);+ const detected = detectImageFormat(buf);+ const mime = detected?.mime || 'image/png';+ return `data:${mime};base64,${buf.toString('base64')}`;+}++function buildRequestBody({ prompt, continueFromClipId, startingFrameDataUri, seconds, seed }) {+ const body = { prompt: prompt.trim().slice(0, REACTOR_MAX_PROMPT_LENGTH) };+ if (continueFromClipId) body.continue_from_clip_id = continueFromClipId;+ if (startingFrameDataUri) body.starting_frame = startingFrameDataUri;+ if (seconds) body.seconds = Number(seconds);+ if (seed !== undefined && seed !== null && seed !== '') body.seed = Number(seed);+ return body;+}++async function submitReactorJob({ jwt, body }) {+ const res = await fetchWithTimeout(`${REACTOR_API_BASE}/v1/${REACTOR_MODEL_ID}/generate`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ }, REACTOR_SUBMIT_TIMEOUT_MS);+ const payload = await res.json().catch(() => null);+ if (!res.ok || !payload?.clip_id) {+ const reason = payload?.detail ? JSON.stringify(payload.detail) : `HTTP ${res.status}`;+ throw new ServerError(`reactor.inc rejected the request: ${reason}`, { status: 502, code: 'REACTOR_SUBMIT_FAILED' });+ }+ return payload;+}++async function pollReactorStatus({ statusUrl, jwt }) {+ const res = await fetchWithTimeout(statusUrl, {+ headers: { Authorization: `Bearer ${jwt}` },+ }, REACTOR_POLL_TIMEOUT_MS);+ if (res.status === 401) {+ throw new ServerError('reactor.inc session expired', { status: 401, code: 'REACTOR_TOKEN_EXPIRED' });+ }+ if (!res.ok) throw new ServerError(`reactor.inc status check failed: HTTP ${res.status}`, { status: 502, code: 'REACTOR_STATUS_FAILED' });+ return res.json();+}++export async function generateVideo({+ settings, prompt = '', negativePrompt,+ continueFromClipId, seconds, seed,+ sourceImagePath = null, jobId: providedJobId = null,+}) {+ await ensureDir(PATHS.videos);+ const renderStartedAtMs = Date.now();++ if (!prompt?.trim()) {+ throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });+ }+ // The reactor API key stays server-side: re-resolve live settings here+ // (mirrors videoGen/fal.js's precedent) rather than threading the secret+ // through job.params, where it would sit in plaintext in media-jobs.json.+ const effectiveSettings = settings || await getSettings().catch(() => null);+ const apiKey = resolveReactorApiKey(effectiveSettings);+ if (!apiKey) {+ throw new ServerError('No reactor.inc API key configured — set it in Settings > Video Gen or the REACTOR_API_KEY env var', { status: 400, code: 'REACTOR_NOT_CONFIGURED' });+ }++ const jobId = providedJobId || randomUUID();+ const filename = `${jobId}.mp4`;+ const outputPath = join(PATHS.videos, filename);++ const meta = {+ id: jobId,+ prompt: prompt.trim(),+ negativePrompt: negativePrompt || '',+ modelId: `reactor:${REACTOR_MODEL_ID}`,+ ...(continueFromClipId ? { continueFromClipId } : {}),+ ...(seconds ? { seconds } : {}),+ filename,+ createdAt: new Date().toISOString(),+ mode: sourceImagePath ? 'image' : 'text',+ };+ const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };+ jobs.set(jobId, job);++ console.log(`🎬 Generating video [${jobId.slice(0, 8)}] reactor (${REACTOR_MODEL_ID}): ${prompt.slice(0, 60)}…`);+ videoGenEvents.emit('started', { generationId: jobId, totalSteps: 1, ...meta });+ activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0 });+ broadcastSse(job, { type: 'status', message: 'Minting reactor.inc session…' });++ runReactorVideo(job, jobId, {+ apiKey, prompt, continueFromClipId, seconds, seed, sourceImagePath, outputPath, filename, meta,+ }).catch((err) => {+ console.log(`❌ reactor video run failed [${jobId.slice(0, 8)}]: ${err?.message}`);+ });++ return {+ jobId, filename, path: `/data/videos/${filename}`, generationId: jobId,+ mode: 'reactor',+ status: 'running',+ };+}++async function runReactorVideo(job, jobId, {+ apiKey, prompt, continueFromClipId, seconds, seed, sourceImagePath, outputPath, filename, meta,+}) {+ const entry = { jwt: null, aborted: false, cancelUrl: null };+ activeRequests.set(jobId, entry);+ const deadline = Date.now() + REACTOR_RENDER_TIMEOUT_MS;+ try {+ let { jwt } = await mintReactorToken(apiKey);+ entry.jwt = jwt;+ if (entry.aborted) return finalizeCanceled(job, jobId);++ const startingFrameDataUri = sourceImagePath ? await toDataUri(sourceImagePath) : null;+ const body = buildRequestBody({+ prompt, continueFromClipId, startingFrameDataUri, seconds, seed,+ });+ broadcastSse(job, { type: 'status', message: 'Submitting to reactor.inc…' });+ const submitted = await submitReactorJob({ jwt, body });+ entry.cancelUrl = submitted.cancel_url || `${REACTOR_API_BASE}/v1/${REACTOR_MODEL_ID}/clips/${submitted.clip_id}/cancel`;+ const statusUrl = submitted.status_url || `${REACTOR_API_BASE}/v1/${REACTOR_MODEL_ID}/clips/${submitted.clip_id}`;++ while (Date.now() < deadline) {+ if (entry.aborted) return finalizeCanceled(job, jobId);+ videoGenEvents.emit('activity', { generationId: jobId });+ // A 20-minute render can outlive a short-lived session JWT — re-mint+ // once and retry rather than failing a render that's still in flight.+ let status;+ try {+ status = await pollReactorStatus({ statusUrl, jwt });+ } catch (err) {+ if (err?.code !== 'REACTOR_TOKEN_EXPIRED') throw err;+ ({ jwt } = await mintReactorToken(apiKey));+ entry.jwt = jwt;+ status = await pollReactorStatus({ statusUrl, jwt });+ }+ if (status.status === 'completed') {+ const videoUrl = status.video_url || status.output?.video_url;+ if (!videoUrl) {+ return finalizeError(job, jobId, 'reactor.inc completed but returned no video URL');+ }+ broadcastSse(job, { type: 'status', message: 'Downloading video…' });+ const videoRes = await fetchWithTimeout(videoUrl, {}, REACTOR_DOWNLOAD_TIMEOUT_MS);+ if (!videoRes.ok) {+ return finalizeError(job, jobId, `reactor.inc video download failed: HTTP ${videoRes.status}`);+ }+ const buffer = Buffer.from(await videoRes.arrayBuffer());+ await writeFile(outputPath, buffer);++ activeRequests.delete(jobId);+ activeJobs.delete(jobId);+ await finalizeGeneratedVideo({+ job,+ jobId,+ outputPath,+ filename,+ meta: { ...meta, clipId: status.clip_id || null },+ actualSeed: seed ?? null,+ mutateHistory: mutateVideoHistory,+ });+ closeJobAfterDelay(jobs, jobId);+ return;+ }+ if (status.status === 'failed') {+ return finalizeError(job, jobId, `reactor.inc render failed: ${status.error || 'unknown error'}`);+ }+ broadcastSse(job, { type: 'status', message: status.status === 'processing' ? 'Rendering…' : 'Queued…' });+ await new Promise((r) => setTimeout(r, REACTOR_POLL_INTERVAL_MS));+ }+ if (entry.aborted) return finalizeCanceled(job, jobId);+ return finalizeError(job, jobId, `reactor.inc did not finish within ${Math.round(REACTOR_RENDER_TIMEOUT_MS / 1000)}s`);+ } catch (err) {+ finalizeError(job, jobId, `reactor.inc video generation failed: ${err?.message || err}`);+ }+}++const finalizeCanceled = (job, jobId) => finalizeError(job, jobId, 'Canceled', { force: true });++const finalizeError = (job, jobId, reason, { force = false } = {}) => {+ if (!force && (job.status === 'error' || job.status === 'complete')) return;+ activeRequests.delete(jobId);+ activeJobs.delete(jobId);+ job.status = 'error';+ console.log(`❌ reactor video generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);+ broadcastSse(job, { type: 'error', error: reason });+ videoGenEvents.emit('failed', { generationId: jobId, error: reason });+ closeJobAfterDelay(jobs, jobId);+};++// Test-only handles.+export const _internals = {+ buildRequestBody,+ toDataUri,+};diff --git a/server/services/videoGen/reactor.test.js b/server/services/videoGen/reactor.test.jsnew file mode 100644index 0000000000..3d0c5cc021--- /dev/null+++ b/server/services/videoGen/reactor.test.js@@ -0,0 +1,280 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdir, rm, readFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';++const TEST_ROOT = join(tmpdir(), `portos-reactor-video-test-${process.pid}-${Date.now()}`);+const FAKE_VIDEOS_DIR = join(TEST_ROOT, 'data-videos');+const FAKE_DATA_DIR = join(TEST_ROOT, 'data');++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ actual.PATHS.videos = FAKE_VIDEOS_DIR;+ actual.PATHS.data = FAKE_DATA_DIR;+ return {+ ...actual,+ ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),+ };+});++vi.mock('../../lib/ffmpeg.js', async () => {+ const actual = await vi.importActual('../../lib/ffmpeg.js');+ return {+ ...actual,+ optimizeForStreaming: vi.fn(async () => {}),+ generateThumbnail: vi.fn(async (_p, jobId) => `${jobId}.jpg`),+ };+});++const getSettingsMock = vi.fn();+vi.mock('../settings.js', () => ({ getSettings: getSettingsMock }));++const reactor = await import('./reactor.js');+const { videoGenEvents } = await import('./events.js');+const { loadHistory } = await import('./history.js');++const flush = () => new Promise((r) => setTimeout(r, 10));++const jsonResponse = (body, ok = true, status = 200) => ({+ ok, status,+ json: async () => body,+});++const TOKEN_URL = `${reactor.REACTOR_API_BASE}/tokens`;+const GENERATE_URL = `${reactor.REACTOR_API_BASE}/v1/${reactor.REACTOR_MODEL_ID}/generate`;++beforeEach(async () => {+ videoGenEvents.removeAllListeners();+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});+ await mkdir(FAKE_DATA_DIR, { recursive: true });+ getSettingsMock.mockReset().mockResolvedValue({});+ vi.restoreAllMocks();+});++afterEach(async () => {+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});+});++describe('videoGen/reactor — resolveReactorApiKey', () => {+ it('prefers the settings-stored key over the REACTOR_API_KEY env var', () => {+ const prevEnv = process.env.REACTOR_API_KEY;+ process.env.REACTOR_API_KEY = 'env-key';+ expect(reactor.resolveReactorApiKey({ videoGen: { reactor: { apiKey: ' settings-key ' } } })).toBe('settings-key');+ if (prevEnv === undefined) delete process.env.REACTOR_API_KEY; else process.env.REACTOR_API_KEY = prevEnv;+ });++ it('falls back to REACTOR_API_KEY when settings carry no key', () => {+ const prevEnv = process.env.REACTOR_API_KEY;+ process.env.REACTOR_API_KEY = 'env-key';+ expect(reactor.resolveReactorApiKey({})).toBe('env-key');+ if (prevEnv === undefined) delete process.env.REACTOR_API_KEY; else process.env.REACTOR_API_KEY = prevEnv;+ });++ it('returns null when neither settings nor env carry a key', () => {+ const prevEnv = process.env.REACTOR_API_KEY;+ delete process.env.REACTOR_API_KEY;+ expect(reactor.resolveReactorApiKey({})).toBeNull();+ if (prevEnv !== undefined) process.env.REACTOR_API_KEY = prevEnv;+ });+});++describe('videoGen/reactor — mintReactorToken', () => {+ it('rejects when no API key is supplied', async () => {+ await expect(reactor.mintReactorToken(null)).rejects.toThrow(/No reactor\.inc API key/);+ });++ it('mints a scoped session JWT from the API key', async () => {+ const fetchMock = vi.fn(async (url, opts) => {+ expect(url).toBe(TOKEN_URL);+ expect(opts.headers.Authorization).toBe('Bearer test-key');+ const body = JSON.parse(opts.body);+ expect(body.authorization_details).toEqual([{ type: 'reactor/fast-h3', max_sessions: 1 }]);+ return jsonResponse({ jwt: 'signed-jwt', expires_at: '2026-01-01T00:00:00Z' });+ });+ vi.stubGlobal('fetch', fetchMock);+ const result = await reactor.mintReactorToken('test-key');+ expect(result).toEqual({ jwt: 'signed-jwt', expiresAt: '2026-01-01T00:00:00Z' });+ vi.unstubAllGlobals();+ });++ it('throws when the token endpoint rejects the key', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ detail: 'invalid key' }, false, 401)));+ await expect(reactor.mintReactorToken('bad-key')).rejects.toThrow(/token minting failed/);+ vi.unstubAllGlobals();+ });+});++describe('videoGen/reactor — _internals.buildRequestBody', () => {+ it('includes only the fields that were actually supplied, truncating an oversized prompt', () => {+ expect(reactor._internals.buildRequestBody({ prompt: ' a fox running ' })).toEqual({ prompt: 'a fox running' });+ expect(reactor._internals.buildRequestBody({+ prompt: 'pan', continueFromClipId: 'clip-1', startingFrameDataUri: 'data:image/png;base64,AA==', seconds: 6, seed: 42,+ })).toEqual({+ prompt: 'pan', continue_from_clip_id: 'clip-1', starting_frame: 'data:image/png;base64,AA==', seconds: 6, seed: 42,+ });+ const longPrompt = 'x'.repeat(reactor.REACTOR_MAX_PROMPT_LENGTH + 50);+ expect(reactor._internals.buildRequestBody({ prompt: longPrompt }).prompt.length).toBe(reactor.REACTOR_MAX_PROMPT_LENGTH);+ });+});++describe('videoGen/reactor — generateVideo', () => {+ it('mints a token, submits, polls to completion, downloads the result, and finalizes history', async () => {+ const clipId = 'clip-123';+ const statusUrl = `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/${clipId}`;+ const fetchMock = vi.fn(async (url, opts) => {+ if (url === TOKEN_URL) return jsonResponse({ jwt: 'session-jwt', expires_at: null });+ if (url === GENERATE_URL) {+ expect(opts.headers.Authorization).toBe('Bearer session-jwt');+ expect(JSON.parse(opts.body)).toEqual({ prompt: 'a fox running' });+ return jsonResponse({ clip_id: clipId, status_url: statusUrl });+ }+ if (url === statusUrl) return jsonResponse({ status: 'completed', video_url: 'https://cdn.reactor.inc/out.mp4', clip_id: clipId });+ if (url === 'https://cdn.reactor.inc/out.mp4') {+ return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('fake-mp4-bytes')).buffer };+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ const job = await reactor.generateVideo({ settings: { videoGen: { reactor: { apiKey: 'test-key' } } }, prompt: 'a fox running' });+ expect(job.mode).toBe('reactor');+ expect(job.status).toBe('running');+ expect(job.filename).toMatch(/^[0-9a-f-]{36}\.mp4$/);++ const outputPath = join(FAKE_VIDEOS_DIR, job.filename);+ let history = [];+ for (let i = 0; i < 50 && history.length === 0; i += 1) {+ await flush();+ history = await loadHistory();+ }++ const written = await readFile(outputPath);+ expect(written.toString()).toBe('fake-mp4-bytes');++ expect(history[0].id).toBe(job.jobId);+ expect(history[0].modelId).toBe('reactor:fast-h3');+ vi.unstubAllGlobals();+ });++ it('resolves the API key from live settings when the caller supplies none (the mediaJobQueue dispatch shape)', async () => {+ getSettingsMock.mockResolvedValue({ videoGen: { reactor: { apiKey: 'live-key' } } });+ const fetchMock = vi.fn(async (url, opts) => {+ if (url === TOKEN_URL) {+ expect(opts.headers.Authorization).toBe('Bearer live-key');+ return jsonResponse({ jwt: 'jwt-1', expires_at: null });+ }+ if (url === GENERATE_URL) return jsonResponse({ clip_id: 'c1', status_url: `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c1` });+ if (url === `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c1`) {+ return jsonResponse({ status: 'completed', video_url: 'https://cdn.reactor.inc/out.mp4' });+ }+ if (url === 'https://cdn.reactor.inc/out.mp4') {+ return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('bytes')).buffer };+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ const job = await reactor.generateVideo({ prompt: 'x' });+ for (let i = 0; i < 50 && fetchMock.mock.calls.length < 1; i += 1) await flush();+ await flush();+ expect(getSettingsMock).toHaveBeenCalled();+ expect(job.status).toBe('running');+ vi.unstubAllGlobals();+ });++ it('rejects when no API key is configured', async () => {+ const prevEnv = process.env.REACTOR_API_KEY;+ delete process.env.REACTOR_API_KEY;+ await expect(reactor.generateVideo({ prompt: 'x', settings: {} })).rejects.toThrow(/No reactor\.inc API key/);+ if (prevEnv !== undefined) process.env.REACTOR_API_KEY = prevEnv;+ });++ it('emits failed and does not write output when reactor.inc reports a failed status', async () => {+ const fetchMock = vi.fn(async (url) => {+ if (url === TOKEN_URL) return jsonResponse({ jwt: 'jwt-2', expires_at: null });+ if (url === GENERATE_URL) return jsonResponse({ clip_id: 'c2', status_url: `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c2` });+ if (url === `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c2`) {+ return jsonResponse({ status: 'failed', error: 'model overloaded' });+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ const failed = vi.fn();+ videoGenEvents.on('failed', failed);+ const job = await reactor.generateVideo({ settings: { videoGen: { reactor: { apiKey: 'test-key' } } }, prompt: 'x' });+ for (let i = 0; i < 20 && failed.mock.calls.length < 1; i += 1) await flush();++ expect(failed).toHaveBeenCalledWith(expect.objectContaining({ generationId: job.jobId, error: expect.stringContaining('model overloaded') }));+ vi.unstubAllGlobals();+ });++ it('threads continue_from_clip_id, seconds, and seed onto the submit body', async () => {+ const fetchMock = vi.fn(async (url, opts) => {+ if (url === TOKEN_URL) return jsonResponse({ jwt: 'jwt-3', expires_at: null });+ if (url === GENERATE_URL) {+ expect(JSON.parse(opts.body)).toEqual({+ prompt: 'continued shot', continue_from_clip_id: 'clip-9', seconds: 6, seed: 7,+ });+ return jsonResponse({ clip_id: 'c3', status_url: `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c3` });+ }+ if (url === `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c3`) {+ return jsonResponse({ status: 'completed', video_url: 'https://cdn.reactor.inc/out.mp4' });+ }+ if (url === 'https://cdn.reactor.inc/out.mp4') {+ return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('bytes')).buffer };+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ await reactor.generateVideo({+ settings: { videoGen: { reactor: { apiKey: 'test-key' } } },+ prompt: 'continued shot',+ continueFromClipId: 'clip-9',+ seconds: 6,+ seed: 7,+ });+ for (let i = 0; i < 50 && fetchMock.mock.calls.length < 2; i += 1) await flush();+ expect(fetchMock).toHaveBeenCalled();+ vi.unstubAllGlobals();+ });++ it('re-mints the session token and retries once when a poll returns 401', async () => {+ const statusUrl = `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c4`;+ let tokenMints = 0;+ let statusCalls = 0;+ const fetchMock = vi.fn(async (url, opts) => {+ if (url === TOKEN_URL) {+ tokenMints += 1;+ return jsonResponse({ jwt: `jwt-${tokenMints}`, expires_at: null });+ }+ if (url === GENERATE_URL) return jsonResponse({ clip_id: 'c4', status_url: statusUrl });+ if (url === statusUrl) {+ statusCalls += 1;+ if (statusCalls === 1) {+ expect(opts.headers.Authorization).toBe('Bearer jwt-1');+ return { ok: false, status: 401, json: async () => ({}) };+ }+ expect(opts.headers.Authorization).toBe('Bearer jwt-2');+ return jsonResponse({ status: 'completed', video_url: 'https://cdn.reactor.inc/out.mp4' });+ }+ if (url === 'https://cdn.reactor.inc/out.mp4') {+ return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('bytes')).buffer };+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ const job = await reactor.generateVideo({ settings: { videoGen: { reactor: { apiKey: 'test-key' } } }, prompt: 'x' });+ const outputPath = join(FAKE_VIDEOS_DIR, job.filename);+ let history = [];+ for (let i = 0; i < 50 && history.length === 0; i += 1) {+ await flush();+ history = await loadHistory();+ }+ expect(await readFile(outputPath)).toBeTruthy();+ expect(tokenMints).toBe(2);+ vi.unstubAllGlobals();+ });+});diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex ef727d4057..f7cfd7397d 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -118,7 +118,9 @@ const submitValidatedVideoGenJob = async (body, uploads) => {? { id: 'grok-video', supportedModes: ['image'] }: backend === VIDEO_GEN_MODE.FAL? { id: 'fal-video', supportedModes: ['text', 'image'] }- : prepared.effectiveModel;+ : backend === VIDEO_GEN_MODE.REACTOR+ ? { id: 'reactor-video', supportedModes: ['text', 'image'] }+ : prepared.effectiveModel;const compiled = await compileFableLoomVisualRequest({tag: body.fableLoom,kind: 'video',@@ -221,6 +223,33 @@ const submitValidatedVideoGenJob = async (body, uploads) => {};}+ if (backend === VIDEO_GEN_MODE.REACTOR) {+ const { sourceImagePath, uploadedTempPath } = prepared;+ const { jobId, position, status } = await enqueue({+ mode: VIDEO_GEN_MODE.REACTOR,+ videoMode: sourceImagePath ? 'image' : 'text',+ prompt: body.prompt,+ negativePrompt: body.negativePrompt || '',+ continueFromClipId: body.reactorClipId,+ seconds: body.reactorSeconds,+ seed: body.reactorSeed,+ 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: 'reactor',+ mode: 'reactor',+ status,+ position,+ };+ }+const {pythonPath, effectiveModelId, effectiveNumFrames, mode,sourceImagePath, lastImagePath, audioFilePath, icReferencePaths,