Spaces:
Paused

HomePilot Deploy Bot commited on
Commit
d0ddc9a
·
1 Parent(s): 4f118e3

chore(hf): sync HomePilot to HF Space

Browse files
.gitattributes CHANGED
@@ -1,9 +1,9 @@
1
  *.jpg filter=lfs diff=lfs merge=lfs -text
2
- *.webp filter=lfs diff=lfs merge=lfs -text
3
- *.woff filter=lfs diff=lfs merge=lfs -text
4
- *.ico filter=lfs diff=lfs merge=lfs -text
5
- *.hpersona filter=lfs diff=lfs merge=lfs -text
6
  *.jpeg filter=lfs diff=lfs merge=lfs -text
 
 
 
7
  *.svg filter=lfs diff=lfs merge=lfs -text
 
8
  *.woff2 filter=lfs diff=lfs merge=lfs -text
9
- *.png filter=lfs diff=lfs merge=lfs -text
 
1
  *.jpg filter=lfs diff=lfs merge=lfs -text
 
 
 
 
2
  *.jpeg filter=lfs diff=lfs merge=lfs -text
3
+ *.hpersona filter=lfs diff=lfs merge=lfs -text
4
+ *.png filter=lfs diff=lfs merge=lfs -text
5
+ *.webp filter=lfs diff=lfs merge=lfs -text
6
  *.svg filter=lfs diff=lfs merge=lfs -text
7
+ *.woff filter=lfs diff=lfs merge=lfs -text
8
  *.woff2 filter=lfs diff=lfs merge=lfs -text
9
+ *.ico filter=lfs diff=lfs merge=lfs -text
backend/app/background.py CHANGED
@@ -196,7 +196,8 @@ def _get_u2net_model_path() -> Optional[Path]:
196
  try:
197
  # First, check if model exists in ComfyUI models directory
198
  from .providers import get_comfy_models_path
199
- comfy_model_path = get_comfy_models_path() / "rembg" / "u2net.onnx"
 
200
  if comfy_model_path.exists() and comfy_model_path.stat().st_size > 100_000_000:
201
  print(f"[BACKGROUND] Using U2Net from ComfyUI models: {comfy_model_path}")
202
  return comfy_model_path
 
196
  try:
197
  # First, check if model exists in ComfyUI models directory
198
  from .providers import get_comfy_models_path
199
+ from .model_storage import find_model_file
200
+ comfy_model_path = find_model_file("rembg/u2net.onnx") or (get_comfy_models_path() / "rembg" / "u2net.onnx")
201
  if comfy_model_path.exists() and comfy_model_path.stat().st_size > 100_000_000:
202
  print(f"[BACKGROUND] Using U2Net from ComfyUI models: {comfy_model_path}")
203
  return comfy_model_path
backend/app/capabilities.py CHANGED
@@ -84,7 +84,8 @@ def _check_rembg() -> tuple[bool, Optional[str]]:
84
 
85
  # Check ComfyUI models path first
86
  try:
87
- comfy_model = get_comfy_models_path() / "rembg" / "u2net.onnx"
 
88
  if comfy_model.exists() and comfy_model.stat().st_size > 100_000_000:
89
  return True, "Using U2Net from ComfyUI models"
90
  except Exception:
 
84
 
85
  # Check ComfyUI models path first
86
  try:
87
+ from .model_storage import find_model_file
88
+ comfy_model = find_model_file("rembg/u2net.onnx") or (get_comfy_models_path() / "rembg" / "u2net.onnx")
89
  if comfy_model.exists() and comfy_model.stat().st_size > 100_000_000:
90
  return True, "Using U2Net from ComfyUI models"
91
  except Exception:
backend/app/comfy.py CHANGED
@@ -826,6 +826,41 @@ def _validate_prompt_graph(prompt_graph: Dict[str, Any], *, workflow_name: str)
826
  )
827
 
828
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
829
  def _post_prompt(client: httpx.Client, prompt: Dict[str, Any]) -> str:
830
  url = f"{COMFY_BASE_URL.rstrip('/')}/prompt"
831
  # Model files in subfolders are listed with the host OS's separator ("a\b" on a
@@ -835,6 +870,7 @@ def _post_prompt(client: httpx.Client, prompt: Dict[str, Any]) -> str:
835
  align_model_paths(prompt, COMFY_BASE_URL.rstrip('/'))
836
  except Exception:
837
  pass
 
838
  # Generate a unique client_id for each request to prevent ComfyUI caching
839
  # Without this, ComfyUI may skip execution for "duplicate" prompts
840
  import uuid
@@ -1138,7 +1174,11 @@ def _inject_lora_loaders(
1138
  lora_fname = f"{lr['id']}.safetensors"
1139
  if entry and hasattr(entry, "filename") and entry.filename:
1140
  lora_fname = entry.filename
1141
- lora_file = _lora_dir / lora_fname
 
 
 
 
1142
 
1143
  # File health check: skip corrupt/truncated LoRA files
1144
  if validate_safetensors_file and lora_file and lora_file.exists():
 
826
  )
827
 
828
 
829
+ # Loader node input -> models subfolder, for the pre-submit file check.
830
+ _MODEL_FILE_INPUTS = {
831
+ "unet_name": "unet", "ckpt_name": "checkpoints", "vae_name": "vae",
832
+ "clip_name": "clip", "clip_name1": "clip", "clip_name2": "clip", "lora_name": "loras",
833
+ }
834
+
835
+
836
+ def _check_model_files(prompt: Dict[str, Any]) -> None:
837
+ """Fail fast, with a clear message, when a model the workflow loads is a cut-off download.
838
+
839
+ ComfyUI would otherwise fail deep inside the loader ("incomplete metadata, file not fully
840
+ covered") and the user just gets no image.
841
+ """
842
+ try:
843
+ from .model_storage import find_model_file, incomplete_model_reason
844
+ except Exception:
845
+ return
846
+ for node in (prompt or {}).values():
847
+ inputs = node.get("inputs") if isinstance(node, dict) else None
848
+ if not isinstance(inputs, dict):
849
+ continue
850
+ for key, sub in _MODEL_FILE_INPUTS.items():
851
+ name = inputs.get(key)
852
+ if not isinstance(name, str) or not name.endswith(".safetensors"):
853
+ continue
854
+ rel = name.replace("\\", "/")
855
+ path = find_model_file(f"{sub}/{rel}")
856
+ reason = incomplete_model_reason(path) if path else None
857
+ if reason:
858
+ raise RuntimeError(
859
+ f"Model '{name}' can't be used: {reason}. Download it again "
860
+ f"(Settings > Models), or pick another model."
861
+ )
862
+
863
+
864
  def _post_prompt(client: httpx.Client, prompt: Dict[str, Any]) -> str:
865
  url = f"{COMFY_BASE_URL.rstrip('/')}/prompt"
866
  # Model files in subfolders are listed with the host OS's separator ("a\b" on a
 
870
  align_model_paths(prompt, COMFY_BASE_URL.rstrip('/'))
871
  except Exception:
872
  pass
873
+ _check_model_files(prompt)
874
  # Generate a unique client_id for each request to prevent ComfyUI caching
875
  # Without this, ComfyUI may skip execution for "duplicate" prompts
876
  import uuid
 
1174
  lora_fname = f"{lr['id']}.safetensors"
1175
  if entry and hasattr(entry, "filename") and entry.filename:
1176
  lora_fname = entry.filename
1177
+ try:
1178
+ from .models.lora_loader import find_lora_file
1179
+ lora_file = find_lora_file(lora_fname) or (_lora_dir / lora_fname)
1180
+ except ImportError:
1181
+ lora_file = _lora_dir / lora_fname
1182
 
1183
  # File health check: skip corrupt/truncated LoRA files
1184
  if validate_safetensors_file and lora_file and lora_file.exists():
backend/app/edit_models.py CHANGED
@@ -54,6 +54,14 @@ class ModelInfo:
54
  @property
55
  def path(self) -> Path:
56
  """Get the full path to this model."""
 
 
 
 
 
 
 
 
57
  models_path = get_comfy_models_path()
58
  return models_path / self.subdir / self.filename
59
 
 
54
  @property
55
  def path(self) -> Path:
56
  """Get the full path to this model."""
57
+ # Whichever model storage location has it; else where it would be in models/comfy.
58
+ try:
59
+ from .model_storage import find_model_file
60
+ found = find_model_file(f"{self.subdir}/{self.filename}")
61
+ if found is not None:
62
+ return found
63
+ except Exception:
64
+ pass
65
  models_path = get_comfy_models_path()
66
  return models_path / self.subdir / self.filename
67
 
backend/app/face_restore.py CHANGED
@@ -159,7 +159,11 @@ def _find_checkpoint() -> str:
159
 
160
  models_path = get_comfy_models_path()
161
  for ckpt in _CHECKPOINT_FALLBACKS:
162
- ckpt_path = models_path / "checkpoints" / ckpt
 
 
 
 
163
  if ckpt_path.exists() and ckpt_path.stat().st_size > 0:
164
  return ckpt
165
  # No checkpoint found — return default, ComfyUI will give a clear error
 
159
 
160
  models_path = get_comfy_models_path()
161
  for ckpt in _CHECKPOINT_FALLBACKS:
162
+ try:
163
+ from .model_storage import find_model_file
164
+ ckpt_path = find_model_file(f"checkpoints/{ckpt}") or (models_path / "checkpoints" / ckpt)
165
+ except Exception:
166
+ ckpt_path = models_path / "checkpoints" / ckpt
167
  if ckpt_path.exists() and ckpt_path.stat().st_size > 0:
168
  return ckpt
169
  # No checkpoint found — return default, ComfyUI will give a clear error
backend/app/main.py CHANGED
@@ -108,6 +108,7 @@ from .password_reset import router as password_reset_router
108
  from .avatar_gallery import router as avatar_gallery_router
109
  from .imagine_history import router as imagine_history_router
110
  from .edit_gallery import router as edit_gallery_router
 
111
 
112
  # Per-User Profile, Secrets & Memory (additive — multi-user aware)
113
  from .user_profile_store import router as user_profile_store_router
@@ -486,6 +487,8 @@ app.include_router(avatar_gallery_router)
486
  app.include_router(imagine_history_router)
487
  # Rebuild the Edit Studio gallery from stored edit sessions (/v1/edit-gallery/recover)
488
  app.include_router(edit_gallery_router)
 
 
489
 
490
  # Connectors: accounts on other services, linked in Settings → Connectors (/v1/connectors/*).
491
  from .connectors.routes import router as connectors_router # noqa: E402
@@ -3160,6 +3163,18 @@ async def install_model(req: ModelInstallRequest) -> JSONResponse:
3160
 
3161
  # Pass Civitai API key via environment variable (secure - not visible in process list)
3162
  env = os.environ.copy()
 
 
 
 
 
 
 
 
 
 
 
 
3163
  if req.civitai_api_key and req.provider == "civitai":
3164
  env["CIVITAI_API_KEY"] = req.civitai_api_key
3165
 
@@ -3284,15 +3299,22 @@ async def delete_model(req: ModelDeleteRequest) -> JSONResponse:
3284
  models_root = get_comfy_models_path()
3285
 
3286
  # Determine subdirectory from catalog hint or common locations
 
 
 
 
 
 
3287
  search_dirs = []
3288
- if install_path_hint:
3289
- search_dirs.append(models_root / install_path_hint.rstrip("/"))
3290
- # Always search common directories as fallback
3291
- for subdir in ["checkpoints", "unet", "clip", "vae", "controlnet",
3292
- "upscale_models", "gfpgan", "sams", "rembg", "diffusion_models"]:
3293
- d = models_root / subdir
3294
- if d not in search_dirs:
3295
- search_dirs.append(d)
 
3296
 
3297
  deleted_files = []
3298
  for directory in search_dirs:
 
108
  from .avatar_gallery import router as avatar_gallery_router
109
  from .imagine_history import router as imagine_history_router
110
  from .edit_gallery import router as edit_gallery_router
111
+ from .model_storage import router as model_storage_router
112
 
113
  # Per-User Profile, Secrets & Memory (additive — multi-user aware)
114
  from .user_profile_store import router as user_profile_store_router
 
487
  app.include_router(imagine_history_router)
488
  # Rebuild the Edit Studio gallery from stored edit sessions (/v1/edit-gallery/recover)
489
  app.include_router(edit_gallery_router)
490
+ # Where ComfyUI models live: built-in models/comfy plus extra locations, e.g. an external drive (/v1/models/storage)
491
+ app.include_router(model_storage_router)
492
 
493
  # Connectors: accounts on other services, linked in Settings → Connectors (/v1/connectors/*).
494
  from .connectors.routes import router as connectors_router # noqa: E402
 
3163
 
3164
  # Pass Civitai API key via environment variable (secure - not visible in process list)
3165
  env = os.environ.copy()
3166
+ # Download into the location chosen in Settings > Models > Model storage (models/comfy
3167
+ # unless another is chosen). Hugging Face's download cache goes on the same drive, so a
3168
+ # download never needs twice its size on the system drive.
3169
+ try:
3170
+ from .model_storage import download_root, builtin_root
3171
+ _dl_root = download_root()
3172
+ env["HOMEPILOT_MODELS_ROOT"] = str(_dl_root)
3173
+ if _dl_root.resolve() != builtin_root().resolve() and not env.get("HF_HUB_CACHE"):
3174
+ env["HF_HUB_CACHE"] = str(_dl_root / ".hf-cache")
3175
+ logger.info(f"Model download target: {_dl_root}")
3176
+ except Exception as _e:
3177
+ logger.warning(f"model storage lookup failed, using default: {_e}")
3178
  if req.civitai_api_key and req.provider == "civitai":
3179
  env["CIVITAI_API_KEY"] = req.civitai_api_key
3180
 
 
3299
  models_root = get_comfy_models_path()
3300
 
3301
  # Determine subdirectory from catalog hint or common locations
3302
+ # Look in every model storage location (built-in models/comfy and any extra ones).
3303
+ try:
3304
+ from .model_storage import comfy_model_roots
3305
+ roots = comfy_model_roots() or [models_root]
3306
+ except Exception:
3307
+ roots = [models_root]
3308
  search_dirs = []
3309
+ for root in roots:
3310
+ if install_path_hint:
3311
+ search_dirs.append(root / install_path_hint.rstrip("/"))
3312
+ # Always search common directories as fallback
3313
+ for subdir in ["checkpoints", "unet", "clip", "vae", "controlnet",
3314
+ "upscale_models", "gfpgan", "sams", "rembg", "diffusion_models"]:
3315
+ d = root / subdir
3316
+ if d not in search_dirs:
3317
+ search_dirs.append(d)
3318
 
3319
  deleted_files = []
3320
  for directory in search_dirs:
backend/app/model_storage.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Model storage locations — where ComfyUI models (image, video, edit, upscale…) live.
3
+
4
+ The built-in location is the existing ``models/comfy`` folder (``providers.get_comfy_models_path``)
5
+ and is never moved or changed. Extra locations — e.g. an external drive, ``E:\\homepilot-models``
6
+ — can be added, and one location is chosen as the target for new downloads. ComfyUI reads models
7
+ from all of them (``--extra-model-paths-config`` written here, one file per OS runtime), and
8
+ HomePilot's "is it installed" checks look in all of them.
9
+
10
+ Stored in ``<data dir>/model-storage.json``::
11
+
12
+ {"locations": [{"path": "/mnt/e/homepilot-models", "label": "External E:"}],
13
+ "download_target": "/mnt/e/homepilot-models"} # or "builtin"
14
+
15
+ With no file, everything behaves exactly as before (one location, ``models/comfy``).
16
+
17
+ GET /v1/models/storage locations with free space, the download target
18
+ PUT /v1/models/storage {"locations": [{path, label?}], "download_target": "builtin" | path}
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import os
24
+ import re
25
+ import shutil
26
+ import subprocess
27
+ from pathlib import Path, PurePosixPath
28
+ from typing import Any, Dict, List, Optional
29
+
30
+ from fastapi import APIRouter, HTTPException
31
+ from pydantic import BaseModel, Field
32
+
33
+ router = APIRouter(prefix="/v1/models/storage", tags=["models"])
34
+
35
+ MAX_LOCATIONS = 5
36
+ BUILTIN = "builtin"
37
+
38
+ # ComfyUI model folders created in (and mapped from) every extra location. The names are the
39
+ # same as under models/comfy, so a location is laid out exactly like the built-in one.
40
+ MODEL_FOLDERS = [
41
+ "checkpoints", "diffusion_models", "unet", "clip", "text_encoders", "clip_vision", "vae",
42
+ "loras", "controlnet", "upscale_models", "embeddings", "hypernetworks", "style_models",
43
+ "photomaker", "instantid", "ipadapter", "insightface", "pulid", "gfpgan", "sams", "rembg",
44
+ "facerestore_models", "vae_approx", "gligen",
45
+ ]
46
+
47
+
48
+ # ── paths ──────────────────────────────────────────────────────────────────────
49
+
50
+ def _data_dir() -> Path:
51
+ from .users import _get_db_path
52
+ return Path(_get_db_path()).resolve().parent
53
+
54
+
55
+ def _config_file() -> Path:
56
+ return _data_dir() / "model-storage.json"
57
+
58
+
59
+ def builtin_root() -> Path:
60
+ from .providers import get_comfy_models_path
61
+ return Path(get_comfy_models_path())
62
+
63
+
64
+ def is_wsl() -> bool:
65
+ try:
66
+ return "microsoft" in Path("/proc/version").read_text().lower()
67
+ except OSError:
68
+ return False
69
+
70
+
71
+ _WIN_PATH = re.compile(r"^[A-Za-z]:[\\/]")
72
+
73
+
74
+ def to_local_path(raw: str) -> Path:
75
+ """A path as this backend sees it. Under WSL a Windows path (E:\\x) becomes /mnt/e/x."""
76
+ raw = (raw or "").strip().strip('"').strip("'")
77
+ if not raw:
78
+ raise ValueError("empty path")
79
+ if _WIN_PATH.match(raw):
80
+ if is_wsl():
81
+ drive, rest = raw[0].lower(), raw[2:].replace("\\", "/").lstrip("/")
82
+ return Path(f"/mnt/{drive}") / rest
83
+ if os.name == "nt":
84
+ return Path(raw)
85
+ raise ValueError(f"{raw} is a Windows path, but this HomePilot runs on Linux")
86
+ p = Path(os.path.expanduser(raw))
87
+ if not p.is_absolute():
88
+ raise ValueError(f"{raw} is not an absolute path")
89
+ return p
90
+
91
+
92
+ def to_windows_path(p: Path) -> Optional[str]:
93
+ """The Windows spelling of a WSL path (/mnt/e/x -> E:\\x), for the Windows ComfyUI."""
94
+ s = str(p)
95
+ m = re.match(r"^/mnt/([a-z])(/.*)?$", s)
96
+ if m:
97
+ return f"{m.group(1).upper()}:" + (m.group(2) or "/").replace("/", "\\")
98
+ try:
99
+ out = subprocess.run(["wslpath", "-w", s], capture_output=True, text=True, timeout=5)
100
+ return out.stdout.strip() or None
101
+ except (OSError, subprocess.SubprocessError):
102
+ return None
103
+
104
+
105
+ def display_path(p: Path) -> str:
106
+ """What to show the user: the Windows form under WSL when it is a Windows drive."""
107
+ if is_wsl():
108
+ w = to_windows_path(p)
109
+ if w and re.match(r"^[A-Z]:\\", w):
110
+ return w
111
+ return str(p)
112
+
113
+
114
+ # ── config ─────────────────────────────────────────────────────────────────────
115
+
116
+ def load_config() -> Dict[str, Any]:
117
+ try:
118
+ data = json.loads(_config_file().read_text(encoding="utf-8"))
119
+ if isinstance(data, dict):
120
+ return {"locations": [l for l in data.get("locations", []) if isinstance(l, dict) and l.get("path")],
121
+ "download_target": data.get("download_target") or BUILTIN}
122
+ except (OSError, ValueError):
123
+ pass
124
+ return {"locations": [], "download_target": BUILTIN}
125
+
126
+
127
+ def extra_roots() -> List[Path]:
128
+ """Configured extra locations that exist right now (an unplugged drive is skipped)."""
129
+ out: List[Path] = []
130
+ for loc in load_config()["locations"]:
131
+ p = Path(loc["path"])
132
+ if p.is_dir() and p not in out:
133
+ out.append(p)
134
+ return out
135
+
136
+
137
+ def comfy_model_roots() -> List[Path]:
138
+ """Every folder ComfyUI models may be in: the built-in one first, then the extra ones."""
139
+ roots = [builtin_root()]
140
+ for p in extra_roots():
141
+ if p.resolve() != roots[0].resolve():
142
+ roots.append(p)
143
+ return roots
144
+
145
+
146
+ def download_root() -> Path:
147
+ """Where new downloads go: the chosen location when it is present and writable,
148
+ otherwise the built-in one (so a missing external drive never breaks installs)."""
149
+ target = load_config()["download_target"]
150
+ if target and target != BUILTIN:
151
+ p = Path(target)
152
+ if p.is_dir() and os.access(p, os.W_OK):
153
+ return p
154
+ return builtin_root()
155
+
156
+
157
+ def find_model_file(rel: str) -> Optional[Path]:
158
+ """The first location that has ``rel`` (e.g. "rembg/u2net.onnx"), or None."""
159
+ for root in comfy_model_roots():
160
+ p = root / rel
161
+ if p.exists():
162
+ return p
163
+ return None
164
+
165
+
166
+ _SAFETENSORS_CHECKS: Dict[tuple, Optional[str]] = {}
167
+
168
+
169
+ def incomplete_model_reason(path: Path) -> Optional[str]:
170
+ """Why a .safetensors file is unusable (cut short / bad header), or None if it is complete.
171
+
172
+ Reads only the header (a few KB), so it is cheap even for 20+ GB models; results are cached
173
+ per (path, size, mtime). Other file types are not checked.
174
+ """
175
+ if path.suffix.lower() != ".safetensors":
176
+ return None
177
+ try:
178
+ st = path.stat()
179
+ except OSError:
180
+ return None
181
+ key = (str(path), st.st_size, st.st_mtime_ns)
182
+ if key in _SAFETENSORS_CHECKS:
183
+ return _SAFETENSORS_CHECKS[key]
184
+ reason: Optional[str] = None
185
+ try:
186
+ with open(path, "rb") as f:
187
+ head = f.read(8)
188
+ n = int.from_bytes(head, "little") if len(head) == 8 else 0
189
+ if n <= 0 or n > 100_000_000 or 8 + n > st.st_size:
190
+ reason = "the file header is damaged"
191
+ else:
192
+ header = json.loads(f.read(n))
193
+ end = max((v["data_offsets"][1] for k, v in header.items()
194
+ if k != "__metadata__" and isinstance(v, dict)), default=0)
195
+ needed = 8 + n + end
196
+ if needed > st.st_size:
197
+ reason = (f"the file is incomplete ({st.st_size / 2**30:.2f} GB of "
198
+ f"{needed / 2**30:.2f} GB), probably an interrupted download")
199
+ except Exception as e: # unreadable JSON, I/O error…
200
+ reason = f"the file could not be read ({e})"
201
+ _SAFETENSORS_CHECKS[key] = reason
202
+ return reason
203
+
204
+
205
+ def model_dirs(sub: str) -> List[Path]:
206
+ """``<root>/<sub>`` for every location (existing or not)."""
207
+ return [root / sub for root in comfy_model_roots()]
208
+
209
+
210
+ # ── files ComfyUI reads ────────────────────────────────────────────────────────
211
+
212
+ def comfy_paths_file(windows: bool) -> Path:
213
+ return _data_dir() / ("comfy-extra-model-paths.windows.yaml" if windows else "comfy-extra-model-paths.yaml")
214
+
215
+
216
+ def _yaml_for(roots: List[str]) -> str:
217
+ lines = ["# Written by HomePilot (app/model_storage.py) from Settings > Models > Model storage.",
218
+ "# Extra ComfyUI model locations; models/comfy is still read as before."]
219
+ for i, base in enumerate(roots):
220
+ lines.append(f"homepilot_location_{i}:")
221
+ lines.append(f" base_path: {json.dumps(base)}")
222
+ for key in MODEL_FOLDERS:
223
+ lines.append(f" {key}: {key}")
224
+ return "\n".join(lines) + "\n"
225
+
226
+
227
+ def write_comfy_paths_files() -> None:
228
+ """Write (or remove) the per-OS extra-model-paths files the ComfyUI launchers pass on."""
229
+ roots = [p for p in extra_roots() if p.resolve() != builtin_root().resolve()]
230
+ linux_file, win_file = comfy_paths_file(False), comfy_paths_file(True)
231
+ if not roots:
232
+ for f in (linux_file, win_file):
233
+ try:
234
+ f.unlink()
235
+ except OSError:
236
+ pass
237
+ return
238
+ linux_file.write_text(_yaml_for([str(p) for p in roots]), encoding="utf-8")
239
+ win = [w for w in (to_windows_path(p) for p in roots) if w]
240
+ if is_wsl() and win:
241
+ win_file.write_text(_yaml_for(win), encoding="utf-8")
242
+ else:
243
+ try:
244
+ win_file.unlink()
245
+ except OSError:
246
+ pass
247
+
248
+
249
+ # ── API ────────────────────────────────────────────────────────────────────────
250
+
251
+ def _describe(p: Path, *, builtin: bool, label: str, target: Path) -> Dict[str, Any]:
252
+ exists = p.is_dir()
253
+ info: Dict[str, Any] = {
254
+ "path": str(p), "display_path": display_path(p), "label": label, "builtin": builtin,
255
+ "exists": exists, "writable": exists and os.access(p, os.W_OK),
256
+ "is_download_target": p.resolve() == target.resolve() if exists else False,
257
+ "free_gb": None, "total_gb": None, "model_files": None,
258
+ }
259
+ if exists:
260
+ try:
261
+ usage = shutil.disk_usage(p)
262
+ info["free_gb"] = round(usage.free / 2**30, 1)
263
+ info["total_gb"] = round(usage.total / 2**30, 1)
264
+ except OSError:
265
+ pass
266
+ n = 0
267
+ for sub in ("checkpoints", "diffusion_models", "unet", "loras", "vae", "controlnet", "upscale_models"):
268
+ d = p / sub
269
+ if d.is_dir():
270
+ try:
271
+ n += sum(1 for f in d.iterdir() if f.is_file() and not f.name.startswith("put_"))
272
+ except OSError:
273
+ pass
274
+ info["model_files"] = n
275
+ return info
276
+
277
+
278
+ def storage_status() -> Dict[str, Any]:
279
+ cfg = load_config()
280
+ target = download_root()
281
+ builtin = builtin_root()
282
+ locations = [_describe(builtin, builtin=True, label="Built-in (current models)", target=target)]
283
+ for loc in cfg["locations"]:
284
+ p = Path(loc["path"])
285
+ locations.append(_describe(p, builtin=False, label=loc.get("label") or display_path(p), target=target))
286
+ return {
287
+ "locations": locations,
288
+ "download_target": display_path(target),
289
+ "download_target_fallback": cfg["download_target"] != BUILTIN and target == builtin,
290
+ "restart_note": "ComfyUI reads new locations when it starts: restart HomePilot (make start) after adding one.",
291
+ }
292
+
293
+
294
+ class LocationIn(BaseModel):
295
+ path: str = Field(..., min_length=1, max_length=500)
296
+ label: str = Field("", max_length=80)
297
+
298
+
299
+ class StorageIn(BaseModel):
300
+ locations: List[LocationIn] = Field(default_factory=list)
301
+ download_target: str = Field(BUILTIN, max_length=500)
302
+
303
+
304
+ @router.get("")
305
+ def get_storage():
306
+ return {"ok": True, **storage_status()}
307
+
308
+
309
+ @router.put("")
310
+ def put_storage(body: StorageIn):
311
+ if len(body.locations) > MAX_LOCATIONS:
312
+ raise HTTPException(400, f"At most {MAX_LOCATIONS} extra locations")
313
+ builtin = builtin_root().resolve()
314
+ seen: List[Path] = []
315
+ stored: List[Dict[str, str]] = []
316
+ for loc in body.locations:
317
+ try:
318
+ p = to_local_path(loc.path)
319
+ except ValueError as e:
320
+ raise HTTPException(400, str(e))
321
+ if p.resolve() == builtin or p in seen:
322
+ continue
323
+ try:
324
+ p.mkdir(parents=True, exist_ok=True)
325
+ for sub in MODEL_FOLDERS:
326
+ (p / sub).mkdir(exist_ok=True)
327
+ except OSError as e:
328
+ raise HTTPException(400, f"Cannot use {loc.path}: {e.strerror or e}")
329
+ if not os.access(p, os.W_OK):
330
+ raise HTTPException(400, f"{loc.path} is not writable")
331
+ seen.append(p)
332
+ stored.append({"path": str(p), "label": loc.label.strip()})
333
+
334
+ target = BUILTIN
335
+ if body.download_target and body.download_target != BUILTIN:
336
+ try:
337
+ t = to_local_path(body.download_target)
338
+ except ValueError as e:
339
+ raise HTTPException(400, str(e))
340
+ if t.resolve() != builtin:
341
+ if t not in seen:
342
+ raise HTTPException(400, "The download location must be one of the listed locations")
343
+ target = str(t)
344
+
345
+ cfg = _config_file()
346
+ cfg.parent.mkdir(parents=True, exist_ok=True)
347
+ cfg.write_text(json.dumps({"locations": stored, "download_target": target}, indent=2), encoding="utf-8")
348
+ write_comfy_paths_files()
349
+ return {"ok": True, **storage_status()}
backend/app/models/lora_loader.py CHANGED
@@ -48,10 +48,38 @@ MIN_LORA_SIZE = 100 * 1024
48
 
49
 
50
  def get_lora_dir() -> Path:
51
- """Return the path to the LoRA models directory."""
52
  return get_comfy_models_path() / "loras"
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def _get_registry_lookup() -> Dict[str, "LoRAEntry"]: # noqa: F821
56
  """Lazily build id→LoRAEntry map from the registry.
57
 
@@ -291,14 +319,24 @@ def scan_installed_loras() -> List[Dict]:
291
  - file_size_human: human-readable size string
292
  - gated: True if LoRA is NSFW/gated (only show when spicy mode enabled)
293
  """
294
- lora_dir = get_lora_dir()
295
- if not lora_dir.exists():
296
  return []
297
 
298
  registry = _get_registry_lookup()
299
 
300
  results: List[Dict] = []
301
- for f in sorted(lora_dir.iterdir()):
 
 
 
 
 
 
 
 
 
 
302
  if f.suffix.lower() in (".safetensors", ".pt", ".ckpt"):
303
  lora_id = f.stem
304
  entry = registry.get(lora_id)
 
48
 
49
 
50
  def get_lora_dir() -> Path:
51
+ """Return the path to the built-in LoRA models directory (models/comfy/loras)."""
52
  return get_comfy_models_path() / "loras"
53
 
54
 
55
+ def get_lora_dirs() -> List[Path]:
56
+ """The loras folder of every model storage location (app/model_storage.py), built-in first."""
57
+ try:
58
+ from ..model_storage import model_dirs
59
+ dirs = model_dirs("loras")
60
+ return dirs or [get_lora_dir()]
61
+ except Exception:
62
+ return [get_lora_dir()]
63
+
64
+
65
+ def get_lora_install_dir() -> Path:
66
+ """Where a new LoRA download goes: the location chosen for new downloads."""
67
+ try:
68
+ from ..model_storage import download_root
69
+ return download_root() / "loras"
70
+ except Exception:
71
+ return get_lora_dir()
72
+
73
+
74
+ def find_lora_file(filename: str) -> Optional[Path]:
75
+ """The LoRA file in whichever storage location has it, or None."""
76
+ for d in get_lora_dirs():
77
+ p = d / filename
78
+ if p.exists():
79
+ return p
80
+ return None
81
+
82
+
83
  def _get_registry_lookup() -> Dict[str, "LoRAEntry"]: # noqa: F821
84
  """Lazily build id→LoRAEntry map from the registry.
85
 
 
319
  - file_size_human: human-readable size string
320
  - gated: True if LoRA is NSFW/gated (only show when spicy mode enabled)
321
  """
322
+ lora_dirs = [d for d in get_lora_dirs() if d.exists()]
323
+ if not lora_dirs:
324
  return []
325
 
326
  registry = _get_registry_lookup()
327
 
328
  results: List[Dict] = []
329
+ seen_names: set = set()
330
+ files = []
331
+ for d in lora_dirs: # every storage location; the first copy of a filename wins
332
+ try:
333
+ files += sorted(d.iterdir())
334
+ except OSError:
335
+ continue
336
+ for f in files:
337
+ if f.name in seen_names:
338
+ continue
339
+ seen_names.add(f.name)
340
  if f.suffix.lower() in (".safetensors", ".pt", ".ckpt"):
341
  lora_id = f.stem
342
  entry = registry.get(lora_id)
backend/app/models/lora_routes.py CHANGED
@@ -26,6 +26,9 @@ from .lora_registry import get_lora_registry, get_lora_by_id
26
  from .lora_loader import (
27
  scan_installed_loras,
28
  get_lora_dir,
 
 
 
29
  is_lora_compatible,
30
  LORA_COMPAT,
31
  ARCH_LABELS,
@@ -273,7 +276,13 @@ async def install_lora(lora_id: str):
273
  if not entry:
274
  return {"ok": False, "error": f"Unknown LoRA: {lora_id}"}
275
 
276
- lora_dir = get_lora_dir()
 
 
 
 
 
 
277
  dest = lora_dir / entry.filename
278
 
279
  if dest.exists() and dest.stat().st_size > 0:
@@ -361,14 +370,14 @@ async def delete_lora(lora_id: str):
361
 
362
  Only deletes files in the loras directory.
363
  """
364
- lora_dir = get_lora_dir()
365
- if not lora_dir.exists():
366
  return {"ok": False, "error": "LoRA directory does not exist"}
367
 
368
- # Find the file (check all supported extensions)
369
  target = None
370
- for f in lora_dir.iterdir():
371
- if f.stem == lora_id and f.suffix.lower() in (".safetensors", ".pt", ".ckpt"):
372
  target = f
373
  break
374
 
 
26
  from .lora_loader import (
27
  scan_installed_loras,
28
  get_lora_dir,
29
+ get_lora_dirs,
30
+ get_lora_install_dir,
31
+ find_lora_file,
32
  is_lora_compatible,
33
  LORA_COMPAT,
34
  ARCH_LABELS,
 
276
  if not entry:
277
  return {"ok": False, "error": f"Unknown LoRA: {lora_id}"}
278
 
279
+ existing = find_lora_file(entry.filename)
280
+ if existing is not None and existing.stat().st_size > 0:
281
+ return {"ok": True, "message": f"{entry.name} is already installed", "already_installed": True}
282
+
283
+ # New downloads go to the location chosen in Settings > Models > Model storage.
284
+ lora_dir = get_lora_install_dir()
285
+ lora_dir.mkdir(parents=True, exist_ok=True)
286
  dest = lora_dir / entry.filename
287
 
288
  if dest.exists() and dest.stat().st_size > 0:
 
370
 
371
  Only deletes files in the loras directory.
372
  """
373
+ lora_dirs = [d for d in get_lora_dirs() if d.exists()]
374
+ if not lora_dirs:
375
  return {"ok": False, "error": "LoRA directory does not exist"}
376
 
377
+ # Find the file in any storage location (check all supported extensions)
378
  target = None
379
+ for f in (f for d in lora_dirs for f in d.iterdir()):
380
+ if target is None and f.stem == lora_id and f.suffix.lower() in (".safetensors", ".pt", ".ckpt"):
381
  target = f
382
  break
383
 
backend/app/providers.py CHANGED
@@ -157,6 +157,16 @@ def check_comfy_nodes_available(node_names: List[str], base_url: str = None) ->
157
  # Check if any of the nodes exist
158
  return any(name in object_info for name in node_names)
159
 
 
 
 
 
 
 
 
 
 
 
160
  def scan_installed_models(model_type: str = "image") -> List[str]:
161
  """
162
  Scan filesystem for actually installed ComfyUI models.
@@ -175,10 +185,11 @@ def scan_installed_models(model_type: str = "image") -> List[str]:
175
  # found here are returned directly as catalog ID matches.
176
  # This ensures newly downloaded models appear immediately
177
  # without needing to update a hardcoded list.
178
- scan_dirs = [
179
- models_path / "checkpoints",
180
- models_path / "unet",
181
- ]
 
182
  extensions = {".safetensors", ".ckpt"}
183
 
184
  disk_files: set = set()
@@ -187,6 +198,10 @@ def scan_installed_models(model_type: str = "image") -> List[str]:
187
  try:
188
  for f in scan_dir.iterdir():
189
  if f.is_file() and f.suffix in extensions and f.stat().st_size > 0:
 
 
 
 
190
  disk_files.add(f.name)
191
  except OSError:
192
  pass
@@ -304,10 +319,18 @@ def scan_installed_models(model_type: str = "image") -> List[str]:
304
  # Unknown model_type, return empty
305
  checks = {}
306
 
307
- # Check which models are actually installed
 
308
  for catalog_id, model_path in checks.items():
309
- if model_path.exists() and model_path.stat().st_size > 0:
310
- installed.append(catalog_id)
 
 
 
 
 
 
 
311
 
312
  return installed
313
 
 
157
  # Check if any of the nodes exist
158
  return any(name in object_info for name in node_names)
159
 
160
+ def _model_roots(builtin: Path) -> List[Path]:
161
+ """Built-in models folder plus the extra model storage locations (if any)."""
162
+ try:
163
+ from .model_storage import comfy_model_roots
164
+ roots = comfy_model_roots()
165
+ return roots if roots else [builtin]
166
+ except Exception:
167
+ return [builtin]
168
+
169
+
170
  def scan_installed_models(model_type: str = "image") -> List[str]:
171
  """
172
  Scan filesystem for actually installed ComfyUI models.
 
185
  # found here are returned directly as catalog ID matches.
186
  # This ensures newly downloaded models appear immediately
187
  # without needing to update a hardcoded list.
188
+ # Every model storage location (built-in models/comfy plus any extra ones,
189
+ # e.g. an external drive — app/model_storage.py).
190
+ scan_dirs = []
191
+ for _root in _model_roots(models_path):
192
+ scan_dirs += [_root / "checkpoints", _root / "unet"]
193
  extensions = {".safetensors", ".ckpt"}
194
 
195
  disk_files: set = set()
 
198
  try:
199
  for f in scan_dir.iterdir():
200
  if f.is_file() and f.suffix in extensions and f.stat().st_size > 0:
201
+ # A cut-off download is not "installed": ComfyUI cannot load it.
202
+ from .model_storage import incomplete_model_reason
203
+ if incomplete_model_reason(f):
204
+ continue
205
  disk_files.add(f.name)
206
  except OSError:
207
  pass
 
319
  # Unknown model_type, return empty
320
  checks = {}
321
 
322
+ # Check which models are actually installed — in any storage location.
323
+ roots = _model_roots(models_path)
324
  for catalog_id, model_path in checks.items():
325
+ try:
326
+ rel = model_path.relative_to(models_path)
327
+ candidates = [root / rel for root in roots]
328
+ except ValueError:
329
+ candidates = [model_path]
330
+ for candidate in candidates:
331
+ if candidate.exists() and (candidate.is_dir() or candidate.stat().st_size > 0):
332
+ installed.append(catalog_id)
333
+ break
334
 
335
  return installed
336
 
build-info.json CHANGED
@@ -1 +1 @@
1
- {"sha": "4cf0ad3a3db659c6b4ebd401c554e3c3cdec0d9f", "built_at": "2026-11-25T17:39:24Z", "ref": "master"}
 
1
+ {"sha": "8f62d34424a98d4e1114ac223bede818102d6706", "built_at": "2026-11-25T18:32:55Z", "ref": "master"}
frontend/.cache-bust CHANGED
@@ -1 +1 @@
1
- 1795628364
 
1
+ 1795631575
frontend/src/ui/SettingsPanel.tsx CHANGED
@@ -1,5 +1,6 @@
1
  import { useBackToClose } from "./lib/useBackToClose";
2
  import ConnectorsPanel from "./connectors/ConnectorsPanel";
 
3
  import React, { useEffect, useMemo, useRef, useState } from "react";
4
  import {
5
  Settings as SettingsIcon,
@@ -1216,6 +1217,13 @@ export default function SettingsPanel({
1216
  >
1217
  <ModelAdvisorToggle />
1218
  </SettingsCard>
 
 
 
 
 
 
 
1219
  <SettingsCard
1220
  title="Model Endpoints"
1221
  description="Optional base URLs and the specific model for each provider."
 
1
  import { useBackToClose } from "./lib/useBackToClose";
2
  import ConnectorsPanel from "./connectors/ConnectorsPanel";
3
+ import ModelStorageSettings from "./components/ModelStorageSettings";
4
  import React, { useEffect, useMemo, useRef, useState } from "react";
5
  import {
6
  Settings as SettingsIcon,
 
1217
  >
1218
  <ModelAdvisorToggle />
1219
  </SettingsCard>
1220
+ <SettingsCard
1221
+ title="Model storage"
1222
+ description="Where image, video and edit models are kept. Add a folder on another drive (for example an external disk) and choose it for new downloads — your current models stay where they are. Applies right away."
1223
+ icon={<Boxes size={16} />}
1224
+ >
1225
+ <ModelStorageSettings />
1226
+ </SettingsCard>
1227
  <SettingsCard
1228
  title="Model Endpoints"
1229
  description="Optional base URLs and the specific model for each provider."
frontend/src/ui/components/ModelStorageSettings.tsx ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ModelStorageSettings — where ComfyUI models (image, video, edit, upscale, LoRA) are stored.
3
+ *
4
+ * The built-in folder (models/comfy) is always kept and never changed. Extra locations, such as
5
+ * an external drive (E:\homepilot-models), can be added, and one of them chosen for new
6
+ * downloads. Backend: GET/PUT /v1/models/storage (backend/app/model_storage.py).
7
+ */
8
+ import React, { useCallback, useEffect, useState } from 'react'
9
+ import { authFetch } from '../lib/authFetch'
10
+ import { resolveBackendUrl } from '../lib/backendUrl'
11
+
12
+ export type StorageLocation = {
13
+ path: string
14
+ display_path: string
15
+ label: string
16
+ builtin: boolean
17
+ exists: boolean
18
+ writable: boolean
19
+ is_download_target: boolean
20
+ free_gb: number | null
21
+ total_gb: number | null
22
+ model_files: number | null
23
+ }
24
+
25
+ type StorageStatus = {
26
+ locations: StorageLocation[]
27
+ download_target: string
28
+ download_target_fallback: boolean
29
+ restart_note: string
30
+ }
31
+
32
+ function endpoint(): string {
33
+ return `${resolveBackendUrl()}/v1/models/storage`
34
+ }
35
+
36
+ export default function ModelStorageSettings() {
37
+ const [status, setStatus] = useState<StorageStatus | null>(null)
38
+ const [newPath, setNewPath] = useState('')
39
+ const [busy, setBusy] = useState(false)
40
+ const [error, setError] = useState('')
41
+ const [saved, setSaved] = useState('')
42
+
43
+ const load = useCallback(async () => {
44
+ try {
45
+ const r = await authFetch(endpoint())
46
+ const data = await r.json()
47
+ if (!r.ok) throw new Error(data?.detail || `HTTP ${r.status}`)
48
+ setStatus(data)
49
+ setError('')
50
+ } catch (e) {
51
+ setError(e instanceof Error ? e.message : 'Could not load model storage')
52
+ }
53
+ }, [])
54
+
55
+ useEffect(() => { void load() }, [load])
56
+
57
+ const save = useCallback(async (locations: { path: string; label?: string }[], downloadTarget: string, message: string) => {
58
+ setBusy(true)
59
+ setError('')
60
+ setSaved('')
61
+ try {
62
+ const r = await authFetch(endpoint(), {
63
+ method: 'PUT',
64
+ headers: { 'Content-Type': 'application/json' },
65
+ body: JSON.stringify({ locations, download_target: downloadTarget }),
66
+ })
67
+ const data = await r.json()
68
+ if (!r.ok) throw new Error(data?.detail || `HTTP ${r.status}`)
69
+ setStatus(data)
70
+ setSaved(message)
71
+ return true
72
+ } catch (e) {
73
+ setError(e instanceof Error ? e.message : 'Could not save')
74
+ return false
75
+ } finally {
76
+ setBusy(false)
77
+ }
78
+ }, [])
79
+
80
+ if (!status) {
81
+ return <p className="text-xs text-white/45">{error || 'Loading model storage…'}</p>
82
+ }
83
+
84
+ const extras = status.locations.filter((l) => !l.builtin)
85
+ const currentTarget = status.locations.find((l) => l.is_download_target)
86
+ const targetValue = (l: StorageLocation) => (l.builtin ? 'builtin' : l.path)
87
+ const extraList = (list: StorageLocation[]) => list.map((l) => ({ path: l.path, label: l.label }))
88
+
89
+ const addLocation = async () => {
90
+ const path = newPath.trim()
91
+ if (!path) return
92
+ const ok = await save([...extraList(extras), { path }],
93
+ currentTarget ? targetValue(currentTarget) : 'builtin',
94
+ `Added ${path}. ${status.restart_note}`)
95
+ if (ok) setNewPath('')
96
+ }
97
+
98
+ const setTarget = (l: StorageLocation) =>
99
+ save(extraList(extras), targetValue(l), `New downloads will go to ${l.display_path}.`)
100
+
101
+ const remove = (l: StorageLocation) =>
102
+ save(extraList(extras.filter((x) => x.path !== l.path)),
103
+ l.is_download_target ? 'builtin' : (currentTarget ? targetValue(currentTarget) : 'builtin'),
104
+ `Removed ${l.display_path} from the list. Its files were not deleted.`)
105
+
106
+ return (
107
+ <div className="space-y-3">
108
+ <ul className="space-y-2" aria-label="Model storage locations">
109
+ {status.locations.map((l) => (
110
+ <li key={l.path} className="rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5">
111
+ <div className="flex items-start justify-between gap-3">
112
+ <label className="flex items-start gap-2.5 min-w-0 cursor-pointer">
113
+ <input
114
+ type="radio"
115
+ name="model-download-target"
116
+ className="mt-1 accent-[#9b5cff]"
117
+ checked={l.is_download_target}
118
+ disabled={busy || !l.exists || !l.writable}
119
+ onChange={() => { void setTarget(l) }}
120
+ aria-label={`Use ${l.display_path} for new downloads`}
121
+ />
122
+ <span className="min-w-0">
123
+ <span className="block text-sm text-white/90 truncate">{l.label}</span>
124
+ <span className="block text-xs text-white/45 font-mono truncate">{l.display_path}</span>
125
+ <span className="block text-[11px] text-white/40 mt-0.5">
126
+ {!l.exists
127
+ ? 'Not available (drive not connected?) — skipped until it is back'
128
+ : `${l.free_gb ?? '?'} GB free of ${l.total_gb ?? '?'} GB · ${l.model_files ?? 0} model files`}
129
+ {l.is_download_target ? ' · default for new downloads' : ''}
130
+ </span>
131
+ </span>
132
+ </label>
133
+ {!l.builtin && (
134
+ <button
135
+ type="button"
136
+ disabled={busy}
137
+ onClick={() => { void remove(l) }}
138
+ className="shrink-0 text-xs text-white/50 hover:text-white/85 px-2 py-1 rounded-lg hover:bg-white/5"
139
+ >
140
+ Remove
141
+ </button>
142
+ )}
143
+ </div>
144
+ </li>
145
+ ))}
146
+ </ul>
147
+
148
+ <div className="flex gap-2">
149
+ <input
150
+ type="text"
151
+ value={newPath}
152
+ onChange={(e) => setNewPath(e.target.value)}
153
+ onKeyDown={(e) => { if (e.key === 'Enter') void addLocation() }}
154
+ placeholder="Add a folder, e.g. E:\homepilot-models"
155
+ aria-label="Folder to add as a model storage location"
156
+ className="flex-1 min-w-0 h-9 rounded-lg bg-black/30 border border-white/10 px-3 text-sm text-white/90 placeholder:text-white/30 outline-none focus:border-[#9b5cff]/60"
157
+ />
158
+ <button
159
+ type="button"
160
+ disabled={busy || !newPath.trim()}
161
+ onClick={() => { void addLocation() }}
162
+ className="h-9 px-3 rounded-lg bg-[#9b5cff]/20 border border-[#9b5cff]/30 text-sm text-white/90 hover:bg-[#9b5cff]/30 disabled:opacity-50"
163
+ >
164
+ {busy ? 'Saving…' : 'Add'}
165
+ </button>
166
+ </div>
167
+
168
+ {status.download_target_fallback && (
169
+ <p className="text-xs text-amber-300/80" role="status">
170
+ The chosen download location is not available right now, so new downloads go to the built-in folder.
171
+ </p>
172
+ )}
173
+ {error && <p className="text-xs text-red-300/90" role="alert">{error}</p>}
174
+ {saved && <p className="text-xs text-emerald-300/80" role="status">{saved}</p>}
175
+ <p className="text-[11px] text-white/35 leading-relaxed">
176
+ Existing models stay where they are. ComfyUI reads every location listed here; it picks up a
177
+ new location after HomePilot restarts. Chat models (Ollama) are not affected.
178
+ </p>
179
+ </div>
180
+ )
181
+ }
frontend/src/ui/components/__tests__/ModelStorageSettings.test.tsx ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react'
2
+ import { afterEach, describe, expect, it, vi } from 'vitest'
3
+ import { cleanup, fireEvent, render, screen } from '@testing-library/react'
4
+ import ModelStorageSettings from '../ModelStorageSettings'
5
+
6
+ const builtin = { path: '/repo/models/comfy', display_path: 'C:\repo\models\comfy', label: 'Built-in (current models)', builtin: true, exists: true, writable: true, is_download_target: true, free_gb: 9.6, total_gb: 929, model_files: 32 }
7
+ const ext = { path: '/mnt/e/homepilot-models', display_path: 'E:\homepilot-models', label: 'E:\homepilot-models', builtin: false, exists: true, writable: true, is_download_target: false, free_gb: 114, total_gb: 466, model_files: 0 }
8
+
9
+ function json(body: unknown, ok = true): Response {
10
+ return { ok, status: ok ? 200 : 400, json: async () => body } as unknown as Response
11
+ }
12
+
13
+ afterEach(() => { cleanup(); vi.unstubAllGlobals() })
14
+
15
+ describe('ModelStorageSettings', () => {
16
+ it('shows locations and adds a folder as a new location', async () => {
17
+ const calls: { method: string; body?: any }[] = []
18
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init?: RequestInit) => {
19
+ const method = init?.method || 'GET'
20
+ calls.push({ method, body: init?.body ? JSON.parse(String(init.body)) : undefined })
21
+ if (method === 'PUT') return json({ locations: [builtin, ext], download_target: 'C:\repo\models\comfy', download_target_fallback: false, restart_note: 'Restart.' })
22
+ return json({ locations: [builtin], download_target: 'C:\repo\models\comfy', download_target_fallback: false, restart_note: 'Restart.' })
23
+ }))
24
+ render(<ModelStorageSettings />)
25
+ expect(await screen.findByText('Built-in (current models)')).toBeTruthy()
26
+ expect(screen.getByText(/9.6 GB free/)).toBeTruthy()
27
+
28
+ fireEvent.change(screen.getByLabelText('Folder to add as a model storage location'), { target: { value: 'E:\homepilot-models' } })
29
+ fireEvent.click(screen.getByText('Add'))
30
+ expect(await screen.findByText(/114 GB free/)).toBeTruthy()
31
+ const put = calls.find((c) => c.method === 'PUT')!
32
+ expect(put.body).toEqual({ locations: [{ path: 'E:\homepilot-models' }], download_target: 'builtin' })
33
+ })
34
+
35
+ it('chooses a location for new downloads', async () => {
36
+ const calls: any[] = []
37
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init?: RequestInit) => {
38
+ if (init?.method === 'PUT') { calls.push(JSON.parse(String(init.body))); return json({ locations: [{ ...builtin, is_download_target: false }, { ...ext, is_download_target: true }], download_target: 'E:\homepilot-models', download_target_fallback: false, restart_note: '' }) }
39
+ return json({ locations: [builtin, ext], download_target: 'C:\repo\models\comfy', download_target_fallback: false, restart_note: '' })
40
+ }))
41
+ render(<ModelStorageSettings />)
42
+ fireEvent.click(await screen.findByLabelText('Use E:\homepilot-models for new downloads'))
43
+ expect(await screen.findByText('New downloads will go to E:\homepilot-models.')).toBeTruthy()
44
+ expect(calls[0]).toEqual({ locations: [{ path: '/mnt/e/homepilot-models', label: 'E:\homepilot-models' }], download_target: '/mnt/e/homepilot-models' })
45
+ })
46
+ })
scripts/download.py CHANGED
@@ -80,7 +80,9 @@ PROJECT_ROOT = SCRIPT_DIR.parent
80
  CATALOG_PATH = PROJECT_ROOT / "backend" / "app" / "model_catalog_data.json"
81
 
82
  # ComfyUI models root - consistent with download_models.sh
83
- COMFYUI_ROOT = PROJECT_ROOT / "models" / "comfy"
 
 
84
 
85
  # ComfyUI installation root (for custom_nodes)
86
  def get_comfyui_install_root() -> Path:
@@ -498,6 +500,22 @@ def get_install_path(model_type: str, custom_path: Optional[str] = None) -> Path
498
  return path
499
 
500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
501
  def download_file(
502
  url: str,
503
  dest: Path,
@@ -547,6 +565,18 @@ def download_file(
547
 
548
  mode = "ab" if start_pos > 0 else "wb"
549
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  if show_progress and total_size > 0:
551
  progress = tqdm(
552
  total=total_size,
@@ -567,6 +597,15 @@ def download_file(
567
  if show_progress and total_size > 0:
568
  progress.close()
569
 
 
 
 
 
 
 
 
 
 
570
  # Move to final location
571
  temp_file.replace(dest)
572
 
 
80
  CATALOG_PATH = PROJECT_ROOT / "backend" / "app" / "model_catalog_data.json"
81
 
82
  # ComfyUI models root - consistent with download_models.sh
83
+ # Where ComfyUI models are downloaded. The backend sets HOMEPILOT_MODELS_ROOT to the location
84
+ # chosen in Settings > Models > Model storage (e.g. an external drive); default models/comfy.
85
+ COMFYUI_ROOT = Path(os.environ["HOMEPILOT_MODELS_ROOT"]) if os.environ.get("HOMEPILOT_MODELS_ROOT") else PROJECT_ROOT / "models" / "comfy"
86
 
87
  # ComfyUI installation root (for custom_nodes)
88
  def get_comfyui_install_root() -> Path:
 
500
  return path
501
 
502
 
503
+ def _safetensors_complete(path: Path) -> bool:
504
+ """True when the safetensors header's tensors all fit inside the file."""
505
+ try:
506
+ size = path.stat().st_size
507
+ with open(path, "rb") as f:
508
+ n = int.from_bytes(f.read(8), "little")
509
+ if n <= 0 or 8 + n > size:
510
+ return False
511
+ header = json.loads(f.read(n))
512
+ end = max((v["data_offsets"][1] for k, v in header.items()
513
+ if k != "__metadata__" and isinstance(v, dict)), default=0)
514
+ return 8 + n + end <= size
515
+ except Exception:
516
+ return False
517
+
518
+
519
  def download_file(
520
  url: str,
521
  dest: Path,
 
565
 
566
  mode = "ab" if start_pos > 0 else "wb"
567
 
568
+ # Not enough room for the rest of the file: stop now rather than leave a cut-off model.
569
+ remaining = total_size - start_pos
570
+ if remaining > 0:
571
+ free = shutil.disk_usage(temp_file.parent).free
572
+ if free < remaining:
573
+ response.close()
574
+ return False, (
575
+ f"Not enough disk space for {dest.name}: needs {remaining / 1024**3:.1f} GB, "
576
+ f"{free / 1024**3:.1f} GB free on {temp_file.parent}. Free up space or add a "
577
+ f"model storage location on a bigger drive (Settings > Models > Model storage)."
578
+ )
579
+
580
  if show_progress and total_size > 0:
581
  progress = tqdm(
582
  total=total_size,
 
597
  if show_progress and total_size > 0:
598
  progress.close()
599
 
600
+ # Only a complete file gets the real name. A short one stays as .part, so the next
601
+ # run resumes it instead of ComfyUI failing on it later.
602
+ got = temp_file.stat().st_size
603
+ if total_size > 0 and got != total_size:
604
+ return False, (f"Download of {dest.name} stopped early ({got / 1024**3:.2f} of "
605
+ f"{total_size / 1024**3:.2f} GB). Run it again to resume.")
606
+ if dest.suffix.lower() == ".safetensors" and not _safetensors_complete(temp_file):
607
+ return False, f"Downloaded {dest.name} is incomplete or damaged; run it again."
608
+
609
  # Move to final location
610
  temp_file.replace(dest)
611