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(video): add on-demand Wan 2.2 MLX runtime

[._.]/ Adam Eivy136f81abfebc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dffda3d187..25f1b5078a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,8 @@
- Series Pipeline **Autonomous mode can now improve the pipeline itself.** A new Options toggle — *Improve the pipeline itself* — lets a run diagnose its own automation rather than only the story. When a run pauses, errors, or finishes carrying unhealthy telemetry (an editorial check that threw, a delegated runner that had to be retried, a step that was skipped), it spends one call asking whether the fault is the manuscript or PortOS: a missing editorial step earlier in the process, a stage prompt breaking its output contract, a runner swallowing a failure, a gate configured so it can't work. A pipeline verdict files a CoS task against PortOS itself — worktree-isolated, PR-opening, and waiting in your CoS approval queue, so an LLM's read of one run's telemetry never starts a coding agent on PortOS's own source by itself. Off by default, and a healthy run never spends anything on it; the diagnosis is billed as one cos action and skipped when the daily budget is spent. Repeat diagnoses of the same defect collapse onto one open task instead of piling up per run, and the verdict lands on the run's status banner. Scheduled runs inherit whatever you saved.
+- Video Gen now offers Apple-local Wan 2.2 TI2V-5B plus validated 4-step A14B Lightning text- and image-to-video profiles through a pinned MLX-Gen runtime. Runtime tools/packages, base weights, and exact Lightning adapters install only after an explicit UI action; existing installs receive an in-app repair/upgrade path, saved Hugging Face credentials are applied automatically, gated-source errors link back to the settings/access UI, and render/queue actions stay blocked until every required file is cached. Wan-specific 4n+1 frame choices, FPS options, mode compatibility, and locked Lightning sampler settings keep the UI aligned with the actual model contract.
+
- Series Pipeline **Autonomous mode** now says which AI it will spend on. The Options popover names the provider and model the run resolves to, links to where per-stage pins and reasoning effort are configured, and offers a per-run provider/model override (never persisted — a one-off run can't silently re-point the whole series). The live progress line names the provider of an in-flight run too, including one the scheduler started.
## Fixed
diff --git a/client/src/components/media/ModelDownloadBadge.jsx b/client/src/components/media/ModelDownloadBadge.jsx
index 3898c598ef..6961d8adbb 100644
--- a/client/src/components/media/ModelDownloadBadge.jsx
+++ b/client/src/components/media/ModelDownloadBadge.jsx
@@ -1,8 +1,8 @@
// Inline "Available · 7.8 GB" / "Download (~8 GB)" badge for the image and
// video gen model pickers. Drops below the model <select> so the user can
// see — before hitting Render — whether their pick still needs a multi-GB
-// HF pull. Hitting Render is NOT blocked: lazy download remains the
-// fallback, so a user who just wants to fire and wait can keep doing that.
+// HF pull. Local generation forms block until required weights are present,
+// keeping downloads explicit and recoverable instead of hiding them in render.
//
// Three render states:
// 1. cached → green CheckCircle, "Available · <size>"
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index 260f47d9e9..d5f307e1d5 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -1133,8 +1133,8 @@ export function ImageGenTab() {
<h2 className="text-lg font-semibold">HuggingFace Token</h2>
</div>
<p className="text-xs text-gray-500">
- Required for gated local models — currently <code className="text-gray-400">FLUX.1-dev</code> and the{' '}
- <code className="text-gray-400">FLUX.2-klein</code> family. Accept each model's license on HuggingFace, then create a read token at{' '}
+ Used for gated local models and model downloads — including <code className="text-gray-400">FLUX.1-dev</code>, the{' '}
+ <code className="text-gray-400">FLUX.2-klein</code> family, and gated video sources. Accept each model's license on HuggingFace, then create a read token at{' '}
<a href="https://huggingface.co/settings/tokens" target="_blank" rel="noreferrer" className="text-port-accent hover:underline">
huggingface.co/settings/tokens
</a>{' '}and paste it below. PortOS reads stored tokens first, then falls back to the{' '}
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsx
index c30a2ad0cf..30f7639aaa 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx
@@ -19,7 +19,7 @@
import { useState } from 'react';
import { ChevronDown, Dice5 } from 'lucide-react';
import { FormField } from '../ui/FormField';
-import { FRAME_OPTIONS, FPS_OPTIONS } from '../../lib/videoGenParams.js';
+import { frameOptionsForModel, fpsOptionsForModel } from '../../lib/videoGenParams.js';
import { VIDEO_TILING_OPTIONS } from '../../lib/videoTilingOptions';
const CHUNK_OPTIONS = [1, 2, 3, 4, 5, 6, 7, 8];
@@ -48,6 +48,9 @@ export default function AdvancedParamsPanel({
// ltx2 extend conditions on the source's latent rather than a single frame,
// so image strength is meaningless for it.
const showImageStrength = mode === 'image' || (mode === 'extend' && currentModel?.runtime !== 'ltx2');
+ const frameOptions = frameOptionsForModel(currentModel);
+ const fpsOptions = fpsOptionsForModel(currentModel);
+ const samplerLocked = currentModel?.samplerLocked === true;
const summary = `${numFrames}f @ ${fps}fps · ${(numFrames / fps).toFixed(1)}s · seed ${seed === '' || seed == null ? 'random' : seed}`;
@@ -73,7 +76,7 @@ export default function AdvancedParamsPanel({
onChange={(e) => onNumFramesChange(Number(e.target.value))}
className={inputCls}
>
- {FRAME_OPTIONS.map((f) => <option key={f} value={f}>{f} ({(f / fps).toFixed(1)}s @ {fps}fps)</option>)}
+ {frameOptions.map((f) => <option key={f} value={f}>{f} ({(f / fps).toFixed(1)}s @ {fps}fps)</option>)}
</select>
{numFrames > 241 && (
<p className="text-[10px] text-gray-500 leading-snug mt-1">
@@ -110,7 +113,7 @@ export default function AdvancedParamsPanel({
onChange={(e) => onFpsChange(Number(e.target.value))}
className={inputCls}
>
- {FPS_OPTIONS.map((f) => <option key={f} value={f}>{f}</option>)}
+ {fpsOptions.map((f) => <option key={f} value={f}>{f}</option>)}
</select>
</FormField>
@@ -144,6 +147,8 @@ export default function AdvancedParamsPanel({
type="number" min={1} max={150}
value={steps}
onChange={(e) => onStepsChange(e.target.value)}
+ disabled={samplerLocked}
+ title={samplerLocked ? 'This validated Lightning profile locks its sampler settings.' : undefined}
placeholder={String(currentModel?.steps || 25)}
className={inputCls}
/>
@@ -157,11 +162,19 @@ export default function AdvancedParamsPanel({
type="number" min={0} max={20} step={0.5}
value={guidanceScale}
onChange={(e) => onGuidanceScaleChange(e.target.value)}
+ disabled={samplerLocked}
+ title={samplerLocked ? 'This validated Lightning profile locks its sampler settings.' : undefined}
placeholder={String(currentModel?.guidance ?? 3.0)}
className={inputCls}
/>
</FormField>
+ {samplerLocked && (
+ <p className="col-span-2 sm:col-span-3 text-[10px] text-port-accent leading-snug">
+ Lightning keeps its validated {currentModel.steps}-step sampler, CFG {currentModel.guidance}, and model-specific schedule locked.
+ </p>
+ )}
+
{showImageStrength && (
<div className="col-span-2 sm:col-span-3">
<div className="flex items-center justify-between gap-3 mb-1">
diff --git a/client/src/hooks/useModelDownloadStatus.js b/client/src/hooks/useModelDownloadStatus.js
index 039572fdc6..6934297e4d 100644
--- a/client/src/hooks/useModelDownloadStatus.js
+++ b/client/src/hooks/useModelDownloadStatus.js
@@ -1,4 +1,4 @@
-import { useEffect, useState, useCallback, useMemo } from 'react';
+import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
import { useSseProgress } from './useSseProgress.js';
import { isIcLoraMode } from '../lib/videoGenParams.js';
import toast from '../components/ui/Toast';
@@ -46,27 +46,34 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
const [statuses, setStatuses] = useState(null);
const [extra, setExtra] = useState({}); // video: { textEncoder: {...} }
const [loading, setLoading] = useState(false);
+ const [statusError, setStatusError] = useState(null);
const [activeModelId, setActiveModelId] = useState(null);
+ const activeModelIdRef = useRef(null);
+ const [lastError, setLastError] = useState(null);
// True only for a repair-initiated re-download — appends `?force=1` so the
// server re-fetches a repo whose surviving shards still read as cached.
const [forceDownload, setForceDownload] = useState(false);
const fetchStatuses = useCallback(async () => {
setLoading(true);
- // Best-effort: a failure leaves the badge in its loading state. The form
- // still works because lazy download is the existing fallback.
+ // Best-effort: a failure resolves to an empty status list. Local forms
+ // stay gated because an unknown cache state must not trigger a hidden
+ // render-time download; retrying the status request remains safe.
const body = await (kind === 'video' ? getVideoModelStatuses() : getImageModelStatuses())
.catch(() => null);
if (body == null) {
+ setStatusError('PortOS could not check the local model cache. Retry before generating.');
setStatuses([]);
setExtra({});
} else if (kind === 'video') {
+ setStatusError(null);
setStatuses(Array.isArray(body?.models) ? body.models : []);
setExtra({
textEncoder: body?.textEncoder || null,
icLoras: Array.isArray(body?.icLoras) ? body.icLoras : [],
});
} else {
+ setStatusError(null);
setStatuses(Array.isArray(body) ? body : []);
setExtra({});
}
@@ -90,16 +97,27 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
useEffect(() => {
if (sse.closed) {
if (sse.latest?.type === 'error' && sse.latest?.message) {
+ setLastError({
+ modelId: activeModelIdRef.current,
+ message: sse.latest.message,
+ kind: sse.latest.kind || 'download_failed',
+ repo: sse.latest.repo || null,
+ });
toast.error(sse.latest.message);
+ } else {
+ setLastError(null);
}
fetchStatuses();
setActiveModelId(null);
+ activeModelIdRef.current = null;
setForceDownload(false);
}
}, [sse.closed, sse.latest, fetchStatuses]);
const start = useCallback((modelId, { force = false } = {}) => {
+ setLastError(null);
setForceDownload(force);
+ activeModelIdRef.current = modelId;
setActiveModelId(modelId);
}, []);
@@ -157,6 +175,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
const cancel = useCallback(() => {
sse.close();
setActiveModelId(null);
+ activeModelIdRef.current = null;
setForceDownload(false);
fetchStatuses();
}, [sse, fetchStatuses]);
@@ -193,6 +212,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
statuses,
extra,
loading,
+ statusError,
refresh: fetchStatuses,
start,
cancel,
@@ -203,6 +223,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
getStatus,
activeModelId,
progress: sse.latest,
+ lastError,
downloading: !!activeModelId,
};
}
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index 50032a29f6..e0b556e835 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -12,6 +12,7 @@ import { VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';
import {
VIDEO_EDGE_BOUNDS,
videoModelMemoryGb, computeFflfSafeFrames, isModelAllowedForMode,
+ normalizeFramesForModel, normalizeFpsForModel,
icLoraSpecForMode, icResolutionIssue,
} from '../lib/videoGenParams.js';
@@ -348,6 +349,15 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
const currentModel = models.find((m) => m.id === modelId);
+ // Remix/deep-link/resume paths set model + sampler fields independently.
+ // Reconcile them once the model is known so a legacy LTX 8n+1 frame count
+ // cannot reach a Wan 4n+1 runner (and a model-specific fps stays selectable).
+ useEffect(() => {
+ if (!currentModel) return;
+ setNumFrames((current) => normalizeFramesForModel(current, currentModel));
+ setFps((current) => normalizeFpsForModel(current, currentModel));
+ }, [currentModel]);
+
// Video-LoRA family for the selected model — 'ltx-video' on ltx2, else null.
// When null the picker is hidden and no LoRAs ride along on submit (the
// route would 400 with LORAS_REQUIRE_LTX2). Derived, not state, so it tracks
@@ -464,7 +474,12 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
// per-model defaults, and carrying one model's numbers onto another is
// usually wrong.
const handleModelChange = (nextId) => {
- setModelId(nextId); setSteps(''); setGuidanceScale('');
+ const nextModel = models.find((model) => model.id === nextId);
+ setModelId(nextId);
+ setNumFrames((current) => normalizeFramesForModel(current, nextModel));
+ setFps((current) => normalizeFpsForModel(current, nextModel));
+ setSteps('');
+ setGuidanceScale('');
};
const dropSourceImageParam = () => {
diff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.js
index f648e2ed89..13043c868d 100644
--- a/client/src/lib/videoGenParams.js
+++ b/client/src/lib/videoGenParams.js
@@ -12,6 +12,20 @@
// see the hint under the Frames dropdown.
export const FRAME_OPTIONS = [25, 49, 73, 97, 121, 145, 169, 193, 217, 241, 265, 313, 361, 481];
export const FPS_OPTIONS = [16, 24, 30];
+export const WAN_FRAME_OPTIONS = [25, 41, 49, 61, 81, 101, 121, 161, 201, 241, 321, 481];
+
+export const frameOptionsForModel = (model) => Number(model?.frameStride) === 4
+ ? WAN_FRAME_OPTIONS
+ : FRAME_OPTIONS;
+export const fpsOptionsForModel = (model) => Array.isArray(model?.fpsOptions) && model.fpsOptions.length > 0
+ ? model.fpsOptions
+ : FPS_OPTIONS;
+const nearestOption = (value, options) => options.reduce(
+ (best, option) => Math.abs(option - Number(value)) < Math.abs(best - Number(value)) ? option : best,
+ options[0],
+);
+export const normalizeFramesForModel = (value, model) => nearestOption(value, frameOptionsForModel(model));
+export const normalizeFpsForModel = (value, model) => nearestOption(value, fpsOptionsForModel(model));
// Per-edge bounds for video: mirrors the videoGen route (64..2048) and the
// server's floor-to-multiple-of-64 (generateVideo in local.js). Shared by the
@@ -127,5 +141,8 @@ export const icResolutionIssue = (spec, width, height) => {
export const isModelAllowedForMode = (model, mode) => {
if (!model) return false;
if (mode === 'a2v' || isIcLoraMode(mode)) return model.runtime === 'ltx2';
+ if (model.runtime === 'wan22') {
+ return Array.isArray(model.supportedModes) && model.supportedModes.includes(mode);
+ }
return true;
};
diff --git a/client/src/lib/videoGenParams.test.js b/client/src/lib/videoGenParams.test.js
index 5867480903..10d88c3c9e 100644
--- a/client/src/lib/videoGenParams.test.js
+++ b/client/src/lib/videoGenParams.test.js
@@ -2,6 +2,8 @@ import { describe, it, expect } from 'vitest';
import {
videoModelMemoryGb, computeFflfSafeFrames, isModelAllowedForMode,
VIDEO_EDGE_BOUNDS, FRAME_OPTIONS, FPS_OPTIONS,
+ WAN_FRAME_OPTIONS, frameOptionsForModel, fpsOptionsForModel,
+ normalizeFramesForModel, normalizeFpsForModel,
IC_LORA_MODES, IC_LORA_MODE_VALUES, isIcLoraMode, icLoraSpecForMode,
icResolutionIssue,
} from './videoGenParams.js';
@@ -47,10 +49,19 @@ describe('isModelAllowedForMode', () => {
it('rejects a null model', () => {
expect(isModelAllowedForMode(null, 'text')).toBe(false);
});
- it('allows any runtime for non-a2v modes', () => {
+ it('allows general runtimes for non-a2v modes', () => {
expect(isModelAllowedForMode({ runtime: 'mlx_video' }, 'text')).toBe(true);
expect(isModelAllowedForMode({ runtime: 'ltx2' }, 'image')).toBe(true);
});
+ it('filters Wan models by their declared text/image capabilities', () => {
+ const ti2v = { runtime: 'wan22', supportedModes: ['text', 'image'] };
+ const i2v = { runtime: 'wan22', supportedModes: ['image'] };
+ expect(isModelAllowedForMode(ti2v, 'text')).toBe(true);
+ expect(isModelAllowedForMode(ti2v, 'image')).toBe(true);
+ expect(isModelAllowedForMode(i2v, 'text')).toBe(false);
+ expect(isModelAllowedForMode(i2v, 'image')).toBe(true);
+ expect(isModelAllowedForMode(ti2v, 'fflf')).toBe(false);
+ });
it('requires the ltx2 runtime for a2v', () => {
expect(isModelAllowedForMode({ runtime: 'ltx2' }, 'a2v')).toBe(true);
expect(isModelAllowedForMode({ runtime: 'mlx_video' }, 'a2v')).toBe(false);
@@ -65,6 +76,14 @@ describe('constants', () => {
expect(FRAME_OPTIONS[0]).toBe(25);
expect(FRAME_OPTIONS.every((f) => (f - 1) % 8 === 0)).toBe(true);
expect(FPS_OPTIONS).toEqual([16, 24, 30]);
+ expect(WAN_FRAME_OPTIONS.every((f) => (f - 1) % 4 === 0)).toBe(true);
+ });
+ it('selects and normalizes model-aware Wan frame/fps values', () => {
+ const wan = { frameStride: 4, fpsOptions: [16, 20, 24] };
+ expect(frameOptionsForModel(wan)).toBe(WAN_FRAME_OPTIONS);
+ expect(fpsOptionsForModel(wan)).toEqual([16, 20, 24]);
+ expect(normalizeFramesForModel(97, wan)).toBe(101);
+ expect(normalizeFpsForModel(30, wan)).toBe(24);
});
});
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index ceb4d626f6..c65fe5385b 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -412,12 +412,18 @@ export default function VideoGen() {
// pull before hitting Render.
const modelDownload = useModelDownloadStatus({ kind: 'video' });
const modelStatus = modelId ? modelDownload.getStatus(modelId) : null;
+ const usesSharedTextEncoder = currentModel?.runtime === 'mlx_video' || currentModel?.runtime === 'ltx2';
const textEncoderInfo = modelDownload.extra.textEncoder || null;
const textEncoderStatus = textEncoderInfo
? (modelDownload.activeModelId === TEXT_ENCODER_DOWNLOAD_ID
? { ...textEncoderInfo, downloading: true, progress: modelDownload.progress }
: textEncoderInfo)
: null;
+ const modelWeightsBlocked = !isGrok && !!modelId
+ && (modelDownload.loading || modelStatus === null || modelStatus?.cached === false);
+ const textEncoderWeightsBlocked = !isGrok && usesSharedTextEncoder
+ && (modelDownload.loading || textEncoderStatus === null || textEncoderStatus?.cached === false);
+ const weightsGateBlocked = modelWeightsBlocked || textEncoderWeightsBlocked;
// Weight-integrity (issue #1324). A corrupt/truncated model decodes to
// garbled "mosaic" video that a clean re-download fixes; surface a Repair
@@ -523,7 +529,7 @@ export default function VideoGen() {
// Without these guards the user could press Enter in the prompt
// textarea and fire a request the disabled button would otherwise
// have prevented.
- if (!prompt.trim() || generating || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || keyframesBlocked))) return;
+ if (!prompt.trim() || generating || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked))) return;
await runGeneration(buildGeneratePayload()).catch(() => {});
};
@@ -532,7 +538,7 @@ export default function VideoGen() {
// would silently queue a doomed job that fails late in the worker with
// VENV_MISSING, hiding the installer banner from the user. Block at
// enqueue time so the only path forward is the install banner above.
- if (!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || keyframesBlocked))) return;
+ if (!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked))) return;
// useVideoGenQueue strips the File blobs into `_blobs` and snapshots the
// rest as a stable summary for the queue UI.
enqueue(buildGeneratePayload());
@@ -575,7 +581,7 @@ export default function VideoGen() {
// configured" error from the unrelated legacy probe.
const notConnected = !!status && status.connected === false && !needsByovProbe;
- const canEnqueue = prompt.trim() && (isGrok || (!notConnected && !extendModeBlocked && !a2vModeBlocked && !byovGateBlocked && !keyframesBlocked));
+ const canEnqueue = prompt.trim() && (isGrok || (!notConnected && !extendModeBlocked && !a2vModeBlocked && !byovGateBlocked && !weightsGateBlocked && !keyframesBlocked));
return (
<div className="space-y-3">
@@ -700,8 +706,8 @@ export default function VideoGen() {
{!isGrok && 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> isn't installed yet.
- PortOS can fetch and install it from {byovStatus.repoUrl?.replace('https://', '')} (~5-15 min, multi-GB on first run).
+ <strong className="font-semibold">{byovStatus.label}</strong> {byovStatus.upgradeAvailable ? 'has an update available.' : "isn't installed yet."}
+ {' '}PortOS can {byovStatus.upgradeAvailable ? 'upgrade' : 'fetch and install'} it from {byovStatus.repoUrl?.replace('https://', '')} on demand.
</div>
<button
type="button"
@@ -710,7 +716,7 @@ export default function VideoGen() {
className="self-start sm:self-auto whitespace-nowrap inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/80 disabled:opacity-50"
>
<Sparkles size={14} />
- Install {byovStatus.label}
+ {byovStatus.upgradeAvailable ? 'Upgrade' : 'Install'} {byovStatus.label}
</button>
</div>
)}
@@ -909,7 +915,35 @@ export default function VideoGen() {
estimateLabel={deriveSizeEstimate(currentModel?.name)}
/>
)}
- {textEncoderStatus && (textEncoderStatus.cached === false || textEncoderStatus.downloading) && (
+ {modelDownload.lastError?.modelId === modelId && (
+ <div className="mt-2 rounded-lg border border-port-error/40 bg-port-error/10 px-3 py-2 text-[11px] text-port-error">
+ <p>{modelDownload.lastError.message}</p>
+ <div className="mt-1 flex flex-wrap gap-2">
+ <button type="button" onClick={openSettings} className="underline hover:text-white">
+ Open Hugging Face settings
+ </button>
+ {modelDownload.lastError.repo && (
+ <a
+ href={`https://huggingface.co/${modelDownload.lastError.repo}`}
+ target="_blank"
+ rel="noreferrer"
+ className="underline hover:text-white"
+ >
+ Open repository access page
+ </a>
+ )}
+ </div>
+ </div>
+ )}
+ {modelDownload.statusError && (
+ <div className="mt-2 rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-[11px] text-port-warning flex flex-wrap items-center justify-between gap-2">
+ <span>{modelDownload.statusError}</span>
+ <button type="button" onClick={modelDownload.refresh} className="underline hover:text-white">
+ Retry cache check
+ </button>
+ </div>
+ )}
+ {usesSharedTextEncoder && textEncoderStatus && (textEncoderStatus.cached === false || textEncoderStatus.downloading) && (
<div className="mt-1">
<p className="text-[10px] text-gray-500">Text encoder ({textEncoderStatus.repo}) is also required:</p>
<ModelDownloadBadge
@@ -1000,11 +1034,13 @@ export default function VideoGen() {
) : (
<button
type="submit"
- disabled={!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || keyframesBlocked))}
+ disabled={!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked))}
className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"
title={
byovRuntimeMissing ? `${byovStatus?.label || byovRuntime} runtime is not installed — use the install banner above`
: byovGateBlocked ? `Checking ${byovRuntime} runtime status…`
+ : modelWeightsBlocked ? 'Download the selected model weights before generating'
+ : textEncoderWeightsBlocked ? 'Download the shared text encoder before generating'
: extendModeBlocked ? 'Pick a prior render and wait for the last frame to extract before generating'
: a2vModeBlocked ? (currentModel?.runtime !== 'ltx2'
? 'a2v mode requires an ltx2-runtime model — pick one from the Model dropdown'
diff --git a/data.reference/media-models.json b/data.reference/media-models.json
index 8db6386754..4c59c7a303 100644
--- a/data.reference/media-models.json
+++ b/data.reference/media-models.json
@@ -44,22 +44,96 @@
"guidance": 3
},
{
- "id": "wan22_t2v_a14b",
- "name": "Wan 2.2 T2V A14B (~28 GB, MoE-14B-active)",
- "repo": "Wan-AI/Wan2.2-T2V-A14B",
+ "id": "wan22_ti2v_5b",
+ "name": "Wan 2.2 TI2V 5B Q8 (~17 GB, text + image)",
+ "repo": "AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit",
"runtime": "wan22",
- "mode": "t2v",
+ "supportedModes": ["text", "image"],
+ "frameStride": 4,
+ "fpsOptions": [16, 20, 24],
+ "memoryGb": 24,
"steps": 25,
- "guidance": 5
+ "guidance": 5,
+ "flowShift": 3,
+ "solver": "unipc"
+ },
+ {
+ "id": "wan22_t2v_a14b",
+ "name": "Wan 2.2 T2V A14B Q8 (~14 GB runtime)",
+ "repo": "AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit",
+ "runtime": "wan22",
+ "supportedModes": ["text"],
+ "frameStride": 4,
+ "fpsOptions": [16, 20, 24],
+ "memoryGb": 16,
+ "steps": 20,
+ "guidance": 4,
+ "guidance2": 3,
+ "flowShift": 3,
+ "solver": "unipc"
},
{
"id": "wan22_i2v_a14b",
- "name": "Wan 2.2 I2V A14B (~28 GB, image-to-video)",
- "repo": "Wan-AI/Wan2.2-I2V-A14B",
+ "name": "Wan 2.2 I2V A14B Q8 (~14 GB runtime)",
+ "repo": "AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit",
"runtime": "wan22",
- "mode": "i2v",
- "steps": 25,
- "guidance": 5
+ "supportedModes": ["image"],
+ "frameStride": 4,
+ "fpsOptions": [16, 20, 24],
+ "memoryGb": 16,
+ "steps": 20,
+ "guidance": 3.5,
+ "guidance2": 3.5,
+ "flowShift": 3,
+ "solver": "unipc"
+ },
+ {
+ "id": "wan22_t2v_a14b_lightning",
+ "name": "Wan 2.2 T2V A14B Lightning Q8 (~14 GB, 4-step)",
+ "repo": "AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit",
+ "runtime": "wan22",
+ "supportedModes": ["text"],
+ "frameStride": 4,
+ "fpsOptions": [16, 20, 24],
+ "memoryGb": 16,
+ "steps": 4,
+ "guidance": 1,
+ "guidance2": 1,
+ "flowShift": 5,
+ "solver": "euler",
+ "samplerLocked": true,
+ "requiredWeights": [{
+ "repo": "lightx2v/Wan2.2-Lightning",
+ "files": [
+ "Wan2.2-T2V-A14B-4steps-lora-rank64-Seko-V1.1/high_noise_model.safetensors",
+ "Wan2.2-T2V-A14B-4steps-lora-rank64-Seko-V1.1/low_noise_model.safetensors"
+ ],
+ "targetRoles": ["high_noise_transformer", "low_noise_transformer"]
+ }]
+ },
+ {
+ "id": "wan22_i2v_a14b_lightning",
+ "name": "Wan 2.2 I2V A14B Lightning Q8 (~14 GB, 4-step)",
+ "repo": "AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit",
+ "runtime": "wan22",
+ "supportedModes": ["image"],
+ "frameStride": 4,
+ "fpsOptions": [16, 20, 24],
+ "memoryGb": 16,
+ "steps": 4,
+ "guidance": 1,
+ "guidance2": 1,
+ "flowShift": 5,
+ "solver": "euler",
+ "samplerLocked": true,
+ "requiredWeights": [{
+ "repo": "lightx2v/Wan2.2-Lightning",
+ "files": [
+ "Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/high_noise_model.safetensors",
+ "Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/low_noise_model.safetensors"
+ ],
+ "targetRoles": ["high_noise_transformer", "low_noise_transformer"]
+ }]
},
{
"id": "hunyuan_video",
diff --git a/scripts/generate_wan22.py b/scripts/generate_wan22.py
index 270960dcee..9d267b39c3 100644
--- a/scripts/generate_wan22.py
+++ b/scripts/generate_wan22.py
@@ -1,27 +1,13 @@
#!/usr/bin/env python3
-"""
-PortOS Wan 2.2 MLX helper.
-
-Subprocesses upstream osama-ata/Wan2.2-mlx generate.py from the cloned repo
-at --repo-dir. PortOS releases an arg shape it controls (--prompt, --width,
---output) and this helper translates to upstream's --task / --size / --ckpt_dir
-form. Done this way (subprocess, not import) because upstream isn't packaged
-as a pip module — it's a repo clone whose internal module layout can shift.
-
-Spawned by server/services/videoGen/local.js when model.runtime === 'wan22'.
-The STAGE: / STATUS: SSE protocol matches generate_ltx2.py so the JS side
-needs no per-runtime parser. Progress hints from upstream tqdm bars are
-forwarded as-is — local.js handleLine() already understands the percentage
-regex.
-
-EXPERIMENTAL: upstream Wan2.2-mlx CLI surface isn't pinned. If a future
-upstream commit renames --task or --ckpt_dir, set the broken flag in
-data/media-models.json (`wan22_t2v_a14b`, `wan22_i2v_a14b`) and grep for
-this helper to update the translation.
+"""Stable PortOS wrapper for the pinned MLX-Gen Wan 2.2 CLI.
+
+The runner is intentionally cache-only. PortOS downloads the base model and
+exact Lightning files through the Video Gen UI before this helper is launched;
+MLX-Gen returns a typed download-required failure if anything is absent.
"""
import argparse
-import os
+import json
import subprocess
import sys
from pathlib import Path
@@ -34,18 +20,23 @@ from _runner_common import emit_runtime_fingerprint # noqa: E402
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="PortOS Wan 2.2 MLX helper")
- p.add_argument("--repo-dir", required=True, help="Cloned osama-ata/Wan2.2-mlx repo root")
- p.add_argument("--task", required=True, help="t2v-A14B | i2v-A14B")
- p.add_argument("--model-repo", required=True, help="HF repo of the Wan 2.2 weights (Wan-AI/Wan2.2-T2V-A14B etc.)")
+ p.add_argument("--model-repo", required=True)
p.add_argument("--prompt", required=True)
p.add_argument("--width", type=int, required=True)
p.add_argument("--height", type=int, required=True)
p.add_argument("--num-frames", type=int, default=81)
+ p.add_argument("--fps", type=int, default=16)
p.add_argument("--steps", type=int, default=25)
p.add_argument("--guidance", type=float, default=5.0)
+ p.add_argument("--guidance-2", type=float, default=None)
+ p.add_argument("--flow-shift", type=float, default=None)
+ p.add_argument("--solver", choices=("unipc", "euler"), default=None)
p.add_argument("--seed", type=int, default=42)
p.add_argument("--output", required=True)
- p.add_argument("--image", default=None, help="i2v source image path")
+ p.add_argument("--image", default=None)
+ p.add_argument("--negative-prompt", default="")
+ p.add_argument("--lora-path", action="append", default=[])
+ p.add_argument("--lora-target-role", action="append", default=[])
return p.parse_args()
@@ -54,61 +45,72 @@ def main() -> int:
# Runtime fingerprint at startup — recorded by PortOS so output can be tied
# to a specific wan/mlx/torch stack on this chip.
- emit_runtime_fingerprint("wan22", ["wan", "mlx", "mlx_metal", "torch"])
-
- repo_dir = Path(args.repo_dir).expanduser().resolve()
- if not repo_dir.is_dir():
- print(f"❌ Wan 2.2 repo not found at {repo_dir}", file=sys.stderr)
- return 64
- generate_py = repo_dir / "generate.py"
- if not generate_py.exists():
- print(f"❌ {generate_py} missing — upstream layout changed?", file=sys.stderr)
- return 64
-
- # Upstream caches weights under ~/.cache/huggingface/ on the first run.
- # The --ckpt_dir convention in upstream's README points at a local
- # snapshot, but `huggingface_hub.snapshot_download(model_repo)` resolves
- # to the same canonical cache path either way.
- print(f"STAGE:download-weights:{args.model_repo}", file=sys.stderr, flush=True)
- try:
- from huggingface_hub import snapshot_download
- except Exception as err:
- print(f"❌ huggingface_hub import failed: {err}", file=sys.stderr)
- return 64
- ckpt_dir = snapshot_download(args.model_repo)
- print(f"🔧 wan22: weights ← {ckpt_dir}", file=sys.stderr)
+ emit_runtime_fingerprint("wan22", ["mlx-gen", "mlx", "mlx_metal", "huggingface-hub"])
upstream_args = [
sys.executable,
- str(generate_py),
- "--task", args.task,
- "--size", f"{args.width}*{args.height}",
- "--ckpt_dir", ckpt_dir,
+ "-m", "mflux.models.wan.cli.wan_generate",
+ "--json-events",
+ "--low-ram",
+ "--model", args.model_repo,
"--prompt", args.prompt,
- "--num_frames", str(args.num_frames),
- "--sample_steps", str(args.steps),
- "--sample_guide_scale", str(args.guidance),
- "--base_seed", str(args.seed),
- "--save_file", args.output,
+ "--width", str(args.width),
+ "--height", str(args.height),
+ "--frames", str(args.num_frames),
+ "--fps", str(args.fps),
+ "--steps", str(args.steps),
+ "--guidance", str(args.guidance),
+ "--seed", str(args.seed),
+ "--output", args.output,
]
+ if args.negative_prompt:
+ upstream_args.extend(["--negative-prompt", args.negative_prompt])
+ if args.guidance_2 is not None:
+ upstream_args.extend(["--guidance-2", str(args.guidance_2)])
+ if args.flow_shift is not None:
+ upstream_args.extend(["--flow-shift", str(args.flow_shift)])
+ if args.solver:
+ upstream_args.extend(["--solver", args.solver])
if args.image:
- upstream_args.extend(["--image", args.image])
+ upstream_args.extend(["--image-path", args.image])
+ if args.lora_path:
+ upstream_args.extend(["--lora-paths", *args.lora_path])
+ if args.lora_target_role:
+ upstream_args.extend(["--lora-target-roles", *args.lora_target_role])
print(f"STAGE:inference", file=sys.stderr, flush=True)
- print(f"🎬 wan22 generate task={args.task} {args.width}x{args.height} steps={args.steps} seed={args.seed}", file=sys.stderr)
+ print(f"🎬 wan22 generate {args.width}x{args.height} steps={args.steps} seed={args.seed}", file=sys.stderr)
- # cwd = repo_dir so upstream's relative imports work. Forward stderr
- # unchanged — upstream emits tqdm progress bars which local.js's
- # handleLine() already parses for the percentage SSE event.
- proc = subprocess.run(
+ # Human diagnostics remain on inherited stderr. JSONL progress on stdout
+ # is translated into PortOS's existing STAGE:/STATUS: protocol below.
+ proc = subprocess.Popen(
upstream_args,
- cwd=str(repo_dir),
- env={**os.environ, "PYTHONUNBUFFERED": "1"},
+ stdout=subprocess.PIPE,
+ text=True,
)
-
- if proc.returncode != 0:
- print(f"❌ wan22 upstream exited {proc.returncode}", file=sys.stderr)
- return proc.returncode
+ assert proc.stdout is not None
+ for raw in proc.stdout:
+ try:
+ event = json.loads(raw)
+ except json.JSONDecodeError:
+ print(raw.rstrip(), file=sys.stderr, flush=True)
+ continue
+ phase = str(event.get("phase", "working"))
+ step = event.get("step")
+ total = event.get("total_steps")
+ if isinstance(step, int) and isinstance(total, int) and total > 0:
+ print(f"STAGE:wan-{phase}:step:{step}:{total}:{phase}", file=sys.stderr, flush=True)
+ else:
+ print(f"STATUS:Wan {phase}", file=sys.stderr, flush=True)
+ remediation = event.get("remediation")
+ if isinstance(remediation, dict) and remediation.get("kind") == "download-required":
+ repo = remediation.get("repo_id") or args.model_repo
+ print(f"❌ Required Wan weight is not cached: {repo}. Use Download in Video Gen.", file=sys.stderr, flush=True)
+ return_code = proc.wait()
+
+ if return_code != 0:
+ print(f"❌ wan22 upstream exited {return_code}", file=sys.stderr)
+ return return_code
if not Path(args.output).exists():
print(f"❌ wan22 finished but {args.output} missing", file=sys.stderr)
diff --git a/scripts/hf_download_repo.py b/scripts/hf_download_repo.py
index 71ed5bdfbb..a8082b9d87 100755
--- a/scripts/hf_download_repo.py
+++ b/scripts/hf_download_repo.py
@@ -37,14 +37,14 @@ from pathlib import Path
# `huggingface_hub` is installed in the FLUX.2 venv (and any mflux venv) —
# the caller picks the python binary that has it. Import errors surface as
-# a USER_ERROR with a clear "venv missing huggingface_hub" message so the
-# UI can route the user to the FLUX.2 install banner.
+# a USER_ERROR with a clear "runtime missing huggingface_hub" message so the
+# UI can route the user to the applicable model setup panel.
try:
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
except Exception as err: # noqa: BLE001
print(f"USER_ERROR:venv_missing_hf_hub:{err}", file=sys.stderr, flush=True)
- print("❌ Python venv is missing huggingface_hub. Run the FLUX.2 install from Image Gen settings.", file=sys.stderr, flush=True)
+ print("❌ The selected model runtime is missing huggingface_hub. Use Install / Repair in the Media Generation UI.", file=sys.stderr, flush=True)
sys.exit(2)
@@ -98,7 +98,7 @@ def main() -> int:
files = api.list_repo_files(args.repo, revision=args.revision, token=token)
except GatedRepoError:
print(f"USER_ERROR:gated_repo:{args.repo}", file=sys.stderr, flush=True)
- print(f"❌ Access to {args.repo} is gated. Accept the license at https://huggingface.co/{args.repo} and paste your HuggingFace token into Image Gen settings, then retry.", file=sys.stderr, flush=True)
+ print(f"❌ Access to {args.repo} is gated. Accept the license at https://huggingface.co/{args.repo} and save your Hugging Face token in Media Generation settings, then retry.", file=sys.stderr, flush=True)
return 2
except RepositoryNotFoundError:
print(f"USER_ERROR:repo_not_found:{args.repo}", file=sys.stderr, flush=True)
@@ -109,7 +109,7 @@ def main() -> int:
# as token-rejected so the UI can prompt for a new HF_TOKEN.
if "401" in str(err) or "Unauthorized" in str(err):
print(f"USER_ERROR:hf_unauthorized:{args.repo}", file=sys.stderr, flush=True)
- print(f"❌ HuggingFace rejected the token. Update HF_TOKEN in Image Gen settings.", file=sys.stderr, flush=True)
+ print("❌ Hugging Face rejected the token. Replace it in Media Generation settings, then retry.", file=sys.stderr, flush=True)
return 2
print(f"USER_ERROR:list_failed:{args.repo}", file=sys.stderr, flush=True)
print(f"❌ Failed to list {args.repo}: {err}", file=sys.stderr, flush=True)
@@ -152,7 +152,7 @@ def main() -> int:
resolved = hf_hub_download(**download_kwargs)
except GatedRepoError:
print(f"USER_ERROR:gated_repo:{args.repo}", file=sys.stderr, flush=True)
- print(f"❌ {args.repo} is gated. Accept the license + paste your HF token.", file=sys.stderr, flush=True)
+ print(f"❌ {args.repo} is gated. Accept its license, save your Hugging Face token in Media Generation settings, then retry.", file=sys.stderr, flush=True)
return 2
except Exception as err: # noqa: BLE001
print(f"USER_ERROR:download_failed:{filename}", file=sys.stderr, flush=True)
diff --git a/scripts/migrations/233-wan-mlx-gen-models.js b/scripts/migrations/233-wan-mlx-gen-models.js
new file mode 100644
index 0000000000..5c3b32b19d
--- /dev/null
+++ b/scripts/migrations/233-wan-mlx-gen-models.js
@@ -0,0 +1,125 @@
+/**
+ * Replace the failed Wan2.2-mlx catalog rows with pinned MLX-Gen q8 profiles,
+ * and add TI2V-5B plus validated A14B Lightning profiles to existing installs.
+ * Runtime/packages/weights are still installed only from the Video Gen UI.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+
+const REL_PATH = 'data/media-models.json';
+const LIGHTNING_REPO = 'lightx2v/Wan2.2-Lightning';
+
+const NEW_ENTRIES = [
+ {
+ id: 'wan22_ti2v_5b', name: 'Wan 2.2 TI2V 5B Q8 (~17 GB, text + image)',
+ repo: 'AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit', runtime: 'wan22',
+ supportedModes: ['text', 'image'], frameStride: 4, fpsOptions: [16, 20, 24],
+ memoryGb: 24, steps: 25, guidance: 5, flowShift: 3, solver: 'unipc',
+ },
+ {
+ id: 'wan22_t2v_a14b_lightning', name: 'Wan 2.2 T2V A14B Lightning Q8 (~14 GB, 4-step)',
+ repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit', runtime: 'wan22',
+ supportedModes: ['text'], frameStride: 4, fpsOptions: [16, 20, 24], memoryGb: 16,
+ steps: 4, guidance: 1, guidance2: 1, flowShift: 5, solver: 'euler', samplerLocked: true,
+ requiredWeights: [{
+ repo: LIGHTNING_REPO,
+ files: [
+ 'Wan2.2-T2V-A14B-4steps-lora-rank64-Seko-V1.1/high_noise_model.safetensors',
+ 'Wan2.2-T2V-A14B-4steps-lora-rank64-Seko-V1.1/low_noise_model.safetensors',
+ ],
+ targetRoles: ['high_noise_transformer', 'low_noise_transformer'],
+ }],
+ },
+ {
+ id: 'wan22_i2v_a14b_lightning', name: 'Wan 2.2 I2V A14B Lightning Q8 (~14 GB, 4-step)',
+ repo: 'AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit', runtime: 'wan22',
+ supportedModes: ['image'], frameStride: 4, fpsOptions: [16, 20, 24], memoryGb: 16,
+ steps: 4, guidance: 1, guidance2: 1, flowShift: 5, solver: 'euler', samplerLocked: true,
+ requiredWeights: [{
+ repo: LIGHTNING_REPO,
+ files: [
+ 'Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/high_noise_model.safetensors',
+ 'Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/low_noise_model.safetensors',
+ ],
+ targetRoles: ['high_noise_transformer', 'low_noise_transformer'],
+ }],
+ },
+];
+
+const UPGRADES = {
+ wan22_t2v_a14b: {
+ oldRepo: 'Wan-AI/Wan2.2-T2V-A14B',
+ oldName: 'Wan 2.2 T2V A14B (~28 GB, MoE-14B-active)',
+ next: {
+ name: 'Wan 2.2 T2V A14B Q8 (~14 GB runtime)',
+ repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ runtime: 'wan22', supportedModes: ['text'], frameStride: 4,
+ fpsOptions: [16, 20, 24], memoryGb: 16, steps: 20, guidance: 4,
+ guidance2: 3, flowShift: 3, solver: 'unipc',
+ },
+ },
+ wan22_i2v_a14b: {
+ oldRepo: 'Wan-AI/Wan2.2-I2V-A14B',
+ oldName: 'Wan 2.2 I2V A14B (~28 GB, image-to-video)',
+ next: {
+ name: 'Wan 2.2 I2V A14B Q8 (~14 GB runtime)',
+ repo: 'AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit',
+ runtime: 'wan22', supportedModes: ['image'], frameStride: 4,
+ fpsOptions: [16, 20, 24], memoryGb: 16, steps: 20, guidance: 3.5,
+ guidance2: 3.5, flowShift: 3, solver: 'unipc',
+ },
+ },
+};
+
+export default {
+ async up({ rootDir }) {
+ const path = join(rootDir, REL_PATH);
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return;
+ let config;
+ try { config = JSON.parse(raw); } catch { return; }
+ const macos = Array.isArray(config?.video?.macos) ? config.video.macos : null;
+ if (!macos) return;
+
+ let changed = false;
+ for (const entry of macos) {
+ const spec = UPGRADES[entry?.id];
+ if (!spec || entry.repo !== spec.oldRepo) continue;
+ const priorName = entry.name;
+ const priorSteps = entry.steps;
+ const priorGuidance = entry.guidance;
+ const preserveSteps = entry.steps !== 25;
+ const preserveGuidance = entry.guidance !== 5;
+ const oldName = entry.name === spec.oldName;
+ Object.assign(entry, spec.next);
+ if (!oldName) entry.name = priorName;
+ if (preserveSteps) entry.steps = priorSteps;
+ if (preserveGuidance) entry.guidance = priorGuidance;
+ if (entry.mode === 't2v' || entry.mode === 'i2v') delete entry.mode;
+ changed = true;
+ }
+
+ const present = new Set(macos.map((entry) => entry?.id));
+ for (const entry of NEW_ENTRIES) {
+ if (present.has(entry.id)) continue;
+ macos.push(entry);
+ present.add(entry.id);
+ changed = true;
+ }
+ const shipped = config?._shippedDefaults?.video?.macos;
+ if (Array.isArray(shipped)) {
+ for (const entry of NEW_ENTRIES) {
+ if (!shipped.includes(entry.id)) { shipped.push(entry.id); changed = true; }
+ }
+ }
+ if (changed) {
+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);
+ console.log(`📝 ${REL_PATH}: upgraded Wan 2.2 to MLX-Gen and added TI2V/Lightning profiles`);
+ }
+ },
+};
diff --git a/scripts/migrations/233-wan-mlx-gen-models.test.js b/scripts/migrations/233-wan-mlx-gen-models.test.js
new file mode 100644
index 0000000000..94f50e5998
--- /dev/null
+++ b/scripts/migrations/233-wan-mlx-gen-models.test.js
@@ -0,0 +1,79 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './233-wan-mlx-gen-models.js';
+
+const oldRows = () => ({
+ video: { macos: [
+ { id: 'wan22_t2v_a14b', name: 'Wan 2.2 T2V A14B (~28 GB, MoE-14B-active)', repo: 'Wan-AI/Wan2.2-T2V-A14B', runtime: 'wan22', mode: 't2v', steps: 25, guidance: 5 },
+ { id: 'wan22_i2v_a14b', name: 'Wan 2.2 I2V A14B (~28 GB, image-to-video)', repo: 'Wan-AI/Wan2.2-I2V-A14B', runtime: 'wan22', mode: 'i2v', steps: 25, guidance: 5 },
+ ] },
+ _shippedDefaults: { video: { macos: ['wan22_t2v_a14b', 'wan22_i2v_a14b'] } },
+});
+
+describe('migration 233 — Wan MLX-Gen models', () => {
+ let rootDir;
+ let path;
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-233-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ path = join(rootDir, 'data', 'media-models.json');
+ });
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+ const write = (value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
+ const read = () => JSON.parse(readFileSync(path, 'utf-8'));
+
+ it('upgrades shipped A14B rows and adds TI2V plus both Lightning profiles', async () => {
+ write(oldRows());
+ await migration.up({ rootDir });
+ const config = read();
+ const byId = new Map(config.video.macos.map((entry) => [entry.id, entry]));
+ expect(byId.get('wan22_t2v_a14b')).toMatchObject({
+ repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ supportedModes: ['text'], frameStride: 4, steps: 20, guidance: 4,
+ });
+ expect(byId.get('wan22_t2v_a14b').mode).toBeUndefined();
+ expect(byId.get('wan22_ti2v_5b').supportedModes).toEqual(['text', 'image']);
+ expect(byId.get('wan22_t2v_a14b_lightning').requiredWeights[0].files).toHaveLength(2);
+ expect(byId.get('wan22_i2v_a14b_lightning').samplerLocked).toBe(true);
+ expect(config._shippedDefaults.video.macos).toContain('wan22_ti2v_5b');
+ });
+
+ it('preserves a forked existing row while still adding genuinely new ids', async () => {
+ const config = oldRows();
+ config.video.macos[0].repo = 'example/Wan-fork';
+ config.video.macos[0].steps = 17;
+ write(config);
+ await migration.up({ rootDir });
+ const next = read();
+ expect(next.video.macos.find((entry) => entry.id === 'wan22_t2v_a14b')).toMatchObject({ repo: 'example/Wan-fork', steps: 17 });
+ expect(next.video.macos.some((entry) => entry.id === 'wan22_ti2v_5b')).toBe(true);
+ });
+
+ it('preserves user-tuned fields while upgrading a shipped repository', async () => {
+ const config = oldRows();
+ Object.assign(config.video.macos[0], {
+ name: 'My Wan profile',
+ steps: 17,
+ guidance: 6,
+ });
+ write(config);
+ await migration.up({ rootDir });
+ const upgraded = read().video.macos.find((entry) => entry.id === 'wan22_t2v_a14b');
+ expect(upgraded).toMatchObject({
+ name: 'My Wan profile',
+ repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ steps: 17,
+ guidance: 6,
+ });
+ });
+
+ it('is idempotent', async () => {
+ write(oldRows());
+ await migration.up({ rootDir });
+ const once = readFileSync(path, 'utf-8');
+ await migration.up({ rootDir });
+ expect(readFileSync(path, 'utf-8')).toBe(once);
+ });
+});
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index 707dacdf9f..a04650baa5 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -266,58 +266,53 @@ fi
INSTALL_WAN22="${INSTALL_WAN22:-0}"
if [[ "$INSTALL_WAN22" == "1" ]]; then
- # osama-ata/Wan2.2-mlx — pure-MLX port of Alibaba's Wan 2.2 video model.
- # MoE-A14B: 14B active params at inference, ~28 GB resident at bf16. The
- # PortOS helper at scripts/generate_wan22.py subprocesses upstream's
- # generate.py from the cloned repo, so PortOS releases own the arg
- # translation layer (PortOS arg stability) while upstream owns the
- # actual inference (upstream-tracked changes).
- #
- # EXPERIMENTAL — the clone is pinned (WAN22_PIN below) so new installs are
- # reproducible, but bumping that pin can still reshape --task / --ckpt_dir;
- # if it does, set `broken: true` on the wan22_* entries in
- # data/media-models.json until generate_wan22.py is updated to match.
- if ! have uv; then
- echo "❌ INSTALL_WAN22=1 requires the 'uv' Python installer." >&2
- echo " curl -LsSf https://astral.sh/uv/install.sh | sh" >&2
- exit 1
- fi
+ # MLX-Gen provides the validated Apple-Silicon Wan 2.2 TI2V-5B and A14B
+ # q8 routes. This path runs only after the user chooses Install in Video Gen;
+ # the regular PortOS install/update path never provisions it automatically.
if ! have git; then
echo "❌ INSTALL_WAN22=1 requires git." >&2
exit 1
fi
- # Pinned to a known-good commit (the repo's HEAD as of 2026-06-02). Floating
- # `main` on a community-maintained port means every new install gets whatever
- # HEAD is that day — a pin keeps installs reproducible. To upgrade: bump this
- # SHA and verify with PortOS's video gen smoke tests. Set WAN22_PIN=main to
- # bypass the pin and track upstream HEAD for development.
- WAN22_PIN="${WAN22_PIN:-0b6b09aaa0d0b7cd7360fa358208437646dece60}"
- WAN22_DIR="${HOME}/.portos/wan2.2-mlx"
+ # Keep uv itself on-demand too. A machine that updated PortOS but never used
+ # a BYOV model should gain no global package or tool. If uv is not already
+ # available, bootstrap a pinned copy inside ~/.portos using the Python that
+ # PortOS already validated above; all output streams back to the install UI.
+ WAN22_UV="$(command -v uv || true)"
+ WAN22_UV_TOOL_DIR="${HOME}/.portos/tools/uv-0.8.14"
+ if [[ -z "$WAN22_UV" ]]; then
+ WAN22_UV="${WAN22_UV_TOOL_DIR}/bin/uv"
+ if [[ ! -x "$WAN22_UV" ]]; then
+ echo "📦 Bootstrapping pinned uv 0.8.14 for MLX-Gen..."
+ "$PYTHON_BIN" -m venv "$WAN22_UV_TOOL_DIR"
+ "${WAN22_UV_TOOL_DIR}/bin/python3" -m pip install --disable-pip-version-check "uv==0.8.14"
+ fi
+ fi
+ # v0.25.0 exact commit, statically audited before integration. Keep the full
+ # SHA so existing installs get an explicit, reproducible UI-driven upgrade.
+ WAN22_PIN="${WAN22_PIN:-2452f0c12edcc8886eebf15772205ce9c417a618}"
+ WAN22_DIR="${HOME}/.portos/mlx-gen"
WAN22_PY="${WAN22_DIR}/.venv/bin/python3"
mkdir -p "${HOME}/.portos"
if [[ ! -d "${WAN22_DIR}/.git" ]]; then
- echo "📦 Cloning osama-ata/Wan2.2-mlx..."
- git clone https://github.com/osama-ata/Wan2.2-mlx.git "${WAN22_DIR}"
+ echo "📦 Cloning MLX-Gen..."
+ git clone https://github.com/lpalbou/mlx-gen.git "${WAN22_DIR}"
else
- echo "📦 Fetching Wan2.2-mlx updates..."
+ echo "📦 Fetching MLX-Gen updates..."
(cd "${WAN22_DIR}" && git fetch origin)
fi
git_checkout_pin "${WAN22_DIR}" "${WAN22_PIN}"
if [[ ! -x "${WAN22_PY}" ]]; then
- echo "📦 Creating Wan2.2-mlx venv with Python 3.11..."
- (cd "${WAN22_DIR}" && uv venv --python 3.11)
+ echo "📦 Creating MLX-Gen venv with Python 3.11..."
+ (cd "${WAN22_DIR}" && "$WAN22_UV" venv --python 3.11)
fi
- # Upstream uses pyproject + requirements rather than a lockfile. Use
- # `uv pip install -r requirements.txt` when present; otherwise `uv sync`
- # falls back to the project config.
- if [[ -f "${WAN22_DIR}/requirements.txt" ]]; then
- echo "📦 Installing Wan2.2-mlx requirements..."
- (cd "${WAN22_DIR}" && uv pip install -r requirements.txt)
- else
- echo "📦 Syncing Wan2.2-mlx packages..."
- (cd "${WAN22_DIR}" && uv sync)
+ echo "📦 Syncing pinned MLX-Gen packages..."
+ (cd "${WAN22_DIR}" && "$WAN22_UV" sync --locked)
+ if ! "${WAN22_PY}" -c "import mflux.models.wan.cli.wan_generate" 2>/dev/null; then
+ echo "❌ MLX-Gen synced but the Wan runtime import failed." >&2
+ echo " Use Repair / Upgrade from the Video Gen runtime panel to retry." >&2
+ exit 1
fi
- echo "✅ Wan2.2-mlx venv ready: ${WAN22_PY}"
+ echo "✅ MLX-Gen Wan runtime ready: ${WAN22_PY}"
fi
INSTALL_HUNYUAN="${INSTALL_HUNYUAN:-0}"
@@ -643,6 +638,10 @@ echo " Videos: ${PORTOS_DATA}/videos"
if [[ "$INSTALL_LTX2" == "1" ]]; then
echo " LTX-2.3: ${HOME}/.portos/ltx-2-mlx/.venv/bin/python3 (separate venv, dgrauet pipeline @ ${LTX2_PIN:0:12})"
fi
+if [[ "$INSTALL_WAN22" == "1" ]]; then
+ echo " Wan 2.2: ${HOME}/.portos/mlx-gen/.venv/bin/python3 (MLX-Gen @ ${WAN22_PIN:0:12})"
+ echo " Weights remain uninstalled until Download is chosen in Video Gen."
+fi
if [[ "$INSTALL_MUSICGEN" == "1" ]] && is_macos; then
echo " MusicGen: ${HOME}/.portos/venv-musicgen/bin/python3 (separate venv, MLX runtime @ ${HOME}/.portos/mlx-examples/musicgen)"
fi
@@ -662,7 +661,7 @@ if [[ "$INSTALL_FLUX2" == "1" ]]; then
echo ""
echo "⚠️ FLUX.2-klein needs HF auth: accept the license at"
echo " https://huggingface.co/black-forest-labs/FLUX.2-klein-4B"
- echo " then export HF_TOKEN=... before running PortOS."
+ echo " then save the Hugging Face token in PortOS Media Generation Settings."
fi
echo ""
echo "Set this Python path in PortOS Settings → Image Gen → Local."
diff --git a/server/lib/README.md b/server/lib/README.md
index 714a6a9391..20d64d0df9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -130,11 +130,11 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
| `hfToken.js` | HuggingFace token resolution (settings > env > CLI): `getHfToken` / `getHfTokenInfo` / `hfTokenEnv`, plus `hfChildEnv(extra?)` for a complete Malloc-stripped child environment that preserves inherited variables while injecting the resolved token. |
| `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure. |
-| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoFile(repoId,filename)` resolves ONE known file in the newest snapshot **without walking it** (the whole-snapshot stat in `inspectModelCache` is prohibitive for an aggregate repo that hosts hundreds of GB of unrelated weights), and `repairCachedFile(path)` is the matching single-file repair (unlinks one snapshot entry AND the blob behind its symlink). `verifySafetensorsStructure(path,size)` is the reusable header/size structural check (reads only the header region) — also used by the Civitai/HF LoRA install path to reject truncated downloads. |
-| `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |
+| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoFile(repoId,filename)` resolves ONE known file in the newest snapshot **without walking it**; `verifyCachedRepoFiles` / `repairCachedRepoFiles` apply that exact-file contract to pinned adapter pairs; and `repairCachedFile(path)` is the matching single-file repair. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check. |
+| `hfDownload.js` | `downloadHfRepo({repo,onEvent,pythonPath?})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in a caller-preferred runtime or the shared fallback venvs and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |
| `icLoraWeights.js` | IC-LoRA weight registry for the local LTX-2 remix modes (`IC_LORA_MODES`, `IC_LORA_MODE_VALUES`, `listIcLoraWeights()`, `isIcLoraMode(mode)`, `icLoraSpecForMode(mode)`, `icLoraRepos()`, `icLoraWeightCandidates(spec)`, `findCachedIcLoraWeight(spec)`, `resolveIcLoraWeight(mode)` → `{path,cached,spec}`). Single source of truth mapping each remix mode (`ic-control`, `ic-colorize`, `ic-ingredients`) → its HF repo/filename, reference-count rule, per-weight `referenceDownscaleFactor` (read from the weight's safetensors metadata, never assumed), and input surface (`referenceKind: 'video' | 'image'`). A `requiresPreDownload` spec (Ingredients) suppresses `resolveIcLoraWeight`'s bare-repo-id fallback — the pipeline would `snapshot_download` it, and its candidates are a gated first-party repo plus a ~708 GB aggregate mirror, so the weight must be pre-fetched single-file instead. Also owns the two rules derived from that data: `assertIcReferenceCount(spec,count,fail)` / `describeIcReferenceRange(spec)` and `icResolutionIssue(spec,w,h)` (the output-resolution divisibility its reference encoder imposes). Mirrored to `client/src/lib/videoGenParams.js`; `icLoraWeights.parity.test.js` diffs the two. |
| `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. |
-| `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})`, `openSseStream(res)` (`{send,safeEnd}` SSE boilerplate; uses `SSE_HEADERS` from `sseHeaders.js`) — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |
+| `sseDownload.js` | `startHfDownloadStream({req,res,repo|repos|fallbacks,alreadyDownloadedMessage,pythonPath?})`, `openSseStream(res)` — shared SSE driver for model downloads. Required targets may name exact `only` files, fallback chains are first-success, and the cross-route in-flight Map deduplicates pulls. |
| `installLogger.js` | `createInstallLogger({installer,target})` → `{start,onEvent,success,failure,cancel}` — server-console chokepoint for install/venv-setup SSE flows (the install-side analogue of `sseDownload.js`). Logs a START line, throttled heartbeats + `stage` milestones (not every raw pip/bash line), and the OUTCOME (success/fail/cancel) with elapsed time. `onEvent(ev)` auto-detects terminal `complete`/`error` SSE events. Used by the music/video runtime installers and the FLUX.2 venv bootstrap. |
## File & I/O
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.js
index 25f982b1c1..7240900704 100644
--- a/server/lib/hfCache.js
+++ b/server/lib/hfCache.js
@@ -151,6 +151,44 @@ export async function findCachedRepoFile(repoId, filename) {
return stat && stat.size > 0 ? candidate : null;
}
+// Verify an explicit file subset inside an aggregate HF repo without walking
+// unrelated siblings. Lightning repositories commonly contain many adapters;
+// a PortOS profile needs only its pinned high/low-noise pair.
+export async function verifyCachedRepoFiles(repoId, filenames, { deep = false } = {}) {
+ const base = {
+ repoId, status: 'missing', cached: false, sizeBytes: 0,
+ snapshotPath: null, checkedDeep: deep, files: [],
+ };
+ const wanted = Array.isArray(filenames)
+ ? filenames.filter((name) => typeof name === 'string' && name.length > 0)
+ : [];
+ if (!repoId || wanted.length === 0) return base;
+ const snapshotPath = await latestSnapshotDir(join(getHfCacheRoot(), repoToDirName(repoId)));
+ if (!snapshotPath) return base;
+ const files = await Promise.all(wanted.map((name) => verifyWeightFile({ name, path: join(snapshotPath, name) }, { deep })));
+ const anyBad = files.some((file) => !file.ok);
+ const anyMissing = files.some((file) => file.reason === 'missing-blob');
+ return {
+ repoId,
+ status: anyMissing ? 'missing' : (anyBad ? 'bad' : 'ok'),
+ cached: !anyBad,
+ sizeBytes: files.filter((file) => file.ok).reduce((sum, file) => sum + (file.sizeBytes || 0), 0),
+ snapshotPath,
+ checkedDeep: deep,
+ files,
+ };
+}
+
+export async function repairCachedRepoFiles(repoId, filenames, { deep = false } = {}) {
+ const verify = await verifyCachedRepoFiles(repoId, filenames, { deep });
+ if (verify.status !== 'bad') return { repoId, status: verify.status, deleted: [] };
+ const deleted = [];
+ for (const file of verify.files.filter((entry) => !entry.ok)) {
+ if (await repairCachedFile(file.path)) deleted.push(file.name);
+ }
+ return { repoId, status: 'bad', deleted };
+}
+
// ---------------------------------------------------------------------------
// Weight-integrity verification (issue #1324)
//
diff --git a/server/lib/hfCache.test.js b/server/lib/hfCache.test.js
index 4cb5610d8d..b0d78cf626 100644
--- a/server/lib/hfCache.test.js
+++ b/server/lib/hfCache.test.js
@@ -6,6 +6,7 @@ import { join } from 'node:path';
import {
inspectModelCache, getHfCacheRoot, isModelCached,
verifyModelCache, repairModelCache, findCachedRepoFile, repairCachedFile,
+ verifyCachedRepoFiles, repairCachedRepoFiles,
} from './hfCache.js';
// Build a minimal *valid* .safetensors buffer: 8-byte LE header length, a JSON
@@ -435,3 +436,58 @@ describe('repairCachedFile', () => {
expect(await repairCachedFile(null)).toBe(false);
});
});
+
+describe('exact-file aggregate verification', () => {
+ const cleanup = [];
+ let previousCache;
+ beforeEach(() => { previousCache = process.env.HF_HUB_CACHE; });
+ afterEach(() => {
+ if (previousCache === undefined) delete process.env.HF_HUB_CACHE;
+ else process.env.HF_HUB_CACHE = previousCache;
+ for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('requires every pinned file without inspecting unrelated siblings', async () => {
+ const { root } = buildContentCache({
+ repoId: 'org/lightning',
+ files: {
+ 'high.safetensors': { content: buildSafetensors() },
+ 'low.safetensors': { content: buildSafetensors() },
+ 'unrelated.safetensors': { content: Buffer.from('not safetensors') },
+ },
+ });
+ cleanup.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const result = await verifyCachedRepoFiles('org/lightning', ['high.safetensors', 'low.safetensors']);
+ expect(result.status).toBe('ok');
+ expect(result.files.map((file) => file.name)).toEqual(['high.safetensors', 'low.safetensors']);
+ });
+
+ it('reports a missing pinned file as not cached', async () => {
+ const { root } = buildContentCache({
+ repoId: 'org/lightning',
+ files: { 'high.safetensors': { content: buildSafetensors() } },
+ });
+ cleanup.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const result = await verifyCachedRepoFiles('org/lightning', ['high.safetensors', 'low.safetensors']);
+ expect(result.status).toBe('missing');
+ expect(result.cached).toBe(false);
+ });
+
+ it('repairs only a corrupt pinned file', async () => {
+ const { root, snapDir } = buildContentCache({
+ repoId: 'org/lightning',
+ files: {
+ 'high.safetensors': { content: buildSafetensors({ truncateBy: 4 }) },
+ 'low.safetensors': { content: buildSafetensors() },
+ },
+ });
+ cleanup.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const result = await repairCachedRepoFiles('org/lightning', ['high.safetensors', 'low.safetensors']);
+ expect(result.deleted).toEqual(['high.safetensors']);
+ expect(existsSync(join(snapDir, 'high.safetensors'))).toBe(false);
+ expect(existsSync(join(snapDir, 'low.safetensors'))).toBe(true);
+ });
+});
diff --git a/server/lib/hfDownload.js b/server/lib/hfDownload.js
index c8fd8a3dd2..ee27f93e22 100644
--- a/server/lib/hfDownload.js
+++ b/server/lib/hfDownload.js
@@ -44,7 +44,8 @@ const HELPER_SCRIPT = join(PATHS.root, 'scripts', 'hf_download_repo.py');
// place but no packages, and resolveFlux2Python() alone would still return
// that broken interpreter. Every download would then fail on the broken
// venv before reaching the working fallback.
-export async function resolveHfDownloadPython() {
+export async function resolveHfDownloadPython(preferredPython = null) {
+ if (preferredPython) return preferredPython;
const flux2 = resolveFlux2Python();
if (flux2 && await isFlux2VenvHealthy()) return flux2;
const settings = await getSettings();
@@ -62,7 +63,7 @@ export async function resolveHfDownloadPython() {
// files. This is MANDATORY for aggregate repos — `DeepBeepMeep/LTX-2` mirrors
// every LTX weight in one ~708 GB repo, so a snapshot would fill the user's
// disk to pull one 1.3 GB IC-LoRA (see server/lib/icLoraWeights.js).
-export function downloadHfRepo({ repo, revision = null, only = null, onEvent }) {
+export function downloadHfRepo({ repo, revision = null, only = null, pythonPath: preferredPython = null, onEvent }) {
let proc = null;
let killed = false;
let errorKind = null;
@@ -70,7 +71,7 @@ export function downloadHfRepo({ repo, revision = null, only = null, onEvent })
let sizeBytes = 0;
const promise = (async () => {
- const pythonPath = await resolveHfDownloadPython();
+ const pythonPath = await resolveHfDownloadPython(preferredPython);
// Cancel-before-spawn check. resolveHfDownloadPython runs an
// isFlux2VenvHealthy() probe (several hundred ms cold) and getHfTokenInfo
// does file I/O; a kill() landing inside either await otherwise still
@@ -79,7 +80,7 @@ export function downloadHfRepo({ repo, revision = null, only = null, onEvent })
// the whole snapshot finishes.
if (killed) return { ok: false, errorKind: 'cancelled', errorMessage: 'Cancelled' };
if (!pythonPath) {
- const msg = 'No Python venv with huggingface_hub found. Install the FLUX.2 venv from Image Gen settings first.';
+ const msg = 'No Python runtime with huggingface_hub is ready. Install or repair the selected runtime from the model setup panel.';
onEvent({ type: 'error', message: msg, kind: 'venv_missing' });
return { ok: false, errorKind: 'venv_missing', errorMessage: msg };
}
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index 024bdfce9d..ee38cceadb 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -49,28 +49,99 @@ const DEFAULT_REGISTRY = {
// via `INSTALL_LTX2=1 bash scripts/setup-image-video.sh`.
{ id: 'ltx23_dgrauet_q4', name: 'LTX-2.3 dgrauet Q4 (~16 GB, true keyframes)', repo: 'dgrauet/ltx-2.3-mlx-q4', runtime: 'ltx2', steps: 8, guidance: 3.0 },
{ id: 'ltx23_dgrauet_q8', name: 'LTX-2.3 dgrauet Q8 (~25 GB, true keyframes)', repo: 'dgrauet/ltx-2.3-mlx-q8', runtime: 'ltx2', steps: 8, guidance: 3.0 },
- // Wan 2.2 (Alibaba) — pure-MLX port at osama-ata/Wan2.2-mlx, weights
- // at Wan-AI/Wan2.2-T2V-A14B. Requires a dedicated venv synced via
- // `INSTALL_WAN22=1 bash scripts/setup-image-video.sh` (clones the
- // runtime repo into ~/.portos/wan2.2-mlx). MoE-A14B = 14B active
- // params at inference, ~28 GB resident at bf16.
+ // Wan 2.2 through pinned MLX-Gen. Generation is cache-only: PortOS owns
+ // the explicit base/adaptor downloads and uses the saved HF token.
{
- id: 'wan22_t2v_a14b',
- name: 'Wan 2.2 T2V A14B (~28 GB, MoE-14B-active)',
- repo: 'Wan-AI/Wan2.2-T2V-A14B',
+ id: 'wan22_ti2v_5b',
+ name: 'Wan 2.2 TI2V 5B Q8 (~17 GB, text + image)',
+ repo: 'AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit',
runtime: 'wan22',
- mode: 't2v',
+ supportedModes: ['text', 'image'],
+ frameStride: 4,
+ fpsOptions: [16, 20, 24],
+ memoryGb: 24,
steps: 25,
guidance: 5.0,
+ flowShift: 3.0,
+ solver: 'unipc',
+ },
+ {
+ id: 'wan22_t2v_a14b',
+ name: 'Wan 2.2 T2V A14B Q8 (~14 GB runtime)',
+ repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ runtime: 'wan22',
+ supportedModes: ['text'],
+ frameStride: 4,
+ fpsOptions: [16, 20, 24],
+ memoryGb: 16,
+ steps: 20,
+ guidance: 4.0,
+ guidance2: 3.0,
+ flowShift: 3.0,
+ solver: 'unipc',
},
{
id: 'wan22_i2v_a14b',
- name: 'Wan 2.2 I2V A14B (~28 GB, image-to-video)',
- repo: 'Wan-AI/Wan2.2-I2V-A14B',
+ name: 'Wan 2.2 I2V A14B Q8 (~14 GB runtime)',
+ repo: 'AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit',
runtime: 'wan22',
- mode: 'i2v',
- steps: 25,
- guidance: 5.0,
+ supportedModes: ['image'],
+ frameStride: 4,
+ fpsOptions: [16, 20, 24],
+ memoryGb: 16,
+ steps: 20,
+ guidance: 3.5,
+ guidance2: 3.5,
+ flowShift: 3.0,
+ solver: 'unipc',
+ },
+ {
+ id: 'wan22_t2v_a14b_lightning',
+ name: 'Wan 2.2 T2V A14B Lightning Q8 (~14 GB, 4-step)',
+ repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ runtime: 'wan22',
+ supportedModes: ['text'],
+ frameStride: 4,
+ fpsOptions: [16, 20, 24],
+ memoryGb: 16,
+ steps: 4,
+ guidance: 1.0,
+ guidance2: 1.0,
+ flowShift: 5.0,
+ solver: 'euler',
+ samplerLocked: true,
+ requiredWeights: [{
+ repo: 'lightx2v/Wan2.2-Lightning',
+ files: [
+ 'Wan2.2-T2V-A14B-4steps-lora-rank64-Seko-V1.1/high_noise_model.safetensors',
+ 'Wan2.2-T2V-A14B-4steps-lora-rank64-Seko-V1.1/low_noise_model.safetensors',
+ ],
+ targetRoles: ['high_noise_transformer', 'low_noise_transformer'],
+ }],
+ },
+ {
+ id: 'wan22_i2v_a14b_lightning',
+ name: 'Wan 2.2 I2V A14B Lightning Q8 (~14 GB, 4-step)',
+ repo: 'AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit',
+ runtime: 'wan22',
+ supportedModes: ['image'],
+ frameStride: 4,
+ fpsOptions: [16, 20, 24],
+ memoryGb: 16,
+ steps: 4,
+ guidance: 1.0,
+ guidance2: 1.0,
+ flowShift: 5.0,
+ solver: 'euler',
+ samplerLocked: true,
+ requiredWeights: [{
+ repo: 'lightx2v/Wan2.2-Lightning',
+ files: [
+ 'Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/high_noise_model.safetensors',
+ 'Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/low_noise_model.safetensors',
+ ],
+ targetRoles: ['high_noise_transformer', 'low_noise_transformer'],
+ }],
},
// HunyuanVideo (Tencent) — MLX port at gaurav-nelson/HunyuanVideo_MLX,
// weights at tencent/HunyuanVideo. 13B params, ~60 GB resident at bf16.
diff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.js
index deab1d7fd9..e73e1b90f4 100644
--- a/server/lib/sseDownload.js
+++ b/server/lib/sseDownload.js
@@ -6,7 +6,7 @@
// FLUX-family repos referenced by both image and video gen would otherwise
// spawn two concurrent children.
-import { inspectModelCache } from './hfCache.js';
+import { findCachedRepoFile, inspectModelCache } from './hfCache.js';
import { downloadHfRepo } from './hfDownload.js';
import { SSE_HEADERS } from './sseHeaders.js';
@@ -29,7 +29,7 @@ export function openSseStream(res) {
return { send, safeEnd };
}
-export async function startHfDownloadStream({ req, res, repo, repos, fallbacks, cachedFile = null, alreadyDownloadedMessage, force = false }) {
+export async function startHfDownloadStream({ req, res, repo, repos, fallbacks, cachedFile = null, alreadyDownloadedMessage, force = false, pythonPath = null }) {
// Three input shapes, two semantics:
// - `repo` (single string) / `repos` (ordered array) — ALL must succeed. Used
// when a model has auxiliary repos that must be present alongside the main
@@ -51,14 +51,17 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,
// user doesn't have. Callers pass an async `() => boolean` that checks the one
// file instead.
const normalizeOnly = (v) => (Array.isArray(v) ? v.filter((f) => typeof f === 'string' && f.length > 0) : []);
+ const normalizeTarget = (target) => {
+ if (typeof target === 'string' && target.length > 0) return { repo: target, only: [] };
+ if (!target || typeof target.repo !== 'string' || target.repo.length === 0) return null;
+ return { repo: target.repo, only: normalizeOnly(target.only) };
+ };
const firstSuccessWins = Array.isArray(fallbacks);
const targets = firstSuccessWins
? fallbacks
.filter((t) => t && typeof t.repo === 'string' && t.repo.length > 0)
.map((t) => ({ repo: t.repo, only: normalizeOnly(t.only) }))
- : (Array.isArray(repos) ? repos : [repo])
- .filter((r) => typeof r === 'string' && r.length > 0)
- .map((r) => ({ repo: r, only: [] }));
+ : (Array.isArray(repos) ? repos : [repo]).map(normalizeTarget).filter(Boolean);
const { send, safeEnd } = openSseStream(res);
if (targets.length === 0) {
@@ -105,7 +108,9 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,
: await inspectModelCache(r);
if (aborted) return;
const alreadyHave = singleFile
- ? (typeof cachedFile === 'function' ? await cachedFile() : false)
+ ? (typeof cachedFile === 'function'
+ ? await cachedFile({ repo: r, only: onlyFiles })
+ : (await Promise.all(onlyFiles.map((file) => findCachedRepoFile(r, file)))).every(Boolean))
: existing.cached;
if (aborted) return;
// `force` is set by a repair-initiated re-download: repairModelCache()
@@ -148,6 +153,7 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,
const handle = downloadHfRepo({
repo: r,
only: singleFile ? onlyFiles : null,
+ pythonPath,
onEvent: (ev) => {
if (ev.type === 'progress' && ev.file) {
console.log(`⬇️ ${r}: ${ev.file} (${ev.step}/${ev.total})`);
diff --git a/server/lib/sseDownload.test.js b/server/lib/sseDownload.test.js
index f4ac0be3d6..b2638f9e7b 100644
--- a/server/lib/sseDownload.test.js
+++ b/server/lib/sseDownload.test.js
@@ -8,6 +8,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('./hfCache.js', () => ({
inspectModelCache: vi.fn(async () => ({ cached: true, sizeBytes: 100, snapshotPath: '/snap' })),
+ findCachedRepoFile: vi.fn(async () => null),
}));
vi.mock('./hfDownload.js', () => ({
@@ -359,4 +360,24 @@ describe('startHfDownloadStream repos (ALL must succeed)', () => {
const parsed = parseFrames(frames);
expect(parsed.at(-1)).toMatchObject({ type: 'complete', repos: ['org/repo-a', 'org/repo-b'], sizeBytes: 200 });
});
+
+ it('downloads only the exact files declared by a required aggregate target', async () => {
+ downloadHfRepo.mockReturnValue({ promise: Promise.resolve({ ok: true, sizeBytes: 50 }), kill: vi.fn() });
+ const { req, res, frames } = makeReqRes();
+ await startHfDownloadStream({
+ req,
+ res,
+ repos: [
+ { repo: 'org/base', only: [] },
+ { repo: 'org/adapters', only: ['profile/high.safetensors', 'profile/low.safetensors'] },
+ ],
+ pythonPath: '/runtime/bin/python3',
+ });
+ expect(downloadHfRepo).toHaveBeenNthCalledWith(2, expect.objectContaining({
+ repo: 'org/adapters',
+ only: ['profile/high.safetensors', 'profile/low.safetensors'],
+ pythonPath: '/runtime/bin/python3',
+ }));
+ expect(parseFrames(frames).at(-1)).toMatchObject({ type: 'complete' });
+ });
});
diff --git a/server/routes/videoGen.integrity.test.js b/server/routes/videoGen.integrity.test.js
index f7d405c1f7..9bd21828f6 100644
--- a/server/routes/videoGen.integrity.test.js
+++ b/server/routes/videoGen.integrity.test.js
@@ -51,7 +51,10 @@ vi.mock('../services/videoGen/local.js', () => ({
BYOV_RUNTIME_INFO: { ltx2: { id: 'ltx2', label: 'LTX-2 MLX', venvPython: '/tmp/x.py', installEnvVar: 'X', repoUrl: 'x', repoDir: '/tmp' } },
isByovRuntimeInstalled: vi.fn(() => false),
isByovRuntimeReady: vi.fn(async () => false),
+ isByovRuntimeCurrent: vi.fn(async () => false),
invalidateByovReadyCache: vi.fn(),
+ invalidateRuntimeFingerprintCache: vi.fn(),
+ resolveRuntimeFingerprint: vi.fn(async () => null),
}));
vi.mock('../services/mediaJobQueue/index.js', () => ({
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index cf6564a74b..4ec81598f4 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -27,6 +27,7 @@ import {
BYOV_RUNTIME_INFO,
isByovRuntimeInstalled,
isByovRuntimeReady,
+ isByovRuntimeCurrent,
invalidateByovReadyCache,
invalidateRuntimeFingerprintCache,
resolveRuntimeFingerprint,
@@ -45,7 +46,10 @@ import {
IC_LORA_MODE_VALUES, icLoraSpecForMode, icLoraRepos, listIcLoraWeights,
icLoraWeightCandidates, findCachedIcLoraWeight,
} from '../lib/icLoraWeights.js';
-import { inspectModelCache, verifyModelCache, repairModelCache, repairCachedFile, summarizeVerify } from '../lib/hfCache.js';
+import {
+ inspectModelCache, verifyModelCache, repairModelCache, repairCachedFile,
+ verifyCachedRepoFiles, repairCachedRepoFiles, summarizeVerify, aggregateVerifies,
+} from '../lib/hfCache.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
@@ -343,12 +347,15 @@ router.get('/setup/runtime-status', asyncHandler(async (req, res) => {
}
const binaryPresent = isByovRuntimeInstalled(info.id);
const packagesReady = binaryPresent ? await isByovRuntimeReady(info.id) : false;
+ const current = packagesReady ? await isByovRuntimeCurrent(info.id) : false;
res.json({
runtime: info.id,
label: info.label,
- installed: binaryPresent && packagesReady,
+ installed: binaryPresent && packagesReady && current,
binaryPresent,
packagesReady,
+ current,
+ upgradeAvailable: binaryPresent && packagesReady && !current,
venvPath: info.venvPython,
repoDir: info.repoDir,
repoUrl: info.repoUrl,
@@ -387,10 +394,14 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
return safeEnd();
}
runtimeInstallInFlight.set(info.id, null);
- // Skip ONLY when both the binary AND the import probe pass. A venv with a
- // python binary but no torch is the partial-install case the user is
- // explicitly re-triggering us to fix — short-circuiting would strand them.
- if (isByovRuntimeInstalled(info.id) && await isByovRuntimeReady(info.id)) {
+ // Skip ONLY when the binary, import probe, AND immutable revision all pass.
+ // A partial install needs Repair, while a healthy checkout on an older pin
+ // needs Upgrade; treating either as "already installed" strands the user
+ // behind a button that can never perform the action it advertises.
+ const alreadyInstalled = isByovRuntimeInstalled(info.id);
+ const alreadyReady = alreadyInstalled && await isByovRuntimeReady(info.id);
+ const alreadyCurrent = alreadyReady && await isByovRuntimeCurrent(info.id);
+ if (alreadyInstalled && alreadyReady && alreadyCurrent) {
runtimeInstallInFlight.delete(info.id);
send({ type: 'log', message: `${info.label} already installed at ${info.venvPython}` });
send({ type: 'complete', message: 'Already installed — nothing to do.' });
@@ -455,12 +466,15 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
// success message can't lie. The banner gate uses the same probe.
const binaryPresent = isByovRuntimeInstalled(info.id);
const packagesReady = binaryPresent && await isByovRuntimeReady(info.id);
- if (code === 0 && binaryPresent && packagesReady) {
+ const current = packagesReady && await isByovRuntimeCurrent(info.id);
+ if (code === 0 && binaryPresent && packagesReady && current) {
emit({ type: 'complete', message: `${info.label} ready: ${info.venvPython}` });
} else if (code === 0 && !binaryPresent) {
- emit({ type: 'error', message: `Installer exited 0 but ${info.venvPython} is still missing. Re-run from a terminal to see what happened.` });
+ emit({ type: 'error', message: `Installer exited 0 but the runtime is still missing. Review the log above, then use Repair in this panel.` });
} else if (code === 0) {
- emit({ type: 'error', message: `Installer exited 0 but the venv can't import its core packages. Check the log above for pip errors; re-run from a terminal if needed.` });
+ emit({ type: 'error', message: packagesReady
+ ? 'Installer exited 0 but the runtime is still on an outdated revision. Review the source-update log above, then use Repair in this panel.'
+ : `Installer exited 0 but the runtime can't import its core packages. Review the package errors above, then use Repair in this panel.` });
} else {
emit({ type: 'error', message: `Installer exited with code ${code}.` });
}
@@ -506,20 +520,39 @@ router.get('/models', (_req, res) => {
// Resolve the repo set an integrity scan should cover. A specific `modelId`
// scopes to that model's repo; no modelId scans every model repo plus the
// shared text encoder.
+const modelDownloadTargets = (model) => {
+ const repo = repoForModel(model);
+ if (!repo) return [];
+ const targets = [{ repo, only: [] }];
+ for (const dep of Array.isArray(model?.requiredWeights) ? model.requiredWeights : []) {
+ if (typeof dep?.repo !== 'string') continue;
+ const only = Array.isArray(dep.files) ? dep.files.filter((file) => typeof file === 'string' && file.length > 0) : [];
+ if (only.length > 0) targets.push({ repo: dep.repo, only });
+ }
+ return targets;
+};
+
+const targetKey = (target) => `${target.repo}::${target.only.join(',')}`;
+const verifyDownloadTarget = (target, { deep = false } = {}) => target.only.length > 0
+ ? verifyCachedRepoFiles(target.repo, target.only, { deep })
+ : verifyModelCache(target.repo, { deep });
+const repairDownloadTarget = (target, { deep = false } = {}) => target.only.length > 0
+ ? repairCachedRepoFiles(target.repo, target.only, { deep })
+ : repairModelCache(target.repo, { deep });
+
const reposToVerify = (modelId) => {
if (modelId) {
const m = listVideoModels().find((x) => x.id === modelId);
- const repo = m ? repoForModel(m) : null;
- return repo ? [repo] : [];
+ return m ? modelDownloadTargets(m) : [];
}
- const repos = listVideoModels().map(repoForModel).filter(Boolean);
+ const targets = listVideoModels().flatMap(modelDownloadTargets);
const enc = getTextEncoderRepo();
- if (isHfRepoId(enc)) repos.push(enc);
+ if (isHfRepoId(enc)) targets.push({ repo: enc, only: [] });
// IC-LoRA remix weights are separate HF pulls that the render path depends
// on, so an unscoped integrity scan must cover them too — otherwise a
// corrupt IC weight only surfaces as a garbled render.
- repos.push(...icLoraRepos());
- return [...new Set(repos)];
+ targets.push(...icLoraRepos().map((repo) => ({ repo, only: [] })));
+ return [...new Map(targets.map((target) => [targetKey(target), target])).values()];
};
// Per-model download status — see /api/image-gen/models/status for the
@@ -536,17 +569,35 @@ const repoCacheStatus = async (repo) => {
return { cached, sizeBytes, integrity: cached ? summarizeVerify(await verifyModelCache(repo)) : null };
};
+const modelCacheStatus = async (model, cache = null) => {
+ const targets = modelDownloadTargets(model);
+ if (targets.length === 0) return { repo: null, cached: null, sizeBytes: 0, integrity: null };
+ const readTarget = (target) => {
+ if (!cache) return verifyDownloadTarget(target);
+ const key = targetKey(target);
+ if (!cache.has(key)) cache.set(key, verifyDownloadTarget(target));
+ return cache.get(key);
+ };
+ const verifies = await Promise.all(targets.map(readTarget));
+ return {
+ repo: targets[0].repo,
+ requiredRepos: [...new Set(targets.map((target) => target.repo))],
+ cached: verifies.every((verify) => verify.status === 'ok'),
+ sizeBytes: verifies.reduce((sum, verify) => sum + (verify.sizeBytes || 0), 0),
+ integrity: aggregateVerifies(verifies),
+ };
+};
+
router.get('/models/status', asyncHandler(async (_req, res) => {
// Text encoder is shared across all video renders. A registry entry with
// `localPath` (e.g. an LM Studio install) trumps the HF cache check, so
// surface both the repo-cache status and the resolved local path so the UI
// can distinguish "not downloaded" from "served from LM Studio".
const encoderRepo = getTextEncoderRepo();
+ const verifyCache = new Map();
const [models, textEncoder, icLoras] = await Promise.all([
Promise.all(listVideoModels().map(async (m) => {
- const repo = repoForModel(m);
- if (!repo) return { id: m.id, repo: null, cached: null, sizeBytes: 0, integrity: null };
- return { id: m.id, repo, ...await repoCacheStatus(repo) };
+ return { id: m.id, ...await modelCacheStatus(m, verifyCache) };
})),
(async () => {
if (!isHfRepoId(encoderRepo)) return { repo: encoderRepo, cached: true, sizeBytes: 0, integrity: null };
@@ -604,7 +655,7 @@ router.post('/models/verify', asyncHandler(async (req, res) => {
if (modelId && repos.length === 0) {
throw new ServerError(`Unknown video model: ${modelId}`, { status: 404, code: 'UNKNOWN_MODEL' });
}
- const results = await Promise.all(repos.map(async (repo) => verifyModelCache(repo, { deep })));
+ const results = await Promise.all(repos.map((target) => verifyDownloadTarget(target, { deep })));
res.json({ deep, models: results.map((r) => ({ repo: r.repoId, ...summarizeVerify(r) })) });
}));
@@ -623,17 +674,19 @@ router.post('/models/:modelId/repair', asyncHandler(async (req, res) => {
if (repos.length === 0) {
throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file.`, { status: 400, code: 'NO_REPO_FOR_MODEL' });
}
- const repaired = await Promise.all(repos.map((repo) => repairModelCache(repo, { deep })));
+ const repaired = await Promise.all(repos.map((target) => repairDownloadTarget(target, { deep })));
const deleted = repaired.flatMap((r) => r.deleted.map((name) => ({ repo: r.repoId, name })));
- res.json({ deep, deleted, repos });
+ res.json({ deep, deleted, repos: [...new Set(repos.map((target) => target.repo))] });
}));
router.get('/models/:modelId/download', asyncHandler(async (req, res) => {
const model = listVideoModels().find((m) => m.id === req.params.modelId);
if (!model) throw new ServerError(`Unknown video model: ${req.params.modelId}`, { status: 404 });
- const repo = repoForModel(model);
- if (!repo) throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file.`, { status: 400, code: 'NO_REPO_FOR_MODEL' });
- await startHfDownloadStream({ req, res, repo, force: req.query.force === '1' });
+ const repos = modelDownloadTargets(model);
+ if (repos.length === 0) throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file.`, { status: 400, code: 'NO_REPO_FOR_MODEL' });
+ const runtimeInfo = BYOV_RUNTIME_INFO[model.runtime];
+ const pythonPath = runtimeInfo && await isByovRuntimeReady(model.runtime) ? runtimeInfo.venvPython : null;
+ await startHfDownloadStream({ req, res, repos, pythonPath, force: req.query.force === '1' });
}));
// IC-LoRA remix weights (issue #3100) get their own download/repair pair for
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 327184862b..b8a3c8441a 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -57,6 +57,7 @@ vi.mock('../services/videoGen/local.js', () => ({
},
isByovRuntimeInstalled: vi.fn(() => false),
isByovRuntimeReady: vi.fn(async () => false),
+ isByovRuntimeCurrent: vi.fn(async () => false),
invalidateByovReadyCache: vi.fn(),
invalidateRuntimeFingerprintCache: vi.fn(),
// /status now surfaces a runtime block (host chip/os + per-runtime versions).
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index d562e2430b..6bb42e1912 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -40,7 +40,6 @@ import {
LTX2_HELPER_SCRIPT,
WAN22_VENV_PYTHON,
WAN22_HELPER_SCRIPT,
- WAN22_REPO_DIR,
HUNYUAN_VENV_PYTHON,
HUNYUAN_HELPER_SCRIPT,
HUNYUAN_REPO_DIR,
@@ -517,36 +516,50 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames
return { bin: LTX2_VENV_PYTHON, args };
};
-// Build args for the Wan 2.2 MLX helper. The helper subprocesses upstream
-// `generate.py` from the cloned osama-ata/Wan2.2-mlx repo. The wrapper
-// translates PortOS's stable arg surface (prompt, output, image) into
-// upstream's --task / --size / --ckpt_dir form so PortOS releases don't
-// fight upstream CLI changes.
-const buildWan22Args = ({ model, prompt, width, height, numFrames, steps, guidance, seed, sourceImagePath, mode, outputPath }) => {
+// Build args for the pinned MLX-Gen Wan CLI. The helper itself never downloads:
+// all base + profile weights must already be present through the UI flow.
+const buildWan22Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, mode, outputPath }) => {
assertByovRuntimeInstalled('wan22');
+ const requestedMode = mode || (sourceImagePath ? 'image' : 'text');
+ const supportedModes = Array.isArray(model.supportedModes) ? model.supportedModes : [];
+ if (!supportedModes.includes(requestedMode)) {
+ throw new ServerError(
+ `${model.name} does not support ${requestedMode}-to-video. Choose a compatible Wan model.`,
+ { status: 400, code: 'WAN22_MODE_UNSUPPORTED' },
+ );
+ }
const args = [
WAN22_HELPER_SCRIPT,
- '--repo-dir', WAN22_REPO_DIR,
- '--task', model.mode === 'i2v' ? 'i2v-A14B' : 't2v-A14B',
'--model-repo', model.repo,
'--prompt', prompt,
'--width', String(width),
'--height', String(height),
'--num-frames', String(numFrames),
+ '--fps', String(fps),
'--steps', String(steps),
'--guidance', String(guidance ?? 5.0),
'--seed', String(seed),
'--output', outputPath,
];
- if (model.mode === 'i2v') {
+ if (negativePrompt) args.push('--negative-prompt', negativePrompt);
+ if (model.guidance2 != null) args.push('--guidance-2', String(model.guidance2));
+ if (model.flowShift != null) args.push('--flow-shift', String(model.flowShift));
+ if (model.solver) args.push('--solver', model.solver);
+ if (requestedMode === 'image') {
if (!sourceImagePath) {
throw new ServerError(
- 'Wan 2.2 i2v requires a source image — upload one before running this model.',
+ 'Wan 2.2 image-to-video requires a source image — upload one before running this model.',
{ status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' },
);
}
args.push('--image', sourceImagePath);
}
+ for (const dep of Array.isArray(model.requiredWeights) ? model.requiredWeights : []) {
+ const files = Array.isArray(dep?.files) ? dep.files : [];
+ const roles = Array.isArray(dep?.targetRoles) ? dep.targetRoles : [];
+ for (const file of files) args.push('--lora-path', `${dep.repo}:${file}`);
+ for (const role of roles) args.push('--lora-target-role', role);
+ }
return { bin: WAN22_VENV_PYTHON, args };
};
@@ -622,7 +635,7 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
);
}
if (model.runtime === 'wan22') {
- return buildWan22Args({ model, prompt, width, height, numFrames, steps, guidance, seed, sourceImagePath, mode, outputPath });
+ return buildWan22Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, mode, outputPath });
}
if (model.runtime === 'hunyuan') {
return buildHunyuanArgs({ model, prompt, negativePrompt, width, height, numFrames, steps, guidance, seed, outputPath });
@@ -727,6 +740,22 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
const model = resolveVideoModel(modelId);
if (!model) throw new ServerError(`Unknown video model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
+ if (model.runtime === 'wan22') {
+ const requestedMode = mode || (sourceImagePath || uploadedTempPath ? 'image' : 'text');
+ if (!Array.isArray(model.supportedModes) || !model.supportedModes.includes(requestedMode)) {
+ throw new ServerError(
+ `${model.name} does not support ${requestedMode}-to-video. Choose a compatible Wan model.`,
+ { status: 400, code: 'WAN22_MODE_UNSUPPORTED' },
+ );
+ }
+ const frameStride = Number(model.frameStride);
+ if (Number.isFinite(frameStride) && frameStride > 0 && (Number(numFrames) - 1) % frameStride !== 0) {
+ throw new ServerError(
+ `${model.name} requires a ${frameStride}n+1 frame count; got ${numFrames}.`,
+ { status: 400, code: 'WAN22_INVALID_FRAME_COUNT' },
+ );
+ }
+ }
// Only require the legacy mlx_video pythonPath when the chosen runtime
// actually uses it. ltx2/wan22/hunyuan resolve their own venv path inside
// buildArgs — gating them on the unrelated mlx_video setting locks users
@@ -781,8 +810,10 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
const w = Math.floor(Number(width) / 64) * 64;
const h = Math.floor(Number(height) / 64) * 64;
const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);
- let actualSteps = steps ? Number(steps) : model.steps;
- let actualGuidance = guidanceScale != null && guidanceScale !== '' ? Number(guidanceScale) : model.guidance;
+ let actualSteps = model.samplerLocked ? model.steps : (steps ? Number(steps) : model.steps);
+ let actualGuidance = model.samplerLocked
+ ? model.guidance
+ : (guidanceScale != null && guidanceScale !== '' ? Number(guidanceScale) : model.guidance);
// Opt-in T2V Standard two-stage perf experiment — overrides steps/guidance
// (and adds an explicit stage-2 step count) only for a plain default text
// render when PORTOS_T2V_TWO_STAGE is on. No-op otherwise.
@@ -1323,7 +1354,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// disagreed — drop the cached "ready" so the next /runtime-status
// re-probes and the install banner re-appears.
invalidateByovReadyCache(runtimeInfo.id);
- reason = `Python module '${missingPyModule}' is missing from the ${runtimeInfo.label} venv. Re-run the installer via Settings → Video (or \`${runtimeInfo.installEnvVar}=1 bash scripts/setup-image-video.sh\`).`;
+ reason = `Python module '${missingPyModule}' is missing from the ${runtimeInfo.label} runtime. Use Install / Repair in Video Gen's model setup panel.`;
} else {
reason = `Python module '${missingPyModule}' is missing. Install it into the configured Python environment and retry.`;
}
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index b958758e8c..04b4fb4f50 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -42,6 +42,23 @@ vi.mock('../../lib/mediaModels.js', () => ({
{ id: 'ltx23_unified', name: 'LTX-2.3 Unified Beta', runtime: 'mlx_video', repo: 'notapalindrome/ltx23-mlx-av', steps: 25, guidance: 3.0 },
// quantized mlx_video model — NOT LoRA-capable (out of scope).
{ id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4', runtime: 'mlx_video', repo: 'notapalindrome/ltx23-mlx-av-q4', steps: 25, guidance: 3.0 },
+ {
+ id: 'wan22_ti2v_5b', name: 'Wan TI2V', runtime: 'wan22',
+ repo: 'AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit',
+ supportedModes: ['text', 'image'], frameStride: 4, steps: 25, guidance: 5,
+ guidance2: null, flowShift: 3, solver: 'unipc',
+ },
+ {
+ id: 'wan22_t2v_a14b_lightning', name: 'Wan T2V Lightning', runtime: 'wan22',
+ repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ supportedModes: ['text'], frameStride: 4, steps: 4, guidance: 1,
+ guidance2: 1, flowShift: 5, solver: 'euler', samplerLocked: true,
+ requiredWeights: [{
+ repo: 'lightx2v/Wan2.2-Lightning',
+ files: ['profile/high.safetensors', 'profile/low.safetensors'],
+ targetRoles: ['high_noise_transformer', 'low_noise_transformer'],
+ }],
+ },
]),
getDefaultVideoModelId: vi.fn(() => 'ltx2_unified'),
getTextEncoderRepo: vi.fn(() => 'some/text-encoder'),
@@ -1454,6 +1471,47 @@ describe('generateVideo — close-handler resilience (issue #1334)', () => {
});
});
+describe('generateVideo — Wan MLX-Gen contract', () => {
+ it('passes the locked Lightning sampler and exact high/low adapter pair', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+ await generateVideo({
+ jobId: 'wan-lightning-args',
+ modelId: 'wan22_t2v_a14b_lightning',
+ prompt: 'a starship lifts off',
+ negativePrompt: 'blur',
+ width: 480, height: 256, numFrames: 81, fps: 20,
+ steps: 99, guidanceScale: 9, mode: 'text',
+ });
+ const call = spawnMock.mock.calls.find(([, args]) => Array.isArray(args) && args.some((arg) => String(arg).endsWith('/generate_wan22.py')));
+ expect(call).toBeDefined();
+ const args = call[1];
+ expect(args[args.indexOf('--steps') + 1]).toBe('4');
+ expect(args[args.indexOf('--guidance') + 1]).toBe('1');
+ expect(args[args.indexOf('--guidance-2') + 1]).toBe('1');
+ expect(args[args.indexOf('--flow-shift') + 1]).toBe('5');
+ expect(args[args.indexOf('--solver') + 1]).toBe('euler');
+ expect(args.filter((arg) => arg === '--lora-path')).toHaveLength(2);
+ expect(args).toContain('lightx2v/Wan2.2-Lightning:profile/high.safetensors');
+ expect(args).toContain('high_noise_transformer');
+ });
+
+ it('rejects a Wan model in an unsupported mode before spawn', async () => {
+ await expect(generateVideo({
+ modelId: 'wan22_t2v_a14b_lightning', prompt: 'test',
+ width: 480, height: 256, numFrames: 81, fps: 20, mode: 'image',
+ })).rejects.toMatchObject({ code: 'WAN22_MODE_UNSUPPORTED' });
+ });
+
+ it('rejects a non-4n+1 Wan frame count', async () => {
+ await expect(generateVideo({
+ modelId: 'wan22_ti2v_5b', prompt: 'test',
+ width: 480, height: 256, numFrames: 82, fps: 20, mode: 'text',
+ })).rejects.toMatchObject({ code: 'WAN22_INVALID_FRAME_COUNT' });
+ });
+});
+
describe('runtime fingerprint (/status)', () => {
it('hostRuntimeFingerprint reports chip/os/platform/arch/node', async () => {
const { hostRuntimeFingerprint } = await import('./local.js');
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index 1d901e9d12..08d51d5789 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -384,6 +384,33 @@ async function resolvePreparedParams({
{ status: 400, code: 'A2V_REQUIRES_LTX2' },
);
}
+ // Wan profiles have narrower mode + temporal-shape contracts than the
+ // shared request schema can express. Mirror the worker's guards here so a
+ // direct API caller cannot persist a job that is already known to fail.
+ // This runs before durable upload staging, keeping rejection cleanup cheap.
+ if (effectiveModel?.runtime === 'wan22') {
+ const requestedMode = body.mode
+ || (uploads.sourceImage || body.sourceImageFile ? 'image' : 'text');
+ const supportedModes = Array.isArray(effectiveModel.supportedModes)
+ ? effectiveModel.supportedModes
+ : [];
+ if (!supportedModes.includes(requestedMode)) {
+ await cleanupStaged();
+ throw new ServerError(
+ `${effectiveModel.name} does not support ${requestedMode}-to-video. Choose a compatible Wan model.`,
+ { status: 400, code: 'WAN22_MODE_UNSUPPORTED' },
+ );
+ }
+ const numFrames = body.numFrames != null ? Number(body.numFrames) : DEFAULT_NUM_FRAMES;
+ const frameStride = Number(effectiveModel.frameStride);
+ if (Number.isFinite(frameStride) && frameStride > 0 && (numFrames - 1) % frameStride !== 0) {
+ await cleanupStaged();
+ throw new ServerError(
+ `${effectiveModel.name} requires a ${frameStride}n+1 frame count; got ${numFrames}.`,
+ { status: 400, code: 'WAN22_INVALID_FRAME_COUNT' },
+ );
+ }
+ }
let sourceImagePath = null;
let lastImagePath = null;
diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.js
index 19f2cd9ef9..89557600e3 100644
--- a/server/services/videoGen/prepareParams.test.js
+++ b/server/services/videoGen/prepareParams.test.js
@@ -44,7 +44,7 @@ vi.mock('fs/promises', () => ({
import { unlink } from 'fs/promises';
import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';
import { getTrack } from '../tracks/index.js';
-import { loadHistory } from './local.js';
+import { listVideoModels, loadHistory } from './local.js';
import { prepareVideoGenParams, withStagedRollback, cleanupMultipartTemp } from './prepareParams.js';
// Field names the route owns Zod schemas for; the service only needs the keys
@@ -105,6 +105,7 @@ describe('cleanupMultipartTemp', () => {
describe('prepareVideoGenParams', () => {
beforeEach(() => {
vi.clearAllMocks();
+ listVideoModels.mockReturnValue([{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' }]);
loadHistory.mockResolvedValue([]);
});
@@ -231,5 +232,30 @@ describe('prepareVideoGenParams', () => {
await expect(prepare({ extendFromVideoId: '22222222-2222-4222-8222-222222222222' }))
.rejects.toMatchObject({ status: 404, code: 'EXTEND_SOURCE_NOT_FOUND' });
});
+
+ it('rejects an unsupported Wan mode before staging its upload', async () => {
+ listVideoModels.mockReturnValue([{
+ id: 'wan_t2v', name: 'Wan T2V', runtime: 'wan22',
+ supportedModes: ['text'], frameStride: 4,
+ }]);
+
+ await expect(prepare(
+ { modelId: 'wan_t2v', mode: 'image' },
+ { sourceImage: upload('sourceImage') },
+ )).rejects.toMatchObject({ status: 400, code: 'WAN22_MODE_UNSUPPORTED' });
+
+ expect(unlinkedDurablePaths()).toEqual([]);
+ expect(unlink).toHaveBeenCalledWith('/tmp/multipart-sourceImage-frame.png');
+ });
+
+ it('rejects a non-4n+1 Wan frame count before enqueue', async () => {
+ listVideoModels.mockReturnValue([{
+ id: 'wan_ti2v', name: 'Wan TI2V', runtime: 'wan22',
+ supportedModes: ['text', 'image'], frameStride: 4,
+ }]);
+
+ await expect(prepare({ modelId: 'wan_ti2v', mode: 'text', numFrames: 120 }))
+ .rejects.toMatchObject({ status: 400, code: 'WAN22_INVALID_FRAME_COUNT' });
+ });
});
});
diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.js
index 34e4f26c5d..e600214513 100644
--- a/server/services/videoGen/runtimes.js
+++ b/server/services/videoGen/runtimes.js
@@ -25,13 +25,11 @@ import { safeChildProcessEnv } from '../../lib/processEnv.js';
export const LTX2_VENV_PYTHON = join(homedir(), '.portos', 'ltx-2-mlx', '.venv', 'bin', 'python3');
export const LTX2_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_ltx2.py');
-// Wan 2.2 MLX runtime — osama-ata/Wan2.2-mlx cloned at
-// ~/.portos/wan2.2-mlx/. The wrapper at scripts/generate_wan22.py
-// subprocesses upstream generate.py so PortOS releases don't drift from
-// upstream's CLI. Provisioned via `INSTALL_WAN22=1 bash scripts/setup-image-video.sh`.
-export const WAN22_VENV_PYTHON = join(homedir(), '.portos', 'wan2.2-mlx', '.venv', 'bin', 'python3');
+// Wan 2.2 MLX runtime — pinned MLX-Gen checkout provisioned on demand.
+export const WAN22_VENV_PYTHON = join(homedir(), '.portos', 'mlx-gen', '.venv', 'bin', 'python3');
export const WAN22_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_wan22.py');
-export const WAN22_REPO_DIR = join(homedir(), '.portos', 'wan2.2-mlx');
+export const WAN22_REPO_DIR = join(homedir(), '.portos', 'mlx-gen');
+export const WAN22_EXPECTED_REVISION = '2452f0c12edcc8886eebf15772205ce9c417a618';
// HunyuanVideo MLX runtime — gaurav-nelson/HunyuanVideo_MLX cloned at
// ~/.portos/hunyuan-video-mlx/. ~60 GB resident at bf16 so practical only
@@ -80,13 +78,11 @@ export const BYOV_RUNTIME_INFO = Object.freeze({
venvPython: WAN22_VENV_PYTHON,
repoDir: WAN22_REPO_DIR,
installEnvVar: 'INSTALL_WAN22',
- repoUrl: 'https://github.com/osama-ata/Wan2.2-mlx',
- // Walks the package's __init__ chain so transitive deps absent from
- // upstream's pyproject.toml (e.g. einops, imported by wan/modules/vae2_1.py)
- // fail the probe instead of slipping past a flat torch/transformers check.
- importProbe: 'import wan',
+ repoUrl: 'https://github.com/lpalbou/mlx-gen',
+ expectedRevision: WAN22_EXPECTED_REVISION,
+ importProbe: 'import mflux.models.wan.cli.wan_generate',
// Mirror scripts/generate_wan22.py's emit_runtime_fingerprint package list.
- fingerprintPackages: ['wan', 'mlx', 'mlx_metal', 'torch'],
+ fingerprintPackages: ['mlx-gen', 'mlx', 'mlx_metal', 'huggingface-hub'],
},
ltx2: {
id: 'ltx2',
@@ -142,6 +138,26 @@ export async function isByovRuntimeReady(runtimeId) {
return probeOk;
}
+// Resolve a checkout's exact revision without trusting a mutable tag/branch.
+// Runtimes without an expectedRevision remain current by definition. A stale
+// pinned checkout makes the UI offer Repair / Upgrade; nothing runs at boot.
+export async function isByovRuntimeCurrent(runtimeId) {
+ const info = BYOV_RUNTIME_INFO[runtimeId];
+ if (!info?.expectedRevision) return true;
+ if (!existsSync(join(info.repoDir, '.git'))) return false;
+ return new Promise((resolve) => {
+ let stdout = '';
+ const child = spawn('git', ['-C', info.repoDir, 'rev-parse', 'HEAD'], {
+ env: safeChildProcessEnv(),
+ stdio: ['ignore', 'pipe', 'ignore'],
+ });
+ const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve(false); }, 10000);
+ child.stdout.on('data', (chunk) => { if (stdout.length < 128) stdout += chunk.toString(); });
+ child.on('close', (code) => { clearTimeout(timer); resolve(code === 0 && stdout.trim() === info.expectedRevision); });
+ child.on('error', () => { clearTimeout(timer); resolve(false); });
+ });
+}
+
// Throws the same shape the per-runtime buildArgs used to throw inline — a
// 500 with a stable runtime-specific code the route layer and tests already
// match against. The error codes are LTX2_VENV_MISSING / WAN22_VENV_MISSING
@@ -151,7 +167,7 @@ export function assertByovRuntimeInstalled(runtimeId) {
if (!info) return;
if (existsSync(info.venvPython)) return;
throw new ServerError(
- `${info.label} venv not found at ${info.venvPython}. Run \`${info.installEnvVar}=1 bash scripts/setup-image-video.sh\` to install.`,
+ `${info.label} runtime is not installed. Install or repair it from Video Gen's model setup panel.`,
{ status: 500, code: `${runtimeId.toUpperCase()}_VENV_MISSING` },
);
}