Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Feat(Model Manager): Add improved download manager with pause/resume partial download. (#8864)
DustyShoeb9f901521490
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.pyindex f67393f2ea..d2e6f6096e 100644--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@ -765,6 +765,7 @@ async def list_model_installs() -> List[ModelInstallJob]:* "waiting" -- Job is waiting in the queue to run* "downloading" -- Model file(s) are downloading* "running" -- Model has downloaded and the model probing and registration process is running+ * "paused" -- Job is paused and can be resumed* "completed" -- Installation completed successfully* "error" -- An error occurred. Details will be in the "error_type" and "error" fields.* "cancelled" -- Job was cancelled before completion.@@ -818,6 +819,89 @@ async def cancel_model_install_job(id: int = Path(description="Model install jobinstaller.cancel_job(job)+@model_manager_router.post(+ "/install/{id}/pause",+ operation_id="pause_model_install_job",+ responses={+ 201: {"description": "The job was paused successfully"},+ 415: {"description": "No such job"},+ },+ status_code=201,+)+async def pause_model_install_job(id: int = Path(description="Model install job ID")) -> ModelInstallJob:+ """Pause the model install job corresponding to the given job ID."""+ installer = ApiDependencies.invoker.services.model_manager.install+ try:+ job = installer.get_job_by_id(id)+ except ValueError as e:+ raise HTTPException(status_code=415, detail=str(e))+ installer.pause_job(job)+ return job+++@model_manager_router.post(+ "/install/{id}/resume",+ operation_id="resume_model_install_job",+ responses={+ 201: {"description": "The job was resumed successfully"},+ 415: {"description": "No such job"},+ },+ status_code=201,+)+async def resume_model_install_job(id: int = Path(description="Model install job ID")) -> ModelInstallJob:+ """Resume a paused model install job corresponding to the given job ID."""+ installer = ApiDependencies.invoker.services.model_manager.install+ try:+ job = installer.get_job_by_id(id)+ except ValueError as e:+ raise HTTPException(status_code=415, detail=str(e))+ installer.resume_job(job)+ return job+++@model_manager_router.post(+ "/install/{id}/restart_failed",+ operation_id="restart_failed_model_install_job",+ responses={+ 201: {"description": "Failed files restarted successfully"},+ 415: {"description": "No such job"},+ },+ status_code=201,+)+async def restart_failed_model_install_job(id: int = Path(description="Model install job ID")) -> ModelInstallJob:+ """Restart failed or non-resumable file downloads for the given job."""+ installer = ApiDependencies.invoker.services.model_manager.install+ try:+ job = installer.get_job_by_id(id)+ except ValueError as e:+ raise HTTPException(status_code=415, detail=str(e))+ installer.restart_failed(job)+ return job+++@model_manager_router.post(+ "/install/{id}/restart_file",+ operation_id="restart_model_install_file",+ responses={+ 201: {"description": "File restarted successfully"},+ 415: {"description": "No such job"},+ },+ status_code=201,+)+async def restart_model_install_file(+ id: int = Path(description="Model install job ID"),+ file_source: AnyHttpUrl = Body(description="File download URL to restart"),+) -> ModelInstallJob:+ """Restart a specific file download for the given job."""+ installer = ApiDependencies.invoker.services.model_manager.install+ try:+ job = installer.get_job_by_id(id)+ except ValueError as e:+ raise HTTPException(status_code=415, detail=str(e))+ installer.restart_file(job, str(file_source))+ return job++@model_manager_router.delete("/install",operation_id="prune_model_install_jobs",diff --git a/invokeai/app/services/download/download_base.py b/invokeai/app/services/download/download_base.pyindex 4880ab98b8..1798fd69df 100644--- a/invokeai/app/services/download/download_base.py+++ b/invokeai/app/services/download/download_base.py@@ -18,6 +18,7 @@ class DownloadJobStatus(str, Enum):WAITING = "waiting" # not enqueued, will not runRUNNING = "running" # actively downloading+ PAUSED = "paused" # paused, can be resumedCOMPLETED = "completed" # finished runningCANCELLED = "cancelled" # user cancelledERROR = "error" # terminated with an error message@@ -61,6 +62,7 @@ class DownloadJobBase(BaseModel):# internal flag_cancelled: bool = PrivateAttr(default=False)+ _paused: bool = PrivateAttr(default=False)# optional event handlers passed in on creation_on_start: Optional[DownloadEventHandler] = PrivateAttr(default=None)@@ -72,6 +74,12 @@ class DownloadJobBase(BaseModel):def cancel(self) -> None:"""Call to cancel the job."""self._cancelled = True+ self._paused = False++ def pause(self) -> None:+ """Pause the job, preserving partial downloads."""+ self._paused = True+ self._cancelled = True# cancelled and the callbacks are private attributes in order to prevent# them from being serialized and/or used in the Json Schema@@ -80,6 +88,11 @@ class DownloadJobBase(BaseModel):"""Call to cancel the job."""return self._cancelled+ @property+ def paused(self) -> bool:+ """Return true if job is paused."""+ return self._paused+@propertydef complete(self) -> bool:"""Return true if job completed without errors."""@@ -161,6 +174,17 @@ class DownloadJob(DownloadJobBase):default=None, description="Timestamp for when the download job ende1d (completed or errored)")content_type: Optional[str] = Field(default=None, description="Content type of downloaded file")+ canonical_url: Optional[str] = Field(default=None, description="Canonical URL to request on resume")+ etag: Optional[str] = Field(default=None, description="ETag from the remote server, if available")+ last_modified: Optional[str] = Field(default=None, description="Last-Modified from the remote server, if available")+ final_url: Optional[str] = Field(default=None, description="Final resolved URL after redirects, if available")+ expected_total_bytes: Optional[int] = Field(default=None, description="Expected total size of the download")+ resume_required: bool = Field(default=False, description="True if server refused resume; restart required")+ resume_message: Optional[str] = Field(default=None, description="Message explaining why resume is required")+ resume_from_scratch: bool = Field(+ default=False,+ description="True if resume metadata existed but the partial file was missing and the download restarted from the beginning",+ )def __hash__(self) -> int:"""Return hash of the string representation of this object, for indexing."""@@ -321,6 +345,10 @@ class DownloadQueueServiceBase(ABC):"""Cancel the job, clearing partial downloads and putting it into ERROR state."""pass+ def pause_job(self, job: DownloadJobBase) -> None: # noqa D401+ """Pause the job, preserving partial downloads."""+ raise NotImplementedError+@abstractmethoddef join(self) -> None:"""Wait until all jobs are off the queue."""diff --git a/invokeai/app/services/download/download_default.py b/invokeai/app/services/download/download_default.pyindex 0db9075dde..f65f00e2ae 100644--- a/invokeai/app/services/download/download_default.py+++ b/invokeai/app/services/download/download_default.py@@ -10,6 +10,7 @@ from pathlib import Pathfrom queue import Empty, PriorityQueuefrom shutil import disk_usagefrom typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Set+from urllib.parse import urlparseimport requestsfrom pydantic.networks import AnyHttpUrl@@ -60,6 +61,8 @@ class DownloadQueueService(DownloadQueueServiceBase):self._app_config = app_config or get_config()self._jobs: Dict[int, DownloadJob] = {}self._download_part2parent: Dict[AnyHttpUrl, MultiFileDownloadJob] = {}+ self._mfd_pending: Dict[int, list[DownloadJob]] = {}+ self._mfd_active: Dict[int, DownloadJob] = {}self._next_job_id = 0self._queue: PriorityQueue[DownloadJob] = PriorityQueue()self._stop_event = threading.Event()@@ -126,6 +129,11 @@ class DownloadQueueService(DownloadQueueServiceBase):self._jobs[job.id] = jobself._queue.put(job)+ def pause_job(self, job: DownloadJobBase) -> None:+ """Pause the indicated job, preserving partial downloads."""+ if job.status in [DownloadJobStatus.WAITING, DownloadJobStatus.RUNNING]:+ job.pause()+def download(self,source: AnyHttpUrl,@@ -189,6 +197,10 @@ class DownloadQueueService(DownloadQueueServiceBase):dest=path,access_token=access_token or self._lookup_access_token(url),)+ if part.size and part.size > 0:+ job.total_bytes = part.size+ job.expected_total_bytes = part.size+ job.canonical_url = str(url)mfdj.download_parts.add(job)self._download_part2parent[job.source] = mfdjif submit_job:@@ -196,15 +208,27 @@ class DownloadQueueService(DownloadQueueServiceBase):return mfdjdef submit_multifile_download(self, job: MultiFileDownloadJob) -> None:- for download_job in job.download_parts:- self.submit_download_job(- download_job,- on_start=self._mfd_started,- on_progress=self._mfd_progress,- on_complete=self._mfd_complete,- on_cancelled=self._mfd_cancelled,- on_error=self._mfd_error,- )+ pending = sorted(job.download_parts, key=lambda j: str(j.source))+ self._mfd_pending[job.id] = list(pending)+ self._mfd_active.pop(job.id, None)+ self._submit_next_mfd_part(job)++ def _submit_next_mfd_part(self, job: MultiFileDownloadJob) -> None:+ pending = self._mfd_pending.get(job.id, [])+ if not pending:+ return+ if self._mfd_active.get(job.id) is not None:+ return+ download_job = pending.pop(0)+ self._mfd_active[job.id] = download_job+ self.submit_download_job(+ download_job,+ on_start=self._mfd_started,+ on_progress=self._mfd_progress,+ on_complete=self._mfd_complete,+ on_cancelled=self._mfd_cancelled,+ on_error=self._mfd_error,+ )def join(self) -> None:"""Wait for all jobs to complete."""@@ -284,12 +308,18 @@ class DownloadQueueService(DownloadQueueServiceBase):except Empty:continuetry:+ if job.cancelled:+ raise DownloadJobCancelledException("Job was cancelled before start")job.job_started = get_iso_timestamp()self._do_download(job)- self._signal_job_complete(job)+ if job.status != DownloadJobStatus.COMPLETED:+ self._signal_job_complete(job)except DownloadJobCancelledException:- self._signal_job_cancelled(job)- self._cleanup_cancelled_job(job)+ if job.paused:+ self._signal_job_paused(job)+ else:+ self._signal_job_cancelled(job)+ self._cleanup_cancelled_job(job)except Exception as excp:job.error_type = excp.__class__.__name__ + f"({str(excp)})"job.error = traceback.format_exc()@@ -298,7 +328,6 @@ class DownloadQueueService(DownloadQueueServiceBase):job.job_ended = get_iso_timestamp()self._job_terminated_event.set() # signal a change to terminal stateself._download_part2parent.pop(job.source, None) # if this is a subpart of a multipart job, remove it- self._job_terminated_event.set()self._queue.task_done()self._logger.debug(f"Download queue worker thread {threading.current_thread().name} exiting.")@@ -306,22 +335,125 @@ class DownloadQueueService(DownloadQueueServiceBase):def _do_download(self, job: DownloadJob) -> None:"""Do the actual download."""- url = job.source+ url = job.canonical_url or str(job.source)header = {"Authorization": f"Bearer {job.access_token}"} if job.access_token else {}+ had_resume_metadata = bool(job.etag or job.last_modified)open_mode = "wb"+ resume_from = 0++ if not job.dest.is_dir():+ job.download_path = job.dest+ in_progress_path = self._in_progress_path(job.download_path)+ if in_progress_path.exists():+ resume_from = in_progress_path.stat().st_size+ job.bytes = resume_from+ self._logger.debug(+ f"Resume check: in-progress file found at {in_progress_path} size={resume_from} bytes"+ )+ if resume_from > 0:+ if job.etag:+ header["If-Range"] = job.etag+ elif job.last_modified:+ header["If-Range"] = job.last_modified+ header["Range"] = f"bytes={resume_from}-"+ open_mode = "ab"+ else:+ self._logger.debug(f"Resume check: no in-progress file at {in_progress_path}")+ elif job.download_path:+ # Resume for directory downloads when we already know the filename.+ in_progress_path = self._in_progress_path(job.download_path)+ if in_progress_path.exists():+ resume_from = in_progress_path.stat().st_size+ job.bytes = resume_from+ self._logger.debug(+ f"Resume check (dir): in-progress file found at {in_progress_path} size={resume_from} bytes"+ )+ if resume_from > 0:+ if job.etag:+ header["If-Range"] = job.etag+ elif job.last_modified:+ header["If-Range"] = job.last_modified+ header["Range"] = f"bytes={resume_from}-"+ open_mode = "ab"+ else:+ self._logger.debug(f"Resume check (dir): no in-progress file at {in_progress_path}")+ elif job.dest.is_dir():+ # Attempt to infer a single in-progress file from disk for directory downloads.+ try:+ candidates = sorted(job.dest.glob("*.downloading"))+ except OSError:+ candidates = []+ if len(candidates) == 1:+ inferred = candidates[0].with_name(candidates[0].name.removesuffix(".downloading"))+ job.download_path = inferred+ resume_from = candidates[0].stat().st_size+ job.bytes = resume_from+ self._logger.debug(+ f"Resume check (dir): inferred in-progress file path={candidates[0]} size={resume_from} bytes"+ )+ if resume_from > 0:+ if job.etag:+ header["If-Range"] = job.etag+ elif job.last_modified:+ header["If-Range"] = job.last_modified+ header["Range"] = f"bytes={resume_from}-"+ open_mode = "ab"+ else:+ self._logger.debug(+ "Resume check (dir): no prior download_path available; cannot resume from disk "+ f"(candidates={len(candidates)})"+ )++ if resume_from == 0:+ job.bytes = 0+ if had_resume_metadata:+ job.resume_from_scratch = True+ job.resume_message = "Partial file missing. Restarted download from the beginning."# Make a streaming request. This will retrieve headers including# content-length and content-disposition, but not fetch any content itselfresp = self._requests.get(str(url), headers=header, stream=True)+ job.final_url = str(resp.url) if resp.url else None+ self._logger.debug(+ "Resume response: "+ f"status={resp.status_code} "+ f"content_length={resp.headers.get('content-length')} "+ f"content_range={resp.headers.get('Content-Range')} "+ f"etag={resp.headers.get('ETag')} "+ f"last_modified={resp.headers.get('Last-Modified')}"+ )+ if resp.status_code == 416 and resume_from > 0:+ # Range not satisfiable - local partial is already complete+ expected = job.expected_total_bytes or job.total_bytes or resume_from+ if resume_from == expected:+ job.total_bytes = expected+ job.bytes = resume_from+ job.download_path = job.download_path or job.dest+ self._signal_job_started(job)+ self._signal_job_complete(job)+ return+ job.resume_required = True+ job.resume_message = "Resume refused by server. Restart required."+ job.pause()+ raise DownloadJobCancelledException("Resume refused by server. Restart required.")if not resp.ok:- raise HTTPError(resp.reason)+ host = urlparse(str(resp.url or url)).netloc+ status = resp.status_code+ reason = resp.reason+ if status >= 500:+ self._logger.error(f"Remote server error from {host}: HTTP {status} {reason}")+ raise HTTPError(reason)+ self._logger.error(f"Download failed from {host}: HTTP {status} {reason}")+ raise HTTPError(reason)job.content_type = resp.headers.get("Content-Type")+ job.etag = resp.headers.get("ETag") or job.etag+ job.last_modified = resp.headers.get("Last-Modified") or job.last_modifiedcontent_length = int(resp.headers.get("content-length", 0))- job.total_bytes = content_lengthif job.dest.is_dir():- file_name = os.path.basename(str(url.path)) # default is to use the last bit of the URL+ parsed_url = urlparse(str(url))+ file_name = os.path.basename(parsed_url.path) # default is to use the last bit of the URLif match := re.search('filename="(.+)"', resp.headers.get("Content-Disposition", "")):remote_name = match.group(1)@@ -336,39 +468,83 @@ class DownloadQueueService(DownloadQueueServiceBase):assert job.download_path+ in_progress_path = self._in_progress_path(job.download_path)++ if resume_from > 0 and resp.status_code == 200:+ # Server ignored Range. Restart download from scratch.+ job.resume_required = True+ job.resume_message = "Resume refused by server. Restart required."+ job.pause()+ raise DownloadJobCancelledException("Resume refused by server. Restart required.")++ if resume_from > 0 and resp.status_code == 206:+ content_range = resp.headers.get("Content-Range", "")+ total_from_range = None+ if match := re.match(r"bytes\s+\d+-\d+/(\d+)", content_range):+ total_from_range = int(match.group(1))+ if total_from_range is not None:+ job.total_bytes = total_from_range+ else:+ job.total_bytes = resume_from + content_length+ job.bytes = resume_from+ job.expected_total_bytes = job.total_bytes+ else:+ job.total_bytes = content_length+ job.expected_total_bytes = content_length++ if job.download_path.exists() and resume_from == 0:+ existing_size = job.download_path.stat().st_size+ if job.total_bytes > 0 and existing_size == job.total_bytes:+ job.bytes = existing_size+ self._signal_job_started(job)+ self._signal_job_complete(job)+ return+ # Existing file does not match expected size; treat as corrupt and restart.+ self._logger.debug(+ "Resume check: existing file size mismatch; deleting and restarting "+ f"path={job.download_path} existing_size={existing_size} expected={job.total_bytes}"+ )+ job.download_path.unlink()+free_space = disk_usage(job.download_path.parent).freeGB = 2**30- self._logger.debug(f"Download is {job.total_bytes / GB:.2f} GB of {free_space / GB:.2f} GB free.")- if free_space < job.total_bytes:+ remaining_bytes = max(job.total_bytes - job.bytes, 0)+ if free_space < remaining_bytes:raise RuntimeError(- f"Free disk space {free_space / GB:.2f} GB is not enough for download of {job.total_bytes / GB:.2f} GB."+ f"Free disk space {free_space / GB:.2f} GB is not enough for download of {remaining_bytes / GB:.2f} GB.")# Don't clobber an existing file. See commit 82c2c85202f88c6d24ff84710f297cfc6ae174af# for code that instead resumes an interrupted download.- if job.download_path.exists():+ if job.download_path.exists() and resume_from == 0:raise OSError(f"[Errno 17] File {job.download_path} exists")# append ".downloading" to the path- in_progress_path = self._in_progress_path(job.download_path)-# signal caller that the download is starting. At this point, key fields such as# download_path and total_bytes will be populated. We call it here because the might# discover that the local file is already complete and generate a COMPLETED status.self._signal_job_started(job)+ expected_total = job.total_bytes or job.expected_total_bytes or content_length# "range not satisfiable" - local file is at least as large as the remote file- if resp.status_code == 416 or (content_length > 0 and job.bytes >= content_length):- self._logger.warning(f"{job.download_path}: complete file found. Skipping.")+ if resp.status_code == 416 or (expected_total > 0 and job.bytes >= expected_total):+ self._logger.info(f"{job.download_path}: complete file found. Skipping.")return# "partial content" - local file is smaller than remote fileelif resp.status_code == 206 or job.bytes > 0:- self._logger.warning(f"{job.download_path}: partial file found. Resuming")+ self._logger.info(f"{job.download_path}: partial file found. Resuming")# some other errorelif resp.status_code != 200:- raise HTTPError(resp.reason)+ host = urlparse(str(resp.url or url)).netloc+ status = resp.status_code+ reason = resp.reason+ if status >= 500:+ self._logger.error(f"Remote server error from {host}: HTTP {status} {reason}")+ raise HTTPError(reason)+ self._logger.error(f"Download failed from {host}: HTTP {status} {reason}")+ raise HTTPError(reason)self._logger.debug(f"{job.source}: Downloading {job.download_path}")report_delta = job.total_bytes / 100 # report every 1% change@@ -385,6 +561,12 @@ class DownloadQueueService(DownloadQueueServiceBase):last_report_bytes = job.bytesself._signal_job_progress(job)+ if job.total_bytes > 0 and job.bytes < job.total_bytes:+ job.resume_required = True+ job.resume_message = "Download interrupted. Resume required."+ job.pause()+ raise DownloadJobCancelledException("Download interrupted. Resume required.")+# if we get here we are done and can rename the file to the original destself._logger.debug(f"{job.source}: saved to {job.download_path} (bytes={job.bytes})")in_progress_path.rename(job.download_path)@@ -445,6 +627,23 @@ class DownloadQueueService(DownloadQueueServiceBase):parent_job.status = DownloadJobStatus.CANCELLEDself._execute_cb(parent_job, "on_cancelled")+ def _signal_job_paused(self, job: DownloadJob) -> None:+ if job.status not in [DownloadJobStatus.RUNNING, DownloadJobStatus.WAITING]:+ return+ if job.download_path:+ in_progress_path = self._in_progress_path(job.download_path)+ if in_progress_path.exists():+ job.bytes = in_progress_path.stat().st_size+ job.status = DownloadJobStatus.PAUSED+ self._execute_cb(job, "on_cancelled")+ if self._event_bus:+ self._event_bus.emit_download_paused(job)++ if parent_job := self._download_part2parent.get(job.source, None):+ if not parent_job.in_terminal_state:+ parent_job.status = DownloadJobStatus.PAUSED+ self._execute_cb(parent_job, "on_cancelled")+def _signal_job_error(self, job: DownloadJob, excp: Optional[Exception] = None) -> None:job.status = DownloadJobStatus.ERRORself._logger.error(f"{str(job.source)}: {traceback.format_exception(excp)}")@@ -454,6 +653,8 @@ class DownloadQueueService(DownloadQueueServiceBase):self._event_bus.emit_download_error(job)def _cleanup_cancelled_job(self, job: DownloadJob) -> None:+ if job.paused:+ returnself._logger.debug(f"Cleaning up leftover files from cancelled download job {job.download_path}")try:if job.download_path:@@ -487,38 +688,56 @@ class DownloadQueueService(DownloadQueueServiceBase):self.cancel_job(part)elif mf_job.running:mf_job.total_bytes = sum(x.total_bytes for x in mf_job.download_parts)- mf_job.bytes = sum(x.total_bytes for x in mf_job.download_parts)+ mf_job.bytes = sum(x.bytes for x in mf_job.download_parts)self._execute_cb(mf_job, "on_progress")def _mfd_complete(self, download_job: DownloadJob) -> None:self._logger.info(f"Download complete: {download_job.source}")+ submit_next = False+ mf_job: Optional[MultiFileDownloadJob] = Nonewith self._lock:mf_job = self._download_part2parent[download_job.source]+ self._mfd_active.pop(mf_job.id, None)+ mf_job.total_bytes = sum(x.total_bytes for x in mf_job.download_parts)+ mf_job.bytes = sum(x.bytes for x in mf_job.download_parts)# are there any more active jobs left in this task?- if mf_job.running and all(x.complete for x in mf_job.download_parts):+ if all(x.complete for x in mf_job.download_parts):mf_job.status = DownloadJobStatus.COMPLETEDself._execute_cb(mf_job, "on_complete")+ elif not mf_job.in_terminal_state and not mf_job.paused:+ submit_next = True# we're done with this sub-jobself._job_terminated_event.set()+ if submit_next and mf_job is not None:+ self._submit_next_mfd_part(mf_job)def _mfd_cancelled(self, download_job: DownloadJob) -> None:with self._lock:mf_job = self._download_part2parent[download_job.source]assert mf_job is not None+ self._mfd_active.pop(mf_job.id, None)if not mf_job.in_terminal_state:- self._logger.warning(f"Download cancelled: {download_job.source}")- mf_job.cancel()-+ if download_job.paused:+ self._logger.warning(f"Download paused: {download_job.source}")+ mf_job.pause()+ else:+ self._logger.warning(f"Download cancelled: {download_job.source}")+ mf_job.cancel()++ if download_job.paused:+ returnfor s in mf_job.download_parts:self.cancel_job(s)+ self._mfd_pending.pop(mf_job.id, None)def _mfd_error(self, download_job: DownloadJob, excp: Optional[Exception] = None) -> None:with self._lock:mf_job = self._download_part2parent[download_job.source]assert mf_job is not None+ self._mfd_active.pop(mf_job.id, None)if not mf_job.in_terminal_state:mf_job.status = download_job.statusmf_job.error = download_job.error@@ -530,6 +749,7 @@ class DownloadQueueService(DownloadQueueServiceBase):for s in [x for x in mf_job.download_parts if x.running]:self.cancel_job(s)self._download_part2parent.pop(download_job.source)+ self._mfd_pending.pop(mf_job.id, None)self._job_terminated_event.set()def _execute_cb(diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.pyindex 4c2d3c5c4c..aa1cbb5e0e 100644--- a/invokeai/app/services/events/events_base.py+++ b/invokeai/app/services/events/events_base.py@@ -11,6 +11,7 @@ from invokeai.app.services.events.events_common import (DownloadCancelledEvent,DownloadCompleteEvent,DownloadErrorEvent,+ DownloadPausedEvent,DownloadProgressEvent,DownloadStartedEvent,EventBase,@@ -135,6 +136,10 @@ class EventServiceBase:"""Emitted when a download is cancelled"""self.dispatch(DownloadCancelledEvent.build(job))+ def emit_download_paused(self, job: "DownloadJob") -> None:+ """Emitted when a download is paused"""+ self.dispatch(DownloadPausedEvent.build(job))+def emit_download_error(self, job: "DownloadJob") -> None:"""Emitted when a download encounters an error"""self.dispatch(DownloadErrorEvent.build(job))diff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.pyindex 082eb8a6b4..cab5861b11 100644--- a/invokeai/app/services/events/events_common.py+++ b/invokeai/app/services/events/events_common.py@@ -382,6 +382,17 @@ class DownloadCancelledEvent(DownloadEventBase):return cls(source=str(job.source))+@payload_schema.register+class DownloadPausedEvent(DownloadEventBase):+ """Event model for download_paused"""++ __event_name__ = "download_paused"++ @classmethod+ def build(cls, job: "DownloadJob") -> "DownloadPausedEvent":+ return cls(source=str(job.source))++@payload_schema.registerclass DownloadErrorEvent(DownloadEventBase):"""Event model for download_error"""diff --git a/invokeai/app/services/model_install/model_install_base.py b/invokeai/app/services/model_install/model_install_base.pyindex 39981071c1..96e1c35141 100644--- a/invokeai/app/services/model_install/model_install_base.py+++ b/invokeai/app/services/model_install/model_install_base.py@@ -205,6 +205,22 @@ class ModelInstallServiceBase(ABC):def cancel_job(self, job: ModelInstallJob) -> None:"""Cancel the indicated job."""+ @abstractmethod+ def pause_job(self, job: ModelInstallJob) -> None:+ """Pause the indicated job, preserving partial downloads."""++ @abstractmethod+ def resume_job(self, job: ModelInstallJob) -> None:+ """Resume a previously paused job."""++ @abstractmethod+ def restart_failed(self, job: ModelInstallJob) -> None:+ """Restart failed or non-resumable downloads for a job."""++ @abstractmethod+ def restart_file(self, job: ModelInstallJob, file_source: str) -> None:+ """Restart a specific file download for a job."""+@abstractmethoddef wait_for_job(self, job: ModelInstallJob, timeout: int = 0) -> ModelInstallJob:"""Wait for the indicated job to reach a terminal state.diff --git a/invokeai/app/services/model_install/model_install_common.py b/invokeai/app/services/model_install/model_install_common.pyindex aa0f6d6d2f..1006135a95 100644--- a/invokeai/app/services/model_install/model_install_common.py+++ b/invokeai/app/services/model_install/model_install_common.py@@ -28,6 +28,7 @@ class InstallStatus(str, Enum):DOWNLOADING = "downloading" # downloading of model files in processDOWNLOADS_DONE = "downloads_done" # downloading done, waiting to runRUNNING = "running" # being processed+ PAUSED = "paused" # paused, can be resumedCOMPLETED = "completed" # finished runningERROR = "error" # terminated with an error messageCANCELLED = "cancelled" # terminated with an error message@@ -185,6 +186,7 @@ class ModelInstallJob(BaseModel):_install_tmpdir: Optional[Path] = PrivateAttr(default=None)_multifile_job: Optional[MultiFileDownloadJob] = PrivateAttr(default=None)_exception: Optional[Exception] = PrivateAttr(default=None)+ _resume_metadata: Optional[dict] = PrivateAttr(default=None)def set_error(self, e: Exception) -> None:"""Record the error and traceback from an exception."""@@ -232,6 +234,11 @@ class ModelInstallJob(BaseModel):"""Return true if job's downloads ae done."""return self.status == InstallStatus.DOWNLOADS_DONE+ @property+ def paused(self) -> bool:+ """Return true if job is paused."""+ return self.status == InstallStatus.PAUSED+@propertydef running(self) -> bool:"""Return true if job is running."""diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.pyindex 77dc3dfa70..c1fb0c651f 100644--- a/invokeai/app/services/model_install/model_install_default.py+++ b/invokeai/app/services/model_install/model_install_default.py@@ -1,6 +1,7 @@"""Model installation class."""import gc+import jsonimport localeimport osimport re@@ -38,6 +39,7 @@ from invokeai.app.services.model_install.model_install_common import ()from invokeai.app.services.model_records import DuplicateModelException, ModelRecordServiceBasefrom invokeai.app.services.model_records.model_records_base import ModelRecordChanges+from invokeai.app.util.misc import get_iso_timestampfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Basefrom invokeai.backend.model_manager.configs.factory import (AnyModelConfig,@@ -65,6 +67,9 @@ if TYPE_CHECKING:TMPDIR_PREFIX = "tmpinstall_"+# Marker file used to resume or pause remote model installs across restarts.+INSTALL_MARKER_FILENAME = ".invokeai_install.json"+INSTALL_MARKER_VERSION = 1class ModelInstallService(ModelInstallServiceBase):@@ -102,6 +107,171 @@ class ModelInstallService(ModelInstallServiceBase):self._install_thread: Optional[threading.Thread] = Noneself._next_job_id = 0+ def _marker_path(self, tmpdir: Path) -> Path:+ return tmpdir / INSTALL_MARKER_FILENAME++ def _write_install_marker(self, job: ModelInstallJob, status: Optional[InstallStatus] = None) -> None:+ if job._install_tmpdir is None:+ return+ files: list[dict] = []+ if job.download_parts:+ for part in job.download_parts:+ files.append(+ {+ "url": str(part.source),+ "canonical_url": part.canonical_url,+ "etag": part.etag,+ "last_modified": part.last_modified,+ "expected_total_bytes": part.expected_total_bytes,+ "final_url": part.final_url,+ "download_path": part.download_path.as_posix() if part.download_path else None,+ "resume_required": part.resume_required,+ "resume_message": part.resume_message,+ }+ )+ marker = {+ "version": INSTALL_MARKER_VERSION,+ "source": str(job.source),+ "config_in": job.config_in.model_dump(),+ "status": (status or job.status).value,+ "updated_at": get_iso_timestamp(),+ "files": files,+ }+ path = self._marker_path(job._install_tmpdir)+ path.parent.mkdir(parents=True, exist_ok=True)+ with open(path, "wt", encoding="utf-8") as f:+ json.dump(marker, f)++ def _read_install_marker(self, tmpdir: Path) -> Optional[dict]:+ path = self._marker_path(tmpdir)+ if not path.exists():+ return None+ try:+ with open(path, "rt", encoding="utf-8") as f:+ marker = json.load(f)+ if marker.get("version") != INSTALL_MARKER_VERSION:+ return None+ return marker+ except Exception as e:+ self._logger.warning(f"Invalid install marker in {tmpdir}: {e}")+ return None++ def _delete_install_marker(self, tmpdir: Path) -> None:+ path = self._marker_path(tmpdir)+ if path.exists():+ try:+ path.unlink()+ except Exception as e:+ self._logger.warning(f"Failed to remove install marker {path}: {e}")++ def _find_reusable_tmpdir(self, source: ModelSource) -> Optional[Path]:+ path = self._app_config.models_path+ source_str = str(source)+ candidates: list[tuple[str, Path]] = []+ for tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):+ marker = self._read_install_marker(tmpdir)+ if not marker:+ continue+ if marker.get("source") != source_str:+ continue+ status = marker.get("status")+ if status in {InstallStatus.COMPLETED.value, InstallStatus.ERROR.value, InstallStatus.CANCELLED.value}:+ continue+ candidates.append((marker.get("updated_at", ""), tmpdir))+ if not candidates:+ return None+ candidates.sort(key=lambda item: item[0], reverse=True)+ return candidates[0][1]++ def _restore_incomplete_installs(self) -> None:+ path = self._app_config.models_path+ seen_sources: set[str] = set()+ for tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):+ marker = self._read_install_marker(tmpdir)+ if not marker:+ continue+ status = marker.get("status")+ if status in {InstallStatus.COMPLETED.value, InstallStatus.ERROR.value, InstallStatus.CANCELLED.value}:+ continue++ try:+ source_str = marker["source"]+ if source_str in seen_sources:+ self._logger.info(f"Removing duplicate temporary directory {tmpdir}")+ self._safe_rmtree(tmpdir, self._logger)+ continue+ seen_sources.add(source_str)+ source = self._guess_source(source_str)+ except Exception as e:+ self._logger.warning(f"Skipping install marker in {tmpdir}: {e}")+ continue++ config_in = ModelRecordChanges(**(marker.get("config_in") or {}))+ job = ModelInstallJob(+ id=self._next_id(),+ source=source,+ config_in=config_in,+ local_path=tmpdir,+ )+ job._install_tmpdir = tmpdir+ files_meta = marker.get("files") or []+ if files_meta:+ job._resume_metadata = {f.get("url"): f for f in files_meta if f.get("url")}+ job.status = InstallStatus(status) if status else InstallStatus.WAITING+ self._install_jobs.append(job)++ if job.paused:+ continue++ if job.status in [InstallStatus.DOWNLOADS_DONE, InstallStatus.RUNNING]:+ job.status = InstallStatus.DOWNLOADS_DONE+ self._put_in_queue(job)+ else:+ try:+ self._resume_remote_download(job)+ except Exception as e:+ self._set_error(job, e)+ if job._install_tmpdir is not None:+ self._safe_rmtree(job._install_tmpdir, self._logger)++ def _restore_incomplete_installs_async(self) -> None:+ def _run() -> None:+ try:+ self._logger.info("Restoring incomplete installs")+ self._restore_incomplete_installs()+ self._logger.info("Finished restoring incomplete installs")+ except Exception as e:+ self._logger.error(f"Failed to restore incomplete installs: {e}")++ threading.Thread(target=_run, daemon=True).start()++ def _resume_remote_download(self, job: ModelInstallJob) -> None:+ job.status = InstallStatus.WAITING+ if job.download_parts:+ for part in job.download_parts:+ if part.complete or part.bytes <= 0:+ continue+ if not part.download_path:+ continue+ in_progress_path = part.download_path.with_name(part.download_path.name + ".downloading")+ if not in_progress_path.exists():+ part.bytes = 0+ part.resume_from_scratch = True+ part.resume_message = "Partial file missing. Restarted download from the beginning."+ job.bytes = sum(p.bytes for p in job.download_parts)+ remote_files, metadata = self._remote_files_from_source(job.source)+ subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []+ self._enqueue_remote_download(+ job=job,+ source=job.source,+ remote_files=remote_files,+ metadata=metadata,+ destdir=job._install_tmpdir or job.local_path,+ subfolder=job.source.subfolder if isinstance(job.source, HFModelSource) and len(subfolders) <= 1 else None,+ subfolders=subfolders if len(subfolders) > 1 else None,+ resume_metadata=job._resume_metadata,+ )+@propertydef app_config(self) -> InvokeAIAppConfig: # noqa D102return self._app_config@@ -138,6 +308,7 @@ class ModelInstallService(ModelInstallServiceBase):self._logger.warning(f"Missing model file: {model.name} at {model.path}")self._write_invoke_managed_models_dir_readme()+ self._restore_incomplete_installs_async()def stop(self, invoker: Optional[Invoker] = None) -> None:"""Stop the installer thread; after this the object can be deleted and garbage collected."""@@ -162,8 +333,12 @@ class ModelInstallService(ModelInstallServiceBase):def _clear_pending_jobs(self) -> None:for job in self.list_jobs():if not job.in_terminal_state:- self._logger.warning(f"Cancelling job {job.id}")- self.cancel_job(job)+ if job._multifile_job is not None:+ self._logger.warning(f"Pausing job {job.id}")+ self.pause_job(job)+ else:+ self._logger.warning(f"Cancelling job {job.id}")+ self.cancel_job(job)while True:try:job = self._install_queue.get(block=False)@@ -315,6 +490,76 @@ class ModelInstallService(ModelInstallServiceBase):self._logger.warning(f"Cancelling {job.source}")if dj := job._multifile_job:self._download_queue.cancel_job(dj)+ if job._install_tmpdir is not None:+ # Mark cancelled before cleanup so we don't reuse the folder if deletion fails.+ self._write_install_marker(job, status=InstallStatus.CANCELLED)+ self._delete_install_marker(job._install_tmpdir)+ self._safe_rmtree(job._install_tmpdir, self._logger)++ def pause_job(self, job: ModelInstallJob) -> None:+ """Pause the indicated job, preserving partial downloads."""+ if job.in_terminal_state:+ return+ job.status = InstallStatus.PAUSED+ self._logger.warning(f"Pausing {job.source}")+ if dj := job._multifile_job:+ for part in dj.download_parts:+ self._download_queue.pause_job(part)+ self._write_install_marker(job, status=InstallStatus.PAUSED)++ def resume_job(self, job: ModelInstallJob) -> None:+ """Resume a previously paused job."""+ if not job.paused:+ return+ self._logger.info(f"Resuming {job.source}")+ self._resume_remote_download(job)++ def restart_failed(self, job: ModelInstallJob) -> None:+ """Restart failed or non-resumable downloads for a job."""+ if not isinstance(job.source, (HFModelSource, URLModelSource)):+ return+ if not job.download_parts:+ return+ if not any(part.resume_required or part.errored for part in job.download_parts):+ return+ sources_to_restart = {str(part.source) for part in job.download_parts if not part.complete}+ if not sources_to_restart:+ return+ job.status = InstallStatus.WAITING+ remote_files, metadata = self._remote_files_from_source(job.source)+ remote_files = [rf for rf in remote_files if str(rf.url) in sources_to_restart]+ subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []+ self._enqueue_remote_download(+ job=job,+ source=job.source,+ remote_files=remote_files,+ metadata=metadata,+ destdir=job._install_tmpdir or job.local_path,+ subfolder=job.source.subfolder if isinstance(job.source, HFModelSource) and len(subfolders) <= 1 else None,+ subfolders=subfolders if len(subfolders) > 1 else None,+ clear_partials=True,+ )++ def restart_file(self, job: ModelInstallJob, file_source: str) -> None:+ """Restart a specific file download for a job."""+ if not isinstance(job.source, (HFModelSource, URLModelSource)):+ return+ job.status = InstallStatus.WAITING+ remote_files, metadata = self._remote_files_from_source(job.source)+ remote_files = [rf for rf in remote_files if str(rf.url) == file_source]+ if not remote_files:+ return+ subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []+ self._enqueue_remote_download(+ job=job,+ source=job.source,+ remote_files=remote_files,+ metadata=metadata,+ destdir=job._install_tmpdir or job.local_path,+ subfolder=job.source.subfolder if isinstance(job.source, HFModelSource) and len(subfolders) <= 1 else None,+ subfolders=subfolders if len(subfolders) > 1 else None,+ clear_partials=True,+ )def prune_jobs(self) -> None:"""Prune all completed and errored jobs."""@@ -596,6 +841,9 @@ class ModelInstallService(ModelInstallServiceBase):if isinstance(job.source_metadata, (HuggingFaceMetadata)):job.config_in.source_api_response = job.source_metadata.api_response+ if job._install_tmpdir is not None:+ self._delete_install_marker(job._install_tmpdir)+if job.inplace:key = self.register_path(job.local_path, job.config_in)else:@@ -624,8 +872,15 @@ class ModelInstallService(ModelInstallServiceBase):"""Remove leftover tmpdirs from aborted installs."""path = self._app_config.models_pathfor tmpdir in path.glob(f"{TMPDIR_PREFIX}*"):- self._logger.info(f"Removing dangling temporary directory {tmpdir}")- self._safe_rmtree(tmpdir, self._logger)+ marker = self._read_install_marker(tmpdir)+ if marker is None:+ self._logger.info(f"Removing dangling temporary directory {tmpdir}")+ self._safe_rmtree(tmpdir, self._logger)+ continue+ status = marker.get("status")+ if status in {InstallStatus.COMPLETED.value, InstallStatus.ERROR.value, InstallStatus.CANCELLED.value}:+ self._logger.info(f"Removing completed/errored temporary directory {tmpdir}")+ self._safe_rmtree(tmpdir, self._logger)def _scan_for_missing_models(self) -> list[AnyModelConfig]:"""Scan the models directory for missing models and return a list of them."""@@ -781,12 +1036,14 @@ class ModelInstallService(ModelInstallServiceBase):) -> ModelInstallJob:if len(remote_files) == 0:raise ValueError(f"{source}: No downloadable files found")- destdir = Path(- mkdtemp(- dir=self._app_config.models_path,- prefix=TMPDIR_PREFIX,+ destdir = self._find_reusable_tmpdir(source)+ if destdir is None:+ destdir = Path(+ mkdtemp(+ dir=self._app_config.models_path,+ prefix=TMPDIR_PREFIX,+ ))- )install_job = ModelInstallJob(id=self._next_id(),source=source,@@ -798,26 +1055,81 @@ class ModelInstallService(ModelInstallServiceBase):)# remember the temporary directory for later removalinstall_job._install_tmpdir = destdir- install_job.total_bytes = sum((x.size or 0) for x in remote_files)# Handle multiple subfolders for HFModelSourcesubfolders = source.subfolders if isinstance(source, HFModelSource) else []- multifile_job = self._multifile_download(+ return self._enqueue_remote_download(+ job=install_job,+ source=source,remote_files=remote_files,- dest=destdir,+ metadata=metadata,+ destdir=destdir,subfolder=source.subfolder if isinstance(source, HFModelSource) and len(subfolders) <= 1 else None,subfolders=subfolders if len(subfolders) > 1 else None,+ )++ def _enqueue_remote_download(+ self,+ job: ModelInstallJob,+ source: HFModelSource | URLModelSource,+ remote_files: List[RemoteModelFile],+ metadata: Optional[AnyModelRepoMetadata],+ destdir: Path,+ subfolder: Optional[Path] = None,+ subfolders: Optional[List[Path]] = None,+ resume_metadata: Optional[dict] = None,+ clear_partials: bool = False,+ ) -> ModelInstallJob:+ job.source_metadata = metadata+ job.local_path = destdir+ job._install_tmpdir = destdir+ job.total_bytes = sum((x.size or 0) for x in remote_files)++ multifile_job = self._multifile_download(+ remote_files=remote_files,+ dest=destdir,+ subfolder=subfolder,+ subfolders=subfolders,access_token=source.access_token,submit_job=False, # Important! Don't submit the job until we have set our _download_cache dict)- self._download_cache[multifile_job.id] = install_job- install_job._multifile_job = multifile_job-+ if clear_partials:+ for part in multifile_job.download_parts:+ target_path = part.dest+ if target_path.exists():+ try:+ self._logger.info(f"Deleting partial file before restart: {target_path}")+ target_path.unlink()+ except Exception:+ pass+ in_progress_path = target_path.with_name(target_path.name + ".downloading")+ if in_progress_path.exists():+ try:+ self._logger.info(f"Deleting partial file before restart: {in_progress_path}")+ in_progress_path.unlink()+ except Exception:+ pass+ if resume_metadata:+ for part in multifile_job.download_parts:+ meta = resume_metadata.get(str(part.source))+ if not meta:+ continue+ part.canonical_url = meta.get("canonical_url") or part.canonical_url+ part.etag = meta.get("etag") or part.etag+ part.last_modified = meta.get("last_modified") or part.last_modified+ part.expected_total_bytes = meta.get("expected_total_bytes") or part.expected_total_bytes+ part.final_url = meta.get("final_url") or part.final_url+ if meta.get("download_path"):+ part.download_path = Path(meta.get("download_path"))+ self._download_cache[multifile_job.id] = job+ job._multifile_job = multifile_job++ self._write_install_marker(job, status=InstallStatus.WAITING)files_string = "file" if len(remote_files) == 1 else "files"self._logger.info(f"Queueing model install: {source} ({len(remote_files)} {files_string})")self._logger.debug(f"remote_files={remote_files}")self._download_queue.submit_multifile_download(multifile_job)- return install_job+ return jobdef _stat_size(self, path: Path) -> int:size = 0@@ -922,7 +1234,9 @@ class ModelInstallService(ModelInstallServiceBase):install_job.local_path = download_job.download_pathinstall_job.download_parts = download_job.download_partsinstall_job.bytes = sum(x.bytes for x in download_job.download_parts)- install_job.total_bytes = download_job.total_bytes+ total_parts = sum(x.total_bytes for x in download_job.download_parts)+ if total_parts > 0:+ install_job.total_bytes = max(install_job.total_bytes or 0, total_parts)self._signal_job_download_started(install_job)def _download_progress_callback(self, download_job: MultiFileDownloadJob) -> None:@@ -933,7 +1247,9 @@ class ModelInstallService(ModelInstallServiceBase):else:# update sizesinstall_job.bytes = sum(x.bytes for x in download_job.download_parts)- install_job.total_bytes = sum(x.total_bytes for x in download_job.download_parts)+ total_parts = sum(x.total_bytes for x in download_job.download_parts)+ if total_parts > 0:+ install_job.total_bytes = max(install_job.total_bytes or 0, total_parts)self._signal_job_downloading(install_job)def _download_complete_callback(self, download_job: MultiFileDownloadJob) -> None:@@ -951,6 +1267,8 @@ class ModelInstallService(ModelInstallServiceBase):assert excp is not Noneself._set_error(install_job, excp)self._download_queue.cancel_job(download_job)+ if install_job._install_tmpdir is not None:+ self._safe_rmtree(install_job._install_tmpdir, self._logger)# Let other threads know that the number of downloads has changedself._downloads_changed_event.set()@@ -959,9 +1277,19 @@ class ModelInstallService(ModelInstallServiceBase):with self._lock:if install_job := self._download_cache.pop(download_job.id, None):self._downloads_changed_event.set()+ if any(part.resume_required for part in download_job.download_parts):+ install_job.status = InstallStatus.PAUSED+ self._write_install_marker(install_job, status=InstallStatus.PAUSED)+ self._downloads_changed_event.set()+ return# if install job has already registered an error, then do not replace its status with cancelled- if not install_job.errored:+ if not install_job.errored and not install_job.paused:install_job.cancel()+ if install_job._install_tmpdir is not None:+ # Mark cancelled before cleanup so we don't reuse the folder if deletion fails.+ self._write_install_marker(install_job, status=InstallStatus.CANCELLED)+ self._delete_install_marker(install_job._install_tmpdir)+ self._safe_rmtree(install_job._install_tmpdir, self._logger)# Let other threads know that the number of downloads has changedself._downloads_changed_event.set()@@ -972,6 +1300,7 @@ class ModelInstallService(ModelInstallServiceBase):def _signal_job_running(self, job: ModelInstallJob) -> None:job.status = InstallStatus.RUNNINGself._logger.info(f"Model install started: {job.source}")+ self._write_install_marker(job, status=InstallStatus.RUNNING)if self._event_bus:self._event_bus.emit_model_install_started(job)@@ -981,6 +1310,7 @@ class ModelInstallService(ModelInstallServiceBase):assert job.bytes is not Noneassert job.total_bytes is not Noneself._event_bus.emit_model_install_download_started(job)+ self._write_install_marker(job, status=InstallStatus.DOWNLOADING)def _signal_job_downloading(self, job: ModelInstallJob) -> None:if self._event_bus:@@ -992,6 +1322,7 @@ class ModelInstallService(ModelInstallServiceBase):def _signal_job_downloads_done(self, job: ModelInstallJob) -> None:job.status = InstallStatus.DOWNLOADS_DONEself._logger.info(f"Model download complete: {job.source}")+ self._write_install_marker(job, status=InstallStatus.DOWNLOADS_DONE)if self._event_bus:self._event_bus.emit_model_install_downloads_complete(job)@@ -1000,6 +1331,8 @@ class ModelInstallService(ModelInstallServiceBase):assert job.config_outself._logger.info(f"Model install complete: {job.source}")self._logger.debug(f"{job.local_path} registered key {job.config_out.key}")+ if job._install_tmpdir is not None:+ self._delete_install_marker(job._install_tmpdir)if self._event_bus:assert job.local_path is not Noneassert job.config_out is not None@@ -1007,6 +1340,8 @@ class ModelInstallService(ModelInstallServiceBase):def _signal_job_errored(self, job: ModelInstallJob) -> None:self._logger.error(f"Model install error: {job.source}\n{job.error_type}: {job.error}")+ if job._install_tmpdir is not None:+ self._delete_install_marker(job._install_tmpdir)if self._event_bus:assert job.error_type is not Noneassert job.error is not None@@ -1014,6 +1349,8 @@ class ModelInstallService(ModelInstallServiceBase):def _signal_job_cancelled(self, job: ModelInstallJob) -> None:self._logger.info(f"Model install canceled: {job.source}")+ if job._install_tmpdir is not None:+ self._delete_install_marker(job._install_tmpdir)if self._event_bus:self._event_bus.emit_model_install_cancelled(job)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 2878975eda..f9adaa28ef 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -153,6 +153,26 @@}}},+ "/api/v2/models/missing": {+ "get": {+ "tags": ["model_manager"],+ "summary": "List Missing Models",+ "description": "Get models whose files are missing from disk.\n\nThese are models that have database entries but their corresponding\nweight files have been deleted externally (not via Model Manager).",+ "operationId": "list_missing_models",+ "responses": {+ "200": {+ "description": "List of models with missing files",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelsList"+ }+ }+ }+ }+ }+ }+ },"/api/v2/models/get_by_attrs": {"get": {"tags": ["model_manager"],@@ -1799,7 +1819,7 @@"get": {"tags": ["model_manager"],"summary": "List Model Installs",- "description": "Return the list of model install jobs.\n\nInstall jobs have a numeric `id`, a `status`, and other fields that provide information on\nthe nature of the job and its progress. The `status` is one of:\n\n* \"waiting\" -- Job is waiting in the queue to run\n* \"downloading\" -- Model file(s) are downloading\n* \"running\" -- Model has downloaded and the model probing and registration process is running\n* \"completed\" -- Installation completed successfully\n* \"error\" -- An error occurred. Details will be in the \"error_type\" and \"error\" fields.\n* \"cancelled\" -- Job was cancelled before completion.\n\nOnce completed, information about the model such as its size, base\nmodel and type can be retrieved from the `config_out` field. For multi-file models such as diffusers,\ninformation on individual files can be retrieved from `download_parts`.\n\nSee the example and schema below for more information.",+ "description": "Return the list of model install jobs.\n\nInstall jobs have a numeric `id`, a `status`, and other fields that provide information on\nthe nature of the job and its progress. The `status` is one of:\n\n* \"waiting\" -- Job is waiting in the queue to run\n* \"downloading\" -- Model file(s) are downloading\n* \"running\" -- Model has downloaded and the model probing and registration process is running\n* \"paused\" -- Job is paused and can be resumed\n* \"completed\" -- Installation completed successfully\n* \"error\" -- An error occurred. Details will be in the \"error_type\" and \"error\" fields.\n* \"cancelled\" -- Job was cancelled before completion.\n\nOnce completed, information about the model such as its size, base\nmodel and type can be retrieved from the `config_out` field. For multi-file models such as diffusers,\ninformation on individual files can be retrieved from `download_parts`.\n\nSee the example and schema below for more information.","operationId": "list_model_installs","responses": {"200": {@@ -1978,6 +1998,204 @@}}},+ "/api/v2/models/install/{id}/pause": {+ "post": {+ "tags": ["model_manager"],+ "summary": "Pause Model Install Job",+ "description": "Pause the model install job corresponding to the given job ID.",+ "operationId": "pause_model_install_job",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "integer",+ "description": "Model install job ID",+ "title": "Id"+ },+ "description": "Model install job ID"+ }+ ],+ "responses": {+ "201": {+ "description": "The job was paused successfully",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelInstallJob"+ }+ }+ }+ },+ "415": {+ "description": "No such job"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v2/models/install/{id}/resume": {+ "post": {+ "tags": ["model_manager"],+ "summary": "Resume Model Install Job",+ "description": "Resume a paused model install job corresponding to the given job ID.",+ "operationId": "resume_model_install_job",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "integer",+ "description": "Model install job ID",+ "title": "Id"+ },+ "description": "Model install job ID"+ }+ ],+ "responses": {+ "201": {+ "description": "The job was resumed successfully",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelInstallJob"+ }+ }+ }+ },+ "415": {+ "description": "No such job"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v2/models/install/{id}/restart_failed": {+ "post": {+ "tags": ["model_manager"],+ "summary": "Restart Failed Model Install Job",+ "description": "Restart failed or non-resumable file downloads for the given job.",+ "operationId": "restart_failed_model_install_job",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "integer",+ "description": "Model install job ID",+ "title": "Id"+ },+ "description": "Model install job ID"+ }+ ],+ "responses": {+ "201": {+ "description": "Failed files restarted successfully",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelInstallJob"+ }+ }+ }+ },+ "415": {+ "description": "No such job"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v2/models/install/{id}/restart_file": {+ "post": {+ "tags": ["model_manager"],+ "summary": "Restart Model Install File",+ "description": "Restart a specific file download for the given job.",+ "operationId": "restart_model_install_file",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "integer",+ "description": "Model install job ID",+ "title": "Id"+ },+ "description": "Model install job ID"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "string",+ "format": "uri",+ "minLength": 1,+ "description": "File download URL to restart",+ "title": "File Source"+ }+ }+ }+ },+ "responses": {+ "201": {+ "description": "File restarted successfully",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelInstallJob"+ }+ }+ }+ },+ "415": {+ "description": "No such job"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/api/v2/models/convert/{key}": {"put": {"tags": ["model_manager"],@@ -2422,6 +2640,68 @@}}},+ "/api/v2/models/sync/orphaned": {+ "get": {+ "tags": ["model_manager"],+ "summary": "Get Orphaned Models",+ "description": "Find orphaned model directories.\n\nOrphaned models are directories in the models folder that contain model files\nbut are not referenced in the database. This can happen when models are deleted\nfrom the database but the files remain on disk.\n\nReturns:\n List of orphaned model directory information",+ "operationId": "get_orphaned_models",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "items": {+ "$ref": "#/components/schemas/OrphanedModelInfo"+ },+ "type": "array",+ "title": "Response Get Orphaned Models"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["model_manager"],+ "summary": "Delete Orphaned Models",+ "description": "Delete specified orphaned model directories.\n\nArgs:\n request: Request containing list of relative paths to delete\n\nReturns:\n Response indicating which paths were deleted and which had errors",+ "operationId": "delete_orphaned_models",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DeleteOrphanedModelsRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DeleteOrphanedModelsResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/api/v1/download_queue/": {"get": {"tags": ["download_queue"],@@ -15677,6 +15957,46 @@"required": ["affected_boards", "deleted_images"],"title": "DeleteImagesResult"},+ "DeleteOrphanedModelsRequest": {+ "properties": {+ "paths": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Paths",+ "description": "List of relative paths to delete"+ }+ },+ "type": "object",+ "required": ["paths"],+ "title": "DeleteOrphanedModelsRequest",+ "description": "Request to delete specific orphaned model directories."+ },+ "DeleteOrphanedModelsResponse": {+ "properties": {+ "deleted": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Deleted",+ "description": "Paths that were successfully deleted"+ },+ "errors": {+ "additionalProperties": {+ "type": "string"+ },+ "type": "object",+ "title": "Errors",+ "description": "Paths that had errors, with error messages"+ }+ },+ "type": "object",+ "required": ["deleted", "errors"],+ "title": "DeleteOrphanedModelsResponse",+ "description": "Response from deleting orphaned models."+ },"DenoiseLatentsInvocation": {"category": "latents","class": "invocation",@@ -16808,6 +17128,90 @@],"title": "Content Type","description": "Content type of downloaded file"+ },+ "canonical_url": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Canonical Url",+ "description": "Canonical URL to request on resume"+ },+ "etag": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Etag",+ "description": "ETag from the remote server, if available"+ },+ "last_modified": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Last Modified",+ "description": "Last-Modified from the remote server, if available"+ },+ "final_url": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Final Url",+ "description": "Final resolved URL after redirects, if available"+ },+ "expected_total_bytes": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Expected Total Bytes",+ "description": "Expected total size of the download"+ },+ "resume_required": {+ "type": "boolean",+ "title": "Resume Required",+ "description": "True if server refused resume; restart required",+ "default": false+ },+ "resume_message": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Resume Message",+ "description": "Message explaining why resume is required"+ },+ "resume_from_scratch": {+ "type": "boolean",+ "title": "Resume From Scratch",+ "description": "True if resume metadata existed but the partial file was missing and the download restarted from the beginning",+ "default": false}},"type": "object",@@ -16817,10 +17221,28 @@},"DownloadJobStatus": {"type": "string",- "enum": ["waiting", "running", "completed", "cancelled", "error"],+ "enum": ["waiting", "running", "paused", "completed", "cancelled", "error"],"title": "DownloadJobStatus","description": "State of a download job."},+ "DownloadPausedEvent": {+ "description": "Event model for download_paused",+ "properties": {+ "timestamp": {+ "description": "The timestamp of the event",+ "title": "Timestamp",+ "type": "integer"+ },+ "source": {+ "description": "The source of the download",+ "title": "Source",+ "type": "string"+ }+ },+ "required": ["timestamp", "source"],+ "title": "DownloadPausedEvent",+ "type": "object"+ },"DownloadProgressEvent": {"description": "Event model for download_progress","properties": {@@ -16877,12 +17299,6 @@"title": "DownloadStartedEvent","type": "object"},- "DyPEPreset": {- "description": "Predefined DyPE configurations.",- "enum": ["off", "auto", "area", "4k"],- "title": "DyPEPreset",- "type": "string"- },"DynamicPromptInvocation": {"category": "prompt","class": "invocation",@@ -20222,13 +20638,23 @@"title": "Kontext Conditioning"},"dype_preset": {- "$ref": "#/components/schemas/DyPEPreset","default": "off",- "description": "DyPE preset for high-resolution generation. 'auto' enables automatically for resolutions > 1536px. '4k' uses optimized settings for 4K output.",+ "description": "DyPE preset for high-resolution generation. 'auto' enables automatically for resolutions > 1536px. 'area' enables automatically based on image area. '4k' uses optimized settings for 4K output.",+ "enum": ["off", "manual", "auto", "area", "4k"],"field_kind": "input","input": "any","orig_default": "off",- "orig_required": false+ "orig_required": false,+ "title": "Dype Preset",+ "type": "string",+ "ui_choice_labels": {+ "4k": "4K Optimized",+ "area": "Area (auto)",+ "auto": "Auto (>1536px)",+ "manual": "Manual",+ "off": "Off"+ },+ "ui_order": 100},"dype_scale": {"anyOf": [@@ -20247,7 +20673,8 @@"input": "any","orig_default": null,"orig_required": false,- "title": "Dype Scale"+ "title": "Dype Scale",+ "ui_order": 101},"dype_exponent": {"anyOf": [@@ -20266,7 +20693,8 @@"input": "any","orig_default": null,"orig_required": false,- "title": "Dype Exponent"+ "title": "Dype Exponent",+ "ui_order": 102},"type": {"const": "flux_denoise",@@ -20280,7 +20708,7 @@"tags": ["image", "flux"],"title": "FLUX Denoise","type": "object",- "version": "4.3.0",+ "version": "4.5.1","output": {"$ref": "#/components/schemas/LatentsOutput"}@@ -20709,13 +21137,23 @@"title": "Kontext Conditioning"},"dype_preset": {- "$ref": "#/components/schemas/DyPEPreset","default": "off",- "description": "DyPE preset for high-resolution generation. 'auto' enables automatically for resolutions > 1536px. '4k' uses optimized settings for 4K output.",+ "description": "DyPE preset for high-resolution generation. 'auto' enables automatically for resolutions > 1536px. 'area' enables automatically based on image area. '4k' uses optimized settings for 4K output.",+ "enum": ["off", "manual", "auto", "area", "4k"],"field_kind": "input","input": "any","orig_default": "off",- "orig_required": false+ "orig_required": false,+ "title": "Dype Preset",+ "type": "string",+ "ui_choice_labels": {+ "4k": "4K Optimized",+ "area": "Area (auto)",+ "auto": "Auto (>1536px)",+ "manual": "Manual",+ "off": "Off"+ },+ "ui_order": 100},"dype_scale": {"anyOf": [@@ -20734,7 +21172,8 @@"input": "any","orig_default": null,"orig_required": false,- "title": "Dype Scale"+ "title": "Dype Scale",+ "ui_order": 101},"dype_exponent": {"anyOf": [@@ -20753,7 +21192,8 @@"input": "any","orig_default": null,"orig_required": false,- "title": "Dype Exponent"+ "title": "Dype Exponent",+ "ui_order": 102},"type": {"const": "flux_denoise_meta",@@ -21454,28 +21894,52 @@"type": "boolean"},"model": {- "$ref": "#/components/schemas/ModelIdentifierField",+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelIdentifierField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,"description": "Flux model (Transformer) to load","field_kind": "input",- "input": "direct",+ "input": "any","orig_required": true,"ui_model_base": ["flux"],"ui_model_type": ["main"]},"t5_encoder_model": {- "$ref": "#/components/schemas/ModelIdentifierField",+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelIdentifierField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,"description": "T5 tokenizer and text encoder","field_kind": "input",- "input": "direct",+ "input": "any","orig_required": true,"title": "T5 Encoder","ui_model_type": ["t5_encoder"]},"clip_embed_model": {- "$ref": "#/components/schemas/ModelIdentifierField",+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelIdentifierField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,"description": "CLIP Embed loader","field_kind": "input",- "input": "direct",+ "input": "any","orig_required": true,"title": "CLIP Embed","ui_model_type": ["clip_embed"]@@ -21506,11 +21970,11 @@"type": "string"}},- "required": ["model", "t5_encoder_model", "clip_embed_model", "type", "id"],+ "required": ["type", "id"],"tags": ["model", "flux"],"title": "Main Model - FLUX","type": "object",- "version": "1.0.6",+ "version": "1.0.7","output": {"$ref": "#/components/schemas/FluxModelLoaderOutput"}@@ -28743,7 +29207,7 @@},"InstallStatus": {"type": "string",- "enum": ["waiting", "downloading", "downloads_done", "running", "completed", "error", "cancelled"],+ "enum": ["waiting", "downloading", "downloads_done", "running", "paused", "completed", "error", "cancelled"],"title": "InstallStatus","description": "State of an install job running in the background."},@@ -31765,234 +32229,234 @@}},"required": [+ "integer_batch",+ "img_ilerp",+ "image_panel_layout",+ "t2i_adapter",+ "metadata_to_model",+ "flux2_klein_model_loader",+ "bounding_box","integer_generator",- "llava_onevision_vllm",- "depth_anything_depth_estimation",+ "flux_text_encoder",+ "img_resize",+ "z_image_seed_variance_enhancer",+ "metadata_to_integer",+ "apply_tensor_mask_to_image",+ "metadata_to_bool_collection",+ "vae_loader",+ "float_batch",+ "paste_image_into_bounding_box",+ "unsharp_mask",+ "invokeai_ealightness",+ "flux_denoise",+ "color_map",+ "face_identifier",+ "float_math",+ "round_float",+ "z_image_denoise_meta",+ "flux_controlnet",+ "metadata_to_float",+ "cogview4_text_encoder",+ "calculate_image_tiles_even_split",+ "lineart_edge_detection",+ "img_noise",+ "color",+ "i2l",+ "metadata_item",+ "metadata_to_string_collection",+ "integer",+ "clip_skip",+ "cogview4_i2l",+ "image_mask_to_tensor",+ "dw_openpose_detection",+ "crop_latents",+ "img_blur","invokeai_img_blend",- "metadata_field_extractor",- "collect",- "integer_collection",- "noise",- "main_model_loader",- "float",+ "grounding_dino",+ "core_metadata",+ "metadata_to_t2i_adapters",+ "z_image_lora_loader","sd3_denoise",- "tensor_mask_to_image",- "cogview4_text_encoder",- "mask_combine",- "image",- "denoise_latents",- "flux2_vae_encode",- "img_channel_multiply",- "invokeai_img_val_thresholds",- "alpha_mask_to_tensor",- "string",- "metadata_to_controlnets",+ "lineart_anime_edge_detection","lblend",- "prompt_template",- "core_metadata",- "lineart_edge_detection",- "pair_tile_image",- "compel",- "z_image_i2l",- "flux_kontext_image_prep",+ "image_collection",+ "metadata_to_loras",+ "flux_fill",+ "cogview4_l2i",+ "sdxl_refiner_model_loader",+ "mediapipe_face_detection",+ "infill_tile",+ "alpha_mask_to_tensor",+ "create_denoise_mask",+ "noise",+ "collect",+ "calculate_image_tiles_min_overlap",+ "string_join","div",- "metadata_to_float",- "dw_openpose_detection",+ "invert_tensor_mask",+ "crop_image_to_bounding_box",+ "latents","z_image_text_encoder",- "mask_edge",- "spandrel_image_to_image",- "image_batch",- "img_hue_adjust",- "metadata_to_integer",- "save_image",- "cogview4_l2i",- "canvas_v2_mask_and_crop",- "spandrel_image_to_image_autoscale",- "flux_lora_loader",- "flux_vae_decode",- "metadata_to_bool_collection",- "img_conv",- "hed_edge_detection",- "flux_kontext",- "tile_to_properties",- "expand_mask_with_fade",- "flux_controlnet",- "esrgan",- "sdxl_lora_loader",- "heuristic_resize",- "range_of_size",- "controlnet",- "apply_mask_to_image",- "img_watermark",+ "metadata",+ "flux2_klein_text_encoder","img_channel_offset",- "infill_rgba","metadata_to_scheduler",- "pidi_edge_detection",- "color_correct",- "conditioning",- "integer_math",- "invokeai_img_composite",- "paste_image_into_bounding_box",- "metadata",- "img_noise",- "t2i_adapter",- "sdxl_lora_collection_loader",+ "dynamic_prompt",+ "seamless",+ "spandrel_image_to_image",+ "string_join_three",+ "depth_anything_depth_estimation",+ "cv_inpaint",+ "float_collection","invokeai_img_dilate_erode",- "img_pad_crop",- "flux_denoise",- "invokeai_img_hue_adjust_plus",- "infill_tile",- "latents",- "float_to_int",- "sd3_text_encoder",- "flux2_klein_model_loader",- "tomask",- "ip_adapter",- "img_ilerp",- "face_mask_detection",+ "lresize",+ "iterate","flux2_vae_decode",- "get_image_mask_bounding_box",- "denoise_latents_meta",- "lscale",- "img_crop",- "rand_int",- "metadata_to_bool",- "invokeai_img_enhance",+ "metadata_to_sdxl_model",+ "apply_mask_to_image",+ "img_chan",+ "esrgan","string_split",- "lresize",- "apply_tensor_mask_to_image",- "sdxl_refiner_model_loader",+ "lscale",+ "image_generator",+ "img_channel_multiply",+ "img_pad_crop",+ "show_image","range",- "z_image_lora_loader",- "string_batch",- "clip_skip",- "string_collection",- "lora_selector",- "metadata_to_model",- "model_identifier",- "ideal_size",- "bounding_box",- "rectangle_mask",- "img_chan",- "flux_fill",- "z_image_denoise_meta",- "seamless",- "image_panel_layout",- "pbr_maps",- "float_generator",- "metadata_from_image",- "flux_ip_adapter",- "boolean",+ "calculate_image_tiles",+ "get_image_mask_bounding_box",+ "sdxl_model_loader",+ "metadata_to_integer_collection","prompt_from_file",- "float_range",- "metadata_to_t2i_adapters",- "add",- "invokeai_ealightness",+ "rectangle_mask",+ "canny_edge_detection",+ "heuristic_resize",+ "blank_image",+ "latents_collection",+ "flux_model_loader",+ "denoise_latents_meta",+ "z_image_model_loader",+ "rand_float",+ "l2i",+ "img_conv",+ "controlnet",+ "flux_redux",+ "boolean_collection",+ "flux_kontext",+ "metadata_to_ip_adapters",+ "metadata_to_string","cogview4_model_loader",- "calculate_image_tiles_even_split",- "tiled_multi_diffusion_denoise_latents",- "face_off",- "random_range",- "flux_text_encoder",- "cv_inpaint",- "color",- "metadata_to_lora_collection",- "round_float",- "merge_metadata",- "img_blur",- "lora_loader",- "calculate_image_tiles",- "image_generator",- "integer_batch",- "freeu",- "metadata_to_float_collection",- "sd3_l2i",- "crop_image_to_bounding_box",- "float_collection",- "img_scale",+ "z_image_l2i",+ "add",+ "lora_collection_loader",+ "string_batch","img_nsfw",- "boolean_collection",- "flux_denoise_meta",- "sd3_i2l",- "vae_loader",- "metadata_to_loras",- "create_gradient_mask",- "scheduler",- "metadata_to_integer_collection",- "metadata_item",- "float_math",- "z_image_seed_variance_enhancer",- "image_collection",- "sd3_model_loader",- "unsharp_mask",- "metadata_item_linked",- "mediapipe_face_detection",- "metadata_to_sdxl_model",- "flux2_klein_text_encoder",- "sdxl_compel_prompt",- "z_image_denoise",- "metadata_to_vae",- "cogview4_denoise",- "image_mask_to_tensor",- "sub",- "segment_anything",- "canvas_paste_back","content_shuffle",- "merge_tiles_to_image",- "integer",- "normal_map",- "z_image_control",- "blank_image",- "iterate",+ "conditioning_collection",+ "string",+ "metadata_to_float_collection",+ "random_range",+ "flux2_denoise",+ "tile_to_properties",+ "mask_edge",+ "ideal_size","sdxl_refiner_compel_prompt","string_split_neg",- "infill_cv2",- "sdxl_model_loader",- "img_lerp",+ "sub",+ "sd3_i2l","string_generator",- "dynamic_prompt",- "z_image_lora_collection_loader",- "string_join",- "lora_collection_loader",- "flux_lora_collection_loader",- "flux_vae_encode",- "flux2_denoise",- "flux_control_lora_loader",- "z_image_model_loader",- "l2i",- "color_map",- "lineart_anime_edge_detection",- "flux_model_loader",- "invert_tensor_mask",- "face_identifier",- "img_paste",- "img_resize",- "infill_lama",- "canny_edge_detection",- "infill_patchmatch",- "string_join_three",- "float_batch",- "show_image",- "z_image_l2i","img_mul",- "mul",- "conditioning_collection",- "calculate_image_tiles_min_overlap",+ "invokeai_img_val_thresholds",+ "pidi_edge_detection",+ "flux_lora_loader",+ "metadata_to_lora_collection",+ "canvas_paste_back",+ "tomask",+ "string_collection",+ "metadata_to_sdlx_loras",+ "compel",+ "sd3_model_loader",+ "denoise_latents",+ "flux_kontext_image_prep","mlsd_detection",- "rand_float",+ "pair_tile_image",+ "flux2_vae_encode",+ "flux_denoise_meta",+ "float_to_int",+ "img_lerp",+ "flux_vae_encode",+ "mul",+ "z_image_denoise",+ "img_crop",+ "invokeai_img_composite",+ "prompt_template",+ "sdxl_compel_prompt",+ "metadata_to_bool",+ "sdxl_lora_loader",+ "lora_loader",+ "metadata_from_image","string_replace",- "grounding_dino",- "metadata_to_sdlx_loras",- "crop_latents",- "metadata_to_ip_adapters",- "latents_collection",- "i2l",- "metadata_to_string_collection",- "create_denoise_mask",- "cogview4_i2l",- "metadata_to_string",+ "infill_lama",+ "img_paste",+ "invokeai_img_enhance",+ "hed_edge_detection",+ "merge_metadata",+ "float_range",+ "range_of_size",+ "integer_math",+ "sd3_text_encoder",+ "model_identifier",+ "infill_patchmatch",+ "img_watermark",+ "scheduler",+ "flux_control_lora_loader",+ "spandrel_image_to_image_autoscale",+ "image_batch",+ "image",+ "flux_vae_decode",+ "float",+ "cogview4_denoise",+ "segment_anything","mask_from_id",- "flux_redux"+ "img_hue_adjust",+ "normal_map",+ "flux_lora_collection_loader",+ "z_image_lora_collection_loader",+ "metadata_item_linked",+ "freeu",+ "face_off",+ "z_image_control",+ "lora_selector",+ "llava_onevision_vllm",+ "metadata_field_extractor",+ "metadata_to_vae",+ "mask_combine",+ "infill_rgba",+ "img_scale",+ "conditioning",+ "boolean",+ "rand_int",+ "sd3_l2i",+ "expand_mask_with_fade",+ "create_gradient_mask",+ "color_correct",+ "metadata_to_controlnets",+ "float_generator",+ "save_image",+ "invokeai_img_hue_adjust_plus",+ "flux_ip_adapter",+ "tiled_multi_diffusion_denoise_latents",+ "sdxl_lora_collection_loader",+ "z_image_i2l",+ "infill_cv2",+ "ip_adapter",+ "canvas_v2_mask_and_crop",+ "pbr_maps",+ "integer_collection",+ "merge_tiles_to_image",+ "face_mask_detection",+ "tensor_mask_to_image",+ "main_model_loader"]},"InvocationProgressEvent": {@@ -48054,6 +48518,37 @@"required": ["limit", "offset", "total", "items"],"title": "OffsetPaginatedResults[ImageDTO]"},+ "OrphanedModelInfo": {+ "properties": {+ "path": {+ "type": "string",+ "title": "Path",+ "description": "Relative path to the orphaned directory from models root"+ },+ "absolute_path": {+ "type": "string",+ "title": "Absolute Path",+ "description": "Absolute path to the orphaned directory"+ },+ "files": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Files",+ "description": "List of model files in this directory"+ },+ "size_bytes": {+ "type": "integer",+ "title": "Size Bytes",+ "description": "Total size of all files in bytes"+ }+ },+ "type": "object",+ "required": ["path", "absolute_path", "files", "size_bytes"],+ "title": "OrphanedModelInfo",+ "description": "Information about an orphaned model directory."+ },"OutputFieldJSONSchemaExtra": {"description": "Extra attributes to be added to input fields and their OpenAPI schema. Used by the workflow editor\nduring schema parsing and UI rendering.","properties": {diff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.jsonindex a4027002c8..9968532303 100644--- a/invokeai/frontend/web/public/locales/en.json+++ b/invokeai/frontend/web/public/locales/en.json@@ -26,6 +26,12 @@"selectedForAutoAdd": "Selected for Auto-Add","bottomMessage": "Deleting images will reset any features currently using them.","cancel": "Cancel",+ "pause": "Pause",+ "resume": "Resume",+ "restartFailed": "Restart failed",+ "restartFile": "Restart file",+ "restartRequired": "Restart required",+ "resumeRefused": "Resume refused by server. Restart required.","changeBoard": "Change Board","clearSearch": "Clear Search","deleteBoard": "Delete Board",@@ -292,6 +298,7 @@"credits": "Credits","pending": "Pending","in_progress": "In Progress",+ "paused": "Paused","completed": "Completed","failed": "Failed","canceled": "Canceled",@@ -875,6 +882,16 @@"modelManager": {"active": "active","actions": "Bulk Actions",+ "pause": "Pause",+ "pauseAll": "Pause All",+ "pauseAllTooltip": "Pause all active downloads",+ "resume": "Resume",+ "resumeAll": "Resume All",+ "resumeAllTooltip": "Resume all paused downloads",+ "restartFailed": "Restart failed",+ "restartFile": "Restart file",+ "restartRequired": "Restart required",+ "resumeRefused": "Resume refused by server. Restart required.","addModel": "Add Model","addModels": "Add Models","advanced": "Advanced",@@ -882,7 +899,10 @@"alpha": "Alpha","availableModels": "Available Models","baseModel": "Base Model",+ "backendDisconnected": "Backend disconnected","cancel": "Cancel",+ "cancelAll": "Cancel All",+ "cancelAllTooltip": "Cancel all active downloads","clipEmbed": "CLIP Embed","clipLEmbed": "CLIP-L Embed","clipGEmbed": "CLIP-G Embed",@@ -1517,6 +1537,11 @@"addedToBoard": "Added to board {{name}}'s assets","addedToUncategorized": "Added to board $t(boards.uncategorized)'s assets","baseModelChanged": "Base Model Changed",+ "modelDownloadPaused": "Model download paused",+ "modelDownloadResumed": "Resuming download",+ "modelDownloadRestartFailed": "Restart failed downloads",+ "modelDownloadRestartFile": "Restarting file download",+ "modelDownloadRestartedFromScratch": "Partial file missing. Restarted download from the beginning.","baseModelChangedCleared_one": "Updated, cleared or disabled {{count}} incompatible submodel","baseModelChangedCleared_other": "Updated, cleared or disabled {{count}} incompatible submodels","kleinEncoderCleared": "Qwen3 Encoder Cleared",diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/socketConnected.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/socketConnected.tsindex f8f7d1659a..d89f89104a 100644--- a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/socketConnected.ts+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/socketConnected.ts@@ -19,8 +19,10 @@ export const addSocketConnectedEventListener = (startAppListening: AppStartListe/*** The rest of this listener has recovery logic for when the socket disconnects and reconnects.*- * We need to re-fetch if something has changed while we were disconnected. In practice, the only- * thing that could change while disconnected is a queue item finishes processing.+ * We need to re-fetch if something has changed while we were disconnected.+ *+ * Session queue status is one proxy for disconnected changes. Model installs need explicit recovery+ * as well because they can transition to paused during backend shutdown while the socket is down.** The queue status is a proxy for this - if the queue status has changed, we need to re-fetch* the queries that may have changed while we were disconnected.@@ -40,6 +42,14 @@ export const addSocketConnectedEventListener = (startAppListening: AppStartListedispatch(api.util.resetApiState());}+ // Always re-sync model installs on reconnect.+ dispatch(+ modelsApi.endpoints.listModelInstalls.initiate(undefined, {+ forceRefetch: true,+ subscribe: false,+ })+ );+// Else, we need to compare the last-known queue status with the current queue status, re-fetching// everything if it has changed.const prevQueueStatusData = selectQueueStatus(getState()).data;diff --git a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueue.tsx b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueue.tsxindex f124462e8b..6050ab84b2 100644--- a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueue.tsx+++ b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueue.tsx@@ -1,56 +1,224 @@import { Box, Button, Flex, Heading } from '@invoke-ai/ui-library';+import { useStore } from '@nanostores/react';import ScrollableContent from 'common/components/OverlayScrollbars/ScrollableContent';+import { getApiErrorDetail } from 'features/modelManagerV2/util/getApiErrorDetail';import { toast } from 'features/toast/toast';import { t } from 'i18next';-import { memo, useCallback, useMemo } from 'react';-import { useListModelInstallsQuery, usePruneCompletedModelInstallsMutation } from 'services/api/endpoints/models';+import { memo, useCallback, useMemo, useRef, useState } from 'react';+import { PiPauseBold, PiPlayBold, PiXBold } from 'react-icons/pi';+import {+ useCancelModelInstallMutation,+ useListModelInstallsQuery,+ usePauseModelInstallMutation,+ usePruneCompletedModelInstallsMutation,+ useResumeModelInstallMutation,+} from 'services/api/endpoints/models';+import type { ModelInstallJob } from 'services/api/types';+import { $isConnected } from 'services/events/stores';import { ModelInstallQueueItem } from './ModelInstallQueueItem';+const hasRestartRequired = (job: ModelInstallJob) => {+ return job.download_parts?.some((part) => part.resume_required || part.status === 'error') ?? false;+};+export const ModelInstallQueue = memo(() => {+ const isConnected = useStore($isConnected);const { data } = useListModelInstallsQuery();+ const [bulkActionInProgress, setBulkActionInProgress] = useState<'pause' | 'resume' | 'cancel' | null>(null);+ const bulkActionLockRef = useRef(false);++ const [cancelModelInstall] = useCancelModelInstallMutation();+ const [pauseModelInstall] = usePauseModelInstallMutation();+ const [resumeModelInstall] = useResumeModelInstallMutation();+ const [_pruneCompletedModelInstalls, { isLoading: isPruning }] = usePruneCompletedModelInstallsMutation();++ const installActionIds = useMemo(() => {+ const pauseable: number[] = [];+ const resumable: number[] = [];+ const cancelable: number[] = [];++ for (const model of data ?? []) {+ if (model.status === 'downloading' || model.status === 'waiting') {+ pauseable.push(model.id);+ }++ if (model.status === 'paused') {+ cancelable.push(model.id);+ if (!hasRestartRequired(model)) {+ resumable.push(model.id);+ }+ continue;+ }++ if (model.status === 'running') {+ cancelable.push(model.id);+ }+ }++ return {+ pauseable,+ resumable,+ cancelable: cancelable.concat(pauseable),+ } as const;+ }, [data]);++ const {+ pauseable: pauseableInstallIds,+ resumable: resumableInstallIds,+ cancelable: cancelableInstallIds,+ } = installActionIds;++ const runBulkAction = useCallback(+ async (action: 'pause' | 'resume' | 'cancel', installIds: number[]) => {+ if (installIds.length === 0 || bulkActionLockRef.current || isPruning) {+ return;+ }++ bulkActionLockRef.current = true;+ setBulkActionInProgress(action);++ try {+ const results = await Promise.allSettled(+ installIds.map((id) => {+ if (action === 'pause') {+ return pauseModelInstall(id).unwrap();+ }+ if (action === 'resume') {+ return resumeModelInstall(id).unwrap();+ }+ return cancelModelInstall(id).unwrap();+ })+ );++ const hasSucceeded = results.some((result) => result.status === 'fulfilled');+ const firstError = results.find((result) => result.status === 'rejected') as PromiseRejectedResult | undefined;++ if (hasSucceeded) {+ const title =+ action === 'pause'+ ? t('toast.modelDownloadPaused')+ : action === 'resume'+ ? t('toast.modelDownloadResumed')+ : t('toast.modelImportCanceled');- const [_pruneCompletedModelInstalls] = usePruneCompletedModelInstallsMutation();-- const pruneCompletedModelInstalls = useCallback(() => {- _pruneCompletedModelInstalls()- .unwrap()- .then((_) => {- toast({- id: 'MODEL_INSTALL_QUEUE_PRUNED',- title: t('toast.prunedQueue'),- status: 'success',- });- })- .catch((error) => {- if (error) {toast({- id: 'MODEL_INSTALL_QUEUE_PRUNE_FAILED',- title: `${error.data.detail} `,+ id: `MODEL_INSTALL_QUEUE_${action.toUpperCase()}_ALL`,+ title,+ status: 'success',+ });+ }++ if (firstError) {+ toast({+ id: `MODEL_INSTALL_QUEUE_${action.toUpperCase()}_ALL_FAILED`,+ title: getApiErrorDetail(firstError.reason),status: 'error',});}+ } finally {+ bulkActionLockRef.current = false;+ setBulkActionInProgress(null);+ }+ },+ [cancelModelInstall, isPruning, pauseModelInstall, resumeModelInstall]+ );++ const pruneCompletedModelInstalls = useCallback(async () => {+ if (bulkActionLockRef.current) {+ return;+ }++ try {+ await _pruneCompletedModelInstalls().unwrap();+ toast({+ id: 'MODEL_INSTALL_QUEUE_PRUNED',+ title: t('toast.prunedQueue'),+ status: 'success',});+ } catch (error) {+ toast({+ id: 'MODEL_INSTALL_QUEUE_PRUNE_FAILED',+ title: getApiErrorDetail(error),+ status: 'error',+ });+ }}, [_pruneCompletedModelInstalls]);+ const hasPauseableInstalls = pauseableInstallIds.length > 0;+ const hasResumableInstalls = resumableInstallIds.length > 0;+ const hasCancelableInstalls = cancelableInstallIds.length > 0;+ const showResumeAll = !hasPauseableInstalls && hasResumableInstalls;+ const pauseResumeAvailable = hasPauseableInstalls || hasResumableInstalls;+const pruneAvailable = useMemo(() => {return data?.some((model) => model.status === 'cancelled' || model.status === 'error' || model.status === 'completed');}, [data]);+ const pauseResumeLabel = showResumeAll ? t('modelManager.resumeAll') : t('modelManager.pauseAll');+ const pauseResumeTooltip = showResumeAll ? t('modelManager.resumeAllTooltip') : t('modelManager.pauseAllTooltip');++ const pauseOrResumeAll = useCallback(() => {+ if (showResumeAll) {+ void runBulkAction('resume', resumableInstallIds);+ return;+ }++ void runBulkAction('pause', pauseableInstallIds);+ }, [pauseableInstallIds, resumableInstallIds, runBulkAction, showResumeAll]);++ const cancelAll = useCallback(() => {+ void runBulkAction('cancel', cancelableInstallIds);+ }, [cancelableInstallIds, runBulkAction]);++ const isBulkActionRunning = bulkActionInProgress !== null;+return (<Flex flexDir="column" p={3} h="full" gap={3}><Flex justifyContent="space-between" alignItems="center">- <Heading size="sm">{t('modelManager.installQueue')}</Heading>- <Button- size="sm"- isDisabled={!pruneAvailable}- onClick={pruneCompletedModelInstalls}- tooltip={t('modelManager.pruneTooltip')}- >- {t('modelManager.prune')}- </Button>+ <Flex alignItems="center" gap={2}>+ <Heading size="sm">{t('modelManager.installQueue')}</Heading>+ {!isConnected && (+ <Box layerStyle="first" px={2} py={0.5} borderRadius="base">+ <Heading size="sm" color="error.300">+ {t('modelManager.backendDisconnected')}+ </Heading>+ </Box>+ )}+ </Flex>+ <Flex gap={2} alignItems="center">+ <Button+ size="sm"+ leftIcon={showResumeAll ? <PiPlayBold /> : <PiPauseBold />}+ isDisabled={!pauseResumeAvailable || isBulkActionRunning || isPruning}+ isLoading={bulkActionInProgress === 'pause' || bulkActionInProgress === 'resume'}+ onClick={pauseOrResumeAll}+ tooltip={pauseResumeTooltip}+ >+ {pauseResumeLabel}+ </Button>+ <Button+ size="sm"+ leftIcon={<PiXBold />}+ isDisabled={!hasCancelableInstalls || isBulkActionRunning || isPruning}+ isLoading={bulkActionInProgress === 'cancel'}+ onClick={cancelAll}+ tooltip={t('modelManager.cancelAllTooltip')}+ >+ {t('modelManager.cancelAll')}+ </Button>+ <Button+ size="sm"+ isDisabled={!pruneAvailable || isBulkActionRunning}+ isLoading={isPruning}+ onClick={pruneCompletedModelInstalls}+ tooltip={t('modelManager.pruneTooltip')}+ >+ {t('modelManager.prune')}+ </Button>+ </Flex></Flex><Box layerStyle="first" p={3} borderRadius="base" w="full" h="full"><ScrollableContent>diff --git a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueBadge.tsx b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueBadge.tsxindex 87b50d0501..27096c2b52 100644--- a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueBadge.tsx+++ b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueBadge.tsx@@ -8,21 +8,23 @@ const STATUSES = {downloading: { colorScheme: 'yellow', translationKey: 'queue.in_progress' },downloads_done: { colorScheme: 'yellow', translationKey: 'queue.in_progress' },running: { colorScheme: 'yellow', translationKey: 'queue.in_progress' },+ paused: { colorScheme: 'orange', translationKey: 'queue.paused' },completed: { colorScheme: 'green', translationKey: 'queue.completed' },error: { colorScheme: 'red', translationKey: 'queue.failed' },cancelled: { colorScheme: 'orange', translationKey: 'queue.canceled' },-};+} as const satisfies Partial<Record<ModelInstallStatus, { colorScheme: string; translationKey: string }>>;const ModelInstallQueueBadge = ({ status }: { status?: ModelInstallStatus }) => {const { t } = useTranslation();+ const statusConfig = status ? STATUSES[status] : undefined;- if (!status || !Object.keys(STATUSES).includes(status)) {+ if (!statusConfig) {return null;}return (- <Badge textAlign="center" w="134px" colorScheme={STATUSES[status].colorScheme}>- {t(STATUSES[status].translationKey)}+ <Badge textAlign="center" w="134px" colorScheme={statusConfig.colorScheme}>+ {t(statusConfig.translationKey)}</Badge>);};diff --git a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueItem.tsx b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueItem.tsxindex bfe81713d0..bd39030cdd 100644--- a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueItem.tsx+++ b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/AddModelPanel/ModelInstallQueue/ModelInstallQueueItem.tsx@@ -1,10 +1,17 @@-import { Flex, IconButton, Progress, Text, Tooltip } from '@invoke-ai/ui-library';+import { Badge, Box, Flex, IconButton, Progress, Text, Tooltip } from '@invoke-ai/ui-library';import { isNil } from 'es-toolkit/compat';+import { getApiErrorDetail } from 'features/modelManagerV2/util/getApiErrorDetail';import { toast } from 'features/toast/toast';import { t } from 'i18next';-import { memo, useCallback, useMemo } from 'react';-import { PiXBold } from 'react-icons/pi';-import { useCancelModelInstallMutation } from 'services/api/endpoints/models';+import { memo, useCallback, useEffect, useMemo, useRef } from 'react';+import { PiArrowClockwiseBold, PiPauseBold, PiPlayBold, PiXBold } from 'react-icons/pi';+import {+ useCancelModelInstallMutation,+ usePauseModelInstallMutation,+ useRestartFailedModelInstallMutation,+ useRestartModelInstallFileMutation,+ useResumeModelInstallMutation,+} from 'services/api/endpoints/models';import type { ModelInstallJob } from 'services/api/types';import ModelInstallQueueBadge from './ModelInstallQueueBadge';@@ -29,6 +36,11 @@ export const ModelInstallQueueItem = memo((props: ModelListItemProps) => {const { installJob } = props;const [deleteImportModel] = useCancelModelInstallMutation();+ const [pauseModelInstall] = usePauseModelInstallMutation();+ const [resumeModelInstall] = useResumeModelInstallMutation();+ const [restartFailedModelInstall] = useRestartFailedModelInstallMutation();+ const [restartModelInstallFile] = useRestartModelInstallFileMutation();+ const resumeFromScratchShown = useRef(false);const handleDeleteModelImport = useCallback(() => {deleteImportModel(installJob.id)@@ -41,15 +53,116 @@ export const ModelInstallQueueItem = memo((props: ModelListItemProps) => {});}).catch((error) => {- if (error) {+ toast({+ id: 'MODEL_INSTALL_CANCEL_FAILED',+ title: getApiErrorDetail(error),+ status: 'error',+ });+ });+ }, [deleteImportModel, installJob]);++ const handlePauseModelInstall = useCallback(() => {+ pauseModelInstall(installJob.id)+ .unwrap()+ .then(() => {+ toast({+ id: 'MODEL_INSTALL_PAUSED',+ title: t('toast.modelDownloadPaused'),+ status: 'success',+ });+ })+ .catch((error) => {+ toast({+ id: 'MODEL_INSTALL_PAUSE_FAILED',+ title: getApiErrorDetail(error),+ status: 'error',+ });+ });+ }, [installJob, pauseModelInstall]);++ const hasRestartedFromScratch = useCallback((job: ModelInstallJob) => {+ return (+ job.download_parts?.some(+ (part) =>+ part.resume_from_scratch || (part.resume_message?.toLowerCase().includes('partial file missing') ?? false)+ ) ?? false+ );+ }, []);++ const handleResumeModelInstall = useCallback(() => {+ resumeModelInstall(installJob.id)+ .unwrap()+ .then((job) => {+ const restartedFromScratch = hasRestartedFromScratch(job);+ if (restartedFromScratch && !resumeFromScratchShown.current) {+ resumeFromScratchShown.current = true;toast({- id: 'MODEL_INSTALL_CANCEL_FAILED',- title: `${error.data.detail} `,- status: 'error',+ id: 'MODEL_INSTALL_RESTARTED_FROM_SCRATCH',+ title: t('toast.modelDownloadRestartedFromScratch'),+ status: 'warning',});+ return;}+ toast({+ id: 'MODEL_INSTALL_RESUMED',+ title: t('toast.modelDownloadResumed'),+ status: 'success',+ });+ })+ .catch((error) => {+ toast({+ id: 'MODEL_INSTALL_RESUME_FAILED',+ title: getApiErrorDetail(error),+ status: 'error',+ });});- }, [deleteImportModel, installJob]);+ }, [hasRestartedFromScratch, installJob, resumeModelInstall]);++ const handleRestartFailed = useCallback(() => {+ restartFailedModelInstall(installJob.id)+ .unwrap()+ .then(() => {+ toast({+ id: 'MODEL_INSTALL_RESTART_FAILED',+ title: t('toast.modelDownloadRestartFailed'),+ status: 'success',+ });+ })+ .catch((error) => {+ toast({+ id: 'MODEL_INSTALL_RESTART_FAILED_ERROR',+ title: getApiErrorDetail(error),+ status: 'error',+ });+ });+ }, [installJob.id, restartFailedModelInstall]);++ const handleRestartFile = useCallback(+ (fileSource: string) => {+ restartModelInstallFile({ id: installJob.id, file_source: fileSource })+ .unwrap()+ .then(() => {+ toast({+ id: 'MODEL_INSTALL_RESTART_FILE',+ title: t('toast.modelDownloadRestartFile'),+ status: 'success',+ });+ })+ .catch((error) => {+ toast({+ id: 'MODEL_INSTALL_RESTART_FILE_ERROR',+ title: getApiErrorDetail(error),+ status: 'error',+ });+ });+ },+ [installJob.id, restartModelInstallFile]+ );++ const getRestartFileHandler = useCallback(+ (fileSource: string) => () => handleRestartFile(fileSource),+ [handleRestartFile]+ );const sourceLocation = useMemo(() => {switch (installJob.source.type) {@@ -87,47 +200,147 @@ export const ModelInstallQueueItem = memo((props: ModelListItemProps) => {return 100;}- if (isNil(installJob.bytes) || isNil(installJob.total_bytes)) {- return null;+ const parts = installJob.download_parts;+ if (parts && parts.length > 0) {+ const totalBytesFromParts = parts.reduce((sum, part) => sum + (part.total_bytes ?? 0), 0);+ const currentBytesFromParts = parts.reduce((sum, part) => sum + (part.bytes ?? 0), 0);+ const totalBytes = Math.max(totalBytesFromParts, installJob.total_bytes ?? 0);+ const currentBytes = Math.max(currentBytesFromParts, installJob.bytes ?? 0);+ if (totalBytes > 0) {+ return (currentBytes / totalBytes) * 100;+ }+ return 0;}- if (installJob.total_bytes === 0) {- return 0;+ if (!isNil(installJob.bytes) && !isNil(installJob.total_bytes) && installJob.total_bytes > 0) {+ return (installJob.bytes / installJob.total_bytes) * 100;}- return (installJob.bytes / installJob.total_bytes) * 100;- }, [installJob.bytes, installJob.status, installJob.total_bytes]);+ return null;+ }, [installJob.bytes, installJob.download_parts, installJob.status, installJob.total_bytes]);++ const restartRequiredParts = useMemo(() => {+ return installJob.download_parts?.filter((part) => part.resume_required || part.status === 'error') ?? [];+ }, [installJob.download_parts]);++ useEffect(() => {+ if (resumeFromScratchShown.current) {+ return;+ }+ const restartedFromScratch = hasRestartedFromScratch(installJob);+ if (restartedFromScratch) {+ resumeFromScratchShown.current = true;+ toast({+ id: 'MODEL_INSTALL_RESTARTED_FROM_SCRATCH_AUTO',+ title: t('toast.modelDownloadRestartedFromScratch'),+ status: 'warning',+ });+ }+ }, [hasRestartedFromScratch, installJob]);++ const hasRestartRequired = restartRequiredParts.length > 0;++ const showPause = installJob.status === 'downloading' || installJob.status === 'waiting';+ const showResume = installJob.status === 'paused' && !hasRestartRequired;+ const showCancel =+ installJob.status === 'downloading' ||+ installJob.status === 'waiting' ||+ installJob.status === 'running' ||+ installJob.status === 'paused';return (- <Flex gap={3} w="full" alignItems="center">- <Tooltip maxW={600} label={<TooltipLabel name={modelName} source={sourceLocation} installJob={installJob} />}>- <Flex gap={3} w="full" alignItems="center">- <Text w={96} whiteSpace="nowrap" overflow="hidden" textOverflow="ellipsis">- {modelName}- </Text>- <Progress- w="full"- flexGrow={1}- value={progressValue ?? 0}- isIndeterminate={progressValue === null}- aria-label={t('accessibility.invokeProgressBar')}- h={2}- />- <ModelInstallQueueBadge status={installJob.status} />+ <>+ <Flex gap={1} w="full" alignItems="center">+ <Tooltip maxW={600} label={<TooltipLabel name={modelName} source={sourceLocation} installJob={installJob} />}>+ <Flex gap={3} w="full" alignItems="center">+ <Text w={96} whiteSpace="nowrap" overflow="hidden" textOverflow="ellipsis">+ {modelName}+ </Text>+ <Progress+ w="full"+ flexGrow={1}+ value={progressValue ?? 0}+ isIndeterminate={progressValue === null}+ aria-label={t('accessibility.invokeProgressBar')}+ h={2}+ />+ <ModelInstallQueueBadge status={installJob.status} />+ </Flex>+ </Tooltip>+ <Flex gap={1} alignItems="center" justifyContent="flex-end" minW="90px">+ {showResume && (+ <IconButton+ size="xs"+ tooltip={t('modelManager.resume')}+ aria-label={t('modelManager.resume')}+ icon={<PiPlayBold />}+ onClick={handleResumeModelInstall}+ variant="ghost"+ />+ )}+ {showPause && (+ <IconButton+ size="xs"+ tooltip={t('modelManager.pause')}+ aria-label={t('modelManager.pause')}+ icon={<PiPauseBold />}+ onClick={handlePauseModelInstall}+ variant="ghost"+ />+ )}+ {hasRestartRequired && (+ <IconButton+ size="xs"+ tooltip={t('modelManager.restartFailed')}+ aria-label={t('modelManager.restartFailed')}+ icon={<PiArrowClockwiseBold />}+ onClick={handleRestartFailed}+ variant="ghost"+ />+ )}+ {showCancel && (+ <IconButton+ size="xs"+ tooltip={t('modelManager.cancel')}+ aria-label={t('modelManager.cancel')}+ icon={<PiXBold />}+ onClick={handleDeleteModelImport}+ variant="ghost"+ />+ )}+ {!showResume && !showPause && !showCancel && <Box w="24px" />}</Flex>- </Tooltip>- <IconButton- isDisabled={- installJob.status !== 'downloading' && installJob.status !== 'waiting' && installJob.status !== 'running'- }- size="xs"- tooltip={t('modelManager.cancel')}- aria-label={t('modelManager.cancel')}- icon={<PiXBold />}- onClick={handleDeleteModelImport}- variant="ghost"- />- </Flex>+ </Flex>+ {hasRestartRequired && (+ <Flex direction="column" gap={1} w="full" mt={1}>+ {restartRequiredParts.map((part) => {+ const fileName = part.source.split('/').slice(-1)[0] ?? t('common.unknown');+ const isResumeRequired = part.resume_required;+ return (+ <Flex key={part.source} gap={2} alignItems="center" wrap="wrap">+ <Text fontSize="xs" color="base.200" maxW="200px" noOfLines={1}>+ {fileName}+ </Text>+ <Badge colorScheme={isResumeRequired ? 'orange' : 'red'} fontSize="10px">+ {isResumeRequired ? t('modelManager.restartRequired') : t('queue.failed')}+ </Badge>+ <Text fontSize="xs" color="warning.400">+ {isResumeRequired ? t('modelManager.resumeRefused') : t('queue.failed')}+ </Text>+ <IconButton+ size="xs"+ tooltip={t('modelManager.restartFile')}+ aria-label={t('modelManager.restartFile')}+ icon={<PiArrowClockwiseBold />}+ onClick={getRestartFileHandler(part.source)}+ variant="ghost"+ />+ </Flex>+ );+ })}+ </Flex>+ )}+ </>);});@@ -141,11 +354,25 @@ type TooltipLabelProps = {const TooltipLabel = memo(({ name, source, installJob }: TooltipLabelProps) => {const progressString = useMemo(() => {- if (installJob.status !== 'downloading' || installJob.bytes === undefined || installJob.total_bytes === undefined) {+ if (installJob.status !== 'downloading') {return '';}- return `${formatBytes(installJob.bytes)} / ${formatBytes(installJob.total_bytes)}`;- }, [installJob.bytes, installJob.total_bytes, installJob.status]);+ const parts = installJob.download_parts;+ if (parts && parts.length > 0) {+ const totalBytesFromParts = parts.reduce((sum, part) => sum + (part.total_bytes ?? 0), 0);+ const currentBytesFromParts = parts.reduce((sum, part) => sum + (part.bytes ?? 0), 0);+ const totalBytes = Math.max(totalBytesFromParts, installJob.total_bytes ?? 0);+ const currentBytes = Math.max(currentBytesFromParts, installJob.bytes ?? 0);+ if (totalBytes > 0) {+ return `${formatBytes(currentBytes)} / ${formatBytes(totalBytes)}`;+ }+ return '';+ }+ if (!isNil(installJob.bytes) && !isNil(installJob.total_bytes) && installJob.total_bytes > 0) {+ return `${formatBytes(installJob.bytes)} / ${formatBytes(installJob.total_bytes)}`;+ }+ return '';+ }, [installJob.bytes, installJob.download_parts, installJob.total_bytes, installJob.status]);return (<>diff --git a/invokeai/frontend/web/src/features/modelManagerV2/util/getApiErrorDetail.ts b/invokeai/frontend/web/src/features/modelManagerV2/util/getApiErrorDetail.tsnew file mode 100644index 0000000000..69f72cc37d--- /dev/null+++ b/invokeai/frontend/web/src/features/modelManagerV2/util/getApiErrorDetail.ts@@ -0,0 +1,22 @@+import { t } from 'i18next';++type ApiErrorLike = {+ data?: {+ detail?: string;+ };+};++export const getApiErrorDetail = (error: unknown): string => {+ if (typeof error === 'object' && error !== null && 'data' in error) {+ const { data } = error as ApiErrorLike;+ if (typeof data?.detail === 'string') {+ return data.detail;+ }+ }++ if (error instanceof Error && error.message) {+ return error.message;+ }++ return t('common.unknown');+};diff --git a/invokeai/frontend/web/src/services/api/endpoints/models.ts b/invokeai/frontend/web/src/services/api/endpoints/models.tsindex 1117f3b61f..f48b586767 100644--- a/invokeai/frontend/web/src/services/api/endpoints/models.ts+++ b/invokeai/frontend/web/src/services/api/endpoints/models.ts@@ -6,6 +6,7 @@ import type { operations, paths } from 'services/api/schema';import type {AnyModelConfig,GetHFTokenStatusResponse,+ ModelInstallJob,ResetHFTokenResponse,SetHFTokenArg,SetHFTokenResponse,@@ -66,6 +67,10 @@ type ListModelInstallsResponse =type CancelModelInstallResponse =paths['/api/v2/models/install/{id}']['delete']['responses']['201']['content']['application/json'];+type PauseModelInstallResponse = ModelInstallJob;+type ResumeModelInstallResponse = ModelInstallJob;+type RestartFailedModelInstallResponse = ModelInstallJob;+type RestartModelInstallFileResponse = ModelInstallJob;type PruneCompletedModelInstallsResponse =paths['/api/v2/models/install']['delete']['responses']['200']['content']['application/json'];@@ -267,6 +272,43 @@ export const modelsApi = api.injectEndpoints({},invalidatesTags: ['ModelInstalls'],}),+ pauseModelInstall: build.mutation<PauseModelInstallResponse, number>({+ query: (id) => {+ return {+ url: buildModelsUrl(`install/${id}/pause`),+ method: 'POST',+ };+ },+ invalidatesTags: ['ModelInstalls'],+ }),+ resumeModelInstall: build.mutation<ResumeModelInstallResponse, number>({+ query: (id) => {+ return {+ url: buildModelsUrl(`install/${id}/resume`),+ method: 'POST',+ };+ },+ invalidatesTags: ['ModelInstalls'],+ }),+ restartFailedModelInstall: build.mutation<RestartFailedModelInstallResponse, number>({+ query: (id) => {+ return {+ url: buildModelsUrl(`install/${id}/restart_failed`),+ method: 'POST',+ };+ },+ invalidatesTags: ['ModelInstalls'],+ }),+ restartModelInstallFile: build.mutation<RestartModelInstallFileResponse, { id: number; file_source: string }>({+ query: ({ id, file_source }) => {+ return {+ url: buildModelsUrl(`install/${id}/restart_file`),+ method: 'POST',+ body: file_source,+ };+ },+ invalidatesTags: ['ModelInstalls'],+ }),pruneCompletedModelInstalls: build.mutation<PruneCompletedModelInstallsResponse, void>({query: () => {return {@@ -410,6 +452,10 @@ export const {useLazyGetHuggingFaceModelsQuery,useListModelInstallsQuery,useCancelModelInstallMutation,+ usePauseModelInstallMutation,+ useResumeModelInstallMutation,+ useRestartFailedModelInstallMutation,+ useRestartModelInstallFileMutation,usePruneCompletedModelInstallsMutation,useGetStarterModelsQuery,useGetHFTokenStatusQuery,diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 8bbf79c4d0..d0dee20306 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -231,6 +231,7 @@ export type paths = {* * "waiting" -- Job is waiting in the queue to run* * "downloading" -- Model file(s) are downloading* * "running" -- Model has downloaded and the model probing and registration process is running+ * * "paused" -- Job is paused and can be resumed* * "completed" -- Installation completed successfully* * "error" -- An error occurred. Details will be in the "error_type" and "error" fields.* * "cancelled" -- Job was cancelled before completion.@@ -328,6 +329,86 @@ export type paths = {patch?: never;trace?: never;};+ "/api/v2/models/install/{id}/pause": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Pause Model Install Job+ * @description Pause the model install job corresponding to the given job ID.+ */+ post: operations["pause_model_install_job"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v2/models/install/{id}/resume": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Resume Model Install Job+ * @description Resume a paused model install job corresponding to the given job ID.+ */+ post: operations["resume_model_install_job"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v2/models/install/{id}/restart_failed": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Restart Failed Model Install Job+ * @description Restart failed or non-resumable file downloads for the given job.+ */+ post: operations["restart_failed_model_install_job"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v2/models/install/{id}/restart_file": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Restart Model Install File+ * @description Restart a specific file download for the given job.+ */+ post: operations["restart_model_install_file"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v2/models/convert/{key}": {parameters: {query?: never;@@ -7127,13 +7208,71 @@ export type components = {* @description Content type of downloaded file*/content_type?: string | null;+ /**+ * Canonical Url+ * @description Canonical URL to request on resume+ */+ canonical_url?: string | null;+ /**+ * Etag+ * @description ETag from the remote server, if available+ */+ etag?: string | null;+ /**+ * Last Modified+ * @description Last-Modified from the remote server, if available+ */+ last_modified?: string | null;+ /**+ * Final Url+ * @description Final resolved URL after redirects, if available+ */+ final_url?: string | null;+ /**+ * Expected Total Bytes+ * @description Expected total size of the download+ */+ expected_total_bytes?: number | null;+ /**+ * Resume Required+ * @description True if server refused resume; restart required+ * @default false+ */+ resume_required?: boolean;+ /**+ * Resume Message+ * @description Message explaining why resume is required+ */+ resume_message?: string | null;+ /**+ * Resume From Scratch+ * @description True if resume metadata existed but the partial file was missing and the download restarted from the beginning+ * @default false+ */+ resume_from_scratch?: boolean;};/*** DownloadJobStatus* @description State of a download job.* @enum {string}*/- DownloadJobStatus: "waiting" | "running" | "completed" | "cancelled" | "error";+ DownloadJobStatus: "waiting" | "running" | "paused" | "completed" | "cancelled" | "error";+ /**+ * DownloadPausedEvent+ * @description Event model for download_paused+ */+ DownloadPausedEvent: {+ /**+ * Timestamp+ * @description The timestamp of the event+ */+ timestamp: number;+ /**+ * Source+ * @description The source of the download+ */+ source: string;+ };/*** DownloadProgressEvent* @description Event model for download_progress@@ -12876,7 +13015,7 @@ export type components = {* @description State of an install job running in the background.* @enum {string}*/- InstallStatus: "waiting" | "downloading" | "downloads_done" | "running" | "completed" | "error" | "cancelled";+ InstallStatus: "waiting" | "downloading" | "downloads_done" | "running" | "paused" | "completed" | "error" | "cancelled";/*** Integer Batch* @description Create a batched generation, where the workflow is executed once for each integer in the batch.@@ -28473,6 +28612,166 @@ export interface operations {};};};+ pause_model_install_job: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ /** @description Model install job ID */+ id: number;+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description The job was paused successfully */+ 201: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ModelInstallJob"];+ };+ };+ /** @description No such job */+ 415: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ resume_model_install_job: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ /** @description Model install job ID */+ id: number;+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description The job was resumed successfully */+ 201: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ModelInstallJob"];+ };+ };+ /** @description No such job */+ 415: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ restart_failed_model_install_job: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ /** @description Model install job ID */+ id: number;+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Failed files restarted successfully */+ 201: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ModelInstallJob"];+ };+ };+ /** @description No such job */+ 415: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ restart_model_install_file: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ /** @description Model install job ID */+ id: number;+ };+ cookie?: never;+ };+ requestBody: {+ content: {+ "application/json": string;+ };+ };+ responses: {+ /** @description File restarted successfully */+ 201: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ModelInstallJob"];+ };+ };+ /** @description No such job */+ 415: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };convert_model: {parameters: {query?: never;