The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(mlx): der Bildinstaller leitet seine Dateiliste aus dem Repo ab und holt kaputte Dateien nach
purple44ce410d8999
diff --git a/e2e/mac-create-mlx.spec.ts b/e2e/mac-create-mlx.spec.tsindex ef654a07..d7bcde8c 100644--- a/e2e/mac-create-mlx.spec.ts+++ b/e2e/mac-create-mlx.spec.ts@@ -25,7 +25,7 @@ const MAC_OPTS: TauriMockOptions = {}test('mac model install reports the missing snapshot component without claiming success', async ({ page }) => {- const error = 'Model installation did not finish: unet/ has no readable, non-empty .safetensors or .bin weights file. Retry the download to repair the missing files.'+ const error = 'Model installation did not finish: unet/diffusion_pytorch_model.fp16.safetensors is missing (expected 5.1 GB). Retry the download to repair the missing files.'await page.addInitScript(tauriMockInit, {...MAC_OPTS,mlx: { engineInstalled: true, installedImages: [], imageInstallError: error },diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rsindex 3c1a8890..a55eabf8 100644--- a/src-tauri/src/commands/mlx.rs+++ b/src-tauri/src/commands/mlx.rs@@ -452,7 +452,7 @@ pub const IMAGE_CATALOG: &[ImageCatalogEntry] = &[id: "nsfw-gen-v2",name: "NSFW-gen v2",repo: "UnfilteredAI/NSFW-gen-v2",- size_gb: 5.3,+ size_gb: 8.6,min_ram_gb: 16,steps: 30,guidance: 7.0,@@ -463,9 +463,15 @@ pub const IMAGE_CATALOG: &[ImageCatalogEntry] = &[default_size: 1024,unfiltered: true,description: "Explicitly unfiltered SDXL by UnfilteredAI — no content restrictions, adult themes included.",+ // This repo has fp16 weights for the unet and the VAE and none for+ // either text encoder, so the fp16 patterns copied from the RealVisXL+ // entry above matched no encoder file at all: GitHub 127. The install+ // now resolves its file set from the hub listing and only falls back+ // to these patterns when the listing cannot be read, but the patterns+ // still have to name files this repository actually contains.allow: allow!["tokenizer/*", "tokenizer_2/*",- "text_encoder/*fp16*", "text_encoder_2/*fp16*",+ "text_encoder/model.safetensors", "text_encoder_2/model.safetensors","unet/*fp16*", "vae/*fp16*"],},@@ -528,92 +534,274 @@ fn image_model_cache_dir(repo: &str) -> PathBuf {.join(format!("models--{}", repo.replace('/', "--")))}-fn image_model_is_installed(entry: &ImageCatalogEntry) -> bool {- let snaps = image_model_cache_dir(entry.repo).join("snapshots");- let Ok(read) = std::fs::read_dir(&snaps) else {- return false;- };- read.flatten().any(|e| snapshot_is_complete(&e.path()))+/// The snapshot directories of one repo, the revision `refs/main` points at+/// first. A cache can hold more than one revision; the one the hub currently+/// serves is the one an install has just written.+fn snapshot_dirs(repo: &str) -> Vec<PathBuf> {+ let root = image_model_cache_dir(repo);+ let mut dirs: Vec<PathBuf> = std::fs::read_dir(root.join("snapshots"))+ .into_iter()+ .flatten()+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| path.is_dir())+ .collect();+ dirs.sort();+ if let Ok(rev) = std::fs::read_to_string(root.join("refs/main")) {+ let head = root.join("snapshots").join(rev.trim());+ if let Some(at) = dirs.iter().position(|d| *d == head) {+ dirs.swap(0, at);+ }+ }+ dirs}-/// A snapshot counts as installed only when the pipeline it manifests can-/// actually load. `snapshot_download` writes the small JSONs first, so-/// checking for `model_index.json` alone declared a download aborted after-/// two seconds "Installed" (live find, 2026-07-31: configs plus the VAE on-/// disk, unet and text_encoder missing, the row offered Remove and a render-/// would have died on local_files_only). The manifest itself says which-/// component directories exist; every model component among them must carry-/// at least one non-empty weights file. Scheduler/tokenizer entries are-/// config-only and skipped.-fn snapshot_is_complete(snap: &std::path::Path) -> bool {- snapshot_problem(snap).is_none()+/// `variant="fp16"` for the load, but only when the repo really carries an+/// fp16 file for every component that holds weights. This is the same trap+/// that produced GitHub 127 from the other side: SDXL repos exist that ship an+/// fp16 unet next to a full-precision text encoder, and asking diffusers for a+/// variant one component does not have turns a complete install into a failed+/// render.+fn fp16_variant_usable(entry: &ImageCatalogEntry) -> bool {+ if !entry.fp16_variant {+ return false;+ }+ match snapshot_dirs(entry.repo).into_iter().next() {+ Some(snap) => fp16_present_in_every_component(&snap),+ // Nothing on disk to judge by: the catalog flag stands.+ None => true,+ }}-fn snapshot_problem(snap: &std::path::Path) -> Option<String> {- let index = snap.join("model_index.json");- let Ok(raw) = std::fs::read_to_string(&index) else {- return Some("model_index.json is missing or unreadable".into());- };- let Ok(json) = serde_json::from_str::<Value>(&raw) else {- return Some("model_index.json contains invalid JSON".into());+fn fp16_present_in_every_component(snap: &std::path::Path) -> bool {+ let Ok(raw) = std::fs::read_to_string(snap.join("model_index.json")) else {+ return true;};- let Some(map) = json.as_object() else {- return Some("model_index.json must contain an object".into());+ let Ok(manifest) = crate::commands::mlx_snapshot::parse_model_index(&raw) else {+ return true;};- for (component, _) in map.iter()- .filter(|(k, _)| !k.starts_with('_'))- // Only real component references count: a ["lib", "Class"] pair.- // Manifests also carry scalars (requires_safety_checker: true) and- // [null, null] stubs for absent components (feature_extractor,- // safety_checker); demanding weights for those declared every- // complete install missing.- .filter_map(|(k, v)| v.get(1).and_then(|c| c.as_str()).map(|class| (k, class)))- .filter(|(_, class)| {- !(class.contains("Scheduler")- || class.contains("Tokenizer")- || class.contains("Processor")- || class.contains("FeatureExtractor"))- })- {- // Reject traversal, platform separators, control characters and alternate streams.- if component.is_empty()- || !component.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')- {- return Some("model_index.json contains an invalid component path".into());+ manifest.weights.iter().all(|component| {+ std::fs::read_dir(snap.join(component))+ .into_iter()+ .flatten()+ .flatten()+ .filter_map(|f| f.file_name().to_str().map(str::to_string))+ .any(|name| name.contains(".fp16."))+ })+}++fn prefer_variant(entry: &ImageCatalogEntry) -> Option<&'static str> {+ entry.fp16_variant.then_some("fp16")+}++/// Audit every snapshot of the repo and keep the best answer. Offline on+/// purpose: the Models page draws this row for each catalog entry and must not+/// wait on the hub to do it.+fn image_model_report(entry: &ImageCatalogEntry) -> crate::commands::mlx_snapshot::SnapshotReport {+ let mut best: Option<crate::commands::mlx_snapshot::SnapshotReport> = None;+ for snap in snapshot_dirs(entry.repo) {+ let report = crate::commands::mlx_snapshot::audit_snapshot(&snap, None, prefer_variant(entry));+ if report.is_complete() {+ return report;}- let dir = snap.join(component);- let Ok(read) = std::fs::read_dir(&dir) else {- return Some(format!("{component}/ is missing or unreadable"));- };- let has_weights = read.flatten().any(|f| {- let p = f.path();- let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");- (ext == "safetensors" || ext == "bin")- && f.metadata().map(|m| m.is_file() && m.len() > 0).unwrap_or(false)- });- if !has_weights {- return Some(format!("{component}/ has no readable, non-empty .safetensors or .bin weights file"));+ if best.as_ref().is_none_or(|b| report.defects.len() < b.defects.len()) {+ best = Some(report);}}- None+ best.unwrap_or(crate::commands::mlx_snapshot::SnapshotReport {+ blocker: Some("no readable model snapshot was found".into()),+ defects: Vec::new(),+ })}-fn image_model_incomplete_message(entry: &ImageCatalogEntry) -> String {- snapshot_cache_incomplete_message(&image_model_cache_dir(entry.repo).join("snapshots"))+fn image_model_is_installed(entry: &ImageCatalogEntry) -> bool {+ image_model_report(entry).is_complete()}-fn snapshot_cache_incomplete_message(snapshots: &std::path::Path) -> String {- let mut paths: Vec<_> = std::fs::read_dir(snapshots)- .into_iter()- .flatten()- .flatten()- .map(|entry| entry.path())- .filter(|path| path.is_dir())- .collect();- paths.sort();- let detail = paths.iter().find_map(|path| snapshot_problem(path))- .unwrap_or_else(|| "no readable model snapshot was found".into());- format!("Model installation did not finish: {detail}. Retry the download to repair the missing files.")+fn install_failed_message(report: &crate::commands::mlx_snapshot::SnapshotReport) -> String {+ format!(+ "Model installation did not finish: {}. Retry the download to repair the missing files.",+ crate::commands::mlx_snapshot::describe(report)+ )+}++/// The verdict on an install, as `Ok` for the completed slot and `Err` for the+/// failed one. It is a function of its own because the two have to stay apart:+/// a failure message handed to `complete()` paints the row green and offers+/// Remove for a model that cannot load.+fn install_outcome(+ id: &str,+ report: &crate::commands::mlx_snapshot::SnapshotReport,+ fetched: &[String],+) -> Result<String, String> {+ if !report.is_complete() {+ return Err(install_failed_message(report));+ }+ Ok(if fetched.is_empty() {+ format!("{id} installed")+ } else {+ format!("{id} installed, re-fetched {}", fetched.join(", "))+ })+}++/// A repo id is a catalog constant, never user input, but it is about to be+/// pasted into a URL and a Python literal, so it is held to the shape the hub+/// itself allows.+fn is_repo_id(repo: &str) -> bool {+ let mut parts = repo.split('/');+ let (Some(org), Some(name), None) = (parts.next(), parts.next(), parts.next()) else {+ return false;+ };+ [org, name].iter().all(|part| {+ !part.is_empty()+ && part.len() <= 96+ && part+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))+ })+}++/// One GET against the hub, with the Settings token when there is one.+fn hub_get(url: &str) -> Result<String, String> {+ crate::commands::proxy::validate_public_url(url)?;+ let client = reqwest::blocking::Client::builder()+ .timeout(std::time::Duration::from_secs(30))+ .build()+ .map_err(|e| e.to_string())?;+ let mut request = client.get(url);+ if let Some(token) = hf_token() {+ request = request.bearer_auth(token);+ }+ let response = request+ .send()+ .map_err(|e| os_error::english_child_text(&e.to_string()).into_owned())?;+ if !response.status().is_success() {+ return Err(format!("the hub answered HTTP {}", response.status().as_u16()));+ }+ response.text().map_err(|e| e.to_string())+}++/// The commit the hub serves as `main` right now.+///+/// Everything an install does is pinned to it: the file listing, the download+/// and the audit afterwards all have to be talking about the same revision, or+/// a repo updated mid-install leaves a snapshot stitched from two versions.+fn fetch_repo_revision(repo: &str) -> Result<String, String> {+ if !is_repo_id(repo) {+ return Err("not a repository id".into());+ }+ let raw = hub_get(&format!("https://huggingface.co/api/models/{repo}"))?;+ let value: Value = serde_json::from_str(&raw).map_err(|_| "the hub returned an unreadable answer")?;+ let sha = value+ .get("sha")+ .and_then(|s| s.as_str())+ .ok_or("the hub named no commit for this repository")?;+ if sha.len() < 7 || sha.len() > 64 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {+ return Err("the hub named a commit we cannot use".into());+ }+ Ok(sha.to_string())+}++/// What the repo holds, straight from the hub: every file with its size and,+/// for the LFS-backed weights, its sha256.+fn fetch_repo_listing(+ repo: &str,+ revision: &str,+) -> Result<Vec<crate::commands::mlx_snapshot::RepoFile>, String> {+ if !is_repo_id(repo) {+ return Err("not a repository id".into());+ }+ let raw = hub_get(&format!(+ "https://huggingface.co/api/models/{repo}/tree/{revision}?recursive=true"+ ))?;+ crate::commands::mlx_snapshot::parse_repo_listing(&raw)+}++/// The pipeline manifest, read before the download so the file set can be+/// derived from it rather than guessed.+fn fetch_model_index(+ repo: &str,+ revision: &str,+) -> Result<crate::commands::mlx_snapshot::Manifest, String> {+ if !is_repo_id(repo) {+ return Err("not a repository id".into());+ }+ let raw = hub_get(&format!(+ "https://huggingface.co/{repo}/resolve/{revision}/model_index.json"+ ))?;+ crate::commands::mlx_snapshot::parse_model_index(&raw)+}++/// Fetch one file again and prove it is the file the hub lists.+///+/// The transfer goes through `huggingface_hub` like every other file of this+/// lane, so the blob and its symlink land where the loader expects them. What+/// is new is what happens afterwards: the size has to match and, when the hub+/// states an LFS digest, the sha256 of the bytes on disk has to match it. A+/// file that fails either is removed again instead of being left behind+/// looking installed.+fn refetch_file(+ slot: &crate::install_state::InstallSlot,+ python: &str,+ repo: &str,+ revision: &str,+ snap: &PathBuf,+ repair: &crate::commands::mlx_snapshot::Repair,+) -> Result<(), String> {+ let cache = mlx_root().join("cache");+ if repair.delete_first {+ crate::commands::mlx_snapshot::drop_broken_file(snap, &cache, &repair.path)?;+ slot.log(format!("discarded the broken copy of {}", repair.path));+ }+ if let Some(sha) = &repair.sha256 {+ let dropped = crate::commands::mlx_snapshot::drop_orphaned_partials(snap, sha);+ if dropped > 0 {+ slot.log(format!(+ "cleared {dropped} unfinished transfer(s) of {} that cannot be resumed",+ repair.path+ ));+ }+ }+ slot.log(format!(+ "re-fetching {} ({})",+ repair.path,+ crate::commands::mlx_snapshot::human_bytes(repair.expected_size)+ ));+ let script = format!(+ "from huggingface_hub import hf_hub_download; hf_hub_download(repo_id={r:?}, filename={f:?}, revision={v:?})",+ r = repo,+ f = repair.path,+ v = revision,+ );+ let mut cmd = Command::new(python);+ cmd.args(["-c", &script]).env("HF_HOME", &cache);+ apply_hf_token(&mut cmd);+ crate::commands::video::run_streamed(slot, &mut cmd)+ .map_err(|e| format!("re-fetching {}: {e}", repair.path))?;++ let full = snap.join(&repair.path);+ let size = std::fs::metadata(&full).map(|m| m.len()).unwrap_or(0);+ if size != repair.expected_size {+ return Err(format!(+ "{} came back as {} instead of the {} the hub lists for it",+ repair.path,+ crate::commands::mlx_snapshot::human_bytes(size),+ crate::commands::mlx_snapshot::human_bytes(repair.expected_size)+ ));+ }+ if let Some(expected) = &repair.sha256 {+ let actual = crate::commands::mlx_snapshot::sha256_of(&full)+ .map_err(|e| format!("checksumming {}: {e}", repair.path))?;+ if &actual != expected {+ let _ = crate::commands::mlx_snapshot::drop_broken_file(snap, &cache, &repair.path);+ return Err(format!(+ "{} does not match the sha256 the hub lists for it and was discarded",+ repair.path+ ));+ }+ slot.log(format!("{} verified against sha256 {}", repair.path, expected));+ }+ Ok(())}pub fn mlx_image_models(_state: &AppState, _args: &Value) -> CmdResult {@@ -674,12 +862,6 @@ pub fn mlx_image_install_model(state: &AppState, args: &Value) -> CmdResult {return Ok(json!({ "ok": true, "status": "complete", "id": entry.id }));}slot.start();- slot.log(format!("pulling {} ({} GB)", entry.repo, entry.size_gb));- crate::install_state::watch_dir_size(- slot.clone(),- image_model_cache_dir(entry.repo),- (entry.size_gb as f64 * 1e9) as u64,- );let slot2 = slot.clone();let entry2 = entry.clone();std::thread::spawn(move || {@@ -693,16 +875,65 @@ pub fn mlx_image_install_model(state: &AppState, args: &Value) -> CmdResult {slot2.fail(e);return;}- let patterns = entry2- .allow- .iter()- .map(|p| format!("{p:?}"))- .collect::<Vec<_>>()- .join(",");+ // Ask the repo what it has before pulling anything. The hand-written+ // allow patterns stay as the offline fallback and nothing more: a+ // pattern that matches no file in this particular repo is how a+ // download finishes at the promised size with a component left empty.+ let revision = fetch_repo_revision(entry2.repo)+ .map_err(|e| slot2.log(format!("could not read the current commit of {} ({e})", entry2.repo)))+ .ok();+ let listing = revision.as_deref().and_then(|rev| match fetch_repo_listing(entry2.repo, rev) {+ Ok(files) => Some(files),+ Err(e) => {+ slot2.log(format!(+ "could not read the file list of {} ({e}) - falling back to the built-in download patterns",+ entry2.repo+ ));+ None+ }+ });+ let prefer = prefer_variant(&entry2);+ let plan = listing.as_ref().zip(revision.as_deref()).and_then(|(files, rev)| {+ fetch_model_index(entry2.repo, rev)+ .map_err(|e| slot2.log(format!("could not read model_index.json ({e})")))+ .ok()+ .map(|manifest| crate::commands::mlx_snapshot::plan_download(files, &manifest, prefer))+ });+ let patterns: Vec<String> = match &plan {+ Some(plan) => {+ for component in &plan.without_weights {+ slot2.log(format!("{} carries no weights file in this repository", component));+ }+ plan.files.iter().map(|f| f.path.clone()).collect()+ }+ None => entry2.allow.iter().map(|p| p.to_string()).collect(),+ };+ let total = plan+ .as_ref()+ .map(|p| p.bytes)+ .unwrap_or((entry2.size_gb as f64 * 1e9) as u64);+ slot2.log(format!(+ "pulling {} ({})",+ entry2.repo,+ crate::commands::mlx_snapshot::human_bytes(total)+ ));+ crate::install_state::watch_dir_size(+ slot2.clone(),+ image_model_cache_dir(entry2.repo),+ total,+ );++ // A pinned revision also makes the snapshot directory predictable:+ // it is `snapshots/<commit>`, not whatever `refs/main` happens to say+ // afterwards.+ let pin = match &revision {+ Some(rev) => format!(", revision={rev:?}"),+ None => String::new(),+ };let script = format!(- "from huggingface_hub import snapshot_download; snapshot_download(repo_id={r:?}, allow_patterns=[{p}])",+ "from huggingface_hub import snapshot_download; snapshot_download(repo_id={r:?}, allow_patterns=[{p}]{pin})",r = entry2.repo,- p = patterns,+ p = patterns.iter().map(|p| format!("{p:?}")).collect::<Vec<_>>().join(","),);let mut cmd = Command::new(&python);cmd.args(["-c", &script])@@ -710,15 +941,66 @@ pub fn mlx_image_install_model(state: &AppState, args: &Value) -> CmdResult {apply_hf_token(&mut cmd);if let Err(e) = crate::commands::video::run_streamed(&slot2, &mut cmd) {slot2.fail(e);- } else if !image_model_is_installed(&entry2) {- slot2.fail(image_model_incomplete_message(&entry2));- } else {- slot2.complete(format!("{} installed", entry2.id));+ return;+ }+ match finish_image_install(&slot2, &python, &entry2, revision.as_deref(), listing.as_deref()) {+ Ok(done) => slot2.complete(done),+ Err(why) => slot2.fail(why),}});Ok(json!({ "ok": true, "status": "installing", "id": entry.id }))}+/// After the pull: check what landed, repair what did not, and say so.+///+/// A defect the hub can name is fetched again on the spot, one file at a time,+/// and nothing that verifies is touched. Anything left after that is reported+/// by name, because the sentence the reporter of GitHub 127 saw named nothing+/// at all and left him with a 5 GB download and no way to tell what was wrong.+fn finish_image_install(+ slot: &crate::install_state::InstallSlot,+ python: &str,+ entry: &ImageCatalogEntry,+ revision: Option<&str>,+ listing: Option<&[crate::commands::mlx_snapshot::RepoFile]>,+) -> Result<String, String> {+ use crate::commands::mlx_snapshot as snapshot;+ let prefer = prefer_variant(entry);+ let pinned = revision+ .map(|rev| image_model_cache_dir(entry.repo).join("snapshots").join(rev))+ .filter(|dir| dir.is_dir());+ let Some(snap) = pinned.or_else(|| snapshot_dirs(entry.repo).into_iter().next()) else {+ return Err(install_failed_message(&snapshot::SnapshotReport {+ blocker: Some("no readable model snapshot was found".into()),+ defects: Vec::new(),+ }));+ };+ let report = snapshot::audit_snapshot(&snap, listing, prefer);+ if report.is_complete() {+ return install_outcome(entry.id, &report, &[]);+ }+ let (repairs, stuck) = snapshot::repair_plan(&report.defects);+ if repairs.is_empty() {+ return install_outcome(entry.id, &report, &[]);+ }+ slot.log(format!(+ "{} file(s) of the snapshot are missing or damaged, fetching them again",+ repairs.len()+ ));+ let mut fetched: Vec<String> = Vec::new();+ for repair in &repairs {+ if let Err(e) = refetch_file(slot, python, entry.repo, revision.unwrap_or("main"), &snap, repair) {+ slot.log(e);+ } else {+ fetched.push(repair.path.clone());+ }+ }+ for defect in &stuck {+ slot.log(format!("{} cannot be fetched again on its own", defect.path));+ }+ install_outcome(entry.id, &snapshot::audit_snapshot(&snap, listing, prefer), &fetched)+}+pub fn mlx_image_install_status(state: &AppState, _args: &Value) -> CmdResult {Ok(serde_json::to_value(state.install_mlx_image_model().snapshot()).unwrap())}@@ -789,7 +1071,7 @@ pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {"height": req.height.unwrap_or(entry.default_size),"model_repo": entry.repo,"dtype": entry.dtype,- "variant": if entry.fp16_variant { Some("fp16") } else { None::<&str> },+ "variant": if fp16_variant_usable(entry) { Some("fp16") } else { None::<&str> },"guidance": entry.guidance,"cfg_param": entry.cfg_param,"disable_safety_checker": entry.disable_safety_checker,@@ -997,13 +1279,15 @@ mod tests {}/// The live find from 2026-07-31: a download killed two seconds in has+ use crate::commands::mlx_snapshot::{audit_snapshot, describe, SnapshotReport};+/// model_index.json and every config on disk, but no unet weights. That/// snapshot must NOT read as installed, or the row offers Remove and a/// local_files_only render dies. Weights present flips it to installed.#[test]fn aborted_snapshot_is_not_installed_until_weights_exist() {- let snap = std::env::temp_dir().join(format!("lu-snap-test-{}", std::process::id()));- let _ = std::fs::remove_dir_all(&snap);+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();for d in ["unet", "vae", "text_encoder", "scheduler", "tokenizer"] {std::fs::create_dir_all(snap.join(d)).unwrap();}@@ -1026,69 +1310,98 @@ mod tests {}"#,).unwrap();+ std::fs::write(snap.join("tokenizer/vocab.json"), "{}").unwrap();// Configs alone (the aborted-download shape): not installed.std::fs::write(snap.join("unet/config.json"), "{}").unwrap();std::fs::write(snap.join("vae/config.json"), "{}").unwrap();- assert!(!snapshot_is_complete(&snap), "configs without weights must not count");+ assert!(!audit_snapshot(snap, None, None).is_complete(), "configs without weights must not count");// Weights for two of three model components: still not installed.std::fs::write(snap.join("vae/diffusion_pytorch_model.fp16.safetensors"), b"w").unwrap();std::fs::write(snap.join("text_encoder/model.fp16.safetensors"), b"w").unwrap();- assert!(!snapshot_is_complete(&snap), "a missing unet must not count");+ assert!(!audit_snapshot(snap, None, None).is_complete(), "a missing unet must not count");// Zero-byte weights are a torn write, not an install.std::fs::write(snap.join("unet/diffusion_pytorch_model.fp16.safetensors"), b"").unwrap();- assert!(!snapshot_is_complete(&snap), "an empty weights file must not count");+ assert!(!audit_snapshot(snap, None, None).is_complete(), "an empty weights file must not count");std::fs::write(snap.join("unet/diffusion_pytorch_model.fp16.safetensors"), b"w").unwrap();- assert!(snapshot_is_complete(&snap), "all model components carrying weights count");-- // Scheduler and tokenizer are config-only and must not be required- // to carry weights (they never do).- let _ = std::fs::remove_dir_all(&snap);+ assert!(audit_snapshot(snap, None, None).is_complete(), "all model components carrying weights count");+ // Every component has an fp16 file, so the load may ask for that variant.+ assert!(fp16_present_in_every_component(snap));+ std::fs::write(snap.join("text_encoder/model.safetensors"), b"w").unwrap();+ std::fs::remove_file(snap.join("text_encoder/model.fp16.safetensors")).unwrap();+ assert!(audit_snapshot(snap, None, None).is_complete(), "plain weights are weights");+ assert!(+ !fp16_present_in_every_component(snap),+ "one component without an fp16 file has to drop the variant for the whole pipeline"+ );}+ /// GitHub 127, suyashnatural, 2026-09-09: the sentence he was shown named+ /// no file. The installer text now does, and still carries no private path.#[test]- fn snapshot_diagnostic_names_manifest_and_missing_component() {+ fn the_install_failure_names_the_file_and_no_private_path() {let temp = tempfile::tempdir().unwrap();let snap = temp.path();- assert_eq!(snapshot_problem(snap).as_deref(), Some("model_index.json is missing or unreadable"));- std::fs::write(snap.join("model_index.json"), "{").unwrap();- assert_eq!(snapshot_problem(snap).as_deref(), Some("model_index.json contains invalid JSON"));- std::fs::write(snap.join("model_index.json"), "[]").unwrap();- assert_eq!(snapshot_problem(snap).as_deref(), Some("model_index.json must contain an object"));- std::fs::write(snap.join("model_index.json"), r#"{"unet":["diffusers","UNet2DConditionModel"]}"#).unwrap();- assert_eq!(snapshot_problem(snap).as_deref(), Some("unet/ is missing or unreadable"));- std::fs::create_dir(snap.join("unet")).unwrap();- std::fs::create_dir(snap.join("unet/fake.safetensors")).unwrap();- assert_eq!(snapshot_problem(snap).as_deref(), Some("unet/ has no readable, non-empty .safetensors or .bin weights file"));- std::fs::write(snap.join("unet/model.safetensors"), b"").unwrap();- assert!(snapshot_problem(snap).is_some());- std::fs::write(snap.join("unet/model.safetensors"), b"fixture").unwrap();- assert_eq!(snapshot_problem(snap), None);+ assert_eq!(+ install_failed_message(&SnapshotReport {+ blocker: Some("no readable model snapshot was found".into()),+ defects: Vec::new(),+ }),+ "Model installation did not finish: no readable model snapshot was found. Retry the download to repair the missing files."+ );+ std::fs::write(+ snap.join("model_index.json"),+ r#"{"text_encoder": ["transformers", "CLIPTextModel"]}"#,+ )+ .unwrap();+ let message = install_failed_message(&audit_snapshot(snap, None, None));+ assert!(message.contains("text_encoder/ is missing"), "{message}");+ assert!(!message.contains(snap.to_str().unwrap()), "no private paths in UI text");}#[test]- fn snapshot_diagnostic_rejects_manifest_path_traversal_without_echoing_it() {+ fn a_manifest_component_that_climbs_out_is_refused_without_being_echoed() {let temp = tempfile::tempdir().unwrap();for component in ["../outside", "..\\outside", "/outside", "a/b", "a\\b", "line\nbreak", "a:stream", ".. "] {let manifest = json!({component: ["diffusers", "UNet2DConditionModel"]});std::fs::write(temp.path().join("model_index.json"), manifest.to_string()).unwrap();- assert_eq!(snapshot_problem(temp.path()).as_deref(), Some("model_index.json contains an invalid component path"));- assert!(!snapshot_is_complete(temp.path()));+ let report = audit_snapshot(temp.path(), None, None);+ assert_eq!(report.blocker.as_deref(), Some("model_index.json contains an invalid component path"));+ assert!(!report.is_complete());+ assert!(!describe(&report).contains("outside"));}}+ /// An install that did not finish must reach `fail`, not `complete` with a+ /// failure sentence in it: the row would go green and offer Remove for a+ /// model that cannot load.#[test]- fn snapshot_cache_diagnostic_reaches_the_install_error_without_private_paths() {- let temp = tempfile::tempdir().unwrap();- assert_eq!(snapshot_cache_incomplete_message(temp.path()),- "Model installation did not finish: no readable model snapshot was found. Retry the download to repair the missing files.");- std::fs::create_dir(temp.path().join("revision")).unwrap();- let message = snapshot_cache_incomplete_message(temp.path());- assert_eq!(message,- "Model installation did not finish: model_index.json is missing or unreadable. Retry the download to repair the missing files.");- assert!(!message.contains(temp.path().to_str().unwrap()));+ fn an_unfinished_install_is_an_error_and_a_repaired_one_says_what_it_fetched() {+ let complete = SnapshotReport::default();+ assert_eq!(install_outcome("nsfw-gen-v2", &complete, &[]).unwrap(), "nsfw-gen-v2 installed");+ assert_eq!(+ install_outcome("nsfw-gen-v2", &complete, &["text_encoder/model.safetensors".into()]).unwrap(),+ "nsfw-gen-v2 installed, re-fetched text_encoder/model.safetensors"+ );+ let broken = SnapshotReport {+ blocker: Some("model_index.json is missing or unreadable".into()),+ defects: Vec::new(),+ };+ let failure = install_outcome("nsfw-gen-v2", &broken, &[]).unwrap_err();+ assert!(failure.starts_with("Model installation did not finish:"), "{failure}");+ assert!(!failure.contains("installed"), "{failure}");+ }++ #[test]+ fn every_catalog_repo_is_a_repository_id() {+ for entry in IMAGE_CATALOG {+ assert!(is_repo_id(entry.repo), "{} has an unusable repo id", entry.id);+ }+ for bad in ["", "no-slash", "a/b/c", "../etc/passwd", "org/na me", "org/"] {+ assert!(!is_repo_id(bad), "{bad} must not pass as a repo id");+ }}#[test]diff --git a/src-tauri/src/commands/mlx_snapshot.rs b/src-tauri/src/commands/mlx_snapshot.rsnew file mode 100644index 00000000..053a5e7f--- /dev/null+++ b/src-tauri/src/commands/mlx_snapshot.rs@@ -0,0 +1,1328 @@+//! What a finished MLX image model looks like on disk, and how to repair one+//! that is not finished.+//!+//! The image lane pulls diffusers-layout repos with+//! `huggingface_hub.snapshot_download` into our own HF_HOME, so a model lands+//! as `cache/hub/models--org--name/snapshots/<commit>/...` with the weights+//! symlinked out of `blobs/`. Two things then have to be true before the row+//! may say "Installed": the pipeline the manifest describes has to be on disk,+//! and every file of it has to be the file the hub actually serves.+//!+//! Both used to be guessed. The download set was a hand-written+//! `allow_patterns` list per catalog entry, and the completeness check only+//! asked whether *some* non-empty `.safetensors` sat in each component folder.+//! GitHub 127 (suyashnatural, 2026-09-09) is what that costs: his entry asked+//! for `text_encoder/*fp16*`, `UnfilteredAI/NSFW-gen-v2` ships no fp16 text+//! encoder at all, the pattern matched nothing, the download reported success+//! at exactly the size the catalog promised, and the install then died with+//! "the model snapshot is incomplete" naming no file. The pattern had been+//! copied from the RealVisXL entry, whose repo does carry fp16 encoders.+//!+//! So both answers now come from the repo itself. The hub's file listing says+//! which weights exist, in which precision variants, at which byte size and+//! (for LFS files) under which sha256; `model_index.json` says which+//! components the pipeline needs. Everything here works on those two lists,+//! stays offline-capable when the listing cannot be fetched, and never names+//! an absolute path in anything a user reads.++use std::path::{Path, PathBuf};++/// One file as the hub lists it for a repo.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct RepoFile {+ /// Repo-relative, forward slashes, exactly as the hub spells it.+ pub path: String,+ pub size: u64,+ /// Content digest, for LFS-backed files only. The small JSON and text+ /// files are plain git blobs whose `oid` is a sha1 over a git header, not+ /// a sha256 over the content, so they carry `None` and are checked by+ /// size alone.+ pub sha256: Option<String>,+}++impl RepoFile {+ fn dir(&self) -> Option<&str> {+ self.path.rsplit_once('/').map(|(d, _)| d)+ }++ fn name(&self) -> &str {+ self.path.rsplit_once('/').map_or(self.path.as_str(), |(_, n)| n)+ }+}++/// `GET /api/models/<repo>/tree/<rev>?recursive=true` into [`RepoFile`]s.+///+/// Directories and anything without a usable path or size are dropped rather+/// than rejected: a new field on the hub must not take the image lane down.+pub(crate) fn parse_repo_listing(raw: &str) -> Result<Vec<RepoFile>, String> {+ let value: serde_json::Value =+ serde_json::from_str(raw).map_err(|_| "the hub returned a file listing we cannot read".to_string())?;+ let array = value+ .as_array()+ .ok_or_else(|| "the hub returned a file listing we cannot read".to_string())?;+ let mut out = Vec::new();+ for item in array {+ if item.get("type").and_then(|t| t.as_str()) != Some("file") {+ continue;+ }+ let Some(path) = item.get("path").and_then(|p| p.as_str()) else {+ continue;+ };+ if !is_safe_repo_path(path) {+ continue;+ }+ let lfs = item.get("lfs");+ // An LFS entry states the real size; the outer `size` of a+ // pointer-backed file agrees with it, but trust the LFS block first.+ let size = lfs+ .and_then(|l| l.get("size"))+ .or_else(|| item.get("size"))+ .and_then(|s| s.as_u64());+ let Some(size) = size else { continue };+ let sha256 = lfs+ .and_then(|l| l.get("oid").or_else(|| l.get("sha256")))+ .and_then(|o| o.as_str())+ .filter(|o| is_sha256(o))+ .map(|o| o.to_ascii_lowercase());+ out.push(RepoFile { path: path.to_string(), size, sha256 });+ }+ if out.is_empty() {+ return Err("the hub listed no files for this repository".into());+ }+ out.sort_by(|a, b| a.path.cmp(&b.path));+ Ok(out)+}++fn is_sha256(s: &str) -> bool {+ s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())+}++/// Repo paths we are willing to join onto a local directory. Rejects+/// traversal, absolute paths, platform separators, control characters and+/// alternate-stream syntax before anything touches the filesystem.+fn is_safe_repo_path(path: &str) -> bool {+ if path.is_empty() || path.len() > 512 || path.starts_with('/') {+ return false;+ }+ path.split('/').all(is_safe_segment)+}++fn is_safe_segment(segment: &str) -> bool {+ !segment.is_empty()+ && segment != "."+ && segment != ".."+ && segment.trim() == segment+ && segment+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))+}++/// What `model_index.json` declares, split by what each component has to+/// carry on disk.+#[derive(Debug, Default, PartialEq, Eq)]+pub(crate) struct Manifest {+ /// Components that hold weights: unet, transformer, vae, text encoders.+ pub weights: Vec<String>,+ /// Tokenizer components. They carry no weights, but they do have to carry+ /// one of several interchangeable vocabulary files.+ pub tokenizers: Vec<String>,+ /// Schedulers and processors: a config file and nothing else.+ pub configs: Vec<String>,+}++impl Manifest {+ fn components(&self) -> impl Iterator<Item = &String> {+ self.weights.iter().chain(self.tokenizers.iter()).chain(self.configs.iter())+ }+}++/// Read the pipeline manifest. `[null, null]` stubs (feature_extractor,+/// safety_checker on SD1.5 repos), scalar flags and plain nulls are not+/// components and are skipped, or every complete install would read as broken.+pub(crate) fn parse_model_index(raw: &str) -> Result<Manifest, String> {+ let json: serde_json::Value =+ serde_json::from_str(raw).map_err(|_| "model_index.json contains invalid JSON".to_string())?;+ let map = json+ .as_object()+ .ok_or_else(|| "model_index.json must contain an object".to_string())?;+ let mut manifest = Manifest::default();+ for (component, class) in map+ .iter()+ .filter(|(k, _)| !k.starts_with('_'))+ .filter_map(|(k, v)| v.get(1).and_then(|c| c.as_str()).map(|class| (k, class)))+ {+ if !is_safe_segment(component) {+ return Err("model_index.json contains an invalid component path".into());+ }+ if class.contains("Tokenizer") {+ manifest.tokenizers.push(component.clone());+ } else if class.contains("Scheduler")+ || class.contains("Processor")+ || class.contains("FeatureExtractor")+ {+ manifest.configs.push(component.clone());+ } else {+ manifest.weights.push(component.clone());+ }+ }+ manifest.weights.sort();+ manifest.tokenizers.sort();+ manifest.configs.sort();+ Ok(manifest)+}++/// One precision family of one component's weights: `model.fp16.safetensors`+/// alone, or every shard of `diffusion_pytorch_model-0000N-of-0000M`.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct WeightSet {+ pub variant: Option<String>,+ pub files: Vec<RepoFile>,+ pub bytes: u64,+}++/// `diffusion_pytorch_model-00001-of-00002` is one shard of one family; the+/// family is what the name says without that suffix.+fn strip_shard(stem: &str) -> &str {+ let five_digits = |s: &str| s.len() == 5 && s.bytes().all(|b| b.is_ascii_digit());+ let Some((head, total)) = stem.rsplit_once("-of-") else {+ return stem;+ };+ match head.rsplit_once('-') {+ Some((base, index)) if five_digits(total) && five_digits(index) && !base.is_empty() => base,+ _ => stem,+ }+}++/// Split `model.fp16-00001-of-00002.safetensors` into ("model", Some("fp16")).+/// A name without a dotted middle segment is the plain, full-precision family.+fn weights_family(name: &str) -> Option<(String, Option<String>)> {+ let (stem, ext) = name.rsplit_once('.')?;+ if ext != "safetensors" && ext != "bin" {+ return None;+ }+ // Shard suffix first: it sits between the variant and the extension.+ let stem = strip_shard(stem);+ match stem.rsplit_once('.') {+ Some((base, variant)) if !base.is_empty() && !variant.is_empty() => {+ Some((base.to_string(), Some(variant.to_string())))+ }+ _ => Some((stem.to_string(), None)),+ }+}++/// Every weights family the repo offers for one component.+pub(crate) fn weight_sets(files: &[RepoFile], component: &str) -> Vec<WeightSet> {+ let mut grouped: Vec<(String, Option<String>, Vec<RepoFile>)> = Vec::new();+ for file in files.iter().filter(|f| f.dir() == Some(component)) {+ let Some((base, variant)) = weights_family(file.name()) else {+ continue;+ };+ match grouped.iter_mut().find(|(b, v, _)| *b == base && *v == variant) {+ Some((_, _, list)) => list.push(file.clone()),+ None => grouped.push((base, variant, vec![file.clone()])),+ }+ }+ grouped+ .into_iter()+ .map(|(_, variant, mut list)| {+ list.sort_by(|a, b| a.path.cmp(&b.path));+ let bytes = list.iter().map(|f| f.size).sum();+ WeightSet { variant, files: list, bytes }+ })+ .collect()+}++/// The family to install for one component.+///+/// The requested variant wins when the repo has it; otherwise the plain family+/// does; otherwise the smallest family there is. That fallback is the whole+/// point: a repo may ship an fp16 unet and a full-precision text encoder, and+/// demanding fp16 everywhere leaves that component with no weights at all.+pub(crate) fn pick_weight_set(files: &[RepoFile], component: &str, prefer: Option<&str>) -> Option<WeightSet> {+ let sets = weight_sets(files, component);+ if let Some(want) = prefer {+ if let Some(hit) = sets.iter().find(|s| s.variant.as_deref() == Some(want)) {+ return Some(hit.clone());+ }+ }+ if let Some(plain) = sets.iter().find(|s| s.variant.is_none()) {+ return Some(plain.clone());+ }+ sets.into_iter().min_by_key(|s| s.bytes)+}++/// The exact file list to hand `snapshot_download` as `allow_patterns`, plus+/// what it will cost. Nothing is guessed: every entry is a path the hub listed.+#[derive(Debug, Default, PartialEq, Eq)]+pub(crate) struct DownloadPlan {+ pub files: Vec<RepoFile>,+ pub bytes: u64,+ /// Components the repo has no weights for at all. The install can still+ /// run, but the audit afterwards will name them.+ pub without_weights: Vec<String>,+}++/// What a component needs beside its weights: the config, the tokenizer+/// vocabulary, the shard index, a chat template. Named by shape rather than by+/// a list of extensions, because the list is exactly the kind of guess this+/// module exists to remove - Qwen-Image ships `tokenizer/chat_template.jinja`+/// and an 11 MB `tokenizer.json`, neither of which an extension list written+/// for SDXL would have contained.+const SUPPORT_FILE_CAP: u64 = 64_000_000;++fn is_support_file(file: &RepoFile) -> bool {+ weights_family(file.name()).is_none() && file.size <= SUPPORT_FILE_CAP+}++pub(crate) fn plan_download(+ files: &[RepoFile],+ manifest: &Manifest,+ prefer_variant: Option<&str>,+) -> DownloadPlan {+ let mut plan = DownloadPlan::default();+ if let Some(index) = files.iter().find(|f| f.path == "model_index.json") {+ plan.files.push(index.clone());+ }+ for component in manifest.components() {+ for support in files+ .iter()+ .filter(|f| f.dir() == Some(component.as_str()) && is_support_file(f))+ {+ plan.files.push(support.clone());+ }+ }+ for component in &manifest.weights {+ match pick_weight_set(files, component, prefer_variant) {+ Some(set) => plan.files.extend(set.files),+ None => plan.without_weights.push(component.clone()),+ }+ }+ plan.files.sort_by(|a, b| a.path.cmp(&b.path));+ plan.files.dedup_by(|a, b| a.path == b.path);+ plan.bytes = plan.files.iter().map(|f| f.size).sum();+ plan+}++/// Why one file of a snapshot cannot be used.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum Defect {+ /// Not on disk at all.+ Missing,+ /// There, but the filesystem will not hand it over. A snapshot entry is a+ /// symlink into `blobs/`; when the blob is gone the link stays behind and+ /// reads as this.+ Unreadable,+ /// Zero bytes: a torn write or a create that never got its content.+ Empty,+ /// An unfinished transfer. Up to huggingface_hub 1.17 that was a+ /// `<name>.incomplete` beside the target; from 1.18 (PR 4306, which+ /// removed cross-run resume to stop concurrent writers poisoning one+ /// shared partial) it is `blobs/<sha256>.<8 hex>.incomplete`, which no+ /// later run can ever pick up again. Both shapes count, and the blob form+ /// is the one that names the file it belongs to: that blob prefix is the+ /// LFS digest the hub lists for it.+ Partial,+ /// macOS only: an iCloud placeholder. The file reports its full length and+ /// holds none of the bytes, so a size check waves it through. Eviction is+ /// time-based, and a model cache that has not been opened in weeks is+ /// exactly what gets evicted.+ Evicted,+ /// A Git LFS pointer: the ~130 byte text stand-in that a clone without+ /// git-lfs, or a `GIT_LFS_SKIP_SMUDGE` checkout, leaves where the weights+ /// belong. It is a valid, non-empty file, which is exactly why a size-free+ /// check waves it through.+ LfsPointer,+ /// The right name, the wrong length. A resumed transfer that appended to a+ /// stale partial ends up here.+ WrongSize { found: u64 },+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct SnapshotDefect {+ /// Snapshot-relative path, never an absolute one: this text reaches the UI.+ pub path: String,+ pub defect: Defect,+ pub expected_size: Option<u64>,+ pub sha256: Option<String>,+}++#[derive(Debug, Default, PartialEq, Eq)]+pub(crate) struct SnapshotReport {+ /// Something that stops the audit before it can look at files, such as a+ /// manifest that is not there when we also have no listing to repair from.+ pub blocker: Option<String>,+ pub defects: Vec<SnapshotDefect>,+}++impl SnapshotReport {+ pub fn is_complete(&self) -> bool {+ self.blocker.is_none() && self.defects.is_empty()+ }+}++/// A tokenizer folder is complete when it carries one of these. Repos differ:+/// SDXL ships `vocab.json` plus `merges.txt`, Llama-style repos ship+/// `tokenizer.model` and no `tokenizer.json`, newer ones ship only+/// `tokenizer.json`. Demanding a fixed list fails most of them.+const TOKENIZER_ALTERNATIVES: &[&str] =+ &["tokenizer.json", "tokenizer.model", "vocab.json", "vocab.txt", "spiece.model"];++fn looks_like_lfs_pointer(path: &Path, len: u64) -> bool {+ // A pointer is three short lines. Anything past a kilobyte is content.+ if len == 0 || len > 1024 {+ return false;+ }+ let Ok(head) = std::fs::read(path) else {+ return false;+ };+ head.starts_with(b"version https://git-lfs")+}++/// `SF_DATALESS`. Apple documents the flag as internal and refuses to let user+/// space set or clear it, so the constant is carried here rather than read+/// from a crate.+const SF_DATALESS: u32 = 0x4000_0000;++fn is_dataless(flags: u32) -> bool {+ flags & SF_DATALESS != 0+}++#[cfg(target_os = "macos")]+fn evicted(meta: &std::fs::Metadata) -> bool {+ use std::os::macos::fs::MetadataExt;+ is_dataless(meta.st_flags())+}++#[cfg(not(target_os = "macos"))]+fn evicted(_meta: &std::fs::Metadata) -> bool {+ false+}++/// `blobs/<digest>.<something>.incomplete` for one digest: the unfinished+/// transfer of exactly this file, left behind by a run that was killed.+///+/// The snapshot sits at `<repo>/snapshots/<commit>`, so the blob store is two+/// levels up. When the cache lives on a volume without symlinks the blob store+/// is empty and this simply finds nothing.+fn orphaned_partials(snap: &Path, sha256: &str) -> Vec<PathBuf> {+ let Some(blobs) = snap.parent().and_then(|p| p.parent()).map(|p| p.join("blobs")) else {+ return Vec::new();+ };+ std::fs::read_dir(blobs)+ .into_iter()+ .flatten()+ .flatten()+ .filter(|entry| {+ entry.file_name().to_str().is_some_and(|name| {+ name.starts_with(sha256) && name.ends_with(".incomplete")+ })+ })+ .map(|entry| entry.path())+ .collect()+}++/// Look at one file the snapshot is supposed to contain.+fn inspect(full: &Path, expected: Option<&RepoFile>) -> Option<Defect> {+ // huggingface_hub parks unfinished bytes beside the target under the very+ // same name plus `.incomplete`, so the suffix is appended, not substituted.+ if partial_beside(full).exists() {+ return Some(Defect::Partial);+ }+ let meta = match std::fs::metadata(full) {+ Ok(m) => m,+ // A symlink whose blob was deleted still answers symlink_metadata.+ Err(_) => {+ return Some(if std::fs::symlink_metadata(full).is_ok() {+ Defect::Unreadable+ } else {+ Defect::Missing+ })+ }+ };+ if !meta.is_file() {+ return Some(Defect::Unreadable);+ }+ if meta.len() == 0 {+ return Some(Defect::Empty);+ }+ if evicted(&meta) {+ return Some(Defect::Evicted);+ }+ if looks_like_lfs_pointer(full, meta.len()) {+ return Some(Defect::LfsPointer);+ }+ match expected {+ Some(file) if file.size != meta.len() => Some(Defect::WrongSize { found: meta.len() }),+ _ => None,+ }+}++fn partial_beside(full: &Path) -> PathBuf {+ PathBuf::from(format!("{}.incomplete", full.to_string_lossy()))+}++fn listed<'a>(files: Option<&'a [RepoFile]>, path: &str) -> Option<&'a RepoFile> {+ files?.iter().find(|f| f.path == path)+}++fn defect_for(path: &str, defect: Defect, expected: Option<&RepoFile>) -> SnapshotDefect {+ SnapshotDefect {+ path: path.to_string(),+ defect,+ expected_size: expected.map(|f| f.size),+ sha256: expected.and_then(|f| f.sha256.clone()),+ }+}++/// Audit one snapshot directory.+///+/// With a hub listing the audit knows the exact file names, their sizes and+/// their digests. Without one (offline, a gated repo, the hub down) it falls+/// back to what the snapshot itself states: the manifest names the components,+/// each component has to hold at least one usable weights file, and each file+/// still has to survive the empty/pointer/partial checks. The row on the+/// Models page is drawn from the offline form, so it never waits on a network+/// call.+pub(crate) fn audit_snapshot(+ snap: &Path,+ files: Option<&[RepoFile]>,+ prefer_variant: Option<&str>,+) -> SnapshotReport {+ let mut report = SnapshotReport::default();+ let index_path = snap.join("model_index.json");+ let raw = match std::fs::read_to_string(&index_path) {+ Ok(raw) => raw,+ Err(_) => {+ match listed(files, "model_index.json") {+ // Repairable: the hub can hand it back.+ Some(file) => {+ report.defects.push(defect_for(+ "model_index.json",+ inspect(&index_path, Some(file)).unwrap_or(Defect::Missing),+ Some(file),+ ));+ return report;+ }+ None => {+ report.blocker = Some("model_index.json is missing or unreadable".into());+ return report;+ }+ }+ }+ };+ let manifest = match parse_model_index(&raw) {+ Ok(m) => m,+ Err(e) => {+ report.blocker = Some(e);+ return report;+ }+ };++ for component in manifest.components() {+ let dir = snap.join(component);+ let carries_weights = manifest.weights.contains(component);+ let required: Vec<RepoFile> = match files {+ // With the listing the required set is simply what the repo has+ // for this component: its small files, plus the weights family we+ // picked for it.+ Some(all) => {+ let mut want: Vec<RepoFile> = all+ .iter()+ .filter(|f| f.dir() == Some(component.as_str()) && is_support_file(f))+ .cloned()+ .collect();+ if carries_weights {+ match pick_weight_set(all, component, prefer_variant) {+ Some(set) => want.extend(set.files),+ None => report.defects.push(no_weights(component)),+ }+ }+ want+ }+ // Offline the snapshot has to speak for itself: the shard index on+ // disk when there is one, otherwise every weights file present.+ None => {+ if manifest.tokenizers.contains(component) && !holds_a_tokenizer(&dir) {+ report.defects.push(SnapshotDefect {+ path: format!("{component}/ (one of {})", TOKENIZER_ALTERNATIVES.join(", ")),+ defect: Defect::Missing,+ expected_size: None,+ sha256: None,+ });+ }+ let local = if carries_weights { local_weight_files(&dir) } else { Vec::new() };+ if carries_weights && local.is_empty() {+ report.defects.push(no_weights(component));+ }+ // Everything the folder holds is still checked for the shapes+ // a size-free look used to wave through.+ let mut want: Vec<String> = std::fs::read_dir(&dir)+ .into_iter()+ .flatten()+ .flatten()+ .filter_map(|e| e.file_name().to_str().map(str::to_string))+ .filter(|n| is_safe_segment(n))+ .collect();+ want.extend(local);+ want.sort();+ want.dedup();+ want+ .into_iter()+ .map(|name| RepoFile { path: format!("{component}/{name}"), size: 0, sha256: None })+ .collect()+ }+ };+ for file in &required {+ let expected = listed(files, &file.path);+ let mut defect = inspect(&snap.join(&file.path), expected);+ if defect == Some(Defect::Missing) {+ // A file that is absent while its unfinished transfer is still+ // sitting in the blob store is not simply missing, and saying+ // which of the two it is decides whether a retry can help.+ if let Some(sha) = expected.and_then(|f| f.sha256.as_deref()) {+ if !orphaned_partials(snap, sha).is_empty() {+ defect = Some(Defect::Partial);+ }+ }+ }+ if let Some(defect) = defect {+ report.defects.push(defect_for(&file.path, defect, expected));+ }+ }+ }++ report.defects.sort_by(|a, b| a.path.cmp(&b.path));+ report.defects.dedup_by(|a, b| a.path == b.path);+ report+}++/// Weights files a component folder holds right now: the ones a local shard+/// index names, or every weights file in the folder when there is no index.+/// One of the interchangeable vocabulary files, which is all a tokenizer+/// folder owes us.+fn holds_a_tokenizer(dir: &Path) -> bool {+ std::fs::read_dir(dir)+ .into_iter()+ .flatten()+ .flatten()+ .filter_map(|e| e.file_name().to_str().map(str::to_string))+ .any(|n| TOKENIZER_ALTERNATIVES.contains(&n.as_str()))+}++fn no_weights(component: &str) -> SnapshotDefect {+ SnapshotDefect {+ path: format!("{component}/"),+ defect: Defect::Missing,+ expected_size: None,+ sha256: None,+ }+}++fn local_weight_files(dir: &Path) -> Vec<String> {+ let names: Vec<String> = std::fs::read_dir(dir)+ .into_iter()+ .flatten()+ .flatten()+ .filter_map(|e| e.file_name().to_str().map(str::to_string))+ .collect();+ if let Some(index) = names.iter().find(|n| n.ends_with(".safetensors.index.json")) {+ if let Ok(raw) = std::fs::read_to_string(dir.join(index)) {+ if let Ok(json) = serde_json::from_str::<serde_json::Value>(&raw) {+ let mut shards: Vec<String> = json+ .get("weight_map")+ .and_then(|m| m.as_object())+ .into_iter()+ .flatten()+ .filter_map(|(_, v)| v.as_str().map(str::to_string))+ .filter(|s| is_safe_segment(s))+ .collect();+ shards.sort();+ shards.dedup();+ if !shards.is_empty() {+ return shards;+ }+ }+ }+ }+ let mut weights: Vec<String> = names+ .into_iter()+ .filter(|n| weights_family(n).is_some())+ .collect();+ weights.sort();+ weights+}++/// One file to fetch again, and whether something broken has to go first.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct Repair {+ pub path: String,+ /// False for a file that is simply absent. A file that verifies is never+ /// in this list at all, so nothing that is usable is ever deleted.+ pub delete_first: bool,+ pub sha256: Option<String>,+ pub expected_size: u64,+}++/// Split an audit into what can be fetched again and what cannot.+///+/// Only a defect the hub listing named is repairable: without a size and a+/// path there is no request to make and no way to tell success from the same+/// failure repeated.+pub(crate) fn repair_plan(defects: &[SnapshotDefect]) -> (Vec<Repair>, Vec<SnapshotDefect>) {+ let mut repairs = Vec::new();+ let mut stuck = Vec::new();+ for defect in defects {+ match defect.expected_size {+ Some(size) if is_safe_repo_path(&defect.path) => repairs.push(Repair {+ path: defect.path.clone(),+ delete_first: defect.defect != Defect::Missing,+ sha256: defect.sha256.clone(),+ expected_size: size,+ }),+ _ => stuck.push(defect.clone()),+ }+ }+ (repairs, stuck)+}++pub(crate) fn human_bytes(bytes: u64) -> String {+ const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];+ if bytes < 1000 {+ return format!("{bytes} bytes");+ }+ let mut value = bytes as f64 / 1000.0;+ let mut unit = 0;+ while value >= 1000.0 && unit + 1 < UNITS.len() {+ value /= 1000.0;+ unit += 1;+ }+ format!("{value:.1} {}", UNITS[unit])+}++fn describe_one(defect: &SnapshotDefect) -> String {+ let what = match &defect.defect {+ Defect::Missing => "is missing".to_string(),+ Defect::Unreadable => "cannot be read".to_string(),+ Defect::Empty => "is empty".to_string(),+ Defect::Partial => "is still a partial download".to_string(),+ Defect::Evicted => "has been evicted to iCloud and holds no data locally".to_string(),+ Defect::LfsPointer => "is a Git LFS pointer, not the weights".to_string(),+ Defect::WrongSize { found } => format!("is {} on disk", human_bytes(*found)),+ };+ match defect.expected_size {+ Some(size) => format!("{} {} (expected {})", defect.path, what, human_bytes(size)),+ None => format!("{} {}", defect.path, what),+ }+}++/// The sentence the installer shows. Names every file it can, with the size+/// the hub states for it, and never an absolute path.+pub(crate) fn describe(report: &SnapshotReport) -> String {+ if let Some(blocker) = &report.blocker {+ return blocker.clone();+ }+ if report.defects.is_empty() {+ return "no files are missing".into();+ }+ const SHOWN: usize = 6;+ let mut parts: Vec<String> = report.defects.iter().take(SHOWN).map(describe_one).collect();+ if report.defects.len() > SHOWN {+ parts.push(format!("and {} more", report.defects.len() - SHOWN));+ }+ parts.join(", ")+}++/// sha256 over a file, streamed so a 10 GB shard does not go through memory.+pub(crate) fn sha256_of(path: &Path) -> Result<String, String> {+ use sha2::{Digest, Sha256};+ use std::io::Read;+ let mut file = std::fs::File::open(path)+ .map_err(|e| format!("open: {}", crate::os_error::english(&e)))?;+ let mut hasher = Sha256::new();+ let mut buffer = vec![0u8; 1 << 20];+ loop {+ let read = file+ .read(&mut buffer)+ .map_err(|e| format!("read: {}", crate::os_error::english(&e)))?;+ if read == 0 {+ break;+ }+ hasher.update(&buffer[..read]);+ }+ Ok(format!("{:x}", hasher.finalize()))+}++/// Remove a broken snapshot entry so the next fetch cannot be answered from+/// the cache that produced it.+///+/// A snapshot entry is a symlink into `blobs/`; deleting the link alone leaves+/// the corrupt blob behind and `hf_hub_download` relinks it, which repairs+/// nothing. The blob goes too, but only when it really sits inside the cache+/// root we own.+/// Throw away the unfinished transfers of one digest. They cannot be resumed+/// (each carries a name unique to the run that made it), `hf cache rm` does+/// not touch them, and leaving one behind means the next attempt starts beside+/// it rather than replacing it.+pub(crate) fn drop_orphaned_partials(snap: &Path, sha256: &str) -> usize {+ let mut dropped = 0;+ for path in orphaned_partials(snap, sha256) {+ if std::fs::remove_file(&path).is_ok() {+ dropped += 1;+ }+ }+ dropped+}++pub(crate) fn drop_broken_file(snap: &Path, cache_root: &Path, relative: &str) -> Result<(), String> {+ if !is_safe_repo_path(relative) {+ return Err("refusing an unsafe repository path".into());+ }+ let full = snap.join(relative);+ if let Ok(target) = std::fs::read_link(&full) {+ let blob = if target.is_absolute() {+ target+ } else {+ full.parent().map(|p| p.join(&target)).unwrap_or(target)+ };+ // Both sides canonicalised: on macOS the cache root arrives as+ // /var/... and the link resolves to /private/var/..., and an+ // uncompared prefix would spare every corrupt blob.+ if let (Ok(blob), Ok(root)) = (blob.canonicalize(), cache_root.canonicalize()) {+ if blob.starts_with(&root) {+ let _ = std::fs::remove_file(&blob);+ }+ }+ }+ let _ = std::fs::remove_file(&full);+ let _ = std::fs::remove_file(partial_beside(&full));+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Trimmed from the live listing of `UnfilteredAI/NSFW-gen-v2`, read from+ /// the hub on 2026-09-11. The shape that matters: fp16 weights for unet+ /// and vae, plain weights only for both text encoders.+ const NSFW_GEN_V2_LISTING: &str = r#"[+ {"type":"directory","path":"unet","size":0},+ {"type":"file","path":"model_index.json","size":685},+ {"type":"file","path":"scheduler/scheduler_config.json","size":488},+ {"type":"file","path":"text_encoder/config.json","size":560},+ {"type":"file","path":"text_encoder/model.safetensors","size":492265168,+ "lfs":{"oid":"34439351fe0077bb6c1b0da495d3dab27d3af52e4bd5c1bfe9ac8a0948d84907","size":492265168}},+ {"type":"file","path":"text_encoder_2/config.json","size":570},+ {"type":"file","path":"text_encoder_2/model.safetensors","size":2778702264,+ "lfs":{"oid":"57f964333dc51d4d02c32badee08103befc93ac769bc257c71c8f49d691167e9","size":2778702264}},+ {"type":"file","path":"tokenizer/merges.txt","size":524619},+ {"type":"file","path":"tokenizer/vocab.json","size":1059962},+ {"type":"file","path":"tokenizer_2/merges.txt","size":524619},+ {"type":"file","path":"tokenizer_2/vocab.json","size":1059962},+ {"type":"file","path":"unet/config.json","size":1729},+ {"type":"file","path":"unet/diffusion_pytorch_model.fp16.safetensors","size":5135149760,+ "lfs":{"oid":"3a223ea0680080ba251db390b9983646eb7ec857586799e6bdf7a4b0da1e67c9","size":5135149760}},+ {"type":"file","path":"unet/diffusion_pytorch_model.safetensors","size":10270077736,+ "lfs":{"oid":"a50b5114d61fc01cbf52a31b29d51e7a347bc6f681f10bfa53eed39077ac1ba4","size":10270077736}},+ {"type":"file","path":"vae/config.json","size":607},+ {"type":"file","path":"vae/diffusion_pytorch_model.fp16.safetensors","size":167335342,+ "lfs":{"oid":"bcb60880a46b63dea58e9bc591abe15f8350bde47b405f9c38f4be70c6161e68","size":167335342}},+ {"type":"file","path":"vae/diffusion_pytorch_model.safetensors","size":334643268,+ "lfs":{"oid":"e8aef7b00195ec3fa8caaa3434e7516eff7d658e1d30eafc9ad6b0e66e9e827e","size":334643268}}+ ]"#;++ const SDXL_MANIFEST: &str = r#"{+ "_class_name": "StableDiffusionXLPipeline",+ "feature_extractor": [null, null],+ "requires_safety_checker": true,+ "image_encoder": null,+ "scheduler": ["diffusers", "EulerDiscreteScheduler"],+ "text_encoder": ["transformers", "CLIPTextModel"],+ "text_encoder_2": ["transformers", "CLIPTextModelWithProjection"],+ "tokenizer": ["transformers", "CLIPTokenizer"],+ "tokenizer_2": ["transformers", "CLIPTokenizer"],+ "unet": ["diffusers", "UNet2DConditionModel"],+ "vae": ["diffusers", "AutoencoderKL"]+ }"#;++ const QWEN_MANIFEST: &str = r#"{"text_encoder":["transformers","Qwen2_5_VLForConditionalGeneration"],+ "tokenizer":["transformers","Qwen2Tokenizer"],+ "vae":["diffusers","AutoencoderKLQwenImage"]}"#;++ /// Trailing whitespace is still valid JSON, and it is the only way a+ /// fixture can carry the exact byte length the hub states for a file.+ fn pad(raw: &str, len: usize) -> String {+ assert!(raw.len() <= len, "fixture manifest is longer than {len} bytes");+ format!("{raw}{}", " ".repeat(len - raw.len()))+ }++ fn listing() -> Vec<RepoFile> {+ parse_repo_listing(NSFW_GEN_V2_LISTING).unwrap()+ }++ fn write(path: &Path, bytes: &[u8]) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, bytes).unwrap();+ }++ /// A file that reports the length the hub states without occupying the+ /// disk: a fixture cannot hold five real gigabytes of unet.+ fn write_sized(path: &Path, len: u64) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::File::create(path).unwrap().set_len(len).unwrap();+ }++ /// The snapshot the reporter ended up with: the manifest and every config,+ /// the two fp16 components, and two text encoder folders that hold nothing+ /// but a config because `text_encoder/*fp16*` matched no file in this repo.+ fn github_127_snapshot(snap: &Path) {+ // Padded to the 685 bytes the listing states for it; trailing space+ // is still valid JSON and a fixture cannot reproduce the real file.+ write(&snap.join("model_index.json"), pad(SDXL_MANIFEST, 685).as_bytes());+ write_sized(&snap.join("scheduler/scheduler_config.json"), 488);+ write_sized(&snap.join("text_encoder/config.json"), 560);+ write_sized(&snap.join("text_encoder_2/config.json"), 570);+ for dir in ["tokenizer", "tokenizer_2"] {+ write_sized(&snap.join(dir).join("vocab.json"), 1059962);+ write_sized(&snap.join(dir).join("merges.txt"), 524619);+ }+ write_sized(&snap.join("unet/config.json"), 1729);+ write_sized(&snap.join("unet/diffusion_pytorch_model.fp16.safetensors"), 5135149760);+ write_sized(&snap.join("vae/config.json"), 607);+ write_sized(&snap.join("vae/diffusion_pytorch_model.fp16.safetensors"), 167335342);+ }++ #[test]+ fn listing_keeps_files_with_their_lfs_digest_and_drops_directories() {+ let files = listing();+ assert!(files.iter().all(|f| f.size > 0));+ assert!(!files.iter().any(|f| f.path == "unet"), "directories are not files");+ let unet = files+ .iter()+ .find(|f| f.path == "unet/diffusion_pytorch_model.fp16.safetensors")+ .unwrap();+ assert_eq!(unet.size, 5135149760);+ assert_eq!(+ unet.sha256.as_deref(),+ Some("3a223ea0680080ba251db390b9983646eb7ec857586799e6bdf7a4b0da1e67c9")+ );+ // A plain git blob has no content digest we can check.+ let config = files.iter().find(|f| f.path == "unet/config.json").unwrap();+ assert_eq!(config.sha256, None);+ }++ #[test]+ fn listing_refuses_garbage_and_paths_that_climb_out() {+ assert!(parse_repo_listing("not json").is_err());+ assert!(parse_repo_listing("{}").is_err());+ assert!(parse_repo_listing("[]").is_err());+ let hostile = r#"[+ {"type":"file","path":"../escape.safetensors","size":1},+ {"type":"file","path":"/etc/passwd","size":1},+ {"type":"file","path":"a/../../b","size":1},+ {"type":"file","path":"good.json","size":2}+ ]"#;+ let files = parse_repo_listing(hostile).unwrap();+ assert_eq!(files.len(), 1);+ assert_eq!(files[0].path, "good.json");+ }++ #[test]+ fn weights_families_split_variant_and_shards() {+ assert_eq!(+ weights_family("model.fp16.safetensors"),+ Some(("model".into(), Some("fp16".into())))+ );+ assert_eq!(+ weights_family("diffusion_pytorch_model.safetensors"),+ Some(("diffusion_pytorch_model".into(), None))+ );+ assert_eq!(+ weights_family("diffusion_pytorch_model-00001-of-00002.safetensors"),+ Some(("diffusion_pytorch_model".into(), None))+ );+ assert_eq!(+ weights_family("model.fp16-00002-of-00002.safetensors"),+ Some(("model".into(), Some("fp16".into())))+ );+ assert_eq!(weights_family("pytorch_model.bin"), Some(("pytorch_model".into(), None)));+ assert_eq!(weights_family("config.json"), None);+ assert_eq!(weights_family("model.safetensors.index.json"), None);+ }++ /// The bug itself, before any file is on disk: asking for fp16 in a repo+ /// that has no fp16 text encoder must fall back to the weights it does+ /// have instead of selecting nothing.+ #[test]+ fn a_missing_variant_falls_back_to_the_weights_the_repo_has() {+ let files = listing();+ let unet = pick_weight_set(&files, "unet", Some("fp16")).unwrap();+ assert_eq!(unet.variant.as_deref(), Some("fp16"));+ assert_eq!(unet.bytes, 5135149760);++ let encoder = pick_weight_set(&files, "text_encoder", Some("fp16")).unwrap();+ assert_eq!(encoder.variant, None, "no fp16 encoder exists, take the plain one");+ assert_eq!(encoder.files[0].path, "text_encoder/model.safetensors");++ // Without a preference the plain family wins outright.+ assert_eq!(pick_weight_set(&files, "unet", None).unwrap().bytes, 10270077736);+ assert!(pick_weight_set(&files, "scheduler", Some("fp16")).is_none());+ }++ #[test]+ fn the_download_plan_covers_every_component_and_prices_itself() {+ let manifest = parse_model_index(SDXL_MANIFEST).unwrap();+ assert_eq!(manifest.weights, ["text_encoder", "text_encoder_2", "unet", "vae"]);+ assert_eq!(manifest.tokenizers, ["tokenizer", "tokenizer_2"]);+ assert_eq!(manifest.configs, ["scheduler"]);++ let plan = plan_download(&listing(), &manifest, Some("fp16"));+ let names: Vec<&str> = plan.files.iter().map(|f| f.path.as_str()).collect();+ assert!(plan.without_weights.is_empty());+ assert!(names.contains(&"model_index.json"));+ assert!(names.contains(&"text_encoder/model.safetensors"));+ assert!(names.contains(&"text_encoder_2/model.safetensors"));+ assert!(names.contains(&"unet/diffusion_pytorch_model.fp16.safetensors"));+ assert!(names.contains(&"vae/diffusion_pytorch_model.fp16.safetensors"));+ assert!(names.contains(&"tokenizer/vocab.json"));+ assert!(names.contains(&"scheduler/scheduler_config.json"));+ // The full-precision duplicates stay on the hub.+ assert!(!names.contains(&"unet/diffusion_pytorch_model.safetensors"));+ assert!(!names.contains(&"vae/diffusion_pytorch_model.safetensors"));+ // 8.57 GB of weights and configs, which is not the 5.3 GB the old+ // pattern set pulled and the catalog still promised.+ assert_eq!(plan.bytes, 8576626335);+ }++ /// Qwen-Image and Z-Image: a nine-shard transformer, a four-shard text+ /// encoder, an 11 MB tokenizer.json and a chat template. Every shard of a+ /// family has to be required together, and none of the support files may+ /// be dropped for having an extension nobody thought of.+ #[test]+ fn a_sharded_repo_keeps_every_shard_and_every_support_file() {+ let raw = r#"[+ {"type":"file","path":"model_index.json","size":443},+ {"type":"file","path":"text_encoder/config.json","size":3217},+ {"type":"file","path":"text_encoder/model-00001-of-00002.safetensors","size":4968243304,+ "lfs":{"oid":"d725335e4ea2399be706469e4b8807716a8fa64bd03468252e9f7acf2415fee4","size":4968243304}},+ {"type":"file","path":"text_encoder/model-00002-of-00002.safetensors","size":1691924384,+ "lfs":{"oid":"5dd068336d14d45ffb43cef374d286cc6ba9d8741b028f90a7d040d847961f4a","size":1691924384}},+ {"type":"file","path":"text_encoder/model.safetensors.index.json","size":57655},+ {"type":"file","path":"tokenizer/chat_template.jinja","size":2427},+ {"type":"file","path":"tokenizer/tokenizer.json","size":11422654},+ {"type":"file","path":"vae/config.json","size":730},+ {"type":"file","path":"vae/diffusion_pytorch_model.safetensors","size":253806966,+ "lfs":{"oid":"0c8bc8b758c649abef9ea407b95408389a3b2f610d0d10fcb054fe171d0a8344","size":253806966}}+ ]"#;+ let files = parse_repo_listing(raw).unwrap();+ let manifest = parse_model_index(QWEN_MANIFEST).unwrap();+ let plan = plan_download(&files, &manifest, None);+ let names: Vec<&str> = plan.files.iter().map(|f| f.path.as_str()).collect();+ assert!(names.contains(&"text_encoder/model-00001-of-00002.safetensors"));+ assert!(names.contains(&"text_encoder/model-00002-of-00002.safetensors"));+ assert!(names.contains(&"text_encoder/model.safetensors.index.json"));+ assert!(names.contains(&"tokenizer/chat_template.jinja"), "{names:?}");+ assert!(names.contains(&"tokenizer/tokenizer.json"));+ assert_eq!(plan.without_weights, ["vae"; 0], "every weights component resolved");++ // One shard short is not installed, and the audit says which shard.+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();+ for file in &plan.files {+ write_sized(&snap.join(&file.path), file.size);+ }+ write(&snap.join("model_index.json"), pad(QWEN_MANIFEST, 443).as_bytes());+ assert!(audit_snapshot(snap, Some(&files), None).is_complete());+ std::fs::remove_file(snap.join("text_encoder/model-00002-of-00002.safetensors")).unwrap();+ let report = audit_snapshot(snap, Some(&files), None);+ assert!(+ describe(&report).contains("text_encoder/model-00002-of-00002.safetensors is missing (expected 1.7 GB)"),+ "{}",+ describe(&report)+ );+ }++ #[test]+ fn a_complete_single_shard_snapshot_passes_with_and_without_the_listing() {+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();+ github_127_snapshot(snap);+ // Complete it the way the repaired plan would.+ write_sized(&snap.join("text_encoder/model.safetensors"), 492265168);+ write_sized(&snap.join("text_encoder_2/model.safetensors"), 2778702264);+ let offline = audit_snapshot(snap, None, Some("fp16"));+ assert!(offline.is_complete(), "offline audit: {}", describe(&offline));+ let online = audit_snapshot(snap, Some(&listing()), Some("fp16"));+ assert!(online.is_complete(), "audit against the listing: {}", describe(&online));+ }++ #[test]+ fn a_complete_sharded_snapshot_passes_from_its_own_index() {+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();+ write(+ &snap.join("model_index.json"),+ br#"{"unet":["diffusers","UNet2DConditionModel"]}"#,+ );+ write(+ &snap.join("unet/diffusion_pytorch_model.safetensors.index.json"),+ br#"{"weight_map":{"a":"diffusion_pytorch_model-00001-of-00002.safetensors",+ "b":"diffusion_pytorch_model-00002-of-00002.safetensors"}}"#,+ );+ write(&snap.join("unet/diffusion_pytorch_model-00001-of-00002.safetensors"), b"one");+ assert!(!audit_snapshot(snap, None, None).is_complete(), "one shard of two");+ let report = audit_snapshot(snap, None, None);+ assert!(+ describe(&report).contains("diffusion_pytorch_model-00002-of-00002.safetensors"),+ "{}",+ describe(&report)+ );+ write(&snap.join("unet/diffusion_pytorch_model-00002-of-00002.safetensors"), b"two");+ assert!(audit_snapshot(snap, None, None).is_complete());+ }++ /// GitHub 127, suyashnatural, 2026-09-09.+ #[test]+ fn github_127_names_the_missing_file_and_offers_to_fetch_it() {+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();+ github_127_snapshot(snap);+ let files = listing();++ let report = audit_snapshot(snap, Some(&files), Some("fp16"));+ assert!(!report.is_complete());+ let text = describe(&report);+ assert!(text.contains("text_encoder/model.safetensors is missing (expected 492.3 MB)"), "{text}");+ assert!(text.contains("text_encoder_2/model.safetensors is missing (expected 2.8 GB)"), "{text}");+ assert!(!text.contains(snap.to_str().unwrap()), "no private paths in UI text");++ let (repairs, stuck) = repair_plan(&report.defects);+ assert!(stuck.is_empty());+ let paths: Vec<&str> = repairs.iter().map(|r| r.path.as_str()).collect();+ assert_eq!(paths, ["text_encoder/model.safetensors", "text_encoder_2/model.safetensors"]);+ assert!(repairs.iter().all(|r| !r.delete_first), "nothing on disk to delete");+ assert!(repairs.iter().all(|r| r.sha256.is_some()), "both come with a digest to check");+ // The unet the reporter did get is left alone.+ assert!(!paths.contains(&"unet/diffusion_pytorch_model.fp16.safetensors"));+ }++ #[test]+ fn an_lfs_pointer_where_a_shard_belongs_is_refetched_not_kept() {+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();+ github_127_snapshot(snap);+ write_sized(&snap.join("text_encoder/model.safetensors"), 492265168);+ write_sized(&snap.join("text_encoder_2/model.safetensors"), 2778702264);+ write(+ &snap.join("unet/diffusion_pytorch_model.fp16.safetensors"),+ b"version https://git-lfs.github.com/spec/v1\noid sha256:3a223ea0\nsize 5135149760\n",+ );+ let files = listing();+ let report = audit_snapshot(snap, Some(&files), Some("fp16"));+ let text = describe(&report);+ assert!(+ text.contains("unet/diffusion_pytorch_model.fp16.safetensors is a Git LFS pointer, not the weights (expected 5.1 GB)"),+ "{text}"+ );+ let (repairs, stuck) = repair_plan(&report.defects);+ assert!(stuck.is_empty());+ let broken: Vec<&Repair> = repairs+ .iter()+ .filter(|r| r.path == "unet/diffusion_pytorch_model.fp16.safetensors")+ .collect();+ assert_eq!(broken.len(), 1);+ assert!(broken[0].delete_first, "a pointer file has to go before the refetch");+ // Offline the pointer is caught too, on shape alone.+ assert!(!audit_snapshot(snap, None, Some("fp16")).is_complete());+ }++ #[test]+ fn a_partial_download_and_a_short_file_are_both_defects() {+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();+ github_127_snapshot(snap);+ write_sized(&snap.join("text_encoder_2/model.safetensors"), 2778702264);+ // The shape huggingface_hub leaves behind mid-transfer.+ write(&snap.join("text_encoder/model.safetensors"), b"half the bytes");+ write(&snap.join("text_encoder/model.safetensors.incomplete"), b"the rest");+ let files = listing();+ let report = audit_snapshot(snap, Some(&files), Some("fp16"));+ let text = describe(&report);+ assert!(text.contains("text_encoder/model.safetensors is still a partial download"), "{text}");++ // Without the .incomplete sibling the same file is merely short, and+ // only the listing can say so.+ std::fs::remove_file(snap.join("text_encoder/model.safetensors.incomplete")).unwrap();+ let report = audit_snapshot(snap, Some(&files), Some("fp16"));+ let text = describe(&report);+ assert!(+ text.contains("text_encoder/model.safetensors is 14 bytes on disk (expected 492.3 MB)"),+ "{text}"+ );+ assert!(audit_snapshot(snap, None, Some("fp16")).is_complete(), "size needs the listing");+ let (repairs, _) = repair_plan(&report.defects);+ assert!(repairs.iter().any(|r| r.path == "text_encoder/model.safetensors" && r.delete_first));+ }++ #[test]+ fn a_tokenizer_needs_one_of_its_alternatives_not_all_of_them() {+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();+ write(+ &snap.join("model_index.json"),+ br#"{"tokenizer":["transformers","LlamaTokenizer"],+ "text_encoder":["transformers","CLIPTextModel"]}"#,+ );+ write(&snap.join("text_encoder/model.safetensors"), b"weights");+ // tokenizer.model and no tokenizer.json is a complete tokenizer.+ write(&snap.join("tokenizer/tokenizer.model"), b"sentencepiece");+ write(&snap.join("tokenizer/tokenizer_config.json"), b"{}");+ assert!(audit_snapshot(snap, None, None).is_complete());++ std::fs::remove_file(snap.join("tokenizer/tokenizer.model")).unwrap();+ let report = audit_snapshot(snap, None, None);+ assert!(!report.is_complete());+ assert!(describe(&report).contains("one of tokenizer.json"), "{}", describe(&report));++ // vocab.json alone is the SDXL shape and also counts.+ write(&snap.join("tokenizer/vocab.json"), b"{}");+ assert!(audit_snapshot(snap, None, None).is_complete());+ }++ #[test]+ fn a_manifest_that_cannot_be_read_blocks_instead_of_pretending() {+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();+ let report = audit_snapshot(snap, None, None);+ assert_eq!(report.blocker.as_deref(), Some("model_index.json is missing or unreadable"));+ assert!(!report.is_complete());++ // With a listing the same state is a repairable missing file.+ let report = audit_snapshot(snap, Some(&listing()), None);+ assert_eq!(report.blocker, None);+ let (repairs, _) = repair_plan(&report.defects);+ assert_eq!(repairs.len(), 1);+ assert_eq!(repairs[0].path, "model_index.json");++ write(&snap.join("model_index.json"), b"{");+ assert_eq!(+ audit_snapshot(snap, None, None).blocker.as_deref(),+ Some("model_index.json contains invalid JSON")+ );+ write(&snap.join("model_index.json"), br#"{"../outside":["diffusers","UNet2DConditionModel"]}"#);+ assert_eq!(+ audit_snapshot(snap, None, None).blocker.as_deref(),+ Some("model_index.json contains an invalid component path")+ );+ }++ #[test]+ fn nothing_that_verifies_is_ever_scheduled_for_deletion() {+ let temp = tempfile::tempdir().unwrap();+ let snap = temp.path();+ github_127_snapshot(snap);+ let files = listing();+ let report = audit_snapshot(snap, Some(&files), Some("fp16"));+ let (repairs, _) = repair_plan(&report.defects);+ for repair in &repairs {+ assert!(+ !snap.join(&repair.path).exists() || repair.delete_first,+ "{} is on disk and healthy",+ repair.path+ );+ }+ // Negative control: a snapshot with nothing wrong schedules no work.+ write_sized(&snap.join("text_encoder/model.safetensors"), 492265168);+ write_sized(&snap.join("text_encoder_2/model.safetensors"), 2778702264);+ let clean = audit_snapshot(snap, None, Some("fp16"));+ assert!(clean.is_complete());+ assert_eq!(describe(&clean), "no files are missing");+ assert!(repair_plan(&clean.defects).0.is_empty());+ }++ #[test]+ fn a_dangling_snapshot_link_reads_as_unreadable_and_takes_its_blob_with_it() {+ let temp = tempfile::tempdir().unwrap();+ let cache = temp.path();+ let snap = cache.join("snapshots/rev");+ let blob = cache.join("blobs/abc123");+ write(&blob, b"corrupt");+ write(&snap.join("model_index.json"), br#"{"unet":["diffusers","UNet2DConditionModel"]}"#);+ std::fs::create_dir_all(snap.join("unet")).unwrap();+ let link = snap.join("unet/diffusion_pytorch_model.safetensors");+ std::os::unix::fs::symlink(&blob, &link).unwrap();+ assert!(audit_snapshot(&snap, None, None).is_complete(), "a live link is a live file");++ drop_broken_file(&snap, cache, "unet/diffusion_pytorch_model.safetensors").unwrap();+ assert!(!blob.exists(), "the blob behind a broken link has to go too");+ assert!(!link.exists());++ // A link left pointing at nothing is not silently treated as absent.+ std::os::unix::fs::symlink(&blob, &link).unwrap();+ let report = audit_snapshot(&snap, None, None);+ assert!(describe(&report).contains("cannot be read"), "{}", describe(&report));+ assert!(drop_broken_file(&snap, cache, "../escape").is_err());+ }++ /// The live shape the huggingface_hub cache actually leaves behind since+ /// version 1.18: the weights file is absent from the snapshot and its+ /// unfinished transfer sits in the blob store under the digest the hub+ /// lists for it, with a per-run suffix that no later run can resume.+ #[test]+ fn an_orphaned_blob_transfer_names_the_file_it_belongs_to() {+ let temp = tempfile::tempdir().unwrap();+ let repo = temp.path();+ let snap = repo.join("snapshots/f70ad5bc");+ github_127_snapshot(&snap);+ write_sized(&snap.join("text_encoder/model.safetensors"), 492265168);+ write_sized(&snap.join("text_encoder_2/model.safetensors"), 2778702264);+ std::fs::remove_file(snap.join("unet/diffusion_pytorch_model.fp16.safetensors")).unwrap();+ let digest = "3a223ea0680080ba251db390b9983646eb7ec857586799e6bdf7a4b0da1e67c9";+ write_sized(&repo.join(format!("blobs/{digest}.d4f6b876.incomplete")), 603561550);+ let files = listing();++ let report = audit_snapshot(&snap, Some(&files), Some("fp16"));+ let text = describe(&report);+ assert!(+ text.contains("unet/diffusion_pytorch_model.fp16.safetensors is still a partial download (expected 5.1 GB)"),+ "{text}"+ );+ // Without the orphan the very same state is a plain missing file.+ assert_eq!(drop_orphaned_partials(&snap, digest), 1);+ let text = describe(&audit_snapshot(&snap, Some(&files), Some("fp16")));+ assert!(text.contains("unet/diffusion_pytorch_model.fp16.safetensors is missing"), "{text}");+ assert_eq!(drop_orphaned_partials(&snap, digest), 0);+ }++ #[test]+ fn an_icloud_placeholder_is_not_a_downloaded_file() {+ // The flag cannot be set from user space, so the predicate is proved+ // on the bit pattern and wired into the size check above it.+ assert!(is_dataless(SF_DATALESS));+ assert!(is_dataless(SF_DATALESS | 0x2));+ assert!(!is_dataless(0));+ assert!(!is_dataless(0x8000_0000));+ }++ #[test]+ fn sizes_read_the_way_the_catalog_writes_them() {+ assert_eq!(human_bytes(0), "0 bytes");+ assert_eq!(human_bytes(999), "999 bytes");+ assert_eq!(human_bytes(492265168), "492.3 MB");+ assert_eq!(human_bytes(5135149760), "5.1 GB");+ }++ #[test]+ fn a_digest_is_taken_over_the_whole_file() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("weights.safetensors");+ std::fs::write(&path, b"").unwrap();+ assert_eq!(+ sha256_of(&path).unwrap(),+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ );+ std::fs::write(&path, vec![7u8; 3 << 20]).unwrap();+ assert_eq!(sha256_of(&path).unwrap().len(), 64);+ assert!(sha256_of(&temp.path().join("absent")).is_err());+ }+}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 62cacb3e..cc140cdb 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -18,6 +18,7 @@ pub mod local_api;pub mod logging;pub mod media_cmds;pub mod mlx;+pub mod mlx_snapshot;pub mod oauth;pub mod process;pub mod proxy;