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

fix(video): harden pinned Wan runtime

[._.]/ Adam Eivy616b4eb5c615
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 25f1b5078a..7388621452 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,7 +6,7 @@
- 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.
+- 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, immutable base snapshots, 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. The catalog identifies the A14B profiles as roughly 40 GiB downloads intended for 64+ GB Apple Silicon rather than understating their footprint. Wan-specific 4n+1 frame choices, FPS options, mode compatibility, process-tree cancellation, 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.
diff --git a/client/src/components/media/ModelDownloadBadge.jsx b/client/src/components/media/ModelDownloadBadge.jsx
index 6961d8adbb..8d4c235936 100644
--- a/client/src/components/media/ModelDownloadBadge.jsx
+++ b/client/src/components/media/ModelDownloadBadge.jsx
@@ -99,9 +99,11 @@ export default function ModelDownloadBadge({
// Pull a size estimate out of the model's display name when the registry
// embedded one (e.g. "Flux 2 Klein 4B (SDNQ 4-bit, ~8 GB @ 512px)"). The
// registry isn't required to carry a structured size field, so we just
-// pluck whatever "~N GB" parenthetical the human-readable label included.
+// pluck whatever "~N GB" or "~N GiB" parenthetical the label included.
export function deriveSizeEstimate(modelName) {
if (!modelName) return null;
- const m = String(modelName).match(/~\s*(\d+(?:\.\d+)?)\s*GB/i);
- return m ? `~${m[1]} GB` : null;
+ const m = String(modelName).match(/~\s*(\d+(?:\.\d+)?)\s*(Gi?B)/i);
+ if (!m) return null;
+ const unit = m[2].toLowerCase() === 'gib' ? 'GiB' : 'GB';
+ return `~${m[1]} ${unit}`;
}
diff --git a/client/src/components/media/ModelDownloadBadge.test.jsx b/client/src/components/media/ModelDownloadBadge.test.jsx
new file mode 100644
index 0000000000..6b1a6ea7a8
--- /dev/null
+++ b/client/src/components/media/ModelDownloadBadge.test.jsx
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+import { deriveSizeEstimate } from './ModelDownloadBadge.jsx';
+
+describe('deriveSizeEstimate', () => {
+ it('preserves decimal and binary gigabyte labels', () => {
+ expect(deriveSizeEstimate('Example model (~8 GB)')).toBe('~8 GB');
+ expect(deriveSizeEstimate('Wan 2.2 (~16.9 GiB download)')).toBe('~16.9 GiB');
+ });
+
+ it('returns null when no estimate is embedded', () => {
+ expect(deriveSizeEstimate('Example model')).toBeNull();
+ expect(deriveSizeEstimate(null)).toBeNull();
+ });
+});
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsx
index 30f7639aaa..e1828668f3 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx
@@ -44,11 +44,13 @@ export default function AdvancedParamsPanel({
// a2v derives its length + audio track from the uploaded audio, so chunking
// and the audio flags don't apply there.
const showAudioFlags = mode !== 'a2v';
- const showChunks = mode !== 'a2v';
+ const showChunks = mode !== 'a2v'
+ && !(currentModel?.runtime === 'wan22'
+ && !currentModel?.supportedModes?.includes('image'));
// 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 frameOptions = frameOptionsForModel(currentModel, numFrames);
const fpsOptions = fpsOptionsForModel(currentModel);
const samplerLocked = currentModel?.samplerLocked === true;
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
index 5ffdaa69a5..1498d8a10a 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
@@ -97,6 +97,14 @@ describe('AdvancedParamsPanel', () => {
expect(screen.getByLabelText('Frames')).toBeTruthy();
});
+ it('hides chunks for a Wan profile that cannot continue via image mode', () => {
+ renderPanel({
+ currentModel: { runtime: 'wan22', supportedModes: ['text'], frameStride: 4 },
+ });
+ fireEvent.click(toggle());
+ expect(screen.queryByLabelText('Chunks')).toBeNull();
+ });
+
it('locks chunks to 1 while multi-keyframe mode is active', () => {
renderPanel({ chunks: 4, keyframesActive: true });
fireEvent.click(toggle());
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index e0b556e835..3952216a62 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -1,4 +1,4 @@
-import { useState, useEffect, useRef, useMemo } from 'react';
+import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { useSearchParams } from 'react-router';
import toast from '../components/ui/Toast';
import { extractLastFrame } from '../services/api';
@@ -288,6 +288,18 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
[models, mode],
);
+ // Every model transition — including automatic compatibility fallback —
+ // drops sampler overrides from the prior model. Keeping one transition path
+ // prevents a mode change from carrying LTX/Wan steps or CFG to its fallback.
+ const applyModelSelection = useCallback((nextId) => {
+ const nextModel = models.find((model) => model.id === nextId);
+ setModelId(nextId);
+ setNumFrames((current) => normalizeFramesForModel(current, nextModel));
+ setFps((current) => normalizeFpsForModel(current, nextModel));
+ setSteps('');
+ setGuidanceScale('');
+ }, [models]);
+
// Validate `modelId` once models are loaded. Two failure modes covered:
// 1. A Remix URL (or hand-edited link) carries a `modelId` that no longer
// exists in the catalog — <ModelSelect> shows nothing and `currentModel`
@@ -344,8 +356,8 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
const fallbackName = models.find((m) => m.id === fallback)?.name || fallback;
toast(`Original model "${modelId}" is no longer available — switched to "${fallbackName}"`);
}
- setModelId(fallback);
- }, [modelId, models, status?.defaultModel, status?.systemMemoryGb, mode, visibleModels]);
+ applyModelSelection(fallback);
+ }, [modelId, models, status?.defaultModel, status?.systemMemoryGb, mode, visibleModels, applyModelSelection]);
const currentModel = models.find((m) => m.id === modelId);
@@ -473,14 +485,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
// Switching model drops the sampler overrides — steps/guidanceScale are
// per-model defaults, and carrying one model's numbers onto another is
// usually wrong.
- const handleModelChange = (nextId) => {
- const nextModel = models.find((model) => model.id === nextId);
- setModelId(nextId);
- setNumFrames((current) => normalizeFramesForModel(current, nextModel));
- setFps((current) => normalizeFpsForModel(current, nextModel));
- setSteps('');
- setGuidanceScale('');
- };
+ const handleModelChange = applyModelSelection;
const dropSourceImageParam = () => {
if (!incomingSourceImage) return;
@@ -912,6 +917,8 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
|| currentModel?.runtime !== 'ltx2'
|| !!icResolutionIssue(icSpec, width, height)
);
+ const modelSupportsChaining = currentModel?.runtime !== 'wan22'
+ || currentModel?.supportedModes?.includes('image');
// Snapshot the current form into a generate-payload. Used both by the
// inline Generate button and by enqueue, so the two paths stay in lockstep.
@@ -1009,7 +1016,8 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
// Keyframes and IC references each anchor a single clip — the route
// rejects chunks > 1 with KEYFRAMES_CHUNKS_CONFLICT /
// IC_LORA_CHUNKS_CONFLICT, so suppress chunking for both.
- chunks: mode !== 'a2v' && !keyframesActive && !icModeActive && chunks > 1 ? chunks : '',
+ chunks: mode !== 'a2v' && !keyframesActive && !icModeActive
+ && modelSupportsChaining && chunks > 1 ? chunks : '',
};
};
diff --git a/client/src/hooks/useVideoGenForm.test.jsx b/client/src/hooks/useVideoGenForm.test.jsx
index 54d14c58ee..872f4e8972 100644
--- a/client/src/hooks/useVideoGenForm.test.jsx
+++ b/client/src/hooks/useVideoGenForm.test.jsx
@@ -15,6 +15,8 @@ const { useVideoGenForm } = await import('./useVideoGenForm.js');
// legacy path that extends from an extracted last frame.
const LTX2 = { id: 'ltx2-model', name: 'LTX-2.3', runtime: 'ltx2' };
const MLX = { id: 'mlx-model', name: 'LTX distilled', runtime: 'mlx_video' };
+const WAN_T2V = { id: 'wan-t2v', name: 'Wan T2V', runtime: 'wan22', supportedModes: ['text'], frameStride: 4 };
+const WAN_TI2V = { id: 'wan-ti2v', name: 'Wan TI2V', runtime: 'wan22', supportedModes: ['text', 'image'], frameStride: 4 };
const MODELS = [MLX, LTX2];
const STATUS = { connected: true, defaultModel: MLX.id };
@@ -160,6 +162,35 @@ describe('useVideoGenForm', () => {
expect(result.current.buildGeneratePayload().audioFile).toBe(wav);
});
+ it('clears sampler overrides on an automatic mode-compatible model fallback', async () => {
+ const { result } = render({
+ models: [WAN_T2V, WAN_TI2V],
+ status: { connected: true, defaultModel: WAN_T2V.id },
+ });
+ await waitFor(() => expect(result.current.modelId).toBe(WAN_T2V.id));
+ act(() => {
+ result.current.setSteps('17');
+ result.current.setGuidanceScale('6');
+ result.current.handleModeChange('image');
+ });
+ await waitFor(() => expect(result.current.modelId).toBe(WAN_TI2V.id));
+ expect(result.current.steps).toBe('');
+ expect(result.current.guidanceScale).toBe('');
+ });
+
+ it('does not submit chunks for a T2V-only Wan profile', async () => {
+ const { result } = render({
+ models: [WAN_T2V],
+ status: { connected: true, defaultModel: WAN_T2V.id },
+ });
+ await waitFor(() => expect(result.current.modelId).toBe(WAN_T2V.id));
+ act(() => {
+ result.current.setPrompt('a test');
+ result.current.setChunks(3);
+ });
+ expect(result.current.buildGeneratePayload().chunks).toBe('');
+ });
+
it('serializes keyframes as JSON and suppresses chunking while they are active', async () => {
const { result } = render();
act(() => result.current.handleModelChange(LTX2.id));
diff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.js
index 13043c868d..5452512c27 100644
--- a/client/src/lib/videoGenParams.js
+++ b/client/src/lib/videoGenParams.js
@@ -12,11 +12,25 @@
// 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 WAN_FRAME_OPTIONS = [...new Set([
+ ...FRAME_OPTIONS,
+ 41, 61, 81, 101, 161, 201, 321,
+])].sort((a, b) => a - b);
-export const frameOptionsForModel = (model) => Number(model?.frameStride) === 4
- ? WAN_FRAME_OPTIONS
- : FRAME_OPTIONS;
+export const isValidFrameCountForModel = (value, model) => {
+ const stride = Number(model?.frameStride);
+ const frames = Number(value);
+ return Number.isInteger(frames) && frames > 0
+ && Number.isFinite(stride) && stride > 0
+ && (frames - 1) % stride === 0;
+};
+export const frameOptionsForModel = (model, currentValue = null) => {
+ const options = Number(model?.frameStride) === 4 ? WAN_FRAME_OPTIONS : FRAME_OPTIONS;
+ const frames = Number(currentValue);
+ return isValidFrameCountForModel(frames, model) && !options.includes(frames)
+ ? [...options, frames].sort((a, b) => a - b)
+ : options;
+};
export const fpsOptionsForModel = (model) => Array.isArray(model?.fpsOptions) && model.fpsOptions.length > 0
? model.fpsOptions
: FPS_OPTIONS;
@@ -24,7 +38,9 @@ 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 normalizeFramesForModel = (value, model) => isValidFrameCountForModel(value, model)
+ ? Number(value)
+ : 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
@@ -34,12 +50,12 @@ export const normalizeFpsForModel = (value, model) => nearestOption(value, fpsOp
export const VIDEO_EDGE_BOUNDS = { min: 64, max: 2048, step: 64 };
// Resolve a video model's memory footprint in GB. Prefers the explicit
-// `memoryGb` field, falling back to a "~NN GB" hint in the display name, then
+// `memoryGb` field, falling back to a "~NN GB/GiB" hint in the display name, then
// +Infinity so an unknown model never spuriously "fits" a memory budget.
export const videoModelMemoryGb = (model) => {
const explicit = Number(model?.memoryGb);
if (Number.isFinite(explicit) && explicit > 0) return explicit;
- const match = String(model?.name || '').match(/~\s*(\d+(?:\.\d+)?)\s*GB/i);
+ const match = String(model?.name || '').match(/~\s*(\d+(?:\.\d+)?)\s*Gi?B/i);
return match ? Number(match[1]) : Number.POSITIVE_INFINITY;
};
diff --git a/client/src/lib/videoGenParams.test.js b/client/src/lib/videoGenParams.test.js
index 10d88c3c9e..c518d1e609 100644
--- a/client/src/lib/videoGenParams.test.js
+++ b/client/src/lib/videoGenParams.test.js
@@ -14,6 +14,7 @@ describe('videoModelMemoryGb', () => {
});
it('falls back to a "~NN GB" hint in the name', () => {
expect(videoModelMemoryGb({ name: 'LTX 2.3 (~12.5 GB)' })).toBe(12.5);
+ expect(videoModelMemoryGb({ name: 'Wan 2.2 (~17 GiB)' })).toBe(17);
});
it('returns +Infinity when neither is present so it never spuriously fits a budget', () => {
expect(videoModelMemoryGb({ name: 'mystery model' })).toBe(Number.POSITIVE_INFINITY);
@@ -82,7 +83,10 @@ describe('constants', () => {
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(normalizeFramesForModel(97, wan)).toBe(97);
+ expect(normalizeFramesForModel(109, wan)).toBe(109);
+ expect(frameOptionsForModel(wan, 109)).toContain(109);
+ expect(normalizeFramesForModel(98, wan)).toBe(97);
expect(normalizeFpsForModel(30, wan)).toBe(24);
});
});
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index c65fe5385b..81f1ce7816 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -419,11 +419,23 @@ export default function VideoGen() {
? { ...textEncoderInfo, downloading: true, progress: modelDownload.progress }
: textEncoderInfo)
: null;
- const modelWeightsBlocked = !isGrok && !!modelId
- && (modelDownload.loading || modelStatus === null || modelStatus?.cached === false);
+ const icWeightStatus = icSpec ? modelDownload.getStatus(icSpec.mode) : null;
+ const modelWeightsBlocked = !isGrok
+ && (statusLoading || !modelId || !currentModel || modelDownload.loading
+ || modelStatus === null || modelStatus?.cached === false);
const textEncoderWeightsBlocked = !isGrok && usesSharedTextEncoder
&& (modelDownload.loading || textEncoderStatus === null || textEncoderStatus?.cached === false);
- const weightsGateBlocked = modelWeightsBlocked || textEncoderWeightsBlocked;
+ const icWeightsBlocked = !isGrok && icModeActive
+ && (modelDownload.loading || icWeightStatus === null || icWeightStatus?.cached === false);
+ const weightsGateBlocked = modelWeightsBlocked || textEncoderWeightsBlocked || icWeightsBlocked;
+ const activeWeightErrorIds = [
+ modelId,
+ usesSharedTextEncoder ? TEXT_ENCODER_DOWNLOAD_ID : null,
+ icModeActive ? icSpec?.mode : null,
+ ].filter(Boolean);
+ const activeWeightError = activeWeightErrorIds.includes(modelDownload.lastError?.modelId)
+ ? modelDownload.lastError
+ : null;
// Weight-integrity (issue #1324). A corrupt/truncated model decodes to
// garbled "mosaic" video that a clean re-download fixes; surface a Repair
@@ -447,6 +459,19 @@ export default function VideoGen() {
const [dismissedEncoderIntegrityKey, setDismissedEncoderIntegrityKey] = useState(null);
const showEncoderIntegrityBanner = encoderIntegrityBad && dismissedEncoderIntegrityKey !== encoderIntegrityKey && !modelDownload.downloading;
+ // IC-LoRA weights are independent downloads too. Keep their corruption
+ // recovery on the originating Video Gen surface instead of requiring a CLI
+ // cache purge or leaving the user with a disabled Generate button.
+ const icIntegrity = icWeightStatus && !icWeightStatus.downloading ? icWeightStatus.integrity : null;
+ const icIntegrityBad = icIntegrity?.status === 'bad';
+ const icIntegrityBadCount = icIntegrityBad ? (icIntegrity.badFiles || []).length : 0;
+ const icIntegrityKey = icIntegrityBad
+ ? `${icSpec?.mode}:${(icIntegrity.badFiles || []).map((file) => file.name).join(',')}`
+ : null;
+ const [dismissedIcIntegrityKey, setDismissedIcIntegrityKey] = useState(null);
+ const showIcIntegrityBanner = icIntegrityBad
+ && dismissedIcIntegrityKey !== icIntegrityKey && !modelDownload.downloading;
+
const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;
// Explicit px sizing — maxWidth + maxHeight + aspectRatio together resolves
@@ -581,7 +606,9 @@ 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 && !weightsGateBlocked && !keyframesBlocked));
+ const canEnqueue = prompt.trim() && (isGrok || (!notConnected && !extendModeBlocked
+ && !a2vModeBlocked && !icLoraModeBlocked && !byovGateBlocked
+ && !weightsGateBlocked && !keyframesBlocked));
return (
<div className="space-y-3">
@@ -746,6 +773,19 @@ export default function VideoGen() {
repairing={modelDownload.repairing}
/>
)}
+ {showIcIntegrityBanner && (
+ <ModelRepairBanner
+ message={<>
+ The <strong className="font-semibold">{icSpec?.label || 'IC-LoRA'}</strong> weight has {icIntegrityBadCount || 'corrupt'} damaged file{icIntegrityBadCount === 1 ? '' : 's'}.
+ Repair deletes the bad file{icIntegrityBadCount === 1 ? '' : 's'} and re-downloads a clean copy.
+ </>}
+ repairLabel={`Repair ${icSpec?.label || 'IC-LoRA'}`}
+ onRepair={() => { setDismissedIcIntegrityKey(icIntegrityKey); modelDownload.repair(icSpec.mode); }}
+ onDismiss={() => setDismissedIcIntegrityKey(icIntegrityKey)}
+ disabled={modelDownload.repairing || modelDownload.downloading}
+ repairing={modelDownload.repairing}
+ />
+ )}
<StylePresetPicker
value={stylePreset?.id || ''}
onChange={setStylePreset}
@@ -861,7 +901,7 @@ export default function VideoGen() {
icSkipStage2={icSkipStage2}
width={width}
height={height}
- weightStatus={modelDownload.getStatus(icSpec.mode)}
+ weightStatus={icWeightStatus}
hasCompatibleModel={visibleModels.length > 0}
onPickFile={pickIcReferenceFile}
onClearFile={() => pickIcReferenceFile(null)}
@@ -915,16 +955,16 @@ export default function VideoGen() {
estimateLabel={deriveSizeEstimate(currentModel?.name)}
/>
)}
- {modelDownload.lastError?.modelId === modelId && (
+ {activeWeightError && (
<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>
+ <p>{activeWeightError.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 && (
+ {activeWeightError.repo && (
<a
- href={`https://huggingface.co/${modelDownload.lastError.repo}`}
+ href={`https://huggingface.co/${activeWeightError.repo}`}
target="_blank"
rel="noreferrer"
className="underline hover:text-white"
@@ -1041,6 +1081,7 @@ export default function VideoGen() {
: byovGateBlocked ? `Checking ${byovRuntime} runtime status…`
: modelWeightsBlocked ? 'Download the selected model weights before generating'
: textEncoderWeightsBlocked ? 'Download the shared text encoder before generating'
+ : icWeightsBlocked ? `Download the ${icSpec?.label || 'IC-LoRA'} weight 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'
@@ -1057,7 +1098,10 @@ export default function VideoGen() {
onClick={handleEnqueue}
disabled={!canEnqueue}
className="flex items-center gap-2 px-4 py-2 border border-port-border text-gray-200 hover:text-white hover:bg-port-border/40 disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium rounded-lg min-h-[40px]"
- title="Add this configuration to the batch queue"
+ title={canEnqueue ? 'Add this configuration to the batch queue'
+ : icWeightsBlocked ? `Download the ${icSpec?.label || 'IC-LoRA'} weight before queueing`
+ : weightsGateBlocked ? 'Finish required model downloads before queueing'
+ : 'Complete the required inputs before queueing'}
>
<ListPlus className="w-4 h-4" /> Add to queue
</button>
diff --git a/data.reference/media-models.json b/data.reference/media-models.json
index 4c59c7a303..cce54bea8a 100644
--- a/data.reference/media-models.json
+++ b/data.reference/media-models.json
@@ -45,8 +45,9 @@
},
{
"id": "wan22_ti2v_5b",
- "name": "Wan 2.2 TI2V 5B Q8 (~17 GB, text + image)",
+ "name": "Wan 2.2 TI2V 5B Q8 (~17 GiB download, text + image)",
"repo": "AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit",
+ "revision": "6875952a110b6bdbcfc00d72b1d89a8e02ab0fc3",
"runtime": "wan22",
"supportedModes": ["text", "image"],
"frameStride": 4,
@@ -59,13 +60,14 @@
},
{
"id": "wan22_t2v_a14b",
- "name": "Wan 2.2 T2V A14B Q8 (~14 GB runtime)",
+ "name": "Wan 2.2 T2V A14B Q8 (~40 GiB download, 64+ GB RAM)",
"repo": "AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit",
+ "revision": "39ee5f1f630789956f29f40b5c2c6d48c6e9a798",
"runtime": "wan22",
"supportedModes": ["text"],
"frameStride": 4,
"fpsOptions": [16, 20, 24],
- "memoryGb": 16,
+ "memoryGb": 48,
"steps": 20,
"guidance": 4,
"guidance2": 3,
@@ -74,13 +76,14 @@
},
{
"id": "wan22_i2v_a14b",
- "name": "Wan 2.2 I2V A14B Q8 (~14 GB runtime)",
+ "name": "Wan 2.2 I2V A14B Q8 (~40 GiB download, 64+ GB RAM)",
"repo": "AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit",
+ "revision": "1a17fbea2649c576de844e08e79fe56296751efa",
"runtime": "wan22",
"supportedModes": ["image"],
"frameStride": 4,
"fpsOptions": [16, 20, 24],
- "memoryGb": 16,
+ "memoryGb": 48,
"steps": 20,
"guidance": 3.5,
"guidance2": 3.5,
@@ -89,13 +92,14 @@
},
{
"id": "wan22_t2v_a14b_lightning",
- "name": "Wan 2.2 T2V A14B Lightning Q8 (~14 GB, 4-step)",
+ "name": "Wan 2.2 T2V A14B Lightning Q8 (~40 GiB download, 64+ GB RAM, 4-step)",
"repo": "AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit",
+ "revision": "39ee5f1f630789956f29f40b5c2c6d48c6e9a798",
"runtime": "wan22",
"supportedModes": ["text"],
"frameStride": 4,
"fpsOptions": [16, 20, 24],
- "memoryGb": 16,
+ "memoryGb": 48,
"steps": 4,
"guidance": 1,
"guidance2": 1,
@@ -104,6 +108,7 @@
"samplerLocked": true,
"requiredWeights": [{
"repo": "lightx2v/Wan2.2-Lightning",
+ "revision": "18bccf8884ec0a078eed79785eb4ef13ea16ce1e",
"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"
@@ -113,13 +118,14 @@
},
{
"id": "wan22_i2v_a14b_lightning",
- "name": "Wan 2.2 I2V A14B Lightning Q8 (~14 GB, 4-step)",
+ "name": "Wan 2.2 I2V A14B Lightning Q8 (~40 GiB download, 64+ GB RAM, 4-step)",
"repo": "AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit",
+ "revision": "1a17fbea2649c576de844e08e79fe56296751efa",
"runtime": "wan22",
"supportedModes": ["image"],
"frameStride": 4,
"fpsOptions": [16, 20, 24],
- "memoryGb": 16,
+ "memoryGb": 48,
"steps": 4,
"guidance": 1,
"guidance2": 1,
@@ -128,6 +134,7 @@
"samplerLocked": true,
"requiredWeights": [{
"repo": "lightx2v/Wan2.2-Lightning",
+ "revision": "18bccf8884ec0a078eed79785eb4ef13ea16ce1e",
"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"
diff --git a/scripts/generate_wan22.py b/scripts/generate_wan22.py
index 9d267b39c3..de8d2fb23d 100644
--- a/scripts/generate_wan22.py
+++ b/scripts/generate_wan22.py
@@ -8,6 +8,7 @@ MLX-Gen returns a typed download-required failure if anything is absent.
import argparse
import json
+import os
import subprocess
import sys
from pathlib import Path
@@ -81,6 +82,12 @@ def main() -> int:
print(f"STAGE:inference", file=sys.stderr, flush=True)
print(f"🎬 wan22 generate {args.width}x{args.height} steps={args.steps} seed={args.seed}", file=sys.stderr)
+ # PortOS cancels this wrapper by process group so the MLX-Gen subprocess
+ # cannot survive as an orphan while holding unified memory. Establish the
+ # group before spawning it; the detached launcher records this wrapper PID.
+ if hasattr(os, "setpgid"):
+ os.setpgid(0, 0)
+
# Human diagnostics remain on inherited stderr. JSONL progress on stdout
# is translated into PortOS's existing STAGE:/STATUS: protocol below.
proc = subprocess.Popen(
diff --git a/scripts/migrations/233-wan-mlx-gen-models.js b/scripts/migrations/233-wan-mlx-gen-models.js
index 5c3b32b19d..16768ec824 100644
--- a/scripts/migrations/233-wan-mlx-gen-models.js
+++ b/scripts/migrations/233-wan-mlx-gen-models.js
@@ -10,21 +10,26 @@ import { atomicWrite } from '../../server/lib/fileUtils.js';
const REL_PATH = 'data/media-models.json';
const LIGHTNING_REPO = 'lightx2v/Wan2.2-Lightning';
+const LIGHTNING_REVISION = '18bccf8884ec0a078eed79785eb4ef13ea16ce1e';
+const TI2V_REVISION = '6875952a110b6bdbcfc00d72b1d89a8e02ab0fc3';
+const T2V_REVISION = '39ee5f1f630789956f29f40b5c2c6d48c6e9a798';
+const I2V_REVISION = '1a17fbea2649c576de844e08e79fe56296751efa';
+const USER_TUNABLE_FIELDS = ['name', 'steps', 'guidance', 'guidance2', 'flowShift', 'solver', 'memoryGb'];
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',
+ id: 'wan22_ti2v_5b', name: 'Wan 2.2 TI2V 5B Q8 (~17 GiB download, text + image)',
+ repo: 'AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit', revision: TI2V_REVISION, 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,
+ id: 'wan22_t2v_a14b_lightning', name: 'Wan 2.2 T2V A14B Lightning Q8 (~40 GiB download, 64+ GB RAM, 4-step)',
+ repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit', revision: T2V_REVISION, runtime: 'wan22',
+ supportedModes: ['text'], frameStride: 4, fpsOptions: [16, 20, 24], memoryGb: 48,
steps: 4, guidance: 1, guidance2: 1, flowShift: 5, solver: 'euler', samplerLocked: true,
requiredWeights: [{
- repo: LIGHTNING_REPO,
+ repo: LIGHTNING_REPO, revision: LIGHTNING_REVISION,
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',
@@ -33,12 +38,12 @@ const NEW_ENTRIES = [
}],
},
{
- 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,
+ id: 'wan22_i2v_a14b_lightning', name: 'Wan 2.2 I2V A14B Lightning Q8 (~40 GiB download, 64+ GB RAM, 4-step)',
+ repo: 'AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit', revision: I2V_REVISION, runtime: 'wan22',
+ supportedModes: ['image'], frameStride: 4, fpsOptions: [16, 20, 24], memoryGb: 48,
steps: 4, guidance: 1, guidance2: 1, flowShift: 5, solver: 'euler', samplerLocked: true,
requiredWeights: [{
- repo: LIGHTNING_REPO,
+ repo: LIGHTNING_REPO, revision: LIGHTNING_REVISION,
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',
@@ -53,10 +58,11 @@ const UPGRADES = {
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)',
+ name: 'Wan 2.2 T2V A14B Q8 (~40 GiB download, 64+ GB RAM)',
repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ revision: T2V_REVISION,
runtime: 'wan22', supportedModes: ['text'], frameStride: 4,
- fpsOptions: [16, 20, 24], memoryGb: 16, steps: 20, guidance: 4,
+ fpsOptions: [16, 20, 24], memoryGb: 48, steps: 20, guidance: 4,
guidance2: 3, flowShift: 3, solver: 'unipc',
},
},
@@ -64,10 +70,11 @@ const UPGRADES = {
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)',
+ name: 'Wan 2.2 I2V A14B Q8 (~40 GiB download, 64+ GB RAM)',
repo: 'AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit',
+ revision: I2V_REVISION,
runtime: 'wan22', supportedModes: ['image'], frameStride: 4,
- fpsOptions: [16, 20, 24], memoryGb: 16, steps: 20, guidance: 3.5,
+ fpsOptions: [16, 20, 24], memoryGb: 48, steps: 20, guidance: 3.5,
guidance2: 3.5, flowShift: 3, solver: 'unipc',
},
},
@@ -82,7 +89,11 @@ export default {
});
if (raw == null) return;
let config;
- try { config = JSON.parse(raw); } catch { return; }
+ try {
+ config = JSON.parse(raw);
+ } catch (err) {
+ throw new Error(`Cannot migrate ${REL_PATH}: invalid JSON (${err.message})`, { cause: err });
+ }
const macos = Array.isArray(config?.video?.macos) ? config.video.macos : null;
if (!macos) return;
@@ -90,16 +101,14 @@ export default {
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;
+ const preserved = Object.fromEntries(USER_TUNABLE_FIELDS
+ .filter((field) => Object.prototype.hasOwnProperty.call(entry, field))
+ .map((field) => [field, entry[field]]));
+ if (entry.name === spec.oldName) delete preserved.name;
+ if (entry.steps === 25) delete preserved.steps;
+ if (entry.guidance === 5) delete preserved.guidance;
Object.assign(entry, spec.next);
- if (!oldName) entry.name = priorName;
- if (preserveSteps) entry.steps = priorSteps;
- if (preserveGuidance) entry.guidance = priorGuidance;
+ Object.assign(entry, preserved);
if (entry.mode === 't2v' || entry.mode === 'i2v') delete entry.mode;
changed = true;
}
diff --git a/scripts/migrations/233-wan-mlx-gen-models.test.js b/scripts/migrations/233-wan-mlx-gen-models.test.js
index 94f50e5998..beab68f7a7 100644
--- a/scripts/migrations/233-wan-mlx-gen-models.test.js
+++ b/scripts/migrations/233-wan-mlx-gen-models.test.js
@@ -31,10 +31,14 @@ describe('migration 233 — Wan MLX-Gen models', () => {
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,
+ revision: '39ee5f1f630789956f29f40b5c2c6d48c6e9a798',
+ supportedModes: ['text'], frameStride: 4, memoryGb: 48, 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]).toMatchObject({
+ revision: '18bccf8884ec0a078eed79785eb4ef13ea16ce1e',
+ });
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');
@@ -57,6 +61,10 @@ describe('migration 233 — Wan MLX-Gen models', () => {
name: 'My Wan profile',
steps: 17,
guidance: 6,
+ guidance2: 7,
+ flowShift: 4,
+ solver: 'euler',
+ memoryGb: 96,
});
write(config);
await migration.up({ rootDir });
@@ -66,9 +74,18 @@ describe('migration 233 — Wan MLX-Gen models', () => {
repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
steps: 17,
guidance: 6,
+ guidance2: 7,
+ flowShift: 4,
+ solver: 'euler',
+ memoryGb: 96,
});
});
+ it('rejects malformed JSON instead of silently marking the migration applied', async () => {
+ writeFileSync(path, '{not-json');
+ await expect(migration.up({ rootDir })).rejects.toThrow(/invalid JSON/);
+ });
+
it('is idempotent', async () => {
write(oldRows());
await migration.up({ rootDir });
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index a04650baa5..9a7022008c 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -277,15 +277,16 @@ if [[ "$INSTALL_WAN22" == "1" ]]; then
# 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
+ WAN22_UV="${WAN22_UV_TOOL_DIR}/bin/uv"
+ # Always use the PortOS-owned exact uv version. A random PATH copy can be too
+ # old for this lockfile or a future release with different sync semantics,
+ # which would defeat the reproducible runtime pin even though MLX-Gen itself
+ # is checked out at an immutable commit.
+ if [[ ! -x "$WAN22_UV" ]] || [[ "$("$WAN22_UV" --version 2>/dev/null || true)" != "uv 0.8.14" ]]; then
+ echo "📦 Bootstrapping pinned uv 0.8.14 for MLX-Gen..."
+ "$PYTHON_BIN" -m venv --clear "$WAN22_UV_TOOL_DIR"
+ "${WAN22_UV_TOOL_DIR}/bin/python3" -m pip install --disable-pip-version-check "uv==0.8.14"
fi
# v0.25.0 exact commit, statically audited before integration. Keep the full
# SHA so existing installs get an explicit, reproducible UI-driven upgrade.
diff --git a/server/lib/README.md b/server/lib/README.md
index 20d64d0df9..41de008ef6 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**; `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. |
+| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId,{revision?})` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep,revision?})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep,revision?})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoSnapshot(repoId,revision)` resolves an immutable local snapshot; `findCachedRepoFile(repoId,filename,{revision?})` resolves ONE known file without walking it; `isSafeHfRepoRelativePath` rejects traversal/absolute dependency filenames; `verifyCachedRepoFiles` / `repairCachedRepoFiles` apply that revision-aware exact-file contract to pinned adapter pairs; and `repairCachedFile(path,{snapshotPath?})` is the containment-checked matching single-file repair. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check. |
+| `hfDownload.js` | `downloadHfRepo({repo,revision?,only?,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|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. |
+| `sseDownload.js` | `startHfDownloadStream({req,res,repo|repos|fallbacks,alreadyDownloadedMessage,pythonPath?})`, `openSseStream(res)` — shared SSE driver for model downloads. Required targets may name an immutable `revision` and 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
@@ -175,7 +175,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000 })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. |
| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.
| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. |
-| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
+| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
| `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |
| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index 1ea2619aaf..f0bf0c9d36 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -47,7 +47,7 @@ import { spawn } from 'child_process';
import { EventEmitter } from 'events';
import { constants as osConstants } from 'os';
import { join } from 'path';
-import { open, readFile, rm, stat, readdir } from 'fs/promises';
+import { open, readFile, writeFile, rm, stat, readdir } from 'fs/promises';
import { ensureDir, sleep } from './fileUtils.js';
import { withSpawnCwdEnv } from './spawnCwd.js';
@@ -63,6 +63,25 @@ const PID_TIMEOUT_MS = 10000;
// escalating to SIGKILL. Matches the in-session cancel escalation (8s) plus
// slack for a final checkpoint write.
const REAP_GRACE_MS = 12000;
+const GROUP_KILL_MARKER = 'kill-process-group';
+
+const signalPid = (pid, signal, killProcessGroup = false) => {
+ if (killProcessGroup) {
+ try {
+ process.kill(-pid, signal);
+ return true;
+ } catch {
+ // The child may not have established its own process group yet. Fall back
+ // to its exact PID; at that early point it cannot have spawned descendants.
+ }
+ }
+ try {
+ process.kill(pid, signal);
+ return true;
+ } catch {
+ return false;
+ }
+};
// `wait` reports a signal-terminated child as 128+signum. Invert os signal
// constants once so we can decode that back into Node's ('code', 'signal')
@@ -208,9 +227,14 @@ function createLogTailer(handle, { controlDir, pollMs, cleanup }) {
* @param {number} [opts.pollMs] - tail/poll cadence (default 250ms)
* @param {boolean} [opts.cleanup] - remove controlDir after the job terminates
* (default false — keep the logs, e.g. inside a run dir for post-mortem)
+ * @param {boolean} [opts.killProcessGroup] - signal `-pid` on cancel/reap so a
+ * group-leader wrapper and every runtime child terminate together. The job is
+ * responsible for establishing its own process group before spawning children.
* @returns {Promise<object>} ChildProcess-like handle (resolves once the PID is known)
*/
-export async function spawnDetached(bin, args = [], { env, cwd, controlDir, pollMs = DEFAULT_POLL_MS, cleanup = false } = {}) {
+export async function spawnDetached(bin, args = [], {
+ env, cwd, controlDir, pollMs = DEFAULT_POLL_MS, cleanup = false, killProcessGroup = false,
+} = {}) {
if (!controlDir) throw new Error('spawnDetached requires a controlDir');
// Windows has no POSIX `sh` for the double-fork, and pm2's process management
@@ -237,6 +261,7 @@ export async function spawnDetached(bin, args = [], { env, cwd, controlDir, poll
const exitFile = join(controlDir, 'exit');
const stdoutLog = join(controlDir, 'stdout.log');
const stderrLog = join(controlDir, 'stderr.log');
+ const groupKillFile = join(controlDir, GROUP_KILL_MARKER);
// Setup is filesystem I/O that can fail (permissions, a stale non-dir path,
// disk full). Surface those as the handle's 'error' event — like a real
@@ -245,7 +270,9 @@ export async function spawnDetached(bin, args = [], { env, cwd, controlDir, poll
// would bypass that and strand a `running` run or leak temp files. Deferred
// so the listener is attached before it fires.
const ensureControlDir = await ensureDir(controlDir).then(
- () => Promise.all([pidFile, exitFile, stdoutLog, stderrLog].map((f) => rm(f, { force: true }))),
+ () => Promise.all([pidFile, exitFile, stdoutLog, stderrLog, groupKillFile].map((f) => rm(f, { force: true }))),
+ ).then(
+ () => (killProcessGroup ? writeFile(groupKillFile, '1') : null),
).then(() => null, (err) => err);
if (ensureControlDir) {
setImmediate(() => {
@@ -309,18 +336,12 @@ export async function spawnDetached(bin, args = [], { env, cwd, controlDir, poll
}
};
- // Signal the job directly by PID (it has reparented away from our tree, but a
- // direct PID signal still reaches it). Mirrors the original `proc.kill()`
- // which also signalled the PID, not the group.
+ // Signal the reparented job by PID, or by its persisted opt-in process group
+ // when the wrapper owns runtime descendants that must never outlive it.
handle.kill = (signal = 'SIGTERM') => {
handle.killed = true;
if (!handle.pid) return false;
- try {
- process.kill(handle.pid, signal);
- return true;
- } catch {
- return false; // ESRCH — already gone
- }
+ return signalPid(handle.pid, signal, killProcessGroup);
};
await awaitPid();
@@ -407,6 +428,7 @@ export async function reattachDetached(controlDir, { pollMs = DEFAULT_POLL_MS, c
const pid = Number.parseInt(pidRaw, 10);
if (!Number.isFinite(pid) || pid <= 0) return null;
const exitWritten = (await readFile(join(controlDir, 'exit'), 'utf8').catch(() => '')).length > 0;
+ const killProcessGroup = (await readFile(join(controlDir, GROUP_KILL_MARKER), 'utf8').catch(() => '')).trim() === '1';
// Dead PID with no exit sentinel → killed mid-run; nothing clean to stream
// (the RESULT line was never written). Let the caller reap+fail.
if (!exitWritten && !isAlive(pid)) return null;
@@ -418,17 +440,11 @@ export async function reattachDetached(controlDir, { pollMs = DEFAULT_POLL_MS, c
handle.killed = false;
handle.exitCode = null;
handle.signalCode = null;
- // Signal the survivor directly by PID (it reparented away from our tree, but
- // a direct PID signal still reaches it) — mirrors spawnDetached's handle.kill
- // so cancel/stall paths work identically on a re-attached run.
+ // Mirror spawnDetached's exact PID/group behavior so cancel/stall paths work
+ // identically on a re-attached run.
handle.kill = (signal = 'SIGTERM') => {
handle.killed = true;
- try {
- process.kill(pid, signal);
- return true;
- } catch {
- return false; // ESRCH — already gone
- }
+ return signalPid(pid, signal, killProcessGroup);
};
const { tick } = createLogTailer(handle, { controlDir, pollMs, cleanup });
@@ -492,6 +508,7 @@ export async function reapDetached(controlDir, { graceMs = REAP_GRACE_MS, pollMs
const pidRaw = await readFile(join(controlDir, 'pid'), 'utf8').catch(() => '');
const pid = Number.parseInt(pidRaw, 10);
if (!Number.isFinite(pid) || pid <= 0) return { reaped: false };
+ const killProcessGroup = (await readFile(join(controlDir, GROUP_KILL_MARKER), 'utf8').catch(() => '')).trim() === '1';
const exitWritten = async () => (await readFile(exitFile, 'utf8').catch(() => '')).length > 0;
// Supervisor already recorded an exit → the job finished; nothing to reap.
if (await exitWritten()) return { reaped: false };
@@ -500,7 +517,7 @@ export async function reapDetached(controlDir, { graceMs = REAP_GRACE_MS, pollMs
// seconds before boot) is vanishingly unlikely on a single-user box; the same
// trust the in-session cancel path places in the child PID.
const wasAlive = isAlive(pid);
- if (wasAlive) { try { process.kill(pid, 'SIGTERM'); } catch { /* raced its own exit */ } }
+ if (wasAlive) signalPid(pid, 'SIGTERM', killProcessGroup);
// Wait for the supervisor's `exit` sentinel — its FINAL act after the child
// dies — not just child death. That sentinel means the supervisor is fully
// done writing into controlDir, so a resume that reuses the dir can't race a
@@ -511,7 +528,7 @@ export async function reapDetached(controlDir, { graceMs = REAP_GRACE_MS, pollMs
for (let waited = 0; waited < hardCapMs; waited += pollMs) {
await sleep(pollMs);
if (await exitWritten()) return { reaped: wasAlive, pid };
- if (waited >= graceMs && isAlive(pid)) { try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ } }
+ if (waited >= graceMs && isAlive(pid)) signalPid(pid, 'SIGKILL', killProcessGroup);
}
return { reaped: wasAlive, pid };
}
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index 7cb8985c40..df36d6455c 100644
--- a/server/lib/detachedSpawn.test.js
+++ b/server/lib/detachedSpawn.test.js
@@ -61,6 +61,10 @@ describe('spawnDetached', () => {
const n = Number.parseInt(stdout.trim(), 10);
return Number.isFinite(n) ? n : 0;
};
+ const aliveByPs = async (pid) => {
+ const { stdout } = await execFileAsync('ps', ['-o', 'pid=', '-p', String(pid)]).catch(() => ({ stdout: '' }));
+ return stdout.trim().length > 0;
+ };
// Walk a process's ancestor chain to the root (PPID 1 / 0).
const ancestorsOf = async (pid) => {
const chain = [];
@@ -106,6 +110,36 @@ describe('spawnDetached', () => {
expect(handle.signalCode).toBe('SIGKILL');
});
+ it.skipIf(process.platform === 'win32')('killProcessGroup terminates a wrapper and its runtime child', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached('python3', ['-c', [
+ 'import os, subprocess, time',
+ 'os.setpgid(0, 0)',
+ "child = subprocess.Popen(['sleep', '30'])",
+ 'print(child.pid, flush=True)',
+ 'time.sleep(30)',
+ ].join('; ')], { controlDir, pollMs: 25, killProcessGroup: true });
+ const getOut = collect(handle.stdout);
+ let runtimePid = 0;
+ for (let i = 0; i < 80; i += 1) {
+ runtimePid = Number.parseInt(getOut().trim(), 10);
+ if (runtimePid > 0) break;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ expect(runtimePid).toBeGreaterThan(0);
+ expect(await aliveByPs(runtimePid)).toBe(true);
+ const closed = onClose(handle);
+ expect(handle.kill('SIGKILL')).toBe(true);
+ await closed;
+ let alive = true;
+ for (let i = 0; i < 80; i += 1) {
+ alive = await aliveByPs(runtimePid);
+ if (!alive) break;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ expect(alive).toBe(false);
+ });
+
it('rejects (via close=1) when the control dir is reused with stale files cleared', async () => {
const controlDir = await tmpControlDir();
// First run leaves pid/exit/logs behind.
@@ -176,11 +210,6 @@ describe('spawnDetached', () => {
});
describe('reapDetached', () => {
- const aliveByPs = async (pid) => {
- const { stdout } = await execFileAsync('ps', ['-o', 'pid=', '-p', String(pid)]).catch(() => ({ stdout: '' }));
- return stdout.trim().length > 0;
- };
-
it('SIGTERMs a surviving orphan and reports it reaped', async () => {
const controlDir = await tmpControlDir();
const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.js
index 7240900704..fc4e1d1580 100644
--- a/server/lib/hfCache.js
+++ b/server/lib/hfCache.js
@@ -22,7 +22,9 @@
import { promises as fs } from 'node:fs';
import { homedir } from 'node:os';
-import { join, dirname, resolve as resolvePath } from 'node:path';
+import {
+ join, dirname, resolve as resolvePath, relative, sep, posix, win32,
+} from 'node:path';
import { sha256File } from './fileUtils.js';
// HF cache root resolution mirrors huggingface_hub's own precedence:
@@ -68,8 +70,19 @@ async function collectWeightFiles(dir, out) {
// Returns the path of the most recently modified snapshot under a repo, or
// null if no snapshots exist. HF writes snapshots/<sha>/ on every revision
// pull; the latest mtime is the most recently downloaded.
-async function latestSnapshotDir(repoDir) {
+const HF_COMMIT_RE = /^[0-9a-f]{40}$/i;
+
+async function latestSnapshotDir(repoDir, revision = null) {
const snapshotsRoot = join(repoDir, 'snapshots');
+ // PortOS-shipped model revisions are immutable HF commit hashes. Resolve an
+ // exact snapshot when one is supplied instead of accepting a newer/mutable
+ // `main` snapshot that happens to have the latest mtime.
+ if (revision != null) {
+ if (typeof revision !== 'string' || !HF_COMMIT_RE.test(revision)) return null;
+ const exact = join(snapshotsRoot, revision.toLowerCase());
+ const stat = await fs.stat(exact).catch(() => null);
+ return stat?.isDirectory() ? exact : null;
+ }
let entries;
try {
entries = await fs.readdir(snapshotsRoot, { withFileTypes: true });
@@ -96,13 +109,13 @@ async function latestSnapshotDir(repoDir) {
// file in the snapshot resolves to a non-zero blob. `sizeBytes` is the sum
// of resolved weight-blob sizes (config/tokenizer files are tiny and ignored
// so the displayed footprint reflects the user-meaningful download).
-export async function inspectModelCache(repoId) {
+export async function inspectModelCache(repoId, { revision = null } = {}) {
if (!repoId || typeof repoId !== 'string') {
return { cached: false, sizeBytes: 0, snapshotPath: null };
}
const root = getHfCacheRoot();
const repoDir = join(root, repoToDirName(repoId));
- const snapshotPath = await latestSnapshotDir(repoDir);
+ const snapshotPath = await latestSnapshotDir(repoDir, revision);
if (!snapshotPath) {
return { cached: false, sizeBytes: 0, snapshotPath: null };
}
@@ -129,6 +142,40 @@ export async function inspectModelCache(repoId) {
export const isModelCached = async (repoId) => (await inspectModelCache(repoId)).cached;
+// Return the exact cached snapshot directory for an immutable revision. The
+// Wan runner consumes this local path instead of a mutable `org/repo` handle,
+// which also guarantees its cache-only subprocess cannot select another
+// snapshot or trigger a hidden network fetch.
+export async function findCachedRepoSnapshot(repoId, revision) {
+ if (!repoId || typeof repoId !== 'string') return null;
+ if (!revision || typeof revision !== 'string') return null;
+ return latestSnapshotDir(join(getHfCacheRoot(), repoToDirName(repoId)), revision);
+}
+
+const isPathInside = (root, candidate) => {
+ const rel = relative(resolvePath(root), resolvePath(candidate));
+ return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`)
+ && !posix.isAbsolute(rel) && !win32.isAbsolute(rel);
+};
+
+// HF filenames are repo-relative POSIX paths. Reject every alternate path
+// shape before touching disk: absolute paths, Windows separators, empty/dot
+// segments, and traversal. The final containment check is defense-in-depth for
+// future path-normalization changes.
+export const isSafeHfRepoRelativePath = (filename) => {
+ if (typeof filename !== 'string' || filename.length === 0) return false;
+ if (filename.includes('\\') || posix.isAbsolute(filename) || win32.isAbsolute(filename)) return false;
+ const parts = filename.split('/');
+ return !parts.some((part) => part === '' || part === '.' || part === '..');
+};
+
+const resolveRepoRelativeFile = (snapshotPath, filename) => {
+ if (!snapshotPath || !isSafeHfRepoRelativePath(filename)) return null;
+ const parts = filename.split('/');
+ const candidate = resolvePath(snapshotPath, ...parts);
+ return isPathInside(snapshotPath, candidate) ? candidate : null;
+};
+
// Resolve ONE known file inside a repo's newest snapshot, without walking the
// snapshot at all. `inspectModelCache` recursively collects and stats every
// weight in the snapshot — correct when the question is "is this whole model
@@ -141,12 +188,13 @@ export const isModelCached = async (repoId) => (await inspectModelCache(repoId))
// isn't resident. The `stat` FOLLOWS the symlink, so a dangling snapshot link
// left by an interrupted download reports null rather than a plausible path
// that fails on open — the same non-zero test inspectModelCache applies.
-export async function findCachedRepoFile(repoId, filename) {
+export async function findCachedRepoFile(repoId, filename, { revision = null } = {}) {
if (!repoId || typeof repoId !== 'string') return null;
if (!filename || typeof filename !== 'string') return null;
- const snapshotPath = await latestSnapshotDir(join(getHfCacheRoot(), repoToDirName(repoId)));
+ const snapshotPath = await latestSnapshotDir(join(getHfCacheRoot(), repoToDirName(repoId)), revision);
if (!snapshotPath) return null;
- const candidate = join(snapshotPath, filename);
+ const candidate = resolveRepoRelativeFile(snapshotPath, filename);
+ if (!candidate) return null;
const stat = await fs.stat(candidate).catch(() => null);
return stat && stat.size > 0 ? candidate : null;
}
@@ -154,7 +202,7 @@ export async function findCachedRepoFile(repoId, filename) {
// 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 } = {}) {
+export async function verifyCachedRepoFiles(repoId, filenames, { deep = false, revision = null } = {}) {
const base = {
repoId, status: 'missing', cached: false, sizeBytes: 0,
snapshotPath: null, checkedDeep: deep, files: [],
@@ -163,9 +211,12 @@ export async function verifyCachedRepoFiles(repoId, filenames, { deep = false }
? filenames.filter((name) => typeof name === 'string' && name.length > 0)
: [];
if (!repoId || wanted.length === 0) return base;
- const snapshotPath = await latestSnapshotDir(join(getHfCacheRoot(), repoToDirName(repoId)));
+ const snapshotPath = await latestSnapshotDir(join(getHfCacheRoot(), repoToDirName(repoId)), revision);
if (!snapshotPath) return base;
- const files = await Promise.all(wanted.map((name) => verifyWeightFile({ name, path: join(snapshotPath, name) }, { deep })));
+ const resolved = wanted.map((name) => ({ name, path: resolveRepoRelativeFile(snapshotPath, name) }));
+ const files = await Promise.all(resolved.map((file) => file.path
+ ? verifyWeightFile(file, { deep })
+ : Promise.resolve({ name: file.name, path: null, ok: false, reason: 'unsafe-path', sizeBytes: 0 })));
const anyBad = files.some((file) => !file.ok);
const anyMissing = files.some((file) => file.reason === 'missing-blob');
return {
@@ -179,12 +230,12 @@ export async function verifyCachedRepoFiles(repoId, filenames, { deep = false }
};
}
-export async function repairCachedRepoFiles(repoId, filenames, { deep = false } = {}) {
- const verify = await verifyCachedRepoFiles(repoId, filenames, { deep });
+export async function repairCachedRepoFiles(repoId, filenames, { deep = false, revision = null } = {}) {
+ const verify = await verifyCachedRepoFiles(repoId, filenames, { deep, revision });
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);
+ if (await repairCachedFile(file.path, { snapshotPath: verify.snapshotPath })) deleted.push(file.name);
}
return { repoId, status: 'bad', deleted };
}
@@ -327,7 +378,7 @@ async function verifyWeightFile(file, { deep }) {
// 'bad' — at least one weight file is corrupt/truncated/missing-blob
// `files` carries a per-file `{ name, ok, reason, sizeBytes }` breakdown so the
// repair path knows exactly which files to delete and the UI can explain why.
-export async function verifyModelCache(repoId, { deep = false } = {}) {
+export async function verifyModelCache(repoId, { deep = false, revision = null } = {}) {
const base = {
repoId, status: 'missing', cached: false, sizeBytes: 0,
snapshotPath: null, checkedDeep: deep, files: [],
@@ -335,7 +386,7 @@ export async function verifyModelCache(repoId, { deep = false } = {}) {
if (!repoId || typeof repoId !== 'string') return base;
const root = getHfCacheRoot();
const repoDir = join(root, repoToDirName(repoId));
- const snapshotPath = await latestSnapshotDir(repoDir);
+ const snapshotPath = await latestSnapshotDir(repoDir, revision);
if (!snapshotPath) return base;
const weights = [];
await collectWeightFiles(snapshotPath, weights);
@@ -366,23 +417,14 @@ export async function verifyModelCache(repoId, { deep = false } = {}) {
// `hf_hub_download` (it keys on the cached etag, not the content) and never
// re-fetched. Returns `{ repoId, status, deleted: [names] }`; an 'ok' or
// 'missing' status deletes nothing (caller just re-downloads from scratch).
-export async function repairModelCache(repoId, { deep = false } = {}) {
- const verify = await verifyModelCache(repoId, { deep });
+export async function repairModelCache(repoId, { deep = false, revision = null } = {}) {
+ const verify = await verifyModelCache(repoId, { deep, revision });
if (verify.status !== 'bad') {
return { repoId, status: verify.status, deleted: [] };
}
const deleted = [];
for (const file of verify.files.filter((f) => !f.ok)) {
- const lst = await fs.lstat(file.path).catch(() => null);
- if (lst?.isSymbolicLink()) {
- const target = await fs.readlink(file.path).catch(() => null);
- if (target) {
- const blobPath = resolvePath(dirname(file.path), target);
- await fs.unlink(blobPath).catch(() => {});
- }
- }
- await fs.unlink(file.path).catch(() => {});
- deleted.push(file.name);
+ if (await repairCachedFile(file.path, { snapshotPath: verify.snapshotPath })) deleted.push(file.name);
}
return { repoId, status: 'bad', deleted };
}
@@ -396,13 +438,36 @@ export async function repairModelCache(repoId, { deep = false } = {}) {
// etag, not the content, so a stale blob with the right name is trusted and never
// re-fetched (same reasoning as repairModelCache). Returns true when something
// was removed.
-export async function repairCachedFile(path) {
+export async function repairCachedFile(path, { snapshotPath = null } = {}) {
if (!path || typeof path !== 'string') return false;
+ const resolvedPath = resolvePath(path);
+ let boundedSnapshot = snapshotPath ? resolvePath(snapshotPath) : null;
+ let repoDir = null;
+ if (boundedSnapshot) {
+ repoDir = dirname(dirname(boundedSnapshot));
+ } else {
+ // Infer `<repo>/snapshots/<sha>` only for a canonical HF snapshot entry.
+ // Refuse arbitrary filesystem paths: this helper is a cache repair tool,
+ // not a general unlink primitive.
+ const marker = `${sep}snapshots${sep}`;
+ const markerIndex = resolvedPath.lastIndexOf(marker);
+ const shaEnd = markerIndex === -1
+ ? -1
+ : resolvedPath.indexOf(sep, markerIndex + marker.length);
+ if (markerIndex === -1 || shaEnd === -1) return false;
+ repoDir = resolvedPath.slice(0, markerIndex);
+ boundedSnapshot = resolvedPath.slice(0, shaEnd);
+ }
+ if (!isPathInside(boundedSnapshot, resolvedPath)) return false;
const lst = await fs.lstat(path).catch(() => null);
if (!lst) return false;
if (lst.isSymbolicLink()) {
const target = await fs.readlink(path).catch(() => null);
- if (target) await fs.unlink(resolvePath(dirname(path), target)).catch(() => {});
+ const blobPath = target ? resolvePath(dirname(path), target) : null;
+ const blobRoot = join(repoDir, 'blobs');
+ if (blobPath && isPathInside(blobRoot, blobPath)) {
+ await fs.unlink(blobPath).catch(() => {});
+ }
}
await fs.unlink(path).catch(() => {});
return true;
diff --git a/server/lib/hfCache.test.js b/server/lib/hfCache.test.js
index b0d78cf626..794b715010 100644
--- a/server/lib/hfCache.test.js
+++ b/server/lib/hfCache.test.js
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
inspectModelCache, getHfCacheRoot, isModelCached,
- verifyModelCache, repairModelCache, findCachedRepoFile, repairCachedFile,
+ verifyModelCache, repairModelCache, findCachedRepoFile, findCachedRepoSnapshot, repairCachedFile,
verifyCachedRepoFiles, repairCachedRepoFiles,
} from './hfCache.js';
@@ -435,6 +435,21 @@ describe('repairCachedFile', () => {
expect(await repairCachedFile('/nope/missing.safetensors')).toBe(false);
expect(await repairCachedFile(null)).toBe(false);
});
+
+ it('never follows a snapshot symlink outside the repository blob directory', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'hfcache-escape-'));
+ cleanup.push(root);
+ const snap = join(root, 'models--org--escape', 'snapshots', 'a'.repeat(40));
+ mkdirSync(snap, { recursive: true });
+ const outside = join(root, 'outside.safetensors');
+ writeFileSync(outside, Buffer.from('must survive'));
+ const link = join(snap, 'escape.safetensors');
+ symlinkSync(outside, link);
+
+ expect(await repairCachedFile(link)).toBe(true);
+ expect(existsSync(link)).toBe(false);
+ expect(existsSync(outside)).toBe(true);
+ });
});
describe('exact-file aggregate verification', () => {
@@ -490,4 +505,41 @@ describe('exact-file aggregate verification', () => {
expect(existsSync(join(snapDir, 'high.safetensors'))).toBe(false);
expect(existsSync(join(snapDir, 'low.safetensors'))).toBe(true);
});
+
+ it('rejects traversal filenames without reading or deleting the outside file', async () => {
+ const { root } = buildContentCache({
+ repoId: 'org/lightning',
+ files: { 'inside.safetensors': { content: buildSafetensors() } },
+ });
+ cleanup.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const outside = join(root, 'outside.safetensors');
+ writeFileSync(outside, Buffer.from('must survive'));
+
+ expect(await findCachedRepoFile('org/lightning', '../../../outside.safetensors')).toBeNull();
+ const verify = await verifyCachedRepoFiles('org/lightning', ['../../../outside.safetensors']);
+ expect(verify.files[0]).toMatchObject({ ok: false, reason: 'unsafe-path' });
+ const repaired = await repairCachedRepoFiles('org/lightning', ['../../../outside.safetensors']);
+ expect(repaired.deleted).toEqual([]);
+ expect(existsSync(outside)).toBe(true);
+ });
+
+ it('pins cache inspection to the requested immutable snapshot revision', async () => {
+ const wanted = 'a'.repeat(40);
+ const other = 'b'.repeat(40);
+ const { root } = buildFakeCache({
+ repoId: 'org/pinned',
+ snapshots: {
+ [wanted]: { 'wanted.safetensors': 1024 },
+ [other]: { 'other.safetensors': 2048 },
+ },
+ });
+ cleanup.push(root);
+ process.env.HF_HUB_CACHE = root;
+
+ expect(await findCachedRepoSnapshot('org/pinned', wanted)).toMatch(new RegExp(`/snapshots/${wanted}$`));
+ expect(await findCachedRepoFile('org/pinned', 'wanted.safetensors', { revision: wanted })).toBeTruthy();
+ expect(await findCachedRepoFile('org/pinned', 'other.safetensors', { revision: wanted })).toBeNull();
+ expect((await inspectModelCache('org/pinned', { revision: wanted })).sizeBytes).toBe(1024);
+ });
});
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index ee38cceadb..cdf577e5b4 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -53,8 +53,9 @@ const DEFAULT_REGISTRY = {
// the explicit base/adaptor downloads and uses the saved HF token.
{
id: 'wan22_ti2v_5b',
- name: 'Wan 2.2 TI2V 5B Q8 (~17 GB, text + image)',
+ name: 'Wan 2.2 TI2V 5B Q8 (~17 GiB download, text + image)',
repo: 'AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit',
+ revision: '6875952a110b6bdbcfc00d72b1d89a8e02ab0fc3',
runtime: 'wan22',
supportedModes: ['text', 'image'],
frameStride: 4,
@@ -67,13 +68,14 @@ const DEFAULT_REGISTRY = {
},
{
id: 'wan22_t2v_a14b',
- name: 'Wan 2.2 T2V A14B Q8 (~14 GB runtime)',
+ name: 'Wan 2.2 T2V A14B Q8 (~40 GiB download, 64+ GB RAM)',
repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ revision: '39ee5f1f630789956f29f40b5c2c6d48c6e9a798',
runtime: 'wan22',
supportedModes: ['text'],
frameStride: 4,
fpsOptions: [16, 20, 24],
- memoryGb: 16,
+ memoryGb: 48,
steps: 20,
guidance: 4.0,
guidance2: 3.0,
@@ -82,13 +84,14 @@ const DEFAULT_REGISTRY = {
},
{
id: 'wan22_i2v_a14b',
- name: 'Wan 2.2 I2V A14B Q8 (~14 GB runtime)',
+ name: 'Wan 2.2 I2V A14B Q8 (~40 GiB download, 64+ GB RAM)',
repo: 'AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit',
+ revision: '1a17fbea2649c576de844e08e79fe56296751efa',
runtime: 'wan22',
supportedModes: ['image'],
frameStride: 4,
fpsOptions: [16, 20, 24],
- memoryGb: 16,
+ memoryGb: 48,
steps: 20,
guidance: 3.5,
guidance2: 3.5,
@@ -97,13 +100,14 @@ const DEFAULT_REGISTRY = {
},
{
id: 'wan22_t2v_a14b_lightning',
- name: 'Wan 2.2 T2V A14B Lightning Q8 (~14 GB, 4-step)',
+ name: 'Wan 2.2 T2V A14B Lightning Q8 (~40 GiB download, 64+ GB RAM, 4-step)',
repo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ revision: '39ee5f1f630789956f29f40b5c2c6d48c6e9a798',
runtime: 'wan22',
supportedModes: ['text'],
frameStride: 4,
fpsOptions: [16, 20, 24],
- memoryGb: 16,
+ memoryGb: 48,
steps: 4,
guidance: 1.0,
guidance2: 1.0,
@@ -112,6 +116,7 @@ const DEFAULT_REGISTRY = {
samplerLocked: true,
requiredWeights: [{
repo: 'lightx2v/Wan2.2-Lightning',
+ revision: '18bccf8884ec0a078eed79785eb4ef13ea16ce1e',
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',
@@ -121,13 +126,14 @@ const DEFAULT_REGISTRY = {
},
{
id: 'wan22_i2v_a14b_lightning',
- name: 'Wan 2.2 I2V A14B Lightning Q8 (~14 GB, 4-step)',
+ name: 'Wan 2.2 I2V A14B Lightning Q8 (~40 GiB download, 64+ GB RAM, 4-step)',
repo: 'AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit',
+ revision: '1a17fbea2649c576de844e08e79fe56296751efa',
runtime: 'wan22',
supportedModes: ['image'],
frameStride: 4,
fpsOptions: [16, 20, 24],
- memoryGb: 16,
+ memoryGb: 48,
steps: 4,
guidance: 1.0,
guidance2: 1.0,
@@ -136,6 +142,7 @@ const DEFAULT_REGISTRY = {
samplerLocked: true,
requiredWeights: [{
repo: 'lightx2v/Wan2.2-Lightning',
+ revision: '18bccf8884ec0a078eed79785eb4ef13ea16ce1e',
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',
diff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.js
index e73e1b90f4..b501f2885d 100644
--- a/server/lib/sseDownload.js
+++ b/server/lib/sseDownload.js
@@ -51,16 +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 normalizeRevision = (v) => (typeof v === 'string' && v.length > 0 ? v : null);
const normalizeTarget = (target) => {
- if (typeof target === 'string' && target.length > 0) return { repo: target, only: [] };
+ if (typeof target === 'string' && target.length > 0) return { repo: target, only: [], revision: null };
if (!target || typeof target.repo !== 'string' || target.repo.length === 0) return null;
- return { repo: target.repo, only: normalizeOnly(target.only) };
+ return { repo: target.repo, only: normalizeOnly(target.only), revision: normalizeRevision(target.revision) };
};
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) }))
+ .map((t) => ({ repo: t.repo, only: normalizeOnly(t.only), revision: normalizeRevision(t.revision) }))
: (Array.isArray(repos) ? repos : [repo]).map(normalizeTarget).filter(Boolean);
const { send, safeEnd } = openSseStream(res);
@@ -93,7 +94,7 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,
let succeededRepo = null;
const attemptErrors = [];
for (let i = 0; i < targets.length; i += 1) {
- const { repo: r, only: onlyFiles } = targets[i];
+ const { repo: r, only: onlyFiles, revision } = targets[i];
const isLastTarget = i === targets.length - 1;
if (aborted) return;
// For a single-file pull the repo-wide cache verdict is both the wrong
@@ -105,12 +106,12 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,
const singleFile = onlyFiles.length > 0;
const existing = singleFile
? { cached: false, sizeBytes: 0 }
- : await inspectModelCache(r);
+ : await inspectModelCache(r, { revision });
if (aborted) return;
const alreadyHave = singleFile
? (typeof cachedFile === 'function'
- ? await cachedFile({ repo: r, only: onlyFiles })
- : (await Promise.all(onlyFiles.map((file) => findCachedRepoFile(r, file)))).every(Boolean))
+ ? await cachedFile({ repo: r, only: onlyFiles, revision })
+ : (await Promise.all(onlyFiles.map((file) => findCachedRepoFile(r, file, { revision })))).every(Boolean))
: existing.cached;
if (aborted) return;
// `force` is set by a repair-initiated re-download: repairModelCache()
@@ -140,7 +141,8 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,
// Dedupe key includes the filenames: an aggregate repo hosts many unrelated
// weights, so two single-file pulls of DIFFERENT files from the same repo are
// not duplicates and must not block each other.
- const flightKey = singleFile ? `${r}::${onlyFiles.join(',')}` : r;
+ const revisionKey = revision ? `@${revision}` : '';
+ const flightKey = singleFile ? `${r}${revisionKey}::${onlyFiles.join(',')}` : `${r}${revisionKey}`;
if (inFlight.has(flightKey)) {
console.log(`⏭️ HuggingFace download already running for ${flightKey} — refusing duplicate`);
send({ type: 'error', message: `Another download for ${r} is already running.`, kind: 'already_running', repo: r });
@@ -152,6 +154,7 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,
console.log(`⬇️ Downloading HuggingFace repo: ${r}${singleFile ? ` (${onlyFiles.length} file(s) only)` : ''}${force ? ' (forced re-fetch)' : ''}`);
const handle = downloadHfRepo({
repo: r,
+ revision,
only: singleFile ? onlyFiles : null,
pythonPath,
onEvent: (ev) => {
@@ -161,8 +164,12 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,
// A failure that we're about to retry against the next candidate isn't a
// user-facing error — downgrade it to a log so the UI doesn't flash a red
// "gated repo" banner for something the mirror then delivers fine.
- if (firstSuccessWins && !isLastTarget && ev.type === 'error') {
- send({ type: 'log', message: `${r}: ${ev.message} — trying the next source.`, repo: r });
+ if (firstSuccessWins && ev.type === 'error') {
+ send({
+ type: 'log',
+ message: `${r}: ${ev.message}${isLastTarget ? '' : ' — trying the next source.'}`,
+ repo: r,
+ });
return;
}
send({ ...ev, repo: r });
diff --git a/server/lib/sseDownload.test.js b/server/lib/sseDownload.test.js
index b2638f9e7b..4d0be8333b 100644
--- a/server/lib/sseDownload.test.js
+++ b/server/lib/sseDownload.test.js
@@ -64,6 +64,20 @@ describe('startHfDownloadStream force', () => {
const events = parseFrames(frames);
expect(events.at(-1)).toMatchObject({ type: 'complete', message: 'org/encoder downloaded.' });
});
+
+ it('uses the immutable revision for cache inspection and download', async () => {
+ inspectModelCache.mockResolvedValueOnce({ cached: false, sizeBytes: 0, snapshotPath: null });
+ const revision = '1111111111111111111111111111111111111111';
+ const { req, res } = makeReqRes();
+ await startHfDownloadStream({
+ req, res,
+ repos: [{ repo: 'org/pinned', revision, only: [] }],
+ });
+ expect(inspectModelCache).toHaveBeenCalledWith('org/pinned', { revision });
+ expect(downloadHfRepo).toHaveBeenCalledWith(expect.objectContaining({
+ repo: 'org/pinned', revision,
+ }));
+ });
});
// The download flow used to surface progress ONLY on the SSE stream to the
@@ -240,14 +254,20 @@ describe('startHfDownloadStream single-file + fallbacks (#3112)', () => {
});
it('reports every attempt when all sources fail', async () => {
- downloadHfRepo.mockImplementation(({ repo }) => ({
- promise: Promise.resolve({ ok: false, errorKind: 'x', errorMessage: `${repo} broke` }),
- kill: vi.fn(),
- }));
+ downloadHfRepo.mockImplementation(({ repo, onEvent }) => {
+ onEvent({ type: 'error', kind: 'x', message: `${repo} broke` });
+ return {
+ promise: Promise.resolve({ ok: false, errorKind: 'x', errorMessage: `${repo} broke` }),
+ kill: vi.fn(),
+ };
+ });
const { req, res, frames } = makeReqRes();
await startHfDownloadStream({ req, res, fallbacks: CANDIDATES, cachedFile: async () => false });
- const last = parseFrames(frames).at(-1);
+ const events = parseFrames(frames);
+ const terminal = events.filter((event) => event.type === 'error');
+ expect(terminal).toHaveLength(1);
+ const last = terminal[0];
expect(last).toMatchObject({ type: 'error', kind: 'all_sources_failed' });
expect(last.message).toContain('org/official broke');
expect(last.message).toContain('org/mirror-708gb broke');
diff --git a/server/routes/videoGen.integrity.test.js b/server/routes/videoGen.integrity.test.js
index 9bd21828f6..0eb50705dd 100644
--- a/server/routes/videoGen.integrity.test.js
+++ b/server/routes/videoGen.integrity.test.js
@@ -9,7 +9,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';
// videoGen.test.js so the route's import graph links under vitest.
vi.mock('../lib/mediaModels.js', () => ({
- repoForModel: vi.fn((m) => `org/${m.id}`),
+ repoForModel: vi.fn((m) => m.repo || `org/${m.id}`),
getTextEncoderRepo: vi.fn(() => 'org/text-encoder'),
isHfRepoId: vi.fn(() => true),
}));
@@ -25,6 +25,18 @@ vi.mock('../lib/hfCache.js', async (importOriginal) => ({
files: [{ name: 'model.safetensors', path: '/snap/model.safetensors', ok: false, reason: 'truncated-data', sizeBytes: 10 }],
})),
repairModelCache: vi.fn(async (repoId) => ({ repoId, status: 'bad', deleted: ['model.safetensors'] })),
+ verifyCachedRepoFiles: vi.fn(async (repoId, files, opts) => ({
+ repoId, status: 'bad', cached: false, sizeBytes: 0, snapshotPath: '/snap',
+ checkedDeep: !!opts?.deep,
+ files: files.map((name) => ({ name, path: `/snap/${name}`, ok: false, reason: 'truncated-data', sizeBytes: 10 })),
+ })),
+ repairCachedRepoFiles: vi.fn(async (repoId, files) => ({ repoId, status: 'bad', deleted: files })),
+}));
+
+const sseDownload = vi.hoisted(() => ({ start: vi.fn() }));
+vi.mock('../lib/sseDownload.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ startHfDownloadStream: sseDownload.start,
}));
vi.mock('../services/settings.js', () => ({
@@ -37,7 +49,18 @@ vi.mock('../lib/pythonSetup.js', () => ({
}));
vi.mock('../services/videoGen/local.js', () => ({
- listVideoModels: vi.fn(() => [{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' }]),
+ listVideoModels: vi.fn(() => [
+ { id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' },
+ {
+ id: 'wan_lightning', name: 'Wan Lightning', runtime: 'wan22',
+ repo: 'org/wan-base', revision: '1111111111111111111111111111111111111111',
+ requiredWeights: [{
+ repo: 'org/wan-lightning', revision: '2222222222222222222222222222222222222222',
+ files: ['profile/high.safetensors', 'profile/low.safetensors'],
+ targetRoles: ['high_noise_transformer', 'low_noise_transformer'],
+ }],
+ },
+ ]),
defaultVideoModelId: vi.fn(() => 'ltx2_unified'),
loadHistory: vi.fn(async () => []),
deleteHistoryItem: vi.fn(),
@@ -47,8 +70,11 @@ vi.mock('../services/videoGen/local.js', () => ({
upscaleHistoryItem: vi.fn(),
DEFAULT_NUM_FRAMES: 121,
resolveFflfLtx2PixelBudget: vi.fn(() => 1000),
- BYOV_VIDEO_RUNTIMES: new Set(['ltx2']),
- BYOV_RUNTIME_INFO: { ltx2: { id: 'ltx2', label: 'LTX-2 MLX', venvPython: '/tmp/x.py', installEnvVar: 'X', repoUrl: 'x', repoDir: '/tmp' } },
+ BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'wan22']),
+ BYOV_RUNTIME_INFO: {
+ ltx2: { id: 'ltx2', label: 'LTX-2 MLX', venvPython: '/tmp/x.py', installEnvVar: 'X', repoUrl: 'x', repoDir: '/tmp' },
+ wan22: { id: 'wan22', label: 'Wan MLX', venvPython: '/tmp/wan.py', installEnvVar: 'WAN', repoUrl: 'x', repoDir: '/tmp' },
+ },
isByovRuntimeInstalled: vi.fn(() => false),
isByovRuntimeReady: vi.fn(async () => false),
isByovRuntimeCurrent: vi.fn(async () => false),
@@ -79,7 +105,9 @@ vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));
vi.mock('fs/promises', () => ({ unlink: vi.fn(async () => {}), copyFile: vi.fn(async () => {}) }));
import videoGenRoutes from './videoGen.js';
-import { verifyModelCache, repairModelCache } from '../lib/hfCache.js';
+import {
+ verifyModelCache, repairModelCache, verifyCachedRepoFiles, repairCachedRepoFiles,
+} from '../lib/hfCache.js';
import { isHfRepoId } from '../lib/mediaModels.js';
describe('Video Gen integrity routes', () => {
@@ -90,6 +118,10 @@ describe('Video Gen integrity routes', () => {
app.use('/api/video-gen', videoGenRoutes);
app.use(errorMiddleware);
vi.clearAllMocks();
+ sseDownload.start.mockImplementation(async ({ res }) => {
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+ res.end('data: {"type":"complete"}\n\n');
+ });
});
it('GET /models/status surfaces integrity for cached models + text encoder', async () => {
@@ -114,6 +146,45 @@ describe('Video Gen integrity routes', () => {
expect(repairModelCache).toHaveBeenCalledWith('org/ltx2_unified', { deep: false });
});
+ it('threads immutable base and exact Lightning revisions through status', async () => {
+ const res = await request(app).get('/api/video-gen/models/status');
+ const lightning = res.body.models.find((model) => model.id === 'wan_lightning');
+ expect(lightning.requiredRepos).toEqual(['org/wan-base', 'org/wan-lightning']);
+ expect(verifyModelCache).toHaveBeenCalledWith(
+ 'org/wan-base',
+ { deep: false, revision: '1111111111111111111111111111111111111111' },
+ );
+ expect(verifyCachedRepoFiles).toHaveBeenCalledWith(
+ 'org/wan-lightning',
+ ['profile/high.safetensors', 'profile/low.safetensors'],
+ { deep: false, revision: '2222222222222222222222222222222222222222' },
+ );
+ });
+
+ it('repairs only the exact pinned Lightning dependency files', async () => {
+ const res = await request(app).post('/api/video-gen/models/wan_lightning/repair').send({ deep: true });
+ expect(res.status).toBe(200);
+ expect(repairCachedRepoFiles).toHaveBeenCalledWith(
+ 'org/wan-lightning',
+ ['profile/high.safetensors', 'profile/low.safetensors'],
+ { deep: true, revision: '2222222222222222222222222222222222222222' },
+ );
+ });
+
+ it('downloads the pinned base snapshot plus both exact Lightning files', async () => {
+ const res = await request(app).get('/api/video-gen/models/wan_lightning/download');
+ expect(res.status).toBe(200);
+ expect(sseDownload.start).toHaveBeenCalledWith(expect.objectContaining({
+ repos: [
+ { repo: 'org/wan-base', revision: '1111111111111111111111111111111111111111', only: [] },
+ {
+ repo: 'org/wan-lightning', revision: '2222222222222222222222222222222222222222',
+ only: ['profile/high.safetensors', 'profile/low.safetensors'],
+ },
+ ],
+ }));
+ });
+
it('POST /models/:id/repair 404s for an unknown model', async () => {
const res = await request(app).post('/api/video-gen/models/nope/repair').send({});
expect(res.status).toBe(404);
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 4ec81598f4..f8ff7d6fd9 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -49,6 +49,7 @@ import {
import {
inspectModelCache, verifyModelCache, repairModelCache, repairCachedFile,
verifyCachedRepoFiles, repairCachedRepoFiles, summarizeVerify, aggregateVerifies,
+ isSafeHfRepoRelativePath,
} from '../lib/hfCache.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
@@ -378,6 +379,23 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
const runtime = String(req.query?.runtime || '');
const info = BYOV_RUNTIME_INFO[runtime];
const { send, safeEnd } = openSseStream(res);
+ let child = null;
+ let aborted = false;
+
+ // Register disconnect handling before any readiness/revision await. Those
+ // probes can take tens of seconds on a damaged venv; closing the modal during
+ // that window must prevent the large installer from starting unattended.
+ res.on('close', () => {
+ if (res.writableEnded) return;
+ aborted = true;
+ if (info && runtimeInstallInFlight.get(info.id) === null) {
+ runtimeInstallInFlight.delete(info.id);
+ }
+ if (child && !child.killed && child.pid) {
+ try { process.kill(-child.pid, 'SIGTERM'); }
+ catch { child.kill('SIGTERM'); }
+ }
+ });
if (!info) {
send({ type: 'error', message: `Unknown runtime: ${runtime}` });
@@ -400,7 +418,9 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
// behind a button that can never perform the action it advertises.
const alreadyInstalled = isByovRuntimeInstalled(info.id);
const alreadyReady = alreadyInstalled && await isByovRuntimeReady(info.id);
+ if (aborted) return safeEnd();
const alreadyCurrent = alreadyReady && await isByovRuntimeCurrent(info.id);
+ if (aborted) return safeEnd();
if (alreadyInstalled && alreadyReady && alreadyCurrent) {
runtimeInstallInFlight.delete(info.id);
send({ type: 'log', message: `${info.label} already installed at ${info.venvPython}` });
@@ -432,8 +452,12 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
// bash leaves a multi-GB `git clone` (and any subsequent pip downloads)
// orphaned to init — the user sees the modal close but the bandwidth keeps
// burning until the network drops or the snapshot completes.
- const child = spawn('bash', [scriptPath], {
- env: safeChildProcessEnv({ [info.installEnvVar]: '1' }),
+ const installEnv = {
+ [info.installEnvVar]: '1',
+ ...(info.pinEnvVar && info.expectedRevision ? { [info.pinEnvVar]: info.expectedRevision } : {}),
+ };
+ child = spawn('bash', [scriptPath], {
+ env: safeChildProcessEnv(installEnv),
stdio: ['ignore', 'pipe', 'pipe'],
detached: true,
});
@@ -481,20 +505,7 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
safeEnd();
});
- req.on('close', () => {
- installLog.cancel();
- if (!child.killed && child.pid) {
- // Negative pid signals the whole process group — required because
- // `setup-image-video.sh` shells out to `uv pip install` / `git clone`,
- // and a plain `child.kill('SIGTERM')` only signals bash itself, leaving
- // the slow children running in the background. Wrap in try/catch so an
- // already-dead group (race with the close handler) doesn't crash the
- // server with ESRCH.
- try { process.kill(-child.pid, 'SIGTERM'); }
- catch { child.kill('SIGTERM'); }
- }
- safeEnd();
- });
+ res.on('close', () => { if (!res.writableEnded) installLog.cancel(); });
}));
async function resolveLocalPythonHealth(py) {
@@ -523,22 +534,32 @@ router.get('/models', (_req, res) => {
const modelDownloadTargets = (model) => {
const repo = repoForModel(model);
if (!repo) return [];
- const targets = [{ repo, only: [] }];
+ const targets = [{ repo, revision: model?.revision || null, 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 });
+ if (only.some((file) => !isSafeHfRepoRelativePath(file))) {
+ throw new ServerError(
+ `Video model "${model.id}" has an unsafe required-weight path. Use repo-relative POSIX filenames only.`,
+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },
+ );
+ }
+ if (only.length > 0) targets.push({ repo: dep.repo, revision: dep.revision || null, only });
}
return targets;
};
-const targetKey = (target) => `${target.repo}::${target.only.join(',')}`;
+const targetKey = (target) => `${target.repo}@${target.revision || 'latest'}::${target.only.join(',')}`;
+const targetVerifyOptions = (target, deep) => ({
+ deep,
+ ...(target.revision ? { revision: target.revision } : {}),
+});
const verifyDownloadTarget = (target, { deep = false } = {}) => target.only.length > 0
- ? verifyCachedRepoFiles(target.repo, target.only, { deep })
- : verifyModelCache(target.repo, { deep });
+ ? verifyCachedRepoFiles(target.repo, target.only, targetVerifyOptions(target, deep))
+ : verifyModelCache(target.repo, targetVerifyOptions(target, deep));
const repairDownloadTarget = (target, { deep = false } = {}) => target.only.length > 0
- ? repairCachedRepoFiles(target.repo, target.only, { deep })
- : repairModelCache(target.repo, { deep });
+ ? repairCachedRepoFiles(target.repo, target.only, targetVerifyOptions(target, deep))
+ : repairModelCache(target.repo, targetVerifyOptions(target, deep));
const reposToVerify = (modelId) => {
if (modelId) {
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index b8a3c8441a..479f53bc17 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -3,6 +3,31 @@ import express from 'express';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
+const installProcess = vi.hoisted(() => {
+ const spawn = vi.fn();
+ const makeChild = () => {
+ const listeners = {};
+ const child = {
+ pid: 4242,
+ killed: false,
+ stdout: { on: vi.fn() },
+ stderr: { on: vi.fn() },
+ kill: vi.fn(() => true),
+ on: vi.fn((event, handler) => {
+ listeners[event] = handler;
+ if (event === 'close') setImmediate(() => handler(0));
+ return child;
+ }),
+ };
+ return child;
+ };
+ return { spawn, makeChild };
+});
+vi.mock('child_process', async (importOriginal) => ({
+ ...(await importOriginal()),
+ spawn: installProcess.spawn,
+}));
+
vi.mock('../services/settings.js', () => ({
getSettings: vi.fn(async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } })),
}));
@@ -52,7 +77,12 @@ vi.mock('../services/videoGen/local.js', () => ({
// `id` and a couple of UI-display fields are read by /status.
BYOV_RUNTIME_INFO: {
ltx2: { id: 'ltx2', label: 'LTX-2 MLX', venvPython: '/tmp/ltx2.py', installEnvVar: 'INSTALL_LTX2', repoUrl: 'x', repoDir: '/tmp' },
- wan22: { id: 'wan22', label: 'Wan 2.2 MLX', venvPython: '/tmp/wan22.py', installEnvVar: 'INSTALL_WAN22', repoUrl: 'x', repoDir: '/tmp' },
+ wan22: {
+ id: 'wan22', label: 'Wan 2.2 MLX', venvPython: '/tmp/wan22.py',
+ installEnvVar: 'INSTALL_WAN22', pinEnvVar: 'WAN22_PIN',
+ expectedRevision: '2452f0c12edcc8886eebf15772205ce9c417a618',
+ repoUrl: 'x', repoDir: '/tmp',
+ },
hunyuan: { id: 'hunyuan', label: 'HunyuanVideo MLX', venvPython: '/tmp/hunyuan.py', installEnvVar: 'INSTALL_HUNYUAN', repoUrl: 'x', repoDir: '/tmp' },
},
isByovRuntimeInstalled: vi.fn(() => false),
@@ -207,6 +237,7 @@ describe('videoGen routes', () => {
// Reset the upload holder so a test that set a pending upload but
// bailed before the route consumed it can't leak into the next test.
pendingUpload.current = null;
+ installProcess.spawn.mockReset().mockImplementation(() => installProcess.makeChild());
});
describe('GET /status', () => {
@@ -248,6 +279,81 @@ describe('videoGen routes', () => {
});
});
+ describe('GET /setup/runtime-status', () => {
+ it('reports a missing runtime without probing readiness or revision', async () => {
+ const r = await request(app).get('/api/video-gen/setup/runtime-status?runtime=wan22');
+ expect(r.status).toBe(200);
+ expect(r.body).toMatchObject({
+ runtime: 'wan22', installed: false, binaryPresent: false,
+ packagesReady: false, current: false, upgradeAvailable: false,
+ });
+ expect(videoGenService.isByovRuntimeReady).not.toHaveBeenCalled();
+ expect(videoGenService.isByovRuntimeCurrent).not.toHaveBeenCalled();
+ });
+
+ it('reports a ready runtime as installed only when its checkout is current', async () => {
+ videoGenService.isByovRuntimeInstalled.mockReturnValueOnce(true);
+ videoGenService.isByovRuntimeReady.mockResolvedValueOnce(true);
+ videoGenService.isByovRuntimeCurrent.mockResolvedValueOnce(true);
+ const r = await request(app).get('/api/video-gen/setup/runtime-status?runtime=wan22');
+ expect(r.body).toMatchObject({
+ installed: true, binaryPresent: true, packagesReady: true,
+ current: true, upgradeAvailable: false,
+ });
+ });
+
+ it('offers an upgrade for a ready runtime on an outdated checkout', async () => {
+ videoGenService.isByovRuntimeInstalled.mockReturnValueOnce(true);
+ videoGenService.isByovRuntimeReady.mockResolvedValueOnce(true);
+ videoGenService.isByovRuntimeCurrent.mockResolvedValueOnce(false);
+ const r = await request(app).get('/api/video-gen/setup/runtime-status?runtime=wan22');
+ expect(r.body).toMatchObject({
+ installed: false, binaryPresent: true, packagesReady: true,
+ current: false, upgradeAvailable: true,
+ });
+ });
+ });
+
+ describe('GET /setup/runtime-install', () => {
+ it('short-circuits only when the runtime packages and pinned revision are current', async () => {
+ videoGenService.isByovRuntimeInstalled.mockReturnValueOnce(true);
+ videoGenService.isByovRuntimeReady.mockResolvedValueOnce(true);
+ videoGenService.isByovRuntimeCurrent.mockResolvedValueOnce(true);
+ const r = await request(app).get('/api/video-gen/setup/runtime-install?runtime=wan22');
+ expect(r.status).toBe(200);
+ expect(r.text).toContain('"type":"complete"');
+ expect(r.text).toContain('Already installed');
+ expect(videoGenService.invalidateByovReadyCache).not.toHaveBeenCalled();
+ });
+
+ it('upgrades an outdated checkout with the pinned revision in the installer environment', async () => {
+ videoGenService.isByovRuntimeInstalled
+ .mockReturnValueOnce(true)
+ .mockReturnValueOnce(true);
+ videoGenService.isByovRuntimeReady
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(true);
+ videoGenService.isByovRuntimeCurrent
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true);
+ const r = await request(app).get('/api/video-gen/setup/runtime-install?runtime=wan22');
+ expect(r.status).toBe(200);
+ expect(r.text).toContain('"type":"complete"');
+ expect(r.text).toContain('Wan 2.2 MLX ready');
+ expect(installProcess.spawn).toHaveBeenCalledWith(
+ 'bash',
+ ['/mock/scripts/setup-image-video.sh'],
+ expect.objectContaining({
+ detached: true,
+ env: expect.objectContaining({
+ INSTALL_WAN22: '1',
+ WAN22_PIN: '2452f0c12edcc8886eebf15772205ce9c417a618',
+ }),
+ }),
+ );
+ });
+ });
+
describe('GET /models', () => {
it('returns the static catalog', async () => {
const r = await request(app).get('/api/video-gen/models');
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 6bb42e1912..28236ad20d 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -27,6 +27,7 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_
import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';
import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x, extractEvaluationFrames } from '../../lib/ffmpeg.js';
import { hfChildEnv } from '../../lib/hfToken.js';
+import { inspectModelCache, findCachedRepoFile } from '../../lib/hfCache.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath } from './generateVideoHelpers.js';
import { assertSafeLoraFilename } from '../loras.js';
@@ -518,7 +519,7 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames
// 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 }) => {
+const buildWan22Args = ({ model, wanModelPath, wanRequiredWeights, 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 : [];
@@ -528,9 +529,15 @@ const buildWan22Args = ({ model, prompt, negativePrompt, width, height, numFrame
{ status: 400, code: 'WAN22_MODE_UNSUPPORTED' },
);
}
+ if (requestedMode === 'text' && sourceImagePath) {
+ throw new ServerError(
+ 'Wan 2.2 text-to-video cannot consume a source image — switch to image mode or remove the source.',
+ { status: 400, code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' },
+ );
+ }
const args = [
WAN22_HELPER_SCRIPT,
- '--model-repo', model.repo,
+ '--model-repo', wanModelPath,
'--prompt', prompt,
'--width', String(width),
'--height', String(height),
@@ -554,11 +561,9 @@ const buildWan22Args = ({ model, prompt, negativePrompt, width, height, numFrame
}
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);
+ for (const weight of wanRequiredWeights) {
+ args.push('--lora-path', weight.path);
+ args.push('--lora-target-role', weight.role);
}
return { bin: WAN22_VENV_PYTHON, args };
};
@@ -601,7 +606,7 @@ const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFra
return { bin: HUNYUAN_VENV_PYTHON, args };
};
-const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, textEncoderRepo, outputPath, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
+const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, textEncoderRepo, outputPath, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
// Route to the dgrauet/ltx-2-mlx helper when the model declares the new
// runtime. Existing notapalindrome models default to runtime: 'mlx_video'
// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).
@@ -635,7 +640,7 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
);
}
if (model.runtime === 'wan22') {
- return buildWan22Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, mode, outputPath });
+ return buildWan22Args({ model, wanModelPath, wanRequiredWeights, 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 });
@@ -740,14 +745,29 @@ 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' });
+ let wanModelPath = null;
+ const wanRequiredWeights = [];
if (model.runtime === 'wan22') {
- const requestedMode = mode || (sourceImagePath || uploadedTempPath ? 'image' : 'text');
+ sourceImagePath ||= uploadedTempPath;
+ const requestedMode = mode || (sourceImagePath ? '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' },
);
}
+ if (requestedMode === 'image' && !sourceImagePath) {
+ throw new ServerError(
+ 'Wan 2.2 image-to-video requires a source image — upload one before running this model.',
+ { status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' },
+ );
+ }
+ if (requestedMode === 'text' && sourceImagePath) {
+ throw new ServerError(
+ 'Wan 2.2 text-to-video cannot consume a source image — switch to image mode or remove the source.',
+ { status: 400, code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' },
+ );
+ }
const frameStride = Number(model.frameStride);
if (Number.isFinite(frameStride) && frameStride > 0 && (Number(numFrames) - 1) % frameStride !== 0) {
throw new ServerError(
@@ -755,6 +775,42 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
{ status: 400, code: 'WAN22_INVALID_FRAME_COUNT' },
);
}
+ if (typeof model.revision !== 'string' || !model.revision) {
+ throw new ServerError(
+ `Wan model "${modelId}" is missing an immutable Hugging Face revision.`,
+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },
+ );
+ }
+ const baseCache = await inspectModelCache(model.repo, { revision: model.revision });
+ if (!baseCache.cached || !baseCache.snapshotPath) {
+ throw new ServerError(
+ `${model.name} revision ${model.revision.slice(0, 8)} is not fully cached. Download or repair it in Video Gen before rendering.`,
+ { status: 400, code: 'WAN22_MODEL_NOT_CACHED' },
+ );
+ }
+ wanModelPath = baseCache.snapshotPath;
+ 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 : [];
+ if (!dep?.repo || !dep?.revision || files.length === 0 || files.length !== roles.length) {
+ throw new ServerError(
+ `Wan model "${modelId}" has an invalid requiredWeights entry.`,
+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },
+ );
+ }
+ const paths = await Promise.all(files.map((file) => findCachedRepoFile(
+ dep.repo, file, { revision: dep.revision },
+ )));
+ for (let i = 0; i < files.length; i += 1) {
+ if (!paths[i]) {
+ throw new ServerError(
+ `${model.name} is missing required weight ${files[i]}. Download or repair its dependencies in Video Gen.`,
+ { status: 400, code: 'WAN22_REQUIRED_WEIGHT_NOT_CACHED' },
+ );
+ }
+ wanRequiredWeights.push({ path: paths[i], role: roles[i] });
+ }
+ }
}
// Only require the legacy mlx_video pythonPath when the chosen runtime
// actually uses it. ltx2/wan22/hunyuan resolve their own venv path inside
@@ -1061,7 +1117,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// logic of the spawn-error handler so failure modes converge.
let bin, args;
try {
- ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
+ ({ bin, args } = buildArgs({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to build video gen args';
@@ -1112,6 +1168,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
env: childEnv,
controlDir: join(PATHS.videos, '.detached', jobId),
cleanup: true,
+ killProcessGroup: model.runtime === 'wan22',
});
activeProcess = proc;
@@ -1421,6 +1478,15 @@ export async function generateChainedVideo({ chunks, jobId: outerJobId, ...rest
}
if (!outerJobId) throw new ServerError('generateChainedVideo requires jobId', { status: 500, code: 'INTERNAL' });
+ const chainModel = resolveVideoModel(rest.modelId || defaultVideoModelId());
+ if (chainModel?.runtime === 'wan22'
+ && !(Array.isArray(chainModel.supportedModes) && chainModel.supportedModes.includes('image'))) {
+ throw new ServerError(
+ `${chainModel.name} cannot generate chunks > 1 because continuation requires image-to-video support.`,
+ { status: 400, code: 'WAN22_CHAIN_REQUIRES_IMAGE_MODE' },
+ );
+ }
+
const chainState = { stopped: false };
activeChain = chainState;
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 04b4fb4f50..3de49620da 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -45,17 +45,39 @@ vi.mock('../../lib/mediaModels.js', () => ({
{
id: 'wan22_ti2v_5b', name: 'Wan TI2V', runtime: 'wan22',
repo: 'AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit',
+ revision: '6875952a110b6bdbcfc00d72b1d89a8e02ab0fc3',
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',
+ revision: '39ee5f1f630789956f29f40b5c2c6d48c6e9a798',
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'],
+ revision: '18bccf8884ec0a078eed79785eb4ef13ea16ce1e',
+ 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 I2V Lightning', runtime: 'wan22',
+ repo: 'AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit',
+ revision: '1a17fbea2649c576de844e08e79fe56296751efa',
+ supportedModes: ['image'], frameStride: 4, steps: 4, guidance: 1,
+ guidance2: 1, flowShift: 5, solver: 'euler', samplerLocked: true,
+ requiredWeights: [{
+ repo: 'lightx2v/Wan2.2-Lightning',
+ revision: '18bccf8884ec0a078eed79785eb4ef13ea16ce1e',
+ 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'],
}],
},
@@ -1492,23 +1514,109 @@ describe('generateVideo — Wan MLX-Gen contract', () => {
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');
+ expect(args[args.indexOf('--model-repo') + 1]).toBe('/mock/hf/snap');
+ expect(args.flatMap((arg, i) => arg === '--lora-path' ? [args[i + 1]] : [])).toEqual([
+ '/mock/hf/snap/Wan2.2-T2V-A14B-4steps-lora-rank64-Seko-V1.1/high_noise_model.safetensors',
+ '/mock/hf/snap/Wan2.2-T2V-A14B-4steps-lora-rank64-Seko-V1.1/low_noise_model.safetensors',
+ ]);
+ expect(args.flatMap((arg, i) => arg === '--lora-target-role' ? [args[i + 1]] : [])).toEqual([
+ 'high_noise_transformer',
+ 'low_noise_transformer',
+ ]);
+ expect(spawnMock.mock.calls.find(([, childArgs]) => childArgs === args)?.[2]).toMatchObject({
+ killProcessGroup: true,
+ });
+ expect(mockInspectModelCache).toHaveBeenCalledWith(
+ 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ { revision: '39ee5f1f630789956f29f40b5c2c6d48c6e9a798' },
+ );
+ expect(mockFindCachedRepoFile).toHaveBeenCalledWith(
+ 'lightx2v/Wan2.2-Lightning',
+ expect.any(String),
+ { revision: '18bccf8884ec0a078eed79785eb4ef13ea16ce1e' },
+ );
+ });
+
+ it('passes the exact ordered I2V Lightning adapter pair', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+ await generateVideo({
+ jobId: 'wan-i2v-lightning-args',
+ modelId: 'wan22_i2v_a14b_lightning', prompt: 'a boat crosses a lake',
+ sourceImagePath: '/mock/data/images/boat.png',
+ width: 480, height: 256, numFrames: 81, fps: 20, mode: 'image',
+ });
+ const args = spawnMock.mock.calls.find(([, childArgs]) => childArgs.some((arg) => String(arg).endsWith('/generate_wan22.py')))[1];
+ expect(args.flatMap((arg, i) => arg === '--lora-path' ? [args[i + 1]] : [])).toEqual([
+ '/mock/hf/snap/Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/high_noise_model.safetensors',
+ '/mock/hf/snap/Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/low_noise_model.safetensors',
+ ]);
+ expect(args.flatMap((arg, i) => arg === '--lora-target-role' ? [args[i + 1]] : [])).toEqual([
+ 'high_noise_transformer',
+ 'low_noise_transformer',
+ ]);
});
it('rejects a Wan model in an unsupported mode before spawn', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
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' });
+ expect(spawnDetached).not.toHaveBeenCalled();
});
it('rejects a non-4n+1 Wan frame count', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
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' });
+ expect(spawnDetached).not.toHaveBeenCalled();
+ });
+
+ it('rejects image mode without a source before cache or spawn work', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
+ await expect(generateVideo({
+ modelId: 'wan22_i2v_a14b_lightning', prompt: 'test',
+ width: 480, height: 256, numFrames: 81, fps: 20, mode: 'image',
+ })).rejects.toMatchObject({ code: 'WAN22_I2V_REQUIRES_IMAGE' });
+ expect(spawnDetached).not.toHaveBeenCalled();
+ });
+
+ it('rejects text mode with a source before cache or spawn work', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
+ await expect(generateVideo({
+ modelId: 'wan22_ti2v_5b', prompt: 'test', sourceImagePath: '/mock/source.png',
+ width: 480, height: 256, numFrames: 81, fps: 20, mode: 'text',
+ })).rejects.toMatchObject({ code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' });
+ expect(spawnDetached).not.toHaveBeenCalled();
+ });
+
+ it('rejects a missing immutable base snapshot before spawn', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
+ mockInspectModelCache.mockResolvedValueOnce({ cached: false, snapshotPath: null, sizeBytes: 0 });
+ await expect(generateVideo({
+ modelId: 'wan22_ti2v_5b', prompt: 'test',
+ width: 480, height: 256, numFrames: 81, fps: 20, mode: 'text',
+ })).rejects.toMatchObject({ code: 'WAN22_MODEL_NOT_CACHED' });
+ expect(spawnDetached).not.toHaveBeenCalled();
+ });
+
+ it('rejects a T2V-only Wan chain before rendering chunk one', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
+ await expect(generateChainedVideo({
+ chunks: 2, jobId: 'wan-chain-reject', modelId: 'wan22_t2v_a14b_lightning',
+ prompt: 'test', width: 480, height: 256, numFrames: 81, fps: 20, mode: 'text',
+ })).rejects.toMatchObject({ code: 'WAN22_CHAIN_REQUIRES_IMAGE_MODE' });
+ expect(spawnDetached).not.toHaveBeenCalled();
});
});
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index 08d51d5789..0d649084c2 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -388,9 +388,12 @@ async function resolvePreparedParams({
// 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.
+ let wanRequestedMode = null;
if (effectiveModel?.runtime === 'wan22') {
+ const hasDeclaredSource = Boolean(uploads.sourceImage || body.sourceImageFile);
const requestedMode = body.mode
|| (uploads.sourceImage || body.sourceImageFile ? 'image' : 'text');
+ wanRequestedMode = requestedMode;
const supportedModes = Array.isArray(effectiveModel.supportedModes)
? effectiveModel.supportedModes
: [];
@@ -401,6 +404,27 @@ async function resolvePreparedParams({
{ status: 400, code: 'WAN22_MODE_UNSUPPORTED' },
);
}
+ if (requestedMode === 'image' && !hasDeclaredSource) {
+ await cleanupStaged();
+ throw new ServerError(
+ 'Wan 2.2 image-to-video requires a source image — upload one before running this model.',
+ { status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' },
+ );
+ }
+ if (requestedMode === 'text' && hasDeclaredSource) {
+ await cleanupStaged();
+ throw new ServerError(
+ 'Wan 2.2 text-to-video cannot consume a source image — switch to image mode or remove the source.',
+ { status: 400, code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' },
+ );
+ }
+ if (body.chunks != null && Number(body.chunks) > 1 && !supportedModes.includes('image')) {
+ await cleanupStaged();
+ throw new ServerError(
+ `${effectiveModel.name} cannot generate chunks > 1 because continuation requires image-to-video support.`,
+ { status: 400, code: 'WAN22_CHAIN_REQUIRES_IMAGE_MODE' },
+ );
+ }
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) {
@@ -438,6 +462,13 @@ async function resolvePreparedParams({
} else if (body.sourceImageFile) {
sourceImagePath = resolveGalleryImage(body.sourceImageFile);
}
+ if (effectiveModel?.runtime === 'wan22' && wanRequestedMode === 'image' && !sourceImagePath) {
+ await cleanupStaged();
+ throw new ServerError(
+ 'Wan 2.2 image-to-video requires a resolvable source image — choose an existing gallery image or upload one.',
+ { status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' },
+ );
+ }
// Music Video director-board renders are always i2v FROM the scene's reference
// frame (#1760 Phase 1). resolveGalleryImage returns null for a missing/invalid
// gallery file (mustExist defaults true), and an unresolved source would
diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.js
index 89557600e3..6decec3b87 100644
--- a/server/services/videoGen/prepareParams.test.js
+++ b/server/services/videoGen/prepareParams.test.js
@@ -42,6 +42,7 @@ vi.mock('fs/promises', () => ({
}));
import { unlink } from 'fs/promises';
+import { resolveGalleryImage } from '../../lib/fileUtils.js';
import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';
import { getTrack } from '../tracks/index.js';
import { listVideoModels, loadHistory } from './local.js';
@@ -257,5 +258,52 @@ describe('prepareVideoGenParams', () => {
await expect(prepare({ modelId: 'wan_ti2v', mode: 'text', numFrames: 120 }))
.rejects.toMatchObject({ status: 400, code: 'WAN22_INVALID_FRAME_COUNT' });
});
+
+ it('rejects Wan image mode without a declared source before staging', async () => {
+ listVideoModels.mockReturnValue([{
+ id: 'wan_ti2v', name: 'Wan TI2V', runtime: 'wan22',
+ supportedModes: ['text', 'image'], frameStride: 4,
+ }]);
+
+ await expect(prepare({ modelId: 'wan_ti2v', mode: 'image', numFrames: 121 }))
+ .rejects.toMatchObject({ status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' });
+ expect(unlinkedDurablePaths()).toEqual([]);
+ });
+
+ it('rejects Wan image mode when its gallery source no longer resolves', async () => {
+ listVideoModels.mockReturnValue([{
+ id: 'wan_ti2v', name: 'Wan TI2V', runtime: 'wan22',
+ supportedModes: ['text', 'image'], frameStride: 4,
+ }]);
+ vi.mocked(resolveGalleryImage).mockReturnValueOnce(null);
+
+ await expect(prepare({
+ modelId: 'wan_ti2v', mode: 'image', numFrames: 121, sourceImageFile: 'missing.png',
+ })).rejects.toMatchObject({ status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' });
+ });
+
+ it('rejects an explicit Wan text render that also supplies a source', 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: 121 },
+ { sourceImage: upload('sourceImage') },
+ )).rejects.toMatchObject({ status: 400, code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' });
+ expect(unlink).toHaveBeenCalledWith('/tmp/multipart-sourceImage-frame.png');
+ });
+
+ it('rejects chunks on a T2V-only Wan model before staging', async () => {
+ listVideoModels.mockReturnValue([{
+ id: 'wan_t2v', name: 'Wan T2V', runtime: 'wan22',
+ supportedModes: ['text'], frameStride: 4,
+ }]);
+
+ await expect(prepare({ modelId: 'wan_t2v', mode: 'text', numFrames: 121, chunks: 2 }))
+ .rejects.toMatchObject({ status: 400, code: 'WAN22_CHAIN_REQUIRES_IMAGE_MODE' });
+ expect(unlinkedDurablePaths()).toEqual([]);
+ });
});
});
diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.js
index e600214513..a82378f883 100644
--- a/server/services/videoGen/runtimes.js
+++ b/server/services/videoGen/runtimes.js
@@ -80,6 +80,7 @@ export const BYOV_RUNTIME_INFO = Object.freeze({
installEnvVar: 'INSTALL_WAN22',
repoUrl: 'https://github.com/lpalbou/mlx-gen',
expectedRevision: WAN22_EXPECTED_REVISION,
+ pinEnvVar: 'WAN22_PIN',
importProbe: 'import mflux.models.wan.cli.wan_generate',
// Mirror scripts/generate_wan22.py's emit_runtime_fingerprint package list.
fingerprintPackages: ['mlx-gen', 'mlx', 'mlx_metal', 'huggingface-hub'],