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
tech(DD): Downloads verlieren nichts mehr — Resume statt Neustart, Byte-genau, mit Prüfsumme
Davida9b6424572fb
diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rsindex afe41c7e..548c2cbd 100644--- a/src-tauri/src/commands/download.rs+++ b/src-tauri/src/commands/download.rs@@ -6,6 +6,7 @@ use std::sync::{Arc, Mutex};use std::time::Instant;use futures_util::StreamExt;+use sha2::{Digest, Sha256};use tauri::State;use tokio_util::sync::CancellationToken;@@ -209,6 +210,7 @@ pub async fn download_model(subfolder: String,filename: String,expectedBytes: Option<u64>,+ expectedSha256: Option<String>,state: State<'_, AppState>,) -> Result<serde_json::Value, String> {let expected_bytes = expectedBytes;@@ -226,27 +228,37 @@ pub async fn download_model(let dest_dir = models_dir(&comfy_path, &subfolder)?;let dest_file = dest_dir.join(sanitize_filename(&filename));+ let expected_sha256 = match expectedSha256.as_deref() {+ Some(s) => Some(normalize_sha256(s)?),+ None => None,+ };+if dest_file.exists() {- // If expected_bytes is provided, verify the file is at least 90% of expected size- // to catch partially downloaded files- let file_complete = match expected_bytes {- Some(expected) if expected > 0 => {- let actual = dest_file.metadata().map(|m| m.len()).unwrap_or(0);- let threshold = (expected as f64 * 0.9) as u64;- let is_complete = actual >= threshold;- if !is_complete {- println!("[Download] File {} exists but is incomplete: {} bytes vs {} expected ({}%)",- filename, actual, expected, (actual as f64 / expected as f64 * 100.0) as u32);- }- is_complete+ let actual = dest_file.metadata().map(|m| m.len()).unwrap_or(0);+ // Ask the SERVER how big the file is. The catalog's `expectedBytes` is a+ // rounded GB estimate and may not decide this — see `judge_existing`.+ match judge_existing(actual, exact_remote_size(&url).await) {+ Existing::Complete => {+ return Ok(serde_json::json!({"status": "exists", "path": dest_file.to_string_lossy()}));+ }+ Existing::Mismatch { actual, exact } => {+ println!(+ "[Download] {} exists with {} bytes but the host states {} — fetching it again",+ filename, actual, exact+ );+ // Fall through to a fresh transfer.+ }+ Existing::Unverified { actual } => {+ // Offline, or a host that states no length. Nothing can be+ // checked, so nothing is claimed: the file stays, and the reason+ // it was not verified is on the record instead of nowhere.+ println!(+ "[Download] {} exists with {} bytes and the host states no size — accepted UNVERIFIED",+ filename, actual+ );+ return Ok(serde_json::json!({"status": "exists", "path": dest_file.to_string_lossy()}));}- _ => true, // No expected size — trust existence (backward compat)- };-- if file_complete {- return Ok(serde_json::json!({"status": "exists", "path": dest_file.to_string_lossy()}));}- // File is incomplete — fall through to re-download (resume from partial)}// Use filename as ID (matches frontend lookup)@@ -288,7 +300,7 @@ pub async fn download_model(let filename_clone = filename.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, expected_bytes, expected_sha256).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@ -398,6 +410,118 @@ fn ended_early(total: u64, downloaded: u64) -> bool {total > 0 && downloaded < total}+/// The full size of the file being fetched, and whether that number is only the+/// catalog's estimate rather than something the server stated.+///+/// A server that sends no `Content-Length` used to switch BOTH guards off+/// without a word: `unwrap_or(0)` produced `total == 0`, and 0 is exactly the+/// value the space check and the truncation check read as "nothing to compare+/// against". A 40 GB transfer then ran until the drive hit zero and a body that+/// stopped halfway was renamed into place, with nobody ever having been told+/// that either safeguard had turned itself off.+///+/// The catalog carries a size for these files, so the space guard gets that+/// estimate to plan with — a rough number is a far better plan than no number.+/// The flag is what keeps the two uses apart: an estimate may refuse a transfer+/// that clearly cannot fit, it may NEVER declare one finished.+fn total_size(declared: Option<u64>, resume_offset: u64, resumed: bool, estimate: Option<u64>) -> (u64, bool) {+ match declared {+ Some(n) if n > 0 => (if resumed { n + resume_offset } else { n }, false),+ _ => (estimate.unwrap_or(0), true),+ }+}++/// What a file that is already sitting at the destination is worth.+#[derive(Debug, PartialEq, Eq)]+pub enum Existing {+ /// Byte for byte the size the server states. Nothing left to fetch.+ Complete,+ /// The server states a different size than the file has. Fetch it again.+ Mismatch { actual: u64, exact: u64 },+ /// Nobody could name an exact size, so nothing here is verified.+ Unverified { actual: u64 },+}++/// Decide what to do with a file already at the destination.+///+/// The old rule was `actual >= expected as f64 * 0.9`, measured against a+/// catalog size that is a rounded GB estimate. A download aborted at 91 % was+/// therefore "complete" and never fetched again: several gigabytes of model+/// weights accepted on a file length with 10 % of slack, and the failure only+/// surfaced much later when a backend tried to load the truncated file.+///+/// There is no safe threshold here. Either a number is exact — then it has to+/// match to the byte — or it is not, and then it may not decide anything. The+/// exact number comes from the server (`exact_remote_size`), never from the+/// catalog.+pub fn judge_existing(actual: u64, exact: Option<u64>) -> Existing {+ match exact {+ Some(e) if e > 0 => {+ if actual == e {+ Existing::Complete+ } else {+ Existing::Mismatch { actual, exact: e }+ }+ }+ _ => Existing::Unverified { actual },+ }+}++/// Total size out of a `Content-Range: bytes 0-0/12345` header. A `*` for the+/// whole means the server knows the range but not the length, which is no+/// number to judge with.+fn total_from_content_range(v: &str) -> Option<u64> {+ v.rsplit('/').next()?.trim().parse::<u64>().ok()+}++/// A 64 character hex SHA256, lowercased.+///+/// Anything else is refused rather than quietly ignored: a mistyped digest that+/// silently disables the check is worse than no digest at all, because it looks+/// like the file was verified.+fn normalize_sha256(v: &str) -> Result<String, String> {+ let t = v.trim();+ if t.len() == 64 && t.chars().all(|c| c.is_ascii_hexdigit()) {+ Ok(t.to_ascii_lowercase())+ } else {+ Err(format!(+ "Expected sha256 must be 64 hex characters, got {} character(s)",+ t.chars().count()+ ))+ }+}++/// Turn a refused HTTP status into something the user can act on, and say in+/// the same breath whether pressing Retry could ever help.+///+/// The catalog hard-codes 106 HuggingFace addresses. The moment a repo is+/// renamed, made private, or gated behind a licence click, every one of them+/// answers 404 or 401/403 for good — and all the user got was the bare string+/// "HTTP 404" next to a Retry button that could not possibly work, which is a+/// loop with no exit.+///+/// The status code stays inside the text on purpose: it is the contract the+/// frontend reads to decide whether to offer Retry at all — see+/// `isPermanentDownloadError` in src/api/discover.ts. Changing the "(HTTP nnn)"+/// shape here breaks that decision there.+pub fn http_error_message(status: u16, filename: &str) -> String {+ match status {+ 404 | 410 => format!(+ "{filename} is not at this address any more (HTTP {status}). The repository was renamed, moved or taken down, so trying again cannot help. Look for a newer version of this model in the Model Manager, or update Locally Uncensored — the address is part of the app's catalog."+ ),+ 401 | 403 => format!(+ "{filename} cannot be downloaded without a HuggingFace login (HTTP {status}). This repository is gated or private: open its page in a browser, accept the licence with your HuggingFace account, and put the file into the model folder by hand. Trying again here cannot help."+ ),+ 429 => format!(+ "The host is rate limiting this download (HTTP {status}). Wait a few minutes, then start {filename} again."+ ),+ 500..=599 => format!(+ "The host could not serve {filename} right now (HTTP {status}). That is a problem on their side — start it again in a few minutes."+ ),+ _ => format!("HTTP {status} while downloading {filename}."),+ }+}+/// Headroom left free on the drive, on top of the bytes the download needs./// Windows starts failing in ways that have nothing to do with us once the/// system drive runs dry, so the last gigabyte is never ours to take.@@ -442,6 +566,86 @@ fn gib(bytes: u64) -> String {format!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))}+/// One reqwest client, built the same way for every request this module makes.+///+/// The SSRF guard is not optional and not a per-call decision: model downloads+/// come from public catalogs, and a crafted catalog or model URL must not be+/// able to reach an internal service or 169.254.169.254 — on the first hop or+/// on any redirect.+fn download_client(connect_secs: u64, read_secs: u64) -> Result<reqwest::Client, String> {+ reqwest::Client::builder()+ .user_agent("LocallyUncensored/1.5")+ .redirect(crate::commands::proxy::ssrf_safe_redirect_policy(10))+ .connect_timeout(std::time::Duration::from_secs(connect_secs))+ .read_timeout(std::time::Duration::from_secs(read_secs))+ .build()+ .map_err(|e| os_error::english(&e))+}++/// The exact byte count the SERVER states for `url`, or None when it will not+/// state one (offline, HEAD refused, chunked transfer, a probe that errors).+///+/// This is the only trustworthy size in the whole download path. The catalog's+/// `sizeGB` is a rounded human number — "9.2" for a file of 9 874 331 648 bytes+/// — so it can size a progress bar or refuse a full drive, but it can never+/// certify that a file on disk is the whole file.+/// Short timeouts, because this runs INSIDE the install click. A machine with+/// no network must cost the user a moment, not half a minute — the answer for+/// an unreachable host is "cannot tell", and arriving at it slowly helps+/// nobody.+async fn exact_remote_size(url: &str) -> Option<u64> {+ crate::commands::proxy::validate_public_url(url).ok()?;+ let client = download_client(8, 15).ok()?;++ // A transport error means offline or a black-holed host. Retrying the same+ // unreachable address with a second request only doubles the wait.+ let head = client.head(url).send().await.ok()?;+ if head.status().is_success() {+ if let Some(n) = head.content_length() {+ if n > 0 {+ return Some(n);+ }+ }+ }++ // The host answered, just not usefully: some CDNs reply 405 to HEAD, or drop+ // the length from it. A one byte ranged GET costs one more round trip and+ // carries the whole size in Content-Range.+ let r = client.get(url).header("Range", "bytes=0-0").send().await.ok()?;+ let v = r.headers().get(reqwest::header::CONTENT_RANGE)?.to_str().ok()?;+ total_from_content_range(v)+}++/// SHA256 of the first `len` bytes of `path`.+///+/// Only needed when a transfer RESUMES with a digest to check: the bytes+/// already on disk never passed through the hasher, so without replaying them+/// the final digest would be the hash of the tail alone and every resumed+/// download would look corrupt. Reading a large partial back costs seconds;+/// throwing the partial away costs hours.+async fn digest_of_prefix(path: &Path, len: u64) -> Result<Sha256, String> {+ use tokio::io::AsyncReadExt;+ let mut f = tokio::fs::File::open(path)+ .await+ .map_err(|e| format!("Open partial file for hashing: {}", os_error::english(&e)))?;+ let mut hasher = Sha256::new();+ let mut buf = vec![0u8; 1 << 20];+ let mut done: u64 = 0;+ while done < len {+ let want = std::cmp::min(buf.len() as u64, len - done) as usize;+ let n = f+ .read(&mut buf[..want])+ .await+ .map_err(|e| format!("Read partial file for hashing: {}", os_error::english(&e)))?;+ if n == 0 {+ break;+ }+ hasher.update(&buf[..n]);+ done += n as u64;+ }+ Ok(hasher)+}+async fn do_download(url: &str,dest: &PathBuf,@@ -449,6 +653,12 @@ async fn do_download(id: &str,token: CancellationToken,resume_offset: u64,+ // Catalog estimate. Plans the space guard when the server states no length;+ // never decides that a transfer is finished.+ expected_bytes: Option<u64>,+ // Digest from the catalog entry, already normalised. `None` means the+ // content of this file cannot be verified at all.+ expected_sha256: Option<String>,) -> Result<(), String> {// SSRF guard: model downloads come from public catalogs (HuggingFace,// civitai, ollama). Block private/loopback/metadata hosts and re-validate@@ -456,22 +666,16 @@ async fn do_download(// internal service or 169.254.169.254.crate::commands::proxy::validate_public_url(url)?;- let client = reqwest::Client::builder()- .user_agent("LocallyUncensored/1.5")- .redirect(crate::commands::proxy::ssrf_safe_redirect_policy(10))- // A deadline on the whole request punishes people for having a slow- // line rather than a broken one: the 2 hour cap this replaces killed- // any download that legitimately took longer, and the catalog offers- // single files of 40 GB and sets of 155 GB. bob80817-dev, Discord- // 2026-07-29, after giving up: "all of your downloads have a habit of- // timing out". What we actually want to catch is a stalled transfer,- // so the limits are per-connect and per-read. A dead socket now fails- // in two minutes and resumes from the partial on the next attempt;- // a slow one is left to finish.- .connect_timeout(std::time::Duration::from_secs(30))- .read_timeout(std::time::Duration::from_secs(120))- .build()- .map_err(|e| os_error::english(&e))?;+ // A deadline on the whole request punishes people for having a slow line+ // rather than a broken one: the 2 hour cap this replaces killed any+ // download that legitimately took longer, and the catalog offers single+ // files of 40 GB and sets of 155 GB. bob80817-dev, Discord 2026-07-29,+ // after giving up: "all of your downloads have a habit of timing out".+ // What we actually want to catch is a stalled transfer, so the limits are+ // per-connect and per-read. A dead socket now fails in two minutes and+ // resumes from the partial on the next attempt; a slow one is left to+ // finish.+ let client = download_client(30, 120)?;let mut request = client.get(url);@@ -488,19 +692,27 @@ async fn do_download(let status = response.status();if !status.is_success() && status.as_u16() != 206 {- return Err(format!("HTTP {}", status));+ let name = dest+ .file_name()+ .map(|n| n.to_string_lossy().to_string())+ .unwrap_or_else(|| "this file".to_string());+ return Err(http_error_message(status.as_u16(), &name));}let already_on_disk = resumed_bytes(resume_offset, status.as_u16());let resumed = already_on_disk > 0;- // For resumed downloads, total = content_length + offset- let content_length = response.content_length().unwrap_or(0);- let total = if resumed {- content_length + resume_offset- } else {- content_length- };+ // For resumed downloads, total = content_length + offset. When the server+ // states no length at all the catalog estimate steps in for the space+ // guard, and `estimated` records that it must not be trusted with anything+ // else — see `total_size`.+ let (total, estimated) = total_size(response.content_length(), resume_offset, resumed, expected_bytes);+ if estimated {+ println!(+ "[Download] {} — the host states no Content-Length. Truncation cannot be detected by size; the space check falls back to the catalog estimate ({} bytes).",+ id, total+ );+ }// Stop before the first byte if the drive cannot hold the rest. Saying it// now costs nothing; finding out at the end costs the whole transfer and@@ -537,6 +749,24 @@ async fn do_download(.map_err(|e| format!("Create file: {}", os_error::english(&e)))?};+ // The digest is only computed when there is something to compare it+ // against. Hashing 155 GB to write the result into a log line nobody reads+ // costs the user real minutes of CPU, so an entry without a `sha256` says+ // so once, loudly, and skips the work.+ let mut hasher = match (&expected_sha256, resumed) {+ (None, _) => {+ println!(+ "[Download] {} — no sha256 in the catalog entry, content will NOT be verified (size only)",+ id+ );+ None+ }+ (Some(_), false) => Some(Sha256::new()),+ // Resuming: the bytes already on disk never passed through the hasher,+ // so replay them or the final digest is the hash of the tail alone.+ (Some(_), true) => Some(digest_of_prefix(&tmp_path, already_on_disk).await?),+ };+let mut stream = response.bytes_stream();let mut downloaded: u64 = already_on_disk;let start = Instant::now();@@ -573,6 +803,7 @@ async fn do_download(match chunk {Some(Ok(bytes)) => {file.write_all(&bytes).await.map_err(|e| format!("Write: {}", os_error::english(&e)))?;+ if let Some(h) = hasher.as_mut() { h.update(&bytes); }downloaded += bytes.len() as u64;// Update progress every 500ms@@ -614,12 +845,41 @@ async fn do_download(// catalog sizes (50%), so the truncated model would read as "Installed" and// only blow up much later, when the backend tries to load it. Keep the// .download part instead — the next attempt resumes from there.- if ended_early(total, downloaded) {+ //+ // `estimated` means the number in `total` is the catalog's guess, not the+ // server's statement. A guess may not fail a transfer that is in fact+ // complete, so the size check is skipped and the digest — if there is one —+ // is what stands between the user and a truncated model.+ if !estimated && ended_early(total, downloaded) {return Err(format!("Download ended early: {} of {} bytes received. Start it again to resume.",downloaded, total));}+ if estimated {+ println!(+ "[Download] {} finished at {} bytes with no size stated by the host — completeness unchecked",+ id, downloaded+ );+ }++ // Content check, when the catalog gave us something to check against. A+ // wrong file is worse than a missing one: it installs, it is listed, and it+ // blows up hours later inside a backend. So the partial goes and the error+ // names the cause instead of leaving a plausible looking model behind.+ if let (Some(expected), Some(h)) = (expected_sha256.as_deref(), hasher) {+ let actual = format!("{:x}", h.finalize());+ if actual != expected {+ let _ = tokio::fs::remove_file(&tmp_path).await;+ return Err(format!(+ "{} does not match the checksum the catalog lists for it (expected sha256 {}, got {}). The file was discarded — the download was corrupted in transit or the host is serving different content. Start it again.",+ dest.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "The file".to_string()),+ expected,+ actual,+ ));+ }+ println!("[Download] {} verified against sha256 {}", id, expected);+ }tokio::fs::rename(&tmp_path, dest).await@@ -659,6 +919,18 @@ pub fn pause_download(id: String, state: State<'_, AppState>) -> Result<serde_jsOk(serde_json::json!({"status": "pausing"}))}+/// The user aborting a transfer. Stops it AND removes the partial file.+///+/// This is one of two ways an entry leaves the progress map, and the two must+/// never be confused. Cancel is a decision: the user does not want this file,+/// so the bytes on disk go with it. `clear_download_entry` is bookkeeping: the+/// row is removed, the partial stays, and the next attempt resumes from it.+///+/// Retrying a failed download used to come through HERE, which is how a short+/// network outage on a 40 GB bundle turned into a full re-download: the error+/// text promised "start it again to resume", the user pressed the button the UI+/// offered, and the button deleted the 36 GB it was about to resume from. On a+/// bad line that never converges.#[tauri::command]pub fn cancel_download(id: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {// Cancel the token@@ -691,7 +963,7 @@ pub fn cancel_download(id: String, state: State<'_, AppState>) -> Result<serde_jif let Some(dest) = dest {if !dest.is_empty() {- let _ = std::fs::remove_file(PathBuf::from(&dest).with_extension("download"));+ remove_partial(&dest);} else if let Ok(comfy_path) = state.comfy_path.lock() {// Entry from before `dest` existed — fall back to the old guess.if let Some(ref path) = *comfy_path {@@ -706,13 +978,307 @@ pub fn cancel_download(id: String, state: State<'_, AppState>) -> Result<serde_jOk(serde_json::json!({"status": "cancelled"}))}+/// Take a SETTLED entry out of the progress map and leave the disk alone.+///+/// The counterpart to `cancel_download`. The frontend has to clear the Rust+/// entry before a retry, or `download_model` short-circuits on the file that is+/// already there, never touches the map, and the next poll resurrects the error+/// row the user just retried (the_mr_pickles). Doing that through cancel meant+/// paying for the bookkeeping with the partial file — several gigabytes for a+/// map key.+///+/// Refuses to touch a transfer that is still live: "connecting", "downloading"+/// and "pausing" own their entry, and dropping it under them would leave a+/// running tokio task writing into a file nothing knows about.+#[tauri::command]+pub fn clear_download_entry(id: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let mut dl = state+ .downloads+ .lock()+ .map_err(|_| "Download state is poisoned".to_string())?;+ match dl.get(&id) {+ Some(p) if !clearable(&p.status) => Ok(serde_json::json!({"status": "still_active"})),+ Some(_) => {+ dl.remove(&id);+ Ok(serde_json::json!({"status": "cleared"}))+ }+ None => Ok(serde_json::json!({"status": "not_found"})),+ }+}++/// May this entry be dropped from the map without stopping anything?+///+/// A live transfer owns its entry: the tokio task writes progress into it and+/// the cancel token is looked up by the same id, so removing it under a running+/// download would leave a writer nothing can reach.+pub fn clearable(status: &str) -> bool {+ !matches!(status, "connecting" | "downloading" | "pausing")+}++/// Remove the partial belonging to `dest`. Reports whether a file went.+///+/// Deliberately its own function with exactly ONE caller, `cancel_download`.+/// Deleting a partial is a user decision, never a side effect of tidying up+/// state — see the note on `cancel_download`.+fn remove_partial(dest: &str) -> bool {+ if dest.is_empty() {+ return false;+ }+ std::fs::remove_file(PathBuf::from(dest).with_extension("download")).is_ok()+}++/// Bytes that transfers already in flight still have to write.+///+/// The per-download space check answers "does the rest of THIS file fit", which+/// is the wrong question when a bundle starts four files at once: each of the+/// four passed against the same free bytes, all four started, and the drive+/// filled anyway. Whatever is still owed counts as taken.+pub fn reserved_bytes(downloads: &HashMap<String, DownloadProgress>) -> u64 {+ downloads+ .values()+ .filter(|p| matches!(p.status.as_str(), "connecting" | "downloading" | "pausing"))+ .map(|p| p.total.saturating_sub(p.progress))+ .sum()+}++/// Does `requiredBytes` still fit next to everything already in flight?+///+/// Asked ONCE for a whole bundle before the first transfer starts, which is the+/// only place the question can be answered honestly — see `reserved_bytes`.+/// Returns the numbers as well as the verdict so the caller can put real+/// gigabytes in front of the user instead of "not enough space".+#[allow(non_snake_case)]+#[tauri::command]+pub fn check_download_space(+ subfolder: Option<String>,+ destDir: Option<String>,+ requiredBytes: u64,+ state: State<'_, AppState>,+) -> Result<serde_json::Value, String> {+ let dir = match (subfolder, destDir) {+ (_, Some(d)) if !d.is_empty() => PathBuf::from(d),+ (Some(sub), _) => {+ let comfy_path = state.comfy_path.lock().unwrap().clone();+ models_dir(&comfy_path, &sub)?+ }+ _ => return Err("check_download_space needs a subfolder or a destDir".to_string()),+ };++ let reserved = state+ .downloads+ .lock()+ .map(|dl| reserved_bytes(&dl))+ .unwrap_or(0);+ let available = available_space_for(&dir);+ let shortfall = space_shortfall(requiredBytes.saturating_add(reserved), 0, available);++ Ok(match shortfall {+ None => serde_json::json!({+ "fits": true,+ "requiredBytes": requiredBytes,+ "reservedBytes": reserved,+ "availableBytes": available,+ }),+ Some((needed, free)) => serde_json::json!({+ "fits": false,+ "requiredBytes": requiredBytes,+ "reservedBytes": reserved,+ "availableBytes": available,+ "message": format!(+ "Not enough free space. This needs {} and the drive has {} free.{} Free up some space and start it again.",+ gib(needed),+ gib(free),+ if reserved > 0 {+ format!(" {} of that is already promised to downloads that are still running.", gib(reserved))+ } else {+ String::new()+ },+ ),+ }),+ })+}++/// A `.download` temp file with nobody watching it.+#[derive(serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct OrphanDownload {+ /// Basename without the `.download` suffix.+ ///+ /// NOT the download id. `Path::with_extension` REPLACES the extension, so+ /// the partial for `wan_2.1_vae.safetensors` is `wan_2.1_vae.download` and+ /// the original suffix is simply gone. The real filename is recovered on the+ /// frontend by matching this stem against the download meta it persisted and+ /// against the catalog — see `orphanFilename` in src/api/discover.ts.+ pub stem: String,+ /// Absolute path OF THE PARTIAL.+ pub path: String,+ /// Directory it sits in — the `destDir` a resume needs for a GGUF that does+ /// not live under the ComfyUI tree.+ pub dir: String,+ pub bytes: u64,+}++/// Basename minus its extension. The one place the `.download` naming rule is+/// read, so the orphan scan and the id matching cannot drift apart.+fn file_stem_of(name: &str) -> String {+ match name.rsplit_once('.') {+ Some((stem, _)) if !stem.is_empty() => stem.to_string(),+ _ => name.to_string(),+ }+}++/// Every root a `.download` file may legitimately live under.+///+/// Also the jail for `delete_orphan_download`: a path handed back to us is only+/// deleted when it still sits under one of these, so a crafted argument cannot+/// turn the sweeper into a "delete any file" command.+fn orphan_roots(state: &State<'_, AppState>, extra: &[String]) -> Vec<PathBuf> {+ let mut roots: Vec<PathBuf> = Vec::new();+ if let Ok(p) = state.comfy_path.lock() {+ if let Some(ref path) = *p {+ roots.push(PathBuf::from(path).join("models"));+ roots.push(PathBuf::from(path).join("custom_nodes"));+ }+ }+ if let Ok(p) = crate::commands::engine::builtin_models_dir() {+ roots.push(p);+ }+ // Provider model dirs (LM Studio, Ollama, a custom path) are only known to+ // the frontend, which persists the destDir of every download it started.+ for d in extra {+ if d.is_empty() {+ continue;+ }+ let p = PathBuf::from(d);+ if p.is_absolute() {+ roots.push(p);+ }+ }+ roots+}++/// Partial downloads left behind by a previous run of the app.+///+/// Both sides of the download kept their state purely in RAM, so closing the+/// app during a multi-gigabyte transfer left the `.download` file on disk with+/// no row, no button and no way to finish or remove it — the bytes were simply+/// unreachable. This is the missing half: the disk still knows what was in+/// flight, so ask it.+///+/// Entries the running app is already working on are left out: those are not+/// orphans, they have a row.+#[allow(non_snake_case)]+#[tauri::command]+pub async fn find_orphan_downloads(+ extraDirs: Option<Vec<String>>,+ state: State<'_, AppState>,+) -> Result<Vec<OrphanDownload>, String> {+ let extra = extraDirs.unwrap_or_default();+ let roots = orphan_roots(&state, &extra);+ // The map is keyed by full filename, the partial keeps only the stem, so the+ // comparison happens on stems.+ let live: Vec<String> = state+ .downloads+ .lock()+ .map(|dl| dl.keys().map(|k| file_stem_of(k)).collect())+ .unwrap_or_default();++ // Off the main thread: this runs at startup and a ComfyUI install with a+ // few dozen node packs is tens of thousands of directory entries. Freezing+ // the window to look for leftovers would be its own bug.+ tokio::task::spawn_blocking(move || scan_for_partials(roots, live))+ .await+ .map_err(|e| format!("Orphan scan failed: {}", e))+}++/// Directories that never hold a model and always hold thousands of files.+/// Skipping them is what keeps the startup scan off the user's clock.+const SCAN_SKIP: &[&str] = &[".git", "__pycache__", "node_modules", ".venv", "venv", ".cache"];++fn scan_for_partials(roots: Vec<PathBuf>, live: Vec<String>) -> Vec<OrphanDownload> {+ let mut out: Vec<OrphanDownload> = Vec::new();+ let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();+ for root in roots {+ if !root.is_dir() {+ continue;+ }+ // Depth 4 covers models/<subfolder>/<nested enum dir>/<file> and the+ // AnimateDiff pack's models dir under custom_nodes, without descending+ // into a whole ComfyUI checkout.+ let walk = walkdir::WalkDir::new(&root).max_depth(4).into_iter().filter_entry(|e| {+ !e.file_type().is_dir()+ || e.depth() == 0+ || !e.file_name().to_str().is_some_and(|n| SCAN_SKIP.contains(&n))+ });+ for entry in walk.filter_map(|e| e.ok()) {+ let p = entry.path();+ if !entry.file_type().is_file() || p.extension().and_then(|e| e.to_str()) != Some("download") {+ continue;+ }+ if !seen.insert(p.to_path_buf()) {+ continue;+ }+ let stem = match p.file_stem().and_then(|s| s.to_str()) {+ Some(s) => s.to_string(),+ None => continue,+ };+ if live.contains(&stem) {+ continue;+ }+ out.push(OrphanDownload {+ stem,+ path: p.to_string_lossy().to_string(),+ dir: p.parent().map(|d| d.to_string_lossy().to_string()).unwrap_or_default(),+ bytes: entry.metadata().map(|m| m.len()).unwrap_or(0),+ });+ }+ }+ // Biggest first: that is the one whose loss would hurt most.+ out.sort_by(|a, b| b.bytes.cmp(&a.bytes));+ out+}++/// Delete one orphaned partial, on the user's explicit say-so.+///+/// Jailed to `orphan_roots` and to the `.download` suffix, because the argument+/// travels through the frontend and back: without both checks this would be a+/// command that deletes any path the webview asks for.+#[allow(non_snake_case)]+#[tauri::command]+pub fn delete_orphan_download(+ path: String,+ extraDirs: Option<Vec<String>>,+ state: State<'_, AppState>,+) -> Result<serde_json::Value, String> {+ let p = PathBuf::from(&path);+ if p.extension().and_then(|e| e.to_str()) != Some("download") {+ return Err("Only .download partials can be removed here".to_string());+ }+ let extra = extraDirs.unwrap_or_default();+ if !orphan_roots(&state, &extra).iter().any(|r| p.starts_with(r)) {+ return Err("That path is not inside a model folder this app downloads into".to_string());+ }+ let bytes = fs::metadata(&p).map(|m| m.len()).unwrap_or(0);+ fs::remove_file(&p).map_err(|e| format!("Delete failed: {}", os_error::english(&e)))?;+ println!("[Download] Removed orphaned partial {} ({} bytes)", p.display(), bytes);+ Ok(serde_json::json!({"status": "deleted", "bytes": bytes}))+}++#[allow(non_snake_case)]#[tauri::command]pub async fn resume_download(id: String,url: String,subfolder: String,+ expectedBytes: Option<u64>,+ expectedSha256: Option<String>,state: State<'_, AppState>,) -> Result<serde_json::Value, String> {+ let expected_bytes = expectedBytes;+ let expected_sha256 = match expectedSha256.as_deref() {+ Some(s) => Some(normalize_sha256(s)?),+ None => None,+ };let comfy_path = {let p = state.comfy_path.lock().unwrap();p.clone()@@ -758,7 +1324,7 @@ pub async fn resume_download(let id_clone = id.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, expected_bytes, expected_sha256).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@ -926,25 +1492,41 @@ pub async fn download_model_to_path(destDir: String,filename: String,expectedBytes: Option<u64>,+ expectedSha256: Option<String>,state: State<'_, AppState>,) -> Result<serde_json::Value, String> {let dest_dir = destDir;let expected_bytes = expectedBytes;+ let expected_sha256 = match expectedSha256.as_deref() {+ Some(s) => Some(normalize_sha256(s)?),+ None => None,+ };let dir = PathBuf::from(&dest_dir);fs::create_dir_all(&dir).map_err(|e| format!("Create dest dir: {}", os_error::english(&e)))?;let dest_file = dir.join(sanitize_filename(&filename));if dest_file.exists() {- let file_complete = match expected_bytes {- Some(expected) if expected > 0 => {- let actual = dest_file.metadata().map(|m| m.len()).unwrap_or(0);- let threshold = (expected as f64 * 0.9) as u64;- actual >= threshold+ // Same rule as download_model: only a size the SERVER states may call a+ // file complete. The catalog estimate with 10 % of slack used to accept+ // a transfer that died at 91 %.+ let actual = dest_file.metadata().map(|m| m.len()).unwrap_or(0);+ match judge_existing(actual, exact_remote_size(&url).await) {+ Existing::Complete => {+ return Ok(serde_json::json!({"status": "exists", "path": dest_file.to_string_lossy()}));+ }+ Existing::Mismatch { actual, exact } => {+ println!(+ "[Download] {} exists with {} bytes but the host states {} — fetching it again",+ filename, actual, exact+ );+ }+ Existing::Unverified { actual } => {+ println!(+ "[Download] {} exists with {} bytes and the host states no size — accepted UNVERIFIED",+ filename, actual+ );+ return Ok(serde_json::json!({"status": "exists", "path": dest_file.to_string_lossy()}));}- _ => true,- };- if file_complete {- return Ok(serde_json::json!({"status": "exists", "path": dest_file.to_string_lossy()}));}}@@ -981,7 +1563,7 @@ pub async fn download_model_to_path(let filename_clone = filename.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, expected_bytes, expected_sha256).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@ -1106,8 +1688,15 @@ pub async fn check_model_sizes(if dest_file.exists() {let actual = dest_file.metadata().map(|m| m.len()).unwrap_or(0);// Use 50% threshold for install checks — sizeGB values are rough estimates- // (e.g. sizeGB: 0.9 for an 800 MB file). The 90% check in download_model- // handles partial downloads; this check just validates the file isn't empty/tiny.+ // (e.g. sizeGB: 0.9 for an 800 MB file), so no tighter bound is possible+ // from a catalog number alone. This answers "is there a plausible file+ // here" for the card, NOT "is this the whole file".+ //+ // The exact question is settled where it can be: download_model asks the+ // host for the byte count and compares to the byte (`judge_existing`), and+ // do_download verifies the digest when the entry carries one. The 90 %+ // rule that used to live there is gone — a threshold may size a card, it+ // may never certify a model.let threshold = if file.expected_bytes > 0 {(file.expected_bytes as f64 * 0.5) as u64} else {@@ -1182,6 +1771,229 @@ mod tests {assert_eq!(resumed_bytes(4096, 200), 0);assert_eq!(resumed_bytes(0, 206), 0);}++ /// Der Kern von Zeitbombe 3: `actual >= expected * 0.9` hat einen bei 91 %+ /// abgebrochenen Download als fertig durchgewinkt.+ #[test]+ fn an_existing_file_counts_only_at_the_exact_byte() {+ let exact = 6_000_000_000u64;+ assert_eq!(judge_existing(exact, Some(exact)), Existing::Complete);++ // 91 % — unter der alten Regel "fertig", hier genau das, was es ist.+ let at_91 = 5_460_000_000u64;+ assert_eq!(+ judge_existing(at_91, Some(exact)),+ Existing::Mismatch { actual: at_91, exact }+ );+ // Ein einziges fehlendes Byte reicht.+ assert_eq!(+ judge_existing(exact - 1, Some(exact)),+ Existing::Mismatch { actual: exact - 1, exact }+ );+ // Zu gross ist genauso falsch wie zu klein.+ assert_eq!(+ judge_existing(exact + 1, Some(exact)),+ Existing::Mismatch { actual: exact + 1, exact }+ );+ // Ohne exakte Zahl wird nichts behauptet — weder fertig noch kaputt.+ assert_eq!(judge_existing(at_91, None), Existing::Unverified { actual: at_91 });+ assert_eq!(judge_existing(at_91, Some(0)), Existing::Unverified { actual: at_91 });+ }++ #[test]+ fn a_missing_content_length_does_not_silently_disable_the_space_guard() {+ let estimate = Some(16_000_000_000u64);+ // Server nennt eine Laenge: die gilt, und sie ist keine Schaetzung.+ assert_eq!(total_size(Some(16_331_849_976), 0, false, estimate), (16_331_849_976, false));+ // Fortsetzung: der Rest plus das, was schon liegt.+ assert_eq!(total_size(Some(4_000_000_000), 12_000_000_000, true, estimate), (16_000_000_000, false));+ // Keine Laenge: der Katalogwert plant den Platz, markiert als Schaetzung.+ assert_eq!(total_size(None, 0, false, estimate), (16_000_000_000, true));+ assert_eq!(total_size(Some(0), 0, false, estimate), (16_000_000_000, true));+ // Weder Laenge noch Katalogwert: 0, und beide Guards wissen das.+ assert_eq!(total_size(None, 0, false, None), (0, true));++ // Die Schaetzung darf einen Abbruch niemals als Abbruch melden — sie+ // wuerde jeden Download bei abweichender Rundung fehlschlagen lassen.+ let (total, estimated) = total_size(None, 0, false, estimate);+ assert!(estimated);+ assert!(ended_early(total, 15_900_000_000), "die Zahl allein wuerde greifen");+ // do_download prueft deshalb `!estimated && ended_early(..)`.+ }++ #[test]+ fn the_whole_size_comes_out_of_content_range() {+ assert_eq!(total_from_content_range("bytes 0-0/12345"), Some(12345));+ assert_eq!(total_from_content_range("bytes 0-0/*"), None);+ assert_eq!(total_from_content_range("nonsense"), None);+ }++ #[test]+ fn only_a_real_digest_is_accepted() {+ // sha256 der leeren Datei, 64 Hexzeichen.+ let full = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";+ assert_eq!(full.len(), 64);+ assert_eq!(normalize_sha256(full).unwrap(), full);+ // Grossschreibung ist erlaubt, das Ergebnis ist normalisiert.+ assert_eq!(normalize_sha256(&full.to_uppercase()).unwrap(), full);+ assert_eq!(normalize_sha256(&format!(" {} ", full)).unwrap(), full);+ // Ein Tippfehler schaltet die Pruefung nicht still ab, er faellt auf.+ assert!(normalize_sha256(&full[..63]).is_err(), "63 Zeichen sind kein sha256");+ assert!(normalize_sha256(&format!("{}ab", full)).is_err());+ assert!(normalize_sha256(&format!("sha256:{}", full)).is_err());+ assert!(normalize_sha256(&full.replace('e', "z")).is_err(), "kein Hex");+ assert!(normalize_sha256("").is_err());+ }++ /// `with_extension` ERSETZT die Endung: die Teildatei zu+ /// `wan_2.1_vae.safetensors` heisst `wan_2.1_vae.download`. Wer aus dem+ /// Fundstueck den Download-Namen zurueckrechnen will, muss das wissen.+ #[test]+ fn a_partial_keeps_only_the_stem_of_its_target() {+ let dest = PathBuf::from("/models/vae/wan_2.1_vae.safetensors");+ let part = dest.with_extension("download");+ assert_eq!(part.file_name().unwrap(), "wan_2.1_vae.download");+ assert_eq!(part.file_stem().unwrap(), "wan_2.1_vae");+ assert_eq!(file_stem_of("wan_2.1_vae.safetensors"), "wan_2.1_vae");+ assert_eq!(file_stem_of("wan_2.1_vae.download"), "wan_2.1_vae");+ // Ein Name ohne Endung bleibt, wie er ist.+ assert_eq!(file_stem_of("model"), "model");+ }++ /// Der Digest muss ueber Fortsetzungen hinweg derselbe sein, sonst waere+ /// jeder wiederaufgenommene Download "korrupt".+ #[tokio::test]+ async fn a_resumed_transfer_hashes_the_bytes_that_already_lie_there() {+ let dir = tempfile::tempdir().unwrap();+ let part = dir.path().join("m.safetensors.download");+ let head = b"the first half of a model file";+ let tail = b" and the second half";+ std::fs::write(&part, head).unwrap();++ let mut resumed = digest_of_prefix(&part, head.len() as u64).await.unwrap();+ resumed.update(tail);++ let mut in_one_go = Sha256::new();+ in_one_go.update(head);+ in_one_go.update(tail);++ assert_eq!(+ format!("{:x}", resumed.finalize()),+ format!("{:x}", in_one_go.finalize()),+ );+ }++ /// 106 fest verdrahtete HuggingFace-Adressen: wird ein Repo umbenannt oder+ /// gated, ist "HTTP 404" plus Retry-Button eine Sackgasse.+ #[test]+ fn a_dead_address_says_what_happened_and_carries_its_status() {+ let gone = http_error_message(404, "wan_2.1_vae.safetensors");+ assert!(gone.contains("(HTTP 404)"), "Frontend liest genau diese Form");+ assert!(gone.contains("wan_2.1_vae.safetensors"));+ assert!(gone.to_lowercase().contains("cannot help"), "Retry darf nicht angeboten werden");++ let gated = http_error_message(403, "flux1-dev.safetensors");+ assert!(gated.contains("(HTTP 403)"));+ assert!(gated.to_lowercase().contains("login"));+ assert!(gated.to_lowercase().contains("cannot help"));++ // Voruebergehendes darf weiterhin zum Wiederholen einladen.+ let busy = http_error_message(429, "m.gguf");+ assert!(busy.contains("(HTTP 429)"));+ assert!(!busy.to_lowercase().contains("cannot help"));+ let server = http_error_message(503, "m.gguf");+ assert!(server.contains("(HTTP 503)"));+ assert!(!server.to_lowercase().contains("cannot help"));+ }++ /// Der Bundle-Fall: vier Dateien starten gleichzeitig und pruefen jede fuer+ /// sich gegen dieselben freien Bytes.+ #[test]+ fn what_is_still_owed_counts_as_taken() {+ let mut map: HashMap<String, DownloadProgress> = HashMap::new();+ let mut add = |id: &str, status: &str, progress: u64, total: u64| {+ map.insert(+ id.to_string(),+ DownloadProgress {+ progress,+ total,+ speed: 0.0,+ filename: id.into(),+ status: status.into(),+ error: None,+ dest: format!("/models/{id}"),+ },+ );+ };+ add("a.safetensors", "downloading", 1_000_000_000, 6_000_000_000);+ add("b.safetensors", "connecting", 0, 4_000_000_000);+ // Erledigtes und Fehlgeschlagenes schuldet nichts mehr.+ add("c.safetensors", "complete", 2_000_000_000, 2_000_000_000);+ add("d.safetensors", "error", 500_000_000, 3_000_000_000);++ assert_eq!(reserved_bytes(&map), 5_000_000_000 + 4_000_000_000);++ // Und daraus folgt die Absage, die die Einzelpruefung nie gegeben haette:+ // 12 GB frei, 9 GB schon versprochen, 8 GB neu angefragt.+ assert!(space_shortfall(8_000_000_000 + reserved_bytes(&map), 0, Some(12_000_000_000)).is_some());+ // Ohne Anrechnung des Laufenden waere derselbe Start durchgegangen.+ assert!(space_shortfall(8_000_000_000, 0, Some(12_000_000_000)).is_none());+ }++ /// Nach einem Neustart weiss nur noch die Platte, was unterwegs war.+ #[test]+ fn the_disk_still_knows_what_was_in_flight() {+ let root = tempfile::tempdir().unwrap();+ let vae = root.path().join("models").join("vae");+ std::fs::create_dir_all(&vae).unwrap();+ std::fs::write(vae.join("wan_2.1_vae.download"), vec![0u8; 4096]).unwrap();+ // Fertige Dateien und Rauschen gehen niemanden etwas an.+ std::fs::write(vae.join("done.safetensors"), b"x").unwrap();+ let noise = root.path().join("models").join("__pycache__");+ std::fs::create_dir_all(&noise).unwrap();+ std::fs::write(noise.join("cached.download"), b"x").unwrap();+ // Ein laufender Transfer ist kein Waisenkind.+ let unet = root.path().join("models").join("diffusion_models");+ std::fs::create_dir_all(&unet).unwrap();+ std::fs::write(unet.join("running.download"), vec![0u8; 8192]).unwrap();++ let found = scan_for_partials(+ vec![root.path().join("models")],+ vec![file_stem_of("running.gguf")],+ );++ assert_eq!(found.len(), 1, "gefunden: {:?}", found.iter().map(|o| &o.path).collect::<Vec<_>>());+ assert_eq!(found[0].stem, "wan_2.1_vae");+ assert_eq!(found[0].bytes, 4096);+ assert!(found[0].dir.ends_with("vae"), "der destDir muss mitkommen");+ }++ /// Wiederholen und Abbrechen sind zwei Wege, und nur einer raeumt auf.+ #[test]+ fn only_the_cancel_path_touches_the_partial_file() {+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("m.safetensors");+ // Wie in do_download: with_extension ersetzt die Endung.+ let part = dest.with_extension("download");+ std::fs::write(&part, b"36 GB, sozusagen").unwrap();++ // Ein fehlgeschlagener oder pausierter Eintrag darf aus der Map — das+ // ist alles, was der Retry braucht, und es fasst die Datei nicht an.+ assert!(clearable("error"));+ assert!(clearable("paused"));+ assert!(clearable("complete"));+ assert!(part.exists(), "Buchhaltung loescht keine Nutzdaten");++ // Ein laufender Transfer besitzt seinen Eintrag.+ assert!(!clearable("downloading"));+ assert!(!clearable("connecting"));+ assert!(!clearable("pausing"));++ // Nur der Abbruch raeumt, und dann wirklich.+ assert!(remove_partial(&dest.to_string_lossy()));+ assert!(!part.exists());+ assert!(!remove_partial(""), "ohne Ziel gibt es nichts zu loeschen");+ }}/// One transfer per destination file.diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 117021bb..319bbd85 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -346,6 +346,10 @@ fn main() {commands::download::download_progress,commands::download::pause_download,commands::download::cancel_download,+ commands::download::clear_download_entry,+ commands::download::check_download_space,+ commands::download::find_orphan_downloads,+ commands::download::delete_orphan_download,commands::download::resume_download,commands::download::detect_model_path,commands::download::check_model_sizes,diff --git a/src/api/__tests__/download-integrity.test.ts b/src/api/__tests__/download-integrity.test.tsnew file mode 100644index 00000000..3d52b2a0--- /dev/null+++ b/src/api/__tests__/download-integrity.test.ts@@ -0,0 +1,183 @@+/**+ * Was ein Download beweisen muss, bevor er als fertig gilt+ *+ * Drei Befunde treffen sich hier, weil sie alle in discover.ts entschieden+ * werden:+ *+ * - Es gab keine Integritaetspruefung. Die Vollstaendigkeit hing an einer+ * Dateigroesse mit 10 % Toleranz gegen einen gerundeten Katalogwert; mehrere+ * Gigabyte Modellgewichte wurden so akzeptiert. HuggingFace nennt fuer jede+ * LFS-Datei den SHA256 — der wird jetzt gelesen und durchgereicht.+ * - Der Speicherplatz-Guard lief N-mal gegen dieselben freien Bytes, weil+ * jede Bundle-Datei ihn fuer sich stellte. Die Summe ist die einzige+ * ehrliche Frage.+ * - 106 fest verdrahtete HF-Adressen ohne Liveness: bei umbenanntem oder+ * gated Repo bekam der Nutzer "HTTP 404" und einen Retry-Knopf, der nie+ * funktionieren kann.+ *+ * Run: npx vitest run src/api/__tests__/download-integrity.test.ts+ */+import { describe, it, expect } from 'vitest'+import {+ bundleBytesToFetch, isPermanentDownloadError, lfsSha256, orphanFilename,+ planModelDownload, selectGgufFromTree, getVideoBundles, getImageBundles,+ type ModelBundle, type DiscoverModel,+} from '../discover'++const GIB = 1_073_741_824++function bundle(files: Array<Partial<DiscoverModel>>, totalSizeGB = 0): ModelBundle {+ return {+ name: 'Test bundle',+ description: '',+ tags: [],+ totalSizeGB,+ vramRequired: '8 GB',+ workflow: 'wan',+ files: files.map(f => ({+ name: '', description: '', pulls: '', tags: [], updated: '',+ downloadUrl: 'https://huggingface.co/x/y/resolve/main/f.safetensors',+ subfolder: 'diffusion_models',+ ...f,+ })) as DiscoverModel[],+ }+}++describe('the bundle asks for space once, for the sum', () => {+ it('adds up every file that still has to be fetched', () => {+ const b = bundle([+ { filename: 'model.gguf', sizeGB: 16 },+ { filename: 'vae.safetensors', sizeGB: 0.3, subfolder: 'vae' },+ { filename: 'text_encoder.safetensors', sizeGB: 6.7, subfolder: 'text_encoders' },+ { filename: 'clip.safetensors', sizeGB: 1 },+ ])++ const need = bundleBytesToFetch(b, new Set())+ expect(need.files).toBe(4)+ expect(need.bytes).toBe(Math.round(24 * GIB))+ // Die alte Vorabpruefung stellte dieselbe Frage viermal mit 16, 0.3, 6.7+ // und 1 GB und liess sie alle durch — auf einer Platte mit 17 GB frei.+ expect(need.bytes).toBeGreaterThan(17 * GIB)+ })++ it('leaves out what is already on disk · sonst wird ein passender Install abgelehnt', () => {+ const b = bundle([+ { filename: 'model.gguf', sizeGB: 16 },+ { filename: 'vae.safetensors', sizeGB: 0.3, subfolder: 'vae' },+ ])+ const need = bundleBytesToFetch(b, new Set(['model.gguf']))+ expect(need.files).toBe(1)+ expect(need.bytes).toBe(Math.round(0.3 * GIB))+ expect(need.subfolder).toBe('vae')+ })++ it('falls back to the bundle total when no file states a size', () => {+ const b = bundle([{ filename: 'model.gguf' }], 9.2)+ expect(bundleBytesToFetch(b, new Set()).bytes).toBe(Math.round(9.2 * GIB))+ })++ it('asks for nothing when everything is already installed', () => {+ const b = bundle([{ filename: 'model.gguf', sizeGB: 16 }], 16)+ expect(bundleBytesToFetch(b, new Set(['model.gguf']))).toEqual({ bytes: 0, files: 0 })+ })++ it('every shipped bundle can be summed · sonst greift die Pruefung nie', () => {+ for (const b of [...getVideoBundles(), ...getImageBundles()]) {+ const need = bundleBytesToFetch(b, new Set())+ expect(need.bytes, `${b.name} hat keine plausible Gesamtgroesse`).toBeGreaterThan(0)+ expect(need.subfolder, `${b.name} hat kein Zielverzeichnis`).toBeTruthy()+ }+ })+})++describe('a dead address is not a retry', () => {+ it('recognises the statuses that can never come back', () => {+ // Genau die Form, die http_error_message in download.rs erzeugt.+ expect(isPermanentDownloadError('x.safetensors is not at this address any more (HTTP 404).')).toBe(true)+ expect(isPermanentDownloadError('needs a HuggingFace login (HTTP 403).')).toBe(true)+ expect(isPermanentDownloadError('needs a HuggingFace login (HTTP 401).')).toBe(true)+ expect(isPermanentDownloadError('gone (HTTP 410).')).toBe(true)+ })++ it('leaves everything temporary retryable', () => {+ expect(isPermanentDownloadError('The host is rate limiting this download (HTTP 429).')).toBe(false)+ expect(isPermanentDownloadError('The host could not serve it right now (HTTP 503).')).toBe(false)+ expect(isPermanentDownloadError('Download ended early: 3 of 6 bytes received.')).toBe(false)+ expect(isPermanentDownloadError('Request failed: connection reset')).toBe(false)+ expect(isPermanentDownloadError('Not enough free space for m.gguf.')).toBe(false)+ expect(isPermanentDownloadError(undefined)).toBe(false)+ expect(isPermanentDownloadError('')).toBe(false)+ // Eine 404 in einer URL ist kein Status.+ expect(isPermanentDownloadError('https://host/404/model.gguf failed')).toBe(false)+ })+})++describe('the digest HuggingFace already publishes', () => {+ it('reads the sha256 out of the LFS pointer', () => {+ const oid = 'b'.repeat(64)+ const files = selectGgufFromTree(+ [{ type: 'file', path: 'model-Q4_K_M.gguf', size: 4_000_000_000, lfs: { oid, size: 4_000_000_000 } }],+ 'unsloth/whatever',+ )+ expect(files?.files[0].sha256).toBe(oid)+ })++ it('refuses a git blob hash · 40 Hexzeichen sind kein Inhalts-Digest', () => {+ expect(lfsSha256({ type: 'file', path: 'x.gguf', lfs: { oid: 'c'.repeat(40) } })).toBeUndefined()+ expect(lfsSha256({ type: 'file', path: 'x.gguf' })).toBeUndefined()+ expect(lfsSha256({ type: 'file', path: 'x.gguf', lfs: { oid: 'not hex at all' } })).toBeUndefined()+ // Grossschreibung normalisiert, statt die Pruefung wegzuwerfen.+ expect(lfsSha256({ type: 'file', path: 'x.gguf', lfs: { oid: 'D'.repeat(64) } })).toBe('d'.repeat(64))+ })++ it('carries the digest into the download plan', () => {+ const sha = 'e'.repeat(64)+ const model: DiscoverModel = {+ name: 'M', description: '', pulls: '', tags: [], updated: '',+ downloadUrl: 'https://huggingface.co/x/y/resolve/main/m.gguf', filename: 'm.gguf', sha256: sha,+ }+ const plan = planModelDownload(model, model.downloadUrl!, 'm.gguf', 100)+ expect(plan[0].sha256).toBe(sha)+ })++ it('drops the catalog digest when the HF tree corrected the URL', () => {+ // Sonst wuerde der Hash einer anderen Datei gegen diese geprueft und JEDER+ // Download dieses Modells als korrupt geloescht.+ const model: DiscoverModel = {+ name: 'M', description: '', pulls: '', tags: [], updated: '',+ downloadUrl: 'https://huggingface.co/x/y/resolve/main/guessed.gguf', filename: 'guessed.gguf',+ sha256: 'f'.repeat(64),+ }+ const plan = planModelDownload(model, 'https://huggingface.co/x/y/resolve/main/Q4_K_M/real.gguf', 'real.gguf', 100)+ expect(plan[0].sha256).toBeUndefined()+ // Der aufgeloeste Hash gewinnt, wenn es einen gibt.+ const resolved = planModelDownload(model, 'https://other/real.gguf', 'real.gguf', 100, 'a'.repeat(64))+ expect(resolved[0].sha256).toBe('a'.repeat(64))+ })++ it('never hands the model digest to its vision projector', () => {+ const model: DiscoverModel = {+ name: 'M', description: '', pulls: '', tags: [], updated: '',+ downloadUrl: 'https://huggingface.co/x/y/resolve/main/m.gguf', filename: 'm.gguf',+ sha256: 'a'.repeat(64), mmprojUrl: 'https://huggingface.co/x/y/resolve/main/mmproj.gguf', mmprojSizeGB: 1,+ }+ const plan = planModelDownload(model, model.downloadUrl!, 'm.gguf', 100)+ expect(plan).toHaveLength(2)+ expect(plan[1].sha256).toBeUndefined()+ })+})++describe('recovering the name of an orphaned partial', () => {+ it('matches the stem back to the real filename', () => {+ // with_extension ERSETZT die Endung: aus wan_2.1_vae.safetensors wird+ // wan_2.1_vae.download, der Rest steht nirgends mehr auf der Platte.+ const known = ['wan_2.1_vae.safetensors', 'umt5_xxl_fp8_e4m3fn_scaled.safetensors']+ expect(orphanFilename('wan_2.1_vae', known)).toBe('wan_2.1_vae.safetensors')+ expect(orphanFilename('umt5_xxl_fp8_e4m3fn_scaled', known)).toBe('umt5_xxl_fp8_e4m3fn_scaled.safetensors')+ expect(orphanFilename('something_else', known)).toBeNull()+ })++ it('takes an exact hit too · nicht jeder Name hat eine Endung', () => {+ expect(orphanFilename('model', ['model'])).toBe('model')+ })+})diff --git a/src/api/discover.ts b/src/api/discover.tsindex 84655264..edf22114 100644--- a/src/api/discover.ts+++ b/src/api/discover.ts@@ -45,6 +45,21 @@ export interface DiscoverModel {// Optional hand-written one-liner for the card. When absent the card derives// a short line from `description` (text after the first "·", first sentence).blurb?: string+ /**+ * SHA256 of the file at `downloadUrl`, 64 hex characters.+ *+ * The only thing that can tell a complete multi-gigabyte model from a+ * plausible-looking truncated one. `sizeGB` cannot: it is a rounded human+ * number ("9.2"), which is why the old completeness check ran on a 10 %+ * tolerance and accepted a download that died at 91 %.+ *+ * Optional on purpose. HuggingFace states this digest for every LFS file+ * (`lfs.oid` in the tree API, which `resolveHfGgufFiles` now reads), but the+ * hand-written catalog entries below carry none yet. When it is absent the+ * download is checked against the server's exact byte count and the Rust side+ * logs, per file, that the CONTENT went unverified.+ */+ sha256?: string}export interface DownloadProgress {@@ -58,8 +73,8 @@ export interface DownloadProgress {// ─── Download API ───-export async function startModelDownload(url: string, subfolder: string, filename: string, expectedBytes?: number): Promise<{ status: string; id: string; error?: string }> {- return backendCall("download_model", { url, subfolder, filename, expectedBytes: expectedBytes ?? null })+export async function startModelDownload(url: string, subfolder: string, filename: string, expectedBytes?: number, sha256?: string): Promise<{ status: string; id: string; error?: string }> {+ return backendCall("download_model", { url, subfolder, filename, expectedBytes: expectedBytes ?? null, expectedSha256: sha256 ?? null })}export async function getDownloadProgress(): Promise<Record<string, DownloadProgress>> {@@ -74,12 +89,140 @@ export async function pauseDownload(id: string): Promise<void> {await backendCall("pause_download", { id })}+/**+ * The user aborting a transfer: stops it AND deletes the partial file.+ *+ * Not the same thing as `clearDownloadEntry`, and the two must never be swapped+ * again. `retry()` used to come through here, so a short outage on a 40 GB+ * bundle cost the whole download: the error text said "start it again to+ * resume", the UI offered Retry, and Retry deleted the bytes it was about to+ * resume from.+ */export async function cancelDownload(id: string): Promise<void> {await backendCall("cancel_download", { id })}-export async function resumeDownload(id: string, url: string, subfolder: string): Promise<void> {- await backendCall("resume_download", { id, url, subfolder })+/**+ * Drop a settled row (error / paused / complete) from the Rust progress map and+ * LEAVE THE PARTIAL FILE ALONE.+ *+ * Clearing the Rust side is not optional before a retry: `download_model`+ * short-circuits on a file that is already on disk without ever touching the+ * map, so the next poll would resurrect the error row the user just retried+ * (the_mr_pickles). That bookkeeping is all this does — it is not a decision+ * about the user's bytes.+ */+export async function clearDownloadEntry(id: string): Promise<void> {+ await backendCall("clear_download_entry", { id })+}++/** Statuses that mean the address itself is dead, so Retry cannot work. */+const PERMANENT_HTTP = /\(HTTP (401|403|404|410)\)/++/**+ * Would pressing Retry on this error ever succeed?+ *+ * The catalog hard-codes 106 HuggingFace addresses. When one of those repos is+ * renamed, gated or taken down, every attempt answers the same 404/403 forever,+ * and the old UI answered with a bare "HTTP 404" and a Retry button — a loop+ * with no exit. The status code inside the message is the contract; it is put+ * there by `http_error_message` in src-tauri/src/commands/download.rs.+ *+ * A transport error, a rate limit and a 5xx are all temporary and stay+ * retryable: only an address that is gone is permanent.+ */+export function isPermanentDownloadError(error?: string | null): boolean {+ return !!error && PERMANENT_HTTP.test(error)+}++export async function resumeDownload(id: string, url: string, subfolder: string, expectedBytes?: number, sha256?: string): Promise<void> {+ await backendCall("resume_download", { id, url, subfolder, expectedBytes: expectedBytes ?? null, expectedSha256: sha256 ?? null })+}++/** A `.download` partial from an earlier run of the app, with no row watching it. */+export interface OrphanDownload {+ /** Basename minus its extension — NOT the download id. See `orphanFilename`. */+ stem: string+ /** Absolute path of the partial. */+ path: string+ /** Directory it sits in; a GGUF outside the ComfyUI tree resumes into this. */+ dir: string+ bytes: number+}++/**+ * Partial downloads a previous run of the app left behind.+ *+ * Both halves of the download kept their state purely in RAM, so quitting+ * during a multi-gigabyte transfer left the `.download` file on disk with no+ * row, no button and no way to finish or delete it. `extraDirs` carries the+ * provider model folders only the frontend knows (LM Studio, a custom path),+ * taken from the download meta the store now persists.+ */+export async function findOrphanDownloads(extraDirs: string[] = []): Promise<OrphanDownload[]> {+ try {+ return await backendCall("find_orphan_downloads", { extraDirs })+ } catch (err) {+ log.warn('[discover] orphan scan failed', { err })+ return []+ }+}++/** Delete one orphaned partial. Jailed to the model folders on the Rust side. */+export async function deleteOrphanDownload(path: string, extraDirs: string[] = []): Promise<void> {+ await backendCall("delete_orphan_download", { path, extraDirs })+}++/**+ * Recover the download id (the real filename) for an orphaned partial.+ *+ * `Path::with_extension("download")` REPLACES the extension, so the partial for+ * `wan_2.1_vae.safetensors` is `wan_2.1_vae.download`: the original suffix is+ * not on disk any more. Everything that can name the file lives up here — the+ * persisted download meta first, because it also knows the destDir, then the+ * catalog. A stem nothing recognises stays unresolved; it can still be shown+ * and deleted, just not resumed.+ */+export function orphanFilename(stem: string, knownFilenames: Iterable<string>): string | null {+ for (const name of knownFilenames) {+ if (name === stem || name.replace(/\.[^.]+$/, '') === stem) return name+ }+ return null+}++/** Verdict of the ONE space check a bundle gets before its first transfer. */+export interface SpaceVerdict {+ fits: boolean+ requiredBytes: number+ reservedBytes: number+ availableBytes?: number | null+ message?: string+}++/**+ * Does `requiredBytes` still fit, counting what running transfers still owe?+ *+ * Asked once for a whole bundle. The per-file check in `do_download` answers+ * "does the rest of THIS file fit", which is the wrong question when four files+ * start at the same moment: all four passed against the same free bytes, all+ * four started, and the drive filled anyway — on Windows a full system+ * partition degrades the whole machine, not just the download.+ */+export async function checkDownloadSpace(+ target: { subfolder?: string; destDir?: string },+ requiredBytes: number,+): Promise<SpaceVerdict | null> {+ try {+ return await backendCall("check_download_space", {+ subfolder: target.subfolder ?? null,+ destDir: target.destDir ?? null,+ requiredBytes: Math.max(0, Math.round(requiredBytes)),+ })+ } catch (err) {+ // A drive we cannot measure must never block a download.+ log.warn('[discover] space check unavailable', { err })+ return null+ }}// ─── Custom Node Installation ───@@ -429,6 +572,33 @@ async function runVisibilityConfirmation(filename: string): Promise<void> {}}+/** One gibibyte, the unit the catalog's `sizeGB` and every size message use. */+const GIB = 1_073_741_824++/**+ * How many bytes this bundle still has to fetch, and where they land.+ *+ * Pure, so the sum can be tested without a drive. Files already on disk are+ * left out — re-checking space for a file that is not going to be fetched would+ * refuse installs that fit perfectly well. `totalSizeGB` is the fallback when+ * the per-file sizes are missing: a rough number is a far better plan than+ * planning for nothing, and it is only ever used to refuse, never to promise.+ */+export function bundleBytesToFetch(+ bundle: ModelBundle,+ installed: Set<string>,+): { bytes: number; subfolder?: string; files: number } {+ const pending = bundle.files.filter(+ f => f.downloadUrl && f.filename && f.subfolder && !installed.has(f.filename),+ )+ if (pending.length === 0) return { bytes: 0, files: 0 }+ const known = pending.reduce((sum, f) => sum + (f.sizeGB ? f.sizeGB * GIB : 0), 0)+ // Not one file states a size: fall back to the bundle total, minus nothing,+ // because we cannot tell which part of it is already there.+ const bytes = known > 0 ? known : (bundle.totalSizeGB || 0) * GIB+ return { bytes: Math.round(bytes), subfolder: pending[0].subfolder, files: pending.length }+}+export async function installBundleComplete(bundle: ModelBundle): Promise<void> {const errors: string[] = []@@ -489,6 +659,21 @@ export async function installBundleComplete(bundle: ModelBundle): Promise<void>return left.length === 0}+ // ONE space check for the whole bundle, before the first byte moves.+ //+ // Every file starts its own transfer and every transfer checked the free+ // space on its own, so a four file bundle passed the same free bytes four+ // times over and then filled the drive between them. The sum is the only+ // honest question, and it has to be asked before anything starts: refusing+ // file three after files one and two have written 20 GB helps nobody.+ const pendingBytes = bundleBytesToFetch(bundle, installedFiles)+ if (pendingBytes.bytes > 0 && pendingBytes.subfolder) {+ const verdict = await checkDownloadSpace({ subfolder: pendingBytes.subfolder }, pendingBytes.bytes)+ if (verdict && !verdict.fits) {+ throw new Error(verdict.message || `${bundle.name} does not fit on this drive.`)+ }+ }+// Step 1: Start downloads only for files NOT already installedfor (const file of bundle.files) {if (!file.downloadUrl || !file.filename || !file.subfolder) continue@@ -504,7 +689,7 @@ export async function installBundleComplete(bundle: ModelBundle): Promise<void>}try {const expectedBytes = file.sizeGB ? Math.round(file.sizeGB * 1_073_741_824) : undefined- const result = await startModelDownload(file.downloadUrl, file.subfolder, file.filename, expectedBytes)+ const result = await startModelDownload(file.downloadUrl, file.subfolder, file.filename, expectedBytes, file.sha256)if (result.status === 'exists') {// File already on disk · emit synthetic 'complete' so UI reflects itwindow.dispatchEvent(new CustomEvent('comfyui-download-exists', { detail: { filename: file.filename } }))@@ -693,6 +878,8 @@ export interface PlannedDownload {url: stringfilename: stringexpectedBytes?: number+ /** Content digest, when the catalog or the HF tree stated one. */+ sha256?: string}/**@@ -705,8 +892,11 @@ export interface PlannedDownload {* this model need a second file, and what is it called" decision is unit* testable without rendering the Models tab.*/-export function planModelDownload(model: DiscoverModel, url: string, filename: string, bytes?: number): PlannedDownload[] {- const plan: PlannedDownload[] = [{ url, filename, expectedBytes: bytes }]+export function planModelDownload(model: DiscoverModel, url: string, filename: string, bytes?: number, sha256?: string): PlannedDownload[] {+ // The resolved digest wins over the catalog's: `url` may have been corrected+ // by the HF tree, and a digest that belongs to a different file is worse than+ // none at all.+ const plan: PlannedDownload[] = [{ url, filename, expectedBytes: bytes, sha256: sha256 ?? (url === model.downloadUrl ? model.sha256 : undefined) }]if (model.mmprojUrl) {plan.push({url: model.mmprojUrl,@@ -1123,9 +1313,24 @@ export async function searchHuggingFaceModels(query: string): Promise<DiscoverMo// 3. The guessed single-file name simply doesn't exist (404).// Resolving against the real tree fixes all three.-export interface HfTreeEntry { type: string; path: string; size?: number }+/**+ * One entry of `/api/models/<repo>/tree/main`.+ *+ * `lfs.oid` is the SHA256 of the file content — every GGUF and safetensors file+ * on HuggingFace is stored via LFS, so this is a free, authoritative digest for+ * exactly the files that are too big to re-download by accident.+ */+export interface HfTreeEntry { type: string; path: string; size?: number; lfs?: { oid?: string; size?: number } }++export interface HfGgufFile { url: string; filename: string; sizeBytes: number; sha256?: string }-export interface HfGgufFile { url: string; filename: string; sizeBytes: number }+/** A 64 hex character digest, or undefined. HF prefixes nothing, but a repo can+ * carry a non-LFS pointer whose oid is a git blob hash (40 hex) — that one is+ * NOT a content digest and must not be handed on as one. */+export function lfsSha256(entry: HfTreeEntry): string | undefined {+ const oid = entry.lfs?.oid?.trim().toLowerCase()+ return oid && /^[0-9a-f]{64}$/.test(oid) ? oid : undefined+}export interface HfGgufResolution {sharded: boolean@@ -1187,6 +1392,7 @@ export function selectGgufFromTree(url: `https://huggingface.co/${repoId}/resolve/main/${p.path}`,filename: p.path.split('/').pop() as string,sizeBytes: p.size || 0,+ sha256: lfsSha256(p),}))return {sharded: files.length > 1,@@ -1234,29 +1440,52 @@ export async function detectProviderModelPath(providerName: string): Promise<str}/** Download a GGUF model to a specific directory (for non-Ollama providers) */-export async function startModelDownloadToPath(url: string, destDir: string, filename: string, expectedBytes?: number): Promise<{ status: string; id: string; error?: string }> {- return backendCall('download_model_to_path', { url, destDir, filename, expectedBytes: expectedBytes ?? null })+export async function startModelDownloadToPath(url: string, destDir: string, filename: string, expectedBytes?: number, sha256?: string): Promise<{ status: string; id: string; error?: string }> {+ return backendCall('download_model_to_path', { url, destDir, filename, expectedBytes: expectedBytes ?? null, expectedSha256: sha256 ?? null })}-/** Look up download URL + subfolder for a file by filename · searches all bundles + text models */-export function lookupFileMeta(filename: string): { url: string; subfolder: string } | null {- // Search image + video + 2.5.8 specialized-lane bundles+/** What the catalog knows about one downloadable file. */+export interface FileMeta {+ url: string+ subfolder: string+ expectedBytes?: number+ sha256?: string+}++/** Every catalog entry that carries a downloadable file, image/video bundles+ * and text models alike. One walk, so the lookups below cannot drift apart. */+function catalogEntries(): DiscoverModel[] {+ const out: DiscoverModel[] = []for (const bundle of [...getImageBundles(), ...getVideoBundles(), ...getAudioBundles(), ...getLipsyncBundles(), ...getMotionBundles()]) {- for (const f of bundle.files) {- if (f.filename === filename && f.downloadUrl && f.subfolder) {- return { url: f.downloadUrl, subfolder: f.subfolder }- }- }+ out.push(...bundle.files)}- // Search text models- for (const m of [...getUncensoredTextModels(), ...getMainstreamTextModels()]) {+ out.push(...getUncensoredTextModels(), ...getMainstreamTextModels())+ return out+}++/** Look up download URL + subfolder for a file by filename · searches all bundles + text models */+export function lookupFileMeta(filename: string): FileMeta | null {+ for (const m of catalogEntries()) {if (m.filename === filename && m.downloadUrl && m.subfolder) {- return { url: m.downloadUrl, subfolder: m.subfolder }+ return {+ url: m.downloadUrl,+ subfolder: m.subfolder,+ expectedBytes: m.sizeGB ? Math.round(m.sizeGB * GIB) : undefined,+ sha256: m.sha256,+ }}}return null}+/** Every filename the catalog can name. Used to turn an orphaned partial's+ * stem back into a real download id — see `orphanFilename`. */+export function catalogFilenames(): string[] {+ const names: string[] = []+ for (const m of catalogEntries()) if (m.filename) names.push(m.filename)+ return names+}+// ─── Image Model Bundles ───export function getImageBundles(): ModelBundle[] {diff --git a/src/components/layout/DownloadBadge.tsx b/src/components/layout/DownloadBadge.tsxindex 796c5bef..358221ed 100644--- a/src/components/layout/DownloadBadge.tsx+++ b/src/components/layout/DownloadBadge.tsx@@ -4,6 +4,7 @@ import { motion, AnimatePresence } from 'framer-motion'import { ArrowDownToLine, Pause, Play, X, CheckCircle, RotateCcw } from 'lucide-react'import { useModels } from '../../hooks/useModels'import { useDownloadStore } from '../../stores/downloadStore'+import { isPermanentDownloadError } from '../../api/discover'import { useMlxInstallStore } from '../../stores/mlxInstallStore'import { isMlxImageHost } from '../../api/mlx-image'import { formatBytes } from '../../lib/formatters'@@ -200,6 +201,18 @@ export function DownloadBadge() {const bundleProg = totalBytes > 0 ? (doneBytes / totalBytes) * 100 : 0const bundleSpeed = files.reduce((s, f) => s + (f.d.status === 'downloading' ? (f.d.speed || 0) : 0), 0)const isBundle = files.length > 1+ // A renamed, gated or deleted repository answers the same way+ // every time, so Retry is not a way out of it — offering the+ // button anyway is a loop with no exit. Only the failures that+ // could plausibly go differently get one; the rest get the+ // reason, which says what to do instead.+ const retryable = files.filter(f => f.d.status === 'error' && !isPermanentDownloadError(f.d.error))+ const dead = files.filter(f => f.d.status === 'error' && isPermanentDownloadError(f.d.error))+ // Bytes on disk waiting for the rest — a paused transfer, or a+ // partial this session adopted from an earlier run. Without a+ // Resume here those files had no way forward at all.+ const resumable = files.filter(f => f.d.status === 'paused')+ const anyActive = files.some(f => f.d.status === 'downloading' || f.d.status === 'connecting' || f.d.status === 'pausing')return (<div key={bundleName} className="px-3 py-2 border-t border-gray-100 dark:border-white/[0.04] first:border-t-0">@@ -207,8 +220,11 @@ export function DownloadBadge() {<div className="flex items-center justify-between gap-2 mb-1"><p className={`${isBundle ? 'text-[0.7rem] font-medium' : 'text-[0.7rem] font-mono'} text-gray-700 dark:text-gray-300 truncate`}>{bundleName}</p><div className="flex items-center gap-0.5 shrink-0">- {files.some(f => f.d.status === 'error') && (- <button onClick={() => files.filter(f => f.d.status === 'error').forEach(f => useDownloadStore.getState().retry(f.id))} className="p-0.5 rounded hover:bg-red-500/20 text-red-400 hover:text-red-300 transition-colors" title="Retry failed"><RotateCcw size={11} /></button>+ {resumable.length > 0 && !anyActive && (+ <button onClick={() => resumable.forEach(f => useDownloadStore.getState().resume(f.id))} className="p-0.5 rounded hover:bg-white/10 text-gray-500 hover:text-gray-300 transition-colors" title="Resume"><Play size={11} /></button>+ )}+ {retryable.length > 0 && (+ <button onClick={() => retryable.forEach(f => useDownloadStore.getState().retry(f.id))} className="p-0.5 rounded hover:bg-red-500/20 text-red-400 hover:text-red-300 transition-colors" title="Retry failed"><RotateCcw size={11} /></button>)}{allComplete ? (<button onClick={() => files.forEach(f => useDownloadStore.getState().dismiss(f.id))} className="p-0.5 rounded hover:bg-white/10 text-gray-500 hover:text-gray-300 transition-colors" title="Dismiss"><X size={11} /></button>@@ -230,9 +246,9 @@ export function DownloadBadge() {{bundleSpeed > 0 && <span className="ml-1.5 text-gray-400">{formatBytes(bundleSpeed)}/s</span>}</p>{/* Retry all failed files in bundle */}- {files.some(f => f.d.status === 'error') && (+ {retryable.length > 0 && (<button- onClick={() => files.filter(f => f.d.status === 'error').forEach(f => useDownloadStore.getState().retry(f.id))}+ onClick={() => retryable.forEach(f => useDownloadStore.getState().retry(f.id))}className="flex items-center gap-1 text-[0.55rem] text-red-400 hover:text-red-300 transition-colors"title="Retry failed downloads">@@ -241,6 +257,11 @@ export function DownloadBadge() {</button>)}</div>+ {/* A dead address has no button, so it has to have the+ reason: what happened and what to do instead. */}+ {dead.map(f => (+ <p key={f.id} className="mt-1 text-[0.55rem] text-red-400 break-words whitespace-pre-line">{f.d.error}</p>+ ))}{/* Individual file rows */}{isBundle && (<div className="mt-1.5 space-y-0.5">@@ -249,6 +270,9 @@ export function DownloadBadge() {<span className="truncate flex-1 font-mono">{d.filename || id}</span><span className="shrink-0 ml-2 flex items-center gap-1">{d.status === 'complete' ? <span className="text-green-400">Done</span>+ : d.status === 'error' && isPermanentDownloadError(d.error) ? (+ <span className="text-red-400" title={d.error}>Unavailable</span>+ ): d.status === 'error' ? (<buttononClick={() => useDownloadStore.getState().retry(id)}@@ -259,7 +283,16 @@ export function DownloadBadge() {<span>Retry</span></button>)- : d.status === 'paused' ? <span className="text-yellow-400">Paused</span>+ : d.status === 'paused' ? (+ <button+ onClick={() => useDownloadStore.getState().resume(id)}+ className="flex items-center gap-0.5 text-yellow-400 hover:text-yellow-300 transition-colors"+ title="Resume this download"+ >+ <Play size={8} />+ <span>Resume</span>+ </button>+ ): d.total > 0 ? <>{Math.round((d.progress / d.total) * 100)}%{d.speed > 0 && <span className="ml-1 text-gray-400">{formatBytes(d.speed)}/s</span>}</>: d.status === 'connecting' ? 'Connecting' : '...'}</span>diff --git a/src/stores/__tests__/downloadStore-orphans.test.ts b/src/stores/__tests__/downloadStore-orphans.test.tsnew file mode 100644index 00000000..38456cb5--- /dev/null+++ b/src/stores/__tests__/downloadStore-orphans.test.ts@@ -0,0 +1,190 @@+/**+ * Was ein Neustart vom Download uebrig laesst+ *+ * Beide Seiten hielten den Download-Zustand rein im Speicher. Ein Neustart der+ * App waehrend eines Multi-GB-Transfers hinterliess damit eine `.download`-Datei+ * ohne Zeile, ohne Knopf und ohne Weg zurueck — und, schlimmer, ohne den+ * `destDir`, den der Retry braucht: ein GGUF-Textmodell landete danach in einem+ * Verzeichnis, in dem kein Backend es findet.+ *+ * Hier wird beides geprueft: dass die Metadaten den Neustart ueberleben, und+ * dass die gefundenen Teildateien wieder als fortsetzbare Zeilen auftauchen.+ *+ * Run: npx vitest run src/stores/__tests__/downloadStore-orphans.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++// zustand/persist writes through `localStorage`, and the store picks its+// backing store up at module scope. In the node test env the shim therefore has+// to exist BEFORE the import runs — vi.hoisted is the only thing that gets+// ahead of an ESM import. Without it persist silently no-ops and this file+// would prove nothing.+//+// Deliberately NOT shimming `window`: the store registers real event listeners+// behind a `typeof window` check, and a half-faked window breaks the import.+vi.hoisted(() => {+ const backing = new Map<string, string>()+ ;(globalThis as any).localStorage = {+ getItem: (k: string) => backing.get(k) ?? null,+ setItem: (k: string, v: string) => void backing.set(k, String(v)),+ removeItem: (k: string) => void backing.delete(k),+ clear: () => backing.clear(),+ key: (i: number) => [...backing.keys()][i] ?? null,+ get length() { return backing.size },+ }+})++const findOrphanDownloads = vi.fn(async (_extra: string[]) => [] as any[])+const deleteOrphanDownload = vi.fn(async () => {})+const resumeDownload = vi.fn(async () => {})+const getDownloadProgress = vi.fn(async () => ({} as Record<string, any>))++vi.mock('../../api/discover', async () => {+ const actual = await vi.importActual<typeof import('../../api/discover')>('../../api/discover')+ return {+ getDownloadProgress: (...a: any[]) => getDownloadProgress(...(a as [])),+ pauseDownload: vi.fn(async () => {}),+ cancelDownload: vi.fn(async () => {}),+ clearDownloadEntry: vi.fn(async () => {}),+ resumeDownload: (...a: any[]) => resumeDownload(...(a as [])),+ startModelDownload: vi.fn(async () => {}),+ startModelDownloadToPath: vi.fn(async () => {}),+ lookupFileMeta: () => undefined,+ findOrphanDownloads: (...a: any[]) => findOrphanDownloads(...(a as [any])),+ deleteOrphanDownload: (...a: any[]) => deleteOrphanDownload(...(a as [])),+ catalogFilenames: () => ['wan_2.1_vae.safetensors'],+ orphanFilename: actual.orphanFilename,+ isPermanentDownloadError: actual.isPermanentDownloadError,+ modelsNotVisibleInComfy: vi.fn(async () => []),+ ENUM_SUBFOLDERS: actual.ENUM_SUBFOLDERS,+ }+})++import { useDownloadStore, orphanRows, flushDownloadPersist } from '../downloadStore'++const GGUF_DIR = '/Users/x/.lmstudio/models'++beforeEach(() => {+ vi.clearAllMocks()+ useDownloadStore.setState({ downloads: {}, downloadMeta: {}, orphans: {}, bundleMap: {} })+ useDownloadStore.getState().stopPolling()+})++describe('download meta survives a restart', () => {+ it('persists url, subfolder AND destDir', async () => {+ useDownloadStore.getState().setMeta('m.gguf', 'https://example.test/m.gguf', 'gguf', GGUF_DIR, {+ expectedBytes: 4_000_000_000,+ sha256: 'a'.repeat(64),+ })+ // Der Schreibvorgang ist gebuendelt (der Poller setzt einmal pro Sekunde);+ // beim Schliessen der App wird genauso geflusht.+ await flushDownloadPersist()++ const raw = localStorage.getItem('locally-uncensored-downloads')+ expect(raw, 'nichts geschrieben — der Neustart verliert alles').toBeTruthy()+ const stored = JSON.parse(raw as string)+ expect(stored.state.downloadMeta['m.gguf']).toEqual({+ url: 'https://example.test/m.gguf',+ subfolder: 'gguf',+ // Ohne destDir faellt der Retry auf den subfolder-Zweig zurueck und+ // schreibt das Modell dorthin, wo kein Backend es sucht.+ destDir: GGUF_DIR,+ expectedBytes: 4_000_000_000,+ sha256: 'a'.repeat(64),+ })+ // Der Live-Zustand gehoert Rust und darf nicht mitgeschrieben werden:+ // "downloading" ohne laufenden Transfer waere eine Luege nach dem Start.+ expect(stored.state.downloads).toBeUndefined()+ expect(stored.state.orphans).toBeUndefined()+ expect(stored.version).toBe(1)+ })+})++describe('orphaned partials', () => {+ it('turns a leftover .download into a resumable row', async () => {+ findOrphanDownloads.mockResolvedValueOnce([+ { stem: 'wan_2.1_vae', path: '/comfy/models/vae/wan_2.1_vae.download', dir: '/comfy/models/vae', bytes: 9_000_000_000 },+ ])++ await useDownloadStore.getState().scanOrphans()++ // `with_extension` ersetzt die Endung, der Stamm allein steht auf der+ // Platte — der echte Name kommt aus Meta bzw. Katalog zurueck.+ const orphan = useDownloadStore.getState().orphans['wan_2.1_vae']+ expect(orphan.filename).toBe('wan_2.1_vae.safetensors')++ const row = useDownloadStore.getState().downloads['wan_2.1_vae.safetensors']+ expect(row?.status).toBe('paused')+ expect(row?.progress).toBe(9_000_000_000)+ })++ it('hands the persisted destDirs to the scan · a GGUF lives outside the ComfyUI tree', async () => {+ useDownloadStore.getState().setMeta('m.gguf', 'https://example.test/m.gguf', 'gguf', GGUF_DIR)+ await useDownloadStore.getState().scanOrphans()++ expect(findOrphanDownloads).toHaveBeenCalledWith([GGUF_DIR])+ })++ it('lists a partial it cannot name, but never offers to resume it', async () => {+ findOrphanDownloads.mockResolvedValueOnce([+ { stem: 'something-a-user-dropped-here', path: '/comfy/models/vae/x.download', dir: '/comfy/models/vae', bytes: 12 },+ ])+ await useDownloadStore.getState().scanOrphans()++ expect(useDownloadStore.getState().orphans['something-a-user-dropped-here'].filename).toBeNull()+ expect(Object.keys(useDownloadStore.getState().downloads)).toHaveLength(0)+ await useDownloadStore.getState().resumeOrphan('something-a-user-dropped-here')+ expect(resumeDownload).not.toHaveBeenCalled()+ })++ it('a live transfer takes the row back from the adopted orphan', async () => {+ findOrphanDownloads.mockResolvedValueOnce([+ { stem: 'wan_2.1_vae', path: '/comfy/models/vae/wan_2.1_vae.download', dir: '/comfy/models/vae', bytes: 9_000_000_000 },+ ])+ await useDownloadStore.getState().scanOrphans()++ getDownloadProgress.mockResolvedValueOnce({+ 'wan_2.1_vae.safetensors': {+ progress: 9_500_000_000, total: 12_000_000_000, speed: 5_000_000,+ filename: 'wan_2.1_vae.safetensors', status: 'downloading',+ },+ })+ await useDownloadStore.getState().refresh()++ expect(useDownloadStore.getState().downloads['wan_2.1_vae.safetensors'].status).toBe('downloading')+ expect(useDownloadStore.getState().orphans['wan_2.1_vae']).toBeUndefined()+ useDownloadStore.getState().stopPolling()+ })++ it('discarding one deletes the file and drops the row for good', async () => {+ findOrphanDownloads.mockResolvedValueOnce([+ { stem: 'wan_2.1_vae', path: '/comfy/models/vae/wan_2.1_vae.download', dir: '/comfy/models/vae', bytes: 9_000_000_000 },+ ])+ await useDownloadStore.getState().scanOrphans()+ await useDownloadStore.getState().discardOrphan('wan_2.1_vae')++ expect(deleteOrphanDownload).toHaveBeenCalledWith('/comfy/models/vae/wan_2.1_vae.download', ['/comfy/models/vae'])+ expect(useDownloadStore.getState().orphans['wan_2.1_vae']).toBeUndefined()+ expect(useDownloadStore.getState().downloads['wan_2.1_vae.safetensors']).toBeUndefined()++ // Und die naechste Runde darf sie nicht zurueckholen.+ getDownloadProgress.mockResolvedValueOnce({})+ await useDownloadStore.getState().refresh()+ expect(useDownloadStore.getState().downloads['wan_2.1_vae.safetensors']).toBeUndefined()+ useDownloadStore.getState().stopPolling()+ })++ it('sizes the bar from the remembered estimate, without claiming completeness', () => {+ const rows = orphanRows(+ { s: { stem: 's', path: '/p/s.download', dir: '/p', bytes: 5, filename: 'm.safetensors' } },+ { 'm.safetensors': { url: 'u', subfolder: 'vae', expectedBytes: 100 } },+ )+ expect(rows['m.safetensors']).toMatchObject({ progress: 5, total: 100, status: 'paused' })+ // Ohne gemerkte Groesse bleibt die Gesamtzahl offen, statt geraten zu werden.+ const blind = orphanRows(+ { s: { stem: 's', path: '/p/s.download', dir: '/p', bytes: 5, filename: 'm.safetensors' } },+ {},+ )+ expect(blind['m.safetensors'].total).toBe(0)+ })+})diff --git a/src/stores/__tests__/downloadStore-retry.test.ts b/src/stores/__tests__/downloadStore-retry.test.tsindex 05a2f780..9859d905 100644--- a/src/stores/__tests__/downloadStore-retry.test.ts+++ b/src/stores/__tests__/downloadStore-retry.test.ts@@ -1,47 +1,71 @@/**- * Retrying a failed model download must clear BOTH sides (2026-07-28)+ * Was "Wiederholen" anfassen darf — und was auf keinen Fall (2026-07-28 / DD-1)*- * An errored entry lives in the Rust download map as well as in this store.- * retry() only deleted the frontend row, and download_model short-circuits- * with "exists" when the file is already on disk — never touching that map. So- * the next refresh() re-read the old error and the card the user had just- * retried came back, making the model look permanently broken. dismiss() had- * already learned this (the_mr_pickles); retry() had not.+ * Zwei Befunde in einer Datei, weil sie dieselbe Zeile betreffen.+ *+ * 2026-07-28: Ein fehlgeschlagener Eintrag lebt auch in der Rust-Map. retry()+ * loeschte nur die Zeile im Frontend, und download_model bricht mit "exists" ab,+ * wenn die Datei schon auf der Platte liegt, ohne die Map je anzufassen. Das+ * naechste refresh() las den alten Fehler wieder ein und die gerade+ * wiederholte Karte kam zurueck.+ *+ * DD-1: Die Loesung dafuer war cancelDownload(id) — und cancel entfernt fuer+ * 'paused' und 'error' die Teildatei. Damit loeschte genau der Knopf, den die+ * Fehlermeldung empfiehlt ("start it again to resume"), die Bytes, ab denen er+ * fortsetzen wollte. Bei einem 40-GB-Bundle auf instabiler Leitung konvergiert+ * das nie: jeder Versuch faengt wieder bei null an.** Run: npx vitest run src/stores/__tests__/downloadStore-retry.test.ts*/import { describe, it, expect, vi, beforeEach } from 'vitest'const cancelDownload = vi.fn(async () => {})+const clearDownloadEntry = vi.fn(async () => {})const startModelDownload = vi.fn(async () => {})const startModelDownloadToPath = vi.fn(async () => {})const getDownloadProgress = vi.fn(async () => ({}))+const resumeDownload = vi.fn(async () => {})-vi.mock('../../api/discover', () => ({- getDownloadProgress: (...a: any[]) => getDownloadProgress(...(a as [])),- pauseDownload: vi.fn(async () => {}),- cancelDownload: (...a: any[]) => cancelDownload(...(a as [])),- resumeDownload: vi.fn(async () => {}),- startModelDownload: (...a: any[]) => startModelDownload(...(a as [])),- startModelDownloadToPath: (...a: any[]) => startModelDownloadToPath(...(a as [])),- lookupFileMeta: () => undefined,-}))+vi.mock('../../api/discover', async () => {+ // isPermanentDownloadError ist reine Logik und genau die Vertragsstelle+ // zwischen Rust-Fehlertext und UI — die echte Implementierung testen, nicht+ // eine Attrappe davon.+ const actual = await vi.importActual<typeof import('../../api/discover')>('../../api/discover')+ return {+ getDownloadProgress: (...a: any[]) => getDownloadProgress(...(a as [])),+ pauseDownload: vi.fn(async () => {}),+ cancelDownload: (...a: any[]) => cancelDownload(...(a as [])),+ clearDownloadEntry: (...a: any[]) => clearDownloadEntry(...(a as [])),+ resumeDownload: (...a: any[]) => resumeDownload(...(a as [])),+ startModelDownload: (...a: any[]) => startModelDownload(...(a as [])),+ startModelDownloadToPath: (...a: any[]) => startModelDownloadToPath(...(a as [])),+ lookupFileMeta: () => undefined,+ findOrphanDownloads: vi.fn(async () => []),+ deleteOrphanDownload: vi.fn(async () => {}),+ catalogFilenames: () => [],+ orphanFilename: actual.orphanFilename,+ isPermanentDownloadError: actual.isPermanentDownloadError,+ modelsNotVisibleInComfy: vi.fn(async () => []),+ ENUM_SUBFOLDERS: actual.ENUM_SUBFOLDERS,+ }+})import { useDownloadStore } from '../downloadStore'-function seedErrored(id: string) {+function seedErrored(id: string, error = 'boom') {useDownloadStore.setState({downloads: {- [id]: { progress: 10, total: 100, speed: 0, filename: id, status: 'error', error: 'boom' } as any,+ [id]: { progress: 10, total: 100, speed: 0, filename: id, status: 'error', error } as any,},downloadMeta: { [id]: { url: 'https://example.test/m.safetensors', subfolder: 'checkpoints' } },+ orphans: {},})}describe('downloadStore.retry', () => {beforeEach(() => {vi.clearAllMocks()- useDownloadStore.setState({ downloads: {}, downloadMeta: {} })+ useDownloadStore.setState({ downloads: {}, downloadMeta: {}, orphans: {} })useDownloadStore.getState().stopPolling()})@@ -49,16 +73,30 @@ describe('downloadStore.retry', () => {seedErrored('model.safetensors')await useDownloadStore.getState().retry('model.safetensors')- expect(cancelDownload).toHaveBeenCalledWith('model.safetensors')+ expect(clearDownloadEntry).toHaveBeenCalledWith('model.safetensors')expect(startModelDownload).toHaveBeenCalledWith('https://example.test/m.safetensors','checkpoints','model.safetensors',+ undefined,+ undefined,)expect(useDownloadStore.getState().downloads['model.safetensors']).toBeUndefined()useDownloadStore.getState().stopPolling()})+ /** DD-1. cancelDownload ist der Weg, der die .download-Datei entfernt.+ * Wiederholen darf ihn nicht gehen — sonst faengt jeder Versuch bei 0 an. */+ it('never routes a retry through cancel, so the partial file survives', async () => {+ seedErrored('big-video-bundle.gguf', 'Download ended early: 38000000000 of 42000000000 bytes received. Start it again to resume.')+ await useDownloadStore.getState().retry('big-video-bundle.gguf')++ expect(cancelDownload).not.toHaveBeenCalled()+ expect(clearDownloadEntry).toHaveBeenCalledWith('big-video-bundle.gguf')+ expect(startModelDownload).toHaveBeenCalled()+ useDownloadStore.getState().stopPolling()+ })+it('does not cancel a transfer that is merely paused', async () => {useDownloadStore.setState({downloads: {@@ -69,7 +107,52 @@ describe('downloadStore.retry', () => {await useDownloadStore.getState().retry('m.gguf')expect(cancelDownload).not.toHaveBeenCalled()+ expect(clearDownloadEntry).not.toHaveBeenCalled()expect(startModelDownload).toHaveBeenCalled()useDownloadStore.getState().stopPolling()})++ /** Ein umbenanntes oder gated Repo antwortet immer gleich. Ein Neustart ist+ * kein Fix, sondern derselbe Fehlschlag noch einmal. */+ it('refuses to restart a download whose address is gone', async () => {+ seedErrored(+ 'wan_2.1_vae.safetensors',+ 'wan_2.1_vae.safetensors is not at this address any more (HTTP 404). The repository was renamed, moved or taken down, so trying again cannot help.',+ )+ await useDownloadStore.getState().retry('wan_2.1_vae.safetensors')++ expect(startModelDownload).not.toHaveBeenCalled()+ expect(clearDownloadEntry).not.toHaveBeenCalled()+ expect(cancelDownload).not.toHaveBeenCalled()+ // Die Karte bleibt mit ihrer Begruendung stehen, statt still zu scheitern.+ expect(useDownloadStore.getState().downloads['wan_2.1_vae.safetensors']?.status).toBe('error')+ })++ it('still restarts a download that failed for a temporary reason', async () => {+ seedErrored('m.safetensors', 'The host could not serve m.safetensors right now (HTTP 503).')+ await useDownloadStore.getState().retry('m.safetensors')++ expect(startModelDownload).toHaveBeenCalled()+ useDownloadStore.getState().stopPolling()+ })++ /** Dieselbe Falle, ein Klick daneben: das X auf einer roten Karte ist kein+ * Beschluss, mehrere Gigabyte wegzuwerfen. */+ it('dismissing an error card clears the row, not the bytes', () => {+ seedErrored('model.safetensors')+ useDownloadStore.getState().dismiss('model.safetensors')++ expect(cancelDownload).not.toHaveBeenCalled()+ expect(clearDownloadEntry).toHaveBeenCalledWith('model.safetensors')+ expect(useDownloadStore.getState().downloads['model.safetensors']).toBeUndefined()+ })++ /** Abbrechen bleibt Abbrechen: der eine Weg, der aufraeumen darf. */+ it('cancel is still the path that removes the partial', async () => {+ seedErrored('model.safetensors')+ await useDownloadStore.getState().cancel('model.safetensors')++ expect(cancelDownload).toHaveBeenCalledWith('model.safetensors')+ expect(clearDownloadEntry).not.toHaveBeenCalled()+ })})diff --git a/src/stores/downloadStore.ts b/src/stores/downloadStore.tsindex a0cf5092..25b118c0 100644--- a/src/stores/downloadStore.ts+++ b/src/stores/downloadStore.ts@@ -1,5 +1,13 @@import { create } from 'zustand'-import { getDownloadProgress, pauseDownload, cancelDownload, resumeDownload, startModelDownload, startModelDownloadToPath, lookupFileMeta, modelsNotVisibleInComfy, ENUM_SUBFOLDERS, type DownloadProgress } from '../api/discover'+import { persist } from 'zustand/middleware'+import {+ getDownloadProgress, pauseDownload, cancelDownload, clearDownloadEntry, resumeDownload,+ startModelDownload, startModelDownloadToPath, lookupFileMeta, modelsNotVisibleInComfy,+ isPermanentDownloadError, findOrphanDownloads, deleteOrphanDownload, orphanFilename,+ catalogFilenames, ENUM_SUBFOLDERS, type DownloadProgress, type OrphanDownload,+} from '../api/discover'+import { isTauri } from '../api/backend'+import { coalescedJSONStorage } from '../lib/coalescedStorage'import { waitForModelsVisible } from '../lib/bundle-install'import { log } from '../lib/logger'@@ -79,17 +87,45 @@ export function invisibleFileMessage(filename: string): string {// Maps filename → bundle name for grouped displaytype BundleMap = Record<string, string>+/**+ * Everything needed to start the same transfer a second time.+ *+ * `destDir` is the part that used to die with the process: a GGUF text model is+ * downloaded by path, not by ComfyUI subfolder, and a retry without the destDir+ * falls back to the subfolder branch and writes the file into a directory no+ * backend looks in — downloaded, invisible, and no error anywhere.+ */+export interface DownloadMeta {+ url: string+ subfolder: string+ destDir?: string+ /** Catalog estimate. Plans the space guard, never decides completeness. */+ expectedBytes?: number+ /** Content digest, when the catalog states one. */+ sha256?: string+}++/** A `.download` file from an earlier run, plus what we could work out about it. */+export interface OrphanEntry extends OrphanDownload {+ /** The download id, when the stem could be matched back to a known file.+ * `null` means it can be shown and deleted but not resumed. */+ filename: string | null+}+interface DownloadStoreState {downloads: Record<string, DownloadProgress>- downloadMeta: Record<string, { url: string; subfolder: string; destDir?: string }>+ downloadMeta: Record<string, DownloadMeta>bundleMap: BundleMap // filename → bundle name+ /** Partials found on disk with no transfer behind them, keyed by stem. */+ orphans: Record<string, OrphanEntry>polling: booleanpollInterval: ReturnType<typeof setInterval> | null+ pollCount: numberrefresh: () => Promise<void>startPolling: () => voidstopPolling: () => void- setMeta: (filename: string, url: string, subfolder: string, destDir?: string) => void+ setMeta: (filename: string, url: string, subfolder: string, destDir?: string, extra?: { expectedBytes?: number; sha256?: string }) => voidsetBundleGroup: (bundleName: string, filenames: string[]) => voidmarkComplete: (filename: string) => voidmarkInvisible: (filename: string) => void@@ -98,6 +134,41 @@ interface DownloadStoreState {resume: (id: string) => Promise<void>retry: (id: string) => Promise<void>dismiss: (id: string) => void+ scanOrphans: () => Promise<void>+ resumeOrphan: (stem: string) => Promise<void>+ discardOrphan: (stem: string) => Promise<void>+}++/**+ * The rows an orphaned partial contributes to the download list.+ *+ * Shown as `paused`, because that is exactly what it is: bytes on disk waiting+ * for the rest. Rendering them through the normal list is what gives a partial+ * that survived a restart a Cancel button at all — before this the file was+ * simply unreachable from inside the app.+ *+ * Only resolvable orphans get a row. One whose stem matches nothing known can+ * be listed and deleted, but a row promising Resume that cannot resume is worse+ * than no row.+ */+export function orphanRows(+ orphans: Record<string, OrphanEntry>,+ meta: Record<string, DownloadMeta>,+): Record<string, DownloadProgress> {+ const rows: Record<string, DownloadProgress> = {}+ for (const o of Object.values(orphans)) {+ if (!o.filename) continue+ rows[o.filename] = {+ progress: o.bytes,+ // The catalog estimate only sizes the bar. It is never the truth about+ // completeness — that question is settled against the server.+ total: meta[o.filename]?.expectedBytes ?? 0,+ speed: 0,+ filename: o.filename,+ status: 'paused',+ }+ }+ return rows}// Listen for "exists" events from installBundleComplete — mark files as complete immediately@@ -113,10 +184,48 @@ if (typeof window !== 'undefined') {}) as EventListener)}-export const useDownloadStore = create<DownloadStoreState>()((set, get) => ({+/**+ * Where the retry information survives a restart.+ *+ * Both sides of the download used to keep everything in RAM. Quitting the app+ * during a 40 GB transfer therefore left the `.download` file on disk with no+ * row, no button and — worse — no `destDir`, so even starting the same model+ * again wrote it somewhere no backend looks.+ *+ * Coalesced, because the poller writes into this store once a second while a+ * download runs and zustand persists on EVERY set(): without it that is a+ * serialise-and-write per tick for state that changes maybe twice an hour.+ */+const downloadStorage = coalescedJSONStorage<DownloadStoreState>(+ typeof localStorage !== 'undefined'+ ? localStorage+ : { getItem: () => null, setItem: () => {}, removeItem: () => {} },+)++/** Push the pending write out now instead of waiting for the coalescing+ * window. The point of persisting this store is surviving a close, so the+ * close is where it has to be on disk. */+export function flushDownloadPersist(): Promise<void> {+ return downloadStorage.flush()+}++if (typeof window !== 'undefined' && typeof document !== 'undefined') {+ window.addEventListener('pagehide', () => { void downloadStorage.flush() })+ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'hidden') void downloadStorage.flush()+ })+}++/** Ceiling on remembered meta. Each entry is a URL and a folder — tiny — but+ * the catalog has ~150 files and a user can add their own, so the map is+ * trimmed rather than grown forever inside a 5 MB origin quota. */+const META_LIMIT = 400++export const useDownloadStore = create<DownloadStoreState>()(persist((set, get) => ({downloads: {},downloadMeta: {},bundleMap: {},+ orphans: {},polling: false,pollInterval: null,@@ -141,7 +250,18 @@ export const useDownloadStore = create<DownloadStoreState>()((set, get) => ({}const count = get().pollCount + 1- set({ downloads: prog, pollCount: count })+ // Rust owns the live rows; an adopted orphan only fills a gap Rust has+ // nothing for. The moment a resume starts, the real entry takes over and+ // the orphan stops being one.+ const { orphans, downloadMeta } = get()+ const stillOrphaned = Object.fromEntries(+ Object.entries(orphans).filter(([, o]) => !o.filename || !prog[o.filename]),+ )+ set({+ downloads: { ...orphanRows(stillOrphaned, downloadMeta), ...prog },+ orphans: stillOrphaned,+ pollCount: count,+ })// Auto-stop polling when no active downloads// BUT wait at least 5 polls before stopping — gives Rust time to register new downloads@@ -171,8 +291,17 @@ export const useDownloadStore = create<DownloadStoreState>()((set, get) => ({set({ polling: false, pollInterval: null })},- setMeta: (filename, url, subfolder, destDir?) => {- set(s => ({ downloadMeta: { ...s.downloadMeta, [filename]: { url, subfolder, destDir } } }))+ setMeta: (filename, url, subfolder, destDir?, extra?) => {+ set(s => {+ const next = { ...s.downloadMeta, [filename]: { url, subfolder, destDir, ...extra } }+ const keys = Object.keys(next)+ if (keys.length > META_LIMIT) {+ // Oldest first — insertion order is the only age we have, and the+ // entries that matter are the ones just started.+ for (const k of keys.slice(0, keys.length - META_LIMIT)) delete next[k]+ }+ return { downloadMeta: next }+ })},setBundleGroup: (bundleName, filenames) => {@@ -209,60 +338,70 @@ export const useDownloadStore = create<DownloadStoreState>()((set, get) => ({await get().refresh()},+ /** The user aborting: the transfer stops AND the partial file goes. The one+ * path that is allowed to throw bytes away. */cancel: async (id: string) => {await cancelDownload(id)set(s => {const updated = { ...s.downloads }delete updated[id]- return { downloads: updated }+ // An adopted orphan must go from BOTH places or the next poll re-adopts+ // the row the user just cancelled.+ return { downloads: updated, orphans: withoutFilename(s.orphans, id) }})},resume: async (id: string) => {- let meta = get().downloadMeta[id]- if (!meta) {- const found = lookupFileMeta(id)- if (found) {- meta = { url: found.url, subfolder: found.subfolder }- get().setMeta(id, found.url, found.subfolder)- } else return- }- await resumeDownload(id, meta.url, meta.subfolder)+ const meta = ensureMeta(get, id)+ if (!meta) return+ await resumeDownload(id, meta.url, meta.subfolder, meta.expectedBytes, meta.sha256)+ set(s => ({ orphans: withoutFilename(s.orphans, id) }))get().startPolling()},+ /**+ * Start the same download again after it failed.+ *+ * This must NOT delete the partial file. It used to: the error path handed+ * the id to `cancelDownload`, and cancel removes `<dest>.download` for a+ * paused or errored entry. So the sequence the UI recommends — "Download+ * ended early ... start it again to resume" next to a Retry button — deleted+ * the bytes it was about to resume from and restarted at zero. On a 40 GB+ * bundle over a shaky line that never finishes, and every attempt costs the+ * user everything the last one achieved.+ *+ * The Rust row still has to be cleared, or `download_model` short-circuits on+ * the file already on disk without touching the map and the next poll+ * resurrects the error card (the_mr_pickles). `clearDownloadEntry` is that+ * bookkeeping without the collateral damage.+ */retry: async (id: string) => {- let meta = get().downloadMeta[id]- // If meta is missing (e.g. after error/restart), try to recover from bundle definitions+ const current = get().downloads[id]+ // A renamed, gated or deleted repository answers the same way forever.+ // Restarting is not a fix, it is the same failure a second time, and the+ // partial that is on disk stays where it is.+ if (current?.status === 'error' && isPermanentDownloadError(current.error)) {+ log.warn('[downloadStore] retry refused · the address itself is dead', { id, error: current.error })+ return+ }+ const meta = ensureMeta(get, id)if (!meta) {- const found = lookupFileMeta(id)- if (found) {- meta = { url: found.url, subfolder: found.subfolder }- get().setMeta(id, found.url, found.subfolder)- } else {- log.warn('[downloadStore] retry: no meta found for', { id })- return- }+ log.warn('[downloadStore] retry: no meta found for', { id })+ return}- // Clear the error state — on BOTH sides. The errored entry also lives in- // the Rust download map, and download_model short-circuits with "exists"- // when the file is already on disk, never touching that map. So a retry- // that hits the short-circuit left the old error row in place and the next- // refresh() resurrected the card the user had just retried, making the- // model look permanently broken. Same reason dismiss() clears it there.- if (get().downloads[id]?.status === 'error') {- await cancelDownload(id).catch(() => { /* best effort — a restart clears it */ })+ if (current?.status === 'error') {+ await clearDownloadEntry(id).catch(() => { /* best effort — a restart clears it */ })}set(s => {const updated = { ...s.downloads }delete updated[id]- return { downloads: updated }+ return { downloads: updated, orphans: withoutFilename(s.orphans, id) }})// Re-start the download — use path-based for GGUF text models, subfolder-based for ComfyUIif (meta.destDir) {- await startModelDownloadToPath(meta.url, meta.destDir, id)+ await startModelDownloadToPath(meta.url, meta.destDir, id, meta.expectedBytes, meta.sha256)} else {- await startModelDownload(meta.url, meta.subfolder, id)+ await startModelDownload(meta.url, meta.subfolder, id, meta.expectedBytes, meta.sha256)}get().startPolling()},@@ -273,13 +412,141 @@ export const useDownloadStore = create<DownloadStoreState>()((set, get) => ({// card the user just cleared (the_mr_pickles). Only for 'error' —// cancelling an active transfer or a completed entry is not dismiss's// job (the badge dismisses completed entries FE-only by design).+ //+ // Clearing the row, NOT cancelling: closing a red card is not a decision+ // to throw away the gigabytes it downloaded before it failed. The partial+ // stays and shows up as a resumable orphan on the next start; Cancel is+ // the button that deletes.if (get().downloads[id]?.status === 'error') {- cancelDownload(id).catch(() => { /* app restart clears it anyway */ })+ clearDownloadEntry(id).catch(() => { /* app restart clears it anyway */ })}set(s => {const updated = { ...s.downloads }delete updated[id]- return { downloads: updated }+ return { downloads: updated, orphans: withoutFilename(s.orphans, id) }+ })+ },++ /**+ * Find `.download` files left behind by an earlier run and make them+ * reachable again.+ *+ * The disk is the only place that still knows what was in flight when the app+ * was closed, so it is what gets asked. The persisted `destDir`s go along:+ * a GGUF for LM Studio lives outside the ComfyUI tree and the Rust side has+ * no way to guess where.+ */+ scanOrphans: async () => {+ const meta = get().downloadMeta+ const extraDirs = [...new Set(Object.values(meta).map(m => m.destDir).filter((d): d is string => !!d))]+ const found = await findOrphanDownloads(extraDirs)+ if (found.length === 0) {+ if (Object.keys(get().orphans).length > 0) set({ orphans: {} })+ return+ }+ // Meta first: it is the only source that also knows the destDir. The+ // catalog is the fallback for a partial from before this store persisted+ // anything.+ const known = [...Object.keys(meta), ...catalogFilenames()]+ const orphans: Record<string, OrphanEntry> = {}+ for (const o of found) {+ const filename = orphanFilename(o.stem, known)+ orphans[o.stem] = { ...o, filename }+ // Backfill what the catalog knows for a partial from before this store+ // persisted anything — the size so the bar means something, the url and+ // subfolder so Resume has somewhere to go.+ if (filename && !get().downloadMeta[filename]) {+ const cat = lookupFileMeta(filename)+ if (cat) {+ get().setMeta(filename, cat.url, cat.subfolder, undefined, {+ expectedBytes: cat.expectedBytes,+ sha256: cat.sha256,+ })+ }+ }+ }+ const unresolved = Object.values(orphans).filter(o => !o.filename)+ if (unresolved.length > 0) {+ log.warn('[downloads] partial files that match no known model', {+ files: unresolved.map(o => o.path),+ })+ }+ log.info('[downloads] adopted partial downloads from an earlier run', {+ count: found.length,+ bytes: found.reduce((s, o) => s + o.bytes, 0),})+ set(s => ({ orphans, downloads: { ...orphanRows(orphans, s.downloadMeta), ...s.downloads } }))+ },++ /** Continue an orphan where it stopped. Needs the meta that now survives a+ * restart — without `destDir` a GGUF would land in the wrong folder. */+ resumeOrphan: async (stem: string) => {+ const o = get().orphans[stem]+ if (!o?.filename) return+ await get().resume(o.filename)+ },++ /** Throw an orphaned partial away, on the user's say-so. */+ discardOrphan: async (stem: string) => {+ const o = get().orphans[stem]+ if (!o) return+ const extraDirs = o.dir ? [o.dir] : []+ await deleteOrphanDownload(o.path, extraDirs).catch(err => {+ log.warn('[downloads] could not remove orphaned partial', { path: o.path, err })+ })+ set(s => {+ const orphans = { ...s.orphans }+ delete orphans[stem]+ const downloads = { ...s.downloads }+ if (o.filename && downloads[o.filename]?.status === 'paused') delete downloads[o.filename]+ return { orphans, downloads }+ })+ },+}), {+ name: 'locally-uncensored-downloads',+ storage: downloadStorage,+ version: 1,+ // Only what a RESTART cannot rebuild. `downloads` is Rust's to report and+ // would come back as a lie ("downloading" with nothing running); `orphans` is+ // re-derived from the disk, which is the only honest source; `pollInterval`+ // is a live timer handle.+ partialize: (s) => ({ downloadMeta: s.downloadMeta, bundleMap: s.bundleMap }) as DownloadStoreState,+ migrate: (persisted) => persisted as DownloadStoreState,+ onRehydrateStorage: () => (state) => {+ // The scan needs the Rust side, so it only runs in the app. In a browser+ // dev build or a test there is no disk to ask.+ if (state && isTauri()) void state.scanOrphans()},}))++/** Meta for `id`, filling in from the catalog and remembering what it found.+ * Retry and resume both need it and both used to lose the destDir. */+function ensureMeta(get: () => DownloadStoreState, id: string): DownloadMeta | null {+ const known = get().downloadMeta[id]+ if (known) return known+ const found = lookupFileMeta(id)+ if (!found) return null+ const meta: DownloadMeta = {+ url: found.url,+ subfolder: found.subfolder,+ expectedBytes: found.expectedBytes,+ sha256: found.sha256,+ }+ get().setMeta(id, meta.url, meta.subfolder, undefined, {+ expectedBytes: meta.expectedBytes,+ sha256: meta.sha256,+ })+ return meta+}++/** Drop the orphan that resolved to `filename`, whatever its stem was. */+function withoutFilename(+ orphans: Record<string, OrphanEntry>,+ filename: string,+): Record<string, OrphanEntry> {+ const hit = Object.entries(orphans).find(([, o]) => o.filename === filename)+ if (!hit) return orphans+ const next = { ...orphans }+ delete next[hit[0]]+ return next+}