Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Unsloth Studio / Desktop: remember the text encoder and VAE files per image model (#14845)
Leo Borcherding711332aa14ff
diff --git a/studio/backend/core/inference/chat_swap_kv.py b/studio/backend/core/inference/chat_swap_kv.pyindex 208fb40dc05..4eceec34c63 100644--- a/studio/backend/core/inference/chat_swap_kv.py+++ b/studio/backend/core/inference/chat_swap_kv.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import contextvarsimport threadingimport timefrom typing import Optional@@ -52,20 +53,111 @@ def saving_progress(media: str) -> Optional[dict]:return None+def _enter_saving(key: tuple[str, Optional[str]]) -> None:+ with _lock:+ _saving[key] = _saving.get(key, 0) + 1+++def _leave_saving(key: tuple[str, Optional[str]]) -> None:+ with _lock:+ left = _saving.get(key, 1) - 1+ if left > 0:+ _saving[key] = left+ else:+ _saving.pop(key, None)+++class PreparingLoad:+ """One load POST still before its engine registers the load; ``/<media>/unload`` cancels it."""++ def __init__(self, media: str):+ self.media = media+ self._cancelled = threading.Event()+ # Held from the check through begin_load's registration, so a cancel lands before or after it.+ self.lock = threading.RLock()++ @property+ def cancelled(self) -> bool:+ return self._cancelled.is_set()++ def cancel(self) -> None:+ with self.lock:+ self._cancelled.set()+++_preparing: dict[tuple[str, Optional[str]], list[PreparingLoad]] = {}+_current_preparing: contextvars.ContextVar[Optional[PreparingLoad]] = contextvars.ContextVar(+ "chat_swap_kv_preparing_load", default = None+)+++def load_preparing(media: str) -> bool:+ """Whether one of the caller's load POSTs is still in its preflight (evidence, checks, acquire)."""+ with _lock:+ return any(not t.cancelled for t in _preparing.get((media, _account_id()), ()))+++def cancel_preparing_loads(+ media: str,+ account: Optional[str],+ *,+ any_account: bool = False,+) -> int:+ """Cancel ``media`` load POSTs in preflight: ``account``'s own, or all when the unload is not account scoped."""+ with _lock:+ tokens = [+ t+ for (m, a), held in _preparing.items()+ if m == media and (any_account or a == account)+ for t in held+ if not t.cancelled+ ]+ # Outside _lock: this waits for a registration in flight under the token's own lock.+ for token in tokens:+ token.cancel()+ return len(tokens)+++def preparing_load_token() -> Optional[PreparingLoad]:+ """The preflight token of the load POST this context runs in, if any."""+ return _current_preparing.get()+++def raise_if_load_cancelled(message: str) -> None:+ """Raise the route's cancelled-load error once an unload cancelled this POST's preflight."""+ token = _current_preparing.get()+ if token is not None and token.cancelled:+ raise RuntimeError(message)+++def preparing_load(media: str):+ """Held around a load POST until begin_load registers it, so load-progress reads it as starting; yields the token an unload cancels."""+ key = (media, _account_id())+ token = PreparingLoad(media)+ with _lock:+ _preparing.setdefault(key, []).append(token)+ reset = _current_preparing.set(token)+ try:+ yield token+ finally:+ _current_preparing.reset(reset)+ with _lock:+ held = _preparing.get(key, [])+ if token in held:+ held.remove(token)+ if not held:+ _preparing.pop(key, None)++@contextlib.contextmanagerdef _saving_marker(media: str, account: Optional[str]):key = (media, account)- with _lock:- _saving[key] = _saving.get(key, 0) + 1+ _enter_saving(key)try:yieldfinally:- with _lock:- left = _saving.get(key, 1) - 1- if left > 0:- _saving[key] = left- else:- _saving.pop(key, None)+ _leave_saving(key)def _delete(manifest) -> None:@@ -103,13 +195,18 @@ class SwapSave:manifest: Optional[dict] = None,*,log_swap: bool = True,+ saving: Optional[tuple[str, Optional[str]]] = None,):self._manifest = manifest# Off logs the eviction here; When they fit's residency code already logs it as "evicted".self._log_swap = log_swap+ self._saving = savingdef close(self) -> None:global _pending, _committed+ saving, self._saving = self._saving, None+ if saving is not None:+ _leave_saving(saving)manifest, self._manifest = self._manifest, Noneif manifest is None:return@@ -249,14 +346,23 @@ async def save_chat_kv_before_swap(abort = threading.Event()deadline = time.monotonic() + budget+ preflight = _current_preparing.get()+def should_abort() -> bool:- return abort.is_set() or time.monotonic() >= deadline or _chat_busy(counted)+ return (+ abort.is_set()+ or time.monotonic() >= deadline+ or (preflight is not None and preflight.cancelled)+ or _chat_busy(counted)+ )loop = asyncio.get_running_loop()future = loop.create_future()manifest = Nonecancelled = None- with _saving_marker(media, account):+ saving = (media, account)+ _enter_saving(saving)+ try:threading.Thread(target = _save_in_thread,args = (llama, should_abort, abort, loop, future),@@ -280,19 +386,26 @@ async def save_chat_kv_before_swap()else:logger.debug("chat KV swap save failed: %s", exc)- if cancelled is not None:- raise cancelled- try:- if manifest and (abort.is_set() or _chat_busy(counted)):+ if cancelled is not None:+ raise cancelled+ try:+ if manifest and (+ abort.is_set()+ or (preflight is not None and preflight.cancelled)+ or _chat_busy(counted)+ ):+ _delete(manifest)+ manifest = None+ except Exception:_delete(manifest)manifest = None- except Exception:- _delete(manifest)- manifest = None+ except BaseException:+ _leave_saving(saving)+ raiseif not manifest:- return SwapSave()+ return SwapSave(saving = saving)entry = {"identity": identity, "origin": "swap", **manifest}with _lock:older, _pending = _pending, entry_delete(older)- return SwapSave(entry, log_swap = policy == "off")+ return SwapSave(entry, log_swap = policy == "off", saving = saving)diff --git a/studio/backend/core/inference/diffusion_comfy_components.py b/studio/backend/core/inference/diffusion_comfy_components.pyindex 7a09be5c20a..b677fc3721b 100644--- a/studio/backend/core/inference/diffusion_comfy_components.py+++ b/studio/backend/core/inference/diffusion_comfy_components.py@@ -98,7 +98,9 @@ class ComponentFileRef:@propertydef name(self) -> str:- return os.path.basename(self.local_path or self.filename or self.spec)+ if self.local_path:+ return re.split(r"[\\/]", self.spec)[-1] or os.path.basename(self.local_path)+ return os.path.basename(self.filename or self.spec)@propertydef is_hub(self) -> bool:diff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.pyindex ab943f575fc..5031bb2fe53 100644--- a/studio/backend/core/inference/gpu_arbiter.py+++ b/studio/backend/core/inference/gpu_arbiter.py@@ -666,6 +666,7 @@ def acquire_for(gpu_ids: Optional[Iterable[int]] = None,need_mib: Optional[dict] = None,evict_first: bool = False,+ admit: Optional[Callable[[], None]] = None,) -> Any:"""Make ``owner`` resident, evicting every other resident under the default policy.@@ -681,6 +682,7 @@ def acquire_for(Under "fit" and "always" only residents on the same GPUs can be evicted (gpu_residency.coreside_locked):``need_mib`` is what an image or video load will hold per physical GPU (None: unknown, so it evicts first),and ``evict_first`` makes a chat load with no estimate before launch evict as "off" does.+ ``admit`` runs under the lock before anything is evicted; raising refuses the acquire untouched."""global _owner, _owner_epoch, _owner_account, _prior_accountif owner not in _EVICTORS:@@ -691,6 +693,8 @@ def acquire_for(# The segmenter's VRAM goes to this owner: a mask call arriving before its register returns stays off the card.handover = owner != DIFFUSION or register is not None or replacingwith _lock, _handover_fence() if handover else nullcontext():+ if admit is not None:+ admit()if expected_current is not None and (_owner, _owner_epoch) != expected_current:raise OwnerChangedError("The resident GPU model changed; retry the load.")coreside = policy != "off" and owner in _KEPT_UNDER_ALWAYSdiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 6d276b98edc..4dbabc3aae9 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -51788,6 +51788,9 @@ def _assert_native_precision_unset()+_DIFFUSION_LOAD_CANCELLED = "Diffusion load was cancelled."++@studio_router.post("/images/load", response_model = DiffusionStatusResponse)@account_access.gpu_busy_routeasync def load_diffusion_model(@@ -51803,8 +51806,11 @@ async def load_diffusion_model(redact_host_paths,restore_inventory_handles,)+ from core.inference.chat_swap_kv import preparing_load+try:- loaded = await load_diffusion_model_gated(request, current_subject, user_initiated = True)+ with preparing_load("image"):+ loaded = await load_diffusion_model_gated(request, current_subject, user_initiated = True)except HTTPException as exc:# A load that RAISES skips both wrappers, and the inner loader redacted native paths# only, which do not know inventory handles.@@ -52109,6 +52115,9 @@ async def load_diffusion_model_gated(note_evictions(replaced_media, evicted_slots)# begin_load signals whatever generation is running, so guard on every device, not just GPU.require_no_foreign_generations()+ from core.inference.chat_swap_kv import preparing_load_token, raise_if_load_cancelled++ raise_if_load_cancelled(_DIFFUSION_LOAD_CANCELLED)if off_torch is not None and pending_name == ENGINE_SD_CPP:await asyncio.to_thread(_unload_native_video_sharing_the_sd_cpp_tree, multi_model_mode, evicted_slots@@ -52255,14 +52264,24 @@ async def load_diffusion_model_gated(note_engine_pick(request.engine, engine, prior_state)return started+ preflight = preparing_load_token()+def _begin_load():# Under the router transition lock: begin_load on a deactivated engine leaves a resident model nothing can reach.- return begin_load_on(- engine,- lambda: account_access.admit_media_load(- "diffusion", _start_engine_load, request.model_path- ),- )+ def _register():+ return begin_load_on(+ engine,+ lambda: account_access.admit_media_load(+ "diffusion", _start_engine_load, request.model_path+ ),+ )++ if preflight is None:+ return _register()+ # A cancel lands before this check or after registration, where the engine unload stops it.+ with preflight.lock:+ raise_if_load_cancelled(_DIFFUSION_LOAD_CANCELLED)+ return _register()if needs_gpu:from core.inference.gpu_residency import media_fit_kwargs@@ -52274,6 +52293,16 @@ async def load_diffusion_model_gated(# Register the in-flight load UNDER the arbiter lock: otherwise a competing acquire in that gap evicts DIFFUSION before# the load is marked, finds nothing to cancel, and both allocate at once. The training admission wraps the same span.def _acquire_and_begin():+ raise_if_load_cancelled(_DIFFUSION_LOAD_CANCELLED)+ admitted = []++ def _admit():+ if preflight is None:+ return+ preflight.lock.acquire()+ admitted.append(True)+ raise_if_load_cancelled(_DIFFUSION_LOAD_CANCELLED)+sink_token = eviction_sink.set(evicted_slots)try:with _diffusion_training_admission():@@ -52282,14 +52311,22 @@ async def load_diffusion_model_gated(guarded_media_begin(DIFFUSION, multi_model_mode, media_names, _begin_load),+ admit = _admit,**fit_kwargs,)finally:+ if admitted:+ preflight.lock.release()eviction_sink.reset(sink_token)from core.inference.chat_swap_kv import acquire_then_close, save_chat_kv_before_swapswap = await save_chat_kv_before_swap(DIFFUSION, "image", **fit_kwargs)+ try:+ raise_if_load_cancelled(_DIFFUSION_LOAD_CANCELLED)+ except BaseException:+ swap.close()+ raisestatus_dict = await acquire_then_close(swap, _acquire_and_begin)else:# A CPU-only native load never touches the GPU, but switching FROM a previous GPU load leaves DIFFUSION marked as owner, so release (owner-guarded).@@ -53871,6 +53908,14 @@ async def unload_diffusion_model(account_access.require_resident_control("diffusion", get_active_diffusion_engine().status().get("repo_id"))+ from core.inference.chat_swap_kv import cancel_preparing_loads++ await asyncio.to_thread(+ cancel_preparing_loads,+ "image",+ current_account_id(),+ any_account = account_access.account_scope() is None,+ )unload = get_active_diffusion_engine().unloadif account_access.account_scope() is not None:unload = functools.partial(unload, expected_account = current_account_id())@@ -53944,6 +53989,20 @@ async def diffusion_inference_info(current_subject: str = Depends(get_current_sureturn DiffusionInferenceInfoResponse(families = family_inference_infos())+def _image_load_preparing_progress() -> Optional[DiffusionLoadProgressResponse]:+ """A load POST of the caller's still in preflight reads as starting: the engine's "ready",+ "error" or null then describes the previous load. Once the engine runs this one, its phase wins."""+ from core.inference.chat_swap_kv import load_preparing++ if not load_preparing("image"):+ return None+ from core.inference.diffusion_engine_router import get_active_diffusion_engine++ if get_active_diffusion_engine().load_progress().get("phase") in ("downloading", "finalizing"):+ return None+ return DiffusionLoadProgressResponse(phase = "downloading")++@studio_router.get("/images/load-progress", response_model = DiffusionLoadProgressResponse)async def diffusion_load_progress(current_subject: str = Depends(get_current_subject),@@ -53954,6 +54013,9 @@ async def diffusion_load_progress(saving = saving_progress("image")if saving is not None:return DiffusionLoadProgressResponse(**saving)+ preparing = _image_load_preparing_progress()+ if preparing is not None:+ return preparingif account_access.resident_hidden("diffusion"):return account_access.hidden_resident_response()from core.inference.diffusion_engine_router import get_active_diffusion_enginediff --git a/studio/backend/tests/test_diffusion_comfy_components.py b/studio/backend/tests/test_diffusion_comfy_components.pyindex dd77ecb5b7c..f9e07aca528 100644--- a/studio/backend/tests/test_diffusion_comfy_components.py+++ b/studio/backend/tests/test_diffusion_comfy_components.py@@ -53,6 +53,24 @@ def test_parse_local_absolute_relative_and_bare(tmp_path):assert bare.local_path.endswith("vae_here.safetensors")+def test_status_summary_names_the_supplied_basename_of_a_symlinked_cache_file(tmp_path):+ blob = _save(tmp_path / "blobs" / "0123abcdef", {"x": torch.zeros(1)})+ snap = tmp_path / "snapshots" / "rev" / "ae.safetensors"+ snap.parent.mkdir(parents = True)+ try:+ snap.symlink_to(blob)+ except (OSError, NotImplementedError):+ pytest.skip("symlinks unavailable")+ ref = C.parse_component_file(str(snap), what = "vae_file")+ assert ref.local_path == str(Path(blob).resolve()) # loads still read the real file+ assert ref.name == "ae.safetensors"+ assert C.ComponentOverrides(files = {"vae": ref}).summary() == {"vae": "ae.safetensors"}+ rel = C.parse_component_file(+ "../snapshots/rev/ae.safetensors", model_path = str(tmp_path / "blobs")+ )+ assert rel.name == "ae.safetensors"++def test_parse_existing_subpath_under_model_dir_is_local(tmp_path):dit_dir = tmp_path / "models" / "diffusion_models"two = _save(dit_dir / "components" / "clip_l.safetensors", {"x": torch.zeros(1)})diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.pyindex 390e67a5cc8..0e3a101e0eb 100644--- a/studio/backend/tests/test_diffusion_routes.py+++ b/studio/backend/tests/test_diffusion_routes.py@@ -1299,8 +1299,14 @@ def _force_engine(monkeypatch, backend, *, engine_name, device):)acquired: list = []- def _fake_acquire(role, register = None):+ def _fake_acquire(+ role,+ register = None,+ admit = None,+ ):acquired.append(role)+ if admit is not None:+ admit()return register() if register is not None else Nonemonkeypatch.setattr(gpu_arbiter, "acquire_for", _fake_acquire)diff --git a/studio/backend/tests/test_mlx_diffusion_backend.py b/studio/backend/tests/test_mlx_diffusion_backend.pyindex 5297a99428a..744ac42ff33 100644--- a/studio/backend/tests/test_mlx_diffusion_backend.py+++ b/studio/backend/tests/test_mlx_diffusion_backend.py@@ -1165,7 +1165,7 @@ def test_the_load_route_takes_the_gpu_arbiter_for_mlx_on_a_cpu_torch_host(monkeymonkeypatch.setattr("routes.inference._selected_gpu_ordinal", _no_ordinal)calls = []monkeypatch.setattr(- arbiter, "acquire_for_request", lambda owner, fn: calls.append("acquire") or fn()+ arbiter, "acquire_for_request", lambda owner, fn, **_: calls.append("acquire") or fn())monkeypatch.setattr(arbiter, "release", lambda owner: calls.append("release"))asyncio.run(diff --git a/studio/backend/tests/test_swap_kv_resume.py b/studio/backend/tests/test_swap_kv_resume.pyindex c4913eda333..09b5de15672 100644--- a/studio/backend/tests/test_swap_kv_resume.py+++ b/studio/backend/tests/test_swap_kv_resume.py@@ -491,3 +491,164 @@ def test_load_progress_is_unchanged_without_a_save(client, env, monkeypatch, cas"error": None,"error_code": None,}++[email protected]("saved", [True, False])[email protected]("raises", [False, True])+def test_the_saving_phase_lasts_until_the_acquire_registers_the_load(+ env, monkeypatch, saved, raises+):+ if not saved:+ monkeypatch.setattr(env, "save_slots_for_resume", lambda should_abort: None)+ seen = []++ def acquire():+ seen.append(cs.saving_progress("image"))+ arb.acquire_for(arb.DIFFUSION)+ seen.append(cs.saving_progress("image"))+ if raises:+ raise arb.GpuBusyForAnotherAccountError(arb.CHAT, 1)++ try:+ _load(acquire = acquire)+ except arb.GpuBusyForAnotherAccountError:+ assert raises+ assert seen == [{"phase": cs.SAVING_CHAT_CONTEXT}] * 2+ assert cs.saving_progress("image") is None and cs._saving == {}+++def test_load_progress_reads_in_flight_through_the_load_preflight(+ client,+ env,+ monkeypatch,+ healthy_diffusers, # noqa: F811+):+ import core.inference.diffusion_hub_evidence as evidence++ _cuda(monkeypatch)+ base, body = _LOADS["image"]+ assert client.post(f"{base}/load", json = body).status_code == 200+ assert client.get(f"{base}/load-progress").json()["phase"] == "ready"+ entered, gate = threading.Event(), threading.Event()++ def _slow_prefetch(*args, **kwargs):+ entered.set()+ gate.wait(10)++ monkeypatch.setattr(evidence, "prefetch_for_pick", _slow_prefetch)+ monkeypatch.setattr(cs, "_preparing", {}, raising = False)+ answer: dict = {}+ poster = threading.Thread(+ target = lambda: answer.setdefault("resp", client.post(f"{base}/load", json = body))+ )+ poster.start()+ try:+ assert entered.wait(5)+ during = client.get(f"{base}/load-progress").json()+ finally:+ gate.set()+ poster.join(10)+ assert during["phase"] in ("downloading", "finalizing", "saving_chat_context")+ assert answer["resp"].status_code == 200+ assert getattr(cs, "_preparing", {}) == {}+ assert client.get(f"{base}/load-progress").json()["phase"] == "ready"++[email protected]("phase", ["evidence", "chat_save"])+def test_an_unload_during_the_preflight_cancels_the_load(+ client,+ env,+ monkeypatch,+ healthy_diffusers,+ phase, # noqa: F811+):+ import core.inference.diffusion_hub_evidence as evidence++ _cuda(monkeypatch)+ base, body = _LOADS["image"]+ monkeypatch.setattr(cs, "_preparing", {})+ gate = threading.Event()+ if phase == "evidence":+ entered = threading.Event()++ def _slow_prefetch(*args, **kwargs):+ entered.set()+ gate.wait(10)++ monkeypatch.setattr(evidence, "prefetch_for_pick", _slow_prefetch)+ else:+ env.gate, entered = gate, env.entered+ answer: dict = {}+ poster = threading.Thread(+ target = lambda: answer.setdefault("resp", client.post(f"{base}/load", json = body))+ )+ poster.start()+ try:+ assert entered.wait(5)+ during = client.get(f"{base}/load-progress").json()["phase"]+ stopped = client.post(f"{base}/unload")+ after = client.get(f"{base}/load-progress").json()["phase"]+ finally:+ gate.set()+ poster.join(10)+ assert not poster.is_alive()+ assert during == ("downloading" if phase == "evidence" else cs.SAVING_CHAT_CONTEXT)+ assert stopped.status_code == 200+ assert after not in ("downloading", "finalizing")+ resp = answer["resp"]+ assert resp.status_code == 409 and resp.json()["detail"] == "Diffusion load was cancelled."+ assert client.get(f"{base}/status").json()["loaded"] is False+ assert env.calls == [] and env.is_loaded and arb._owner == arb.CHAT+ assert cs._pending is None and kw._kv_resume is None and _no_files(env)+ assert cs._preparing == {} and cs._saving == {}+++def test_a_cancelled_preflight_stops_before_the_native_video_unload():+ import inspect++ import routes.inference as routes++ src = inspect.getsource(routes.load_diffusion_model_gated)+ assert src.index("raise_if_load_cancelled(") < src.index(+ "_unload_native_video_sharing_the_sd_cpp_tree"+ )+++def test_an_unload_while_the_acquire_waits_never_evicts_chat(+ client, env, monkeypatch, healthy_diffusers+):+ _cuda(monkeypatch)+ base, body = _LOADS["image"]+ monkeypatch.setattr(cs, "_preparing", {})+ entered, gate = threading.Event(), threading.Event()+ real_acquire_for = arb.acquire_for++ def _waiting_acquire_for(*args, **kwargs):+ if args and args[0] == arb.DIFFUSION:+ entered.set()+ gate.wait(10)+ return real_acquire_for(*args, **kwargs)++ monkeypatch.setattr(arb, "acquire_for", _waiting_acquire_for)+ answer: dict = {}+ poster = threading.Thread(+ target = lambda: answer.setdefault("resp", client.post(f"{base}/load", json = body))+ )+ poster.start()+ try:+ assert entered.wait(5)+ stopped = client.post(f"{base}/unload")+ finally:+ gate.set()+ poster.join(10)+ assert not poster.is_alive()+ assert stopped.status_code == 200+ resp = answer["resp"]+ assert resp.status_code == 409 and resp.json()["detail"] == "Diffusion load was cancelled."+ assert client.get(f"{base}/status").json()["loaded"] is False+ assert (+ not [c for c in env.calls if c[0] == "evict-chat"]+ and env.is_loaded+ and arb._owner == arb.CHAT+ )+ assert cs._preparing == {}diff --git a/studio/frontend/src/features/images/image-model-recall.ts b/studio/frontend/src/features/images/image-model-recall.tsindex be9ac95dcae..83deebef10e 100644--- a/studio/frontend/src/features/images/image-model-recall.ts+++ b/studio/frontend/src/features/images/image-model-recall.ts@@ -102,6 +102,234 @@ export function rememberImageModel(model: RememberedImageModel): void {}}+export type ImageModelKey = Pick<RememberedImageModel, "repoId" | "kind" | "filename">;+export type ImageComponentFiles = Pick<RememberedImageModel, "textEncoderFiles" | "vaeFile">;++// Encoder / VAE paths each model last loaded with, most recent last.+const COMPONENTS_KEY = "unsloth:images:component-files";+const COMPONENTS_CAP = 50;++type ComponentEntry = ImageComponentFiles & { key: string };++const componentsKey = ({ repoId, kind, filename }: ImageModelKey): string =>+ [repoId, kind, kind === "pipeline" ? "" : (filename ?? "")].join("\n");++function cleanComponentFiles(value: unknown): ImageComponentFiles {+ const raw = (value ?? {}) as { textEncoderFiles?: unknown; vaeFile?: unknown };+ const encoders = Array.isArray(raw.textEncoderFiles)+ ? raw.textEncoderFiles.filter((f): f is string => typeof f === "string" && f.trim().length > 0)+ : [];+ const vae = typeof raw.vaeFile === "string" ? raw.vaeFile.trim() : "";+ return {+ ...(encoders.length > 0 ? { textEncoderFiles: encoders } : {}),+ ...(vae ? { vaeFile: vae } : {}),+ };+}++function readComponentEntries(): ComponentEntry[] {+ try {+ const value = JSON.parse(localStorage.getItem(COMPONENTS_KEY) ?? "[]");+ return Array.isArray(value)+ ? value.filter((e): e is ComponentEntry => Boolean(e) && typeof e.key === "string")+ : [];+ } catch {+ return [];+ }+}++export function sameComponentFiles(a: ImageComponentFiles, b: ImageComponentFiles): boolean {+ const x = cleanComponentFiles(a);+ const y = cleanComponentFiles(b);+ return (x.textEncoderFiles ?? []).join("\n") === (y.textEncoderFiles ?? []).join("\n") && x.vaeFile === y.vaeFile;+}++export function readImageComponents(model: ImageModelKey): ImageComponentFiles | null {+ const key = componentsKey(model);+ const entry = readComponentEntries().find((e) => e.key === key);+ const files = cleanComponentFiles(entry);+ return files.textEncoderFiles || files.vaeFile ? files : null;+}++const sameEncoders = (a: ImageComponentFiles, b: ImageComponentFiles): boolean =>+ (cleanComponentFiles(a).textEncoderFiles ?? []).join("\n") === (cleanComponentFiles(b).textEncoderFiles ?? []).join("\n");+const sameVae = (a: ImageComponentFiles, b: ImageComponentFiles): boolean =>+ cleanComponentFiles(a).vaeFile === cleanComponentFiles(b).vaeFile;++/** Advanced-field files a load of `model` sends: a field still holding `owner`'s value is not a user edit, so the model's saved file replaces it. */+export function componentFilesForModel(+ typed: ImageComponentFiles,+ owner: ImageComponentFiles,+ model: ImageModelKey,+): { files: ImageComponentFiles; owner: ImageComponentFiles; replaceEncoders: boolean; replaceVae: boolean } {+ const replaceEncoders = sameEncoders(typed, owner);+ const replaceVae = sameVae(typed, owner);+ if (!replaceEncoders && !replaceVae) return { files: typed, owner, replaceEncoders, replaceVae };+ const saved = readImageComponents(model) ?? {};+ const pick = (encoders: ImageComponentFiles, vae: ImageComponentFiles) =>+ cleanComponentFiles({ textEncoderFiles: encoders.textEncoderFiles, vaeFile: vae.vaeFile });+ return {+ files: pick(replaceEncoders ? saved : typed, replaceVae ? saved : typed),+ owner: pick(replaceEncoders ? saved : owner, replaceVae ? saved : owner),+ replaceEncoders,+ replaceVae,+ };+}++/** A recalled model's files: its per-model entry, else the last-model slot's. */+export function recalledComponentFiles(model: RememberedImageModel): ImageComponentFiles {+ return readImageComponents(model) ?? cleanComponentFiles(model);+}++/** Seed the remembered model's files on page open, migrating the last-model slot into the map. */+export function seedImageComponents(model: RememberedImageModel): ImageComponentFiles {+ const saved = readImageComponents(model);+ if (saved) return saved;+ const slot = cleanComponentFiles(model);+ if (slot.textEncoderFiles || slot.vaeFile) rememberImageComponents(model, slot);+ return slot;+}++/** Forget a model's saved files when its resident build uses others; native (sd_cpp) builds keep the entry. */+export function forgetStaleImageComponents(+ model: ImageModelKey,+ status: { engine?: string | null; component_files?: Record<string, string> | null },+): void {+ if (status.engine === "sd_cpp") return;+ const saved = readImageComponents(model);+ if (saved && !componentFilesMatch(saved, status.component_files))+ rememberImageComponents(model, engagedComponentFiles(saved, status.component_files));+}++/** The part of `files` the resident build still engages, encoders and VAE judged separately. */+function engagedComponentFiles(+ files: ImageComponentFiles,+ componentFiles: Record<string, string> | null | undefined,+): ImageComponentFiles {+ const { vae, ...encoders } = componentFiles ?? {};+ const clean = cleanComponentFiles(files);+ return cleanComponentFiles({+ textEncoderFiles: componentFilesMatch({ textEncoderFiles: clean.textEncoderFiles }, encoders)+ ? clean.textEncoderFiles+ : undefined,+ vaeFile: componentFilesMatch({ vaeFile: clean.vaeFile }, vae ? { vae } : {}) ? clean.vaeFile : undefined,+ });+}++/** Forget the resident model's saved files (and the slot's, if it names that model) when its build does not use them. */+export function forgetStaleResidentComponents(status: {+ loaded: boolean;+ repo_id?: string | null;+ model_kind?: string | null;+ gguf_filename?: string | null;+ engine?: string | null;+ component_files?: Record<string, string> | null;+}): RememberedImageModel | null {+ const kind = status.model_kind;+ if (!status.loaded || !status.repo_id) return null;+ let resident: ImageModelKey;+ if (kind === "pipeline") resident = { repoId: status.repo_id, kind };+ else if ((kind === "gguf" || kind === "single_file") && status.gguf_filename)+ resident = { repoId: status.repo_id, kind, filename: status.gguf_filename };+ else return null;+ forgetStaleImageComponents(resident, status);+ if (status.engine === "sd_cpp") return null;+ const slot = readImageModel();+ if (!slot || componentsKey(slot) !== componentsKey(resident)) return null;+ const files = cleanComponentFiles(slot);+ if ((!files.textEncoderFiles && !files.vaeFile) || componentFilesMatch(files, status.component_files)) return null;+ const { textEncoderFiles: _te, vaeFile: _vae, ...bare } = slot;+ const next = { ...bare, ...engagedComponentFiles(files, status.component_files) };+ rememberImageModel(next);+ return next;+}++/** First loaded status: drop the remembered model's files its resident build no longer uses; returns the trimmed model or null. */+export function reconcileRememberedComponents<T extends ImageModelKey & ImageComponentFiles>(+ model: T,+ status: {+ loaded: boolean;+ repo_id?: string | null;+ model_kind?: string | null;+ gguf_filename?: string | null;+ engine?: string | null;+ component_files?: Record<string, string> | null;+ },+): (Omit<T, "textEncoderFiles" | "vaeFile"> & ImageComponentFiles) | null {+ const saved = status.loaded && matchesRememberedModel(model, status) ? readImageComponents(model) : null;+ if (!saved) return null;+ forgetStaleImageComponents(model, status);+ // What the build still engages (one part when a reload changed only the other), or nothing.+ const kept = readImageComponents(model) ?? {};+ if (sameComponentFiles(kept, saved)) return null;+ const slot = readImageModel();+ if (slot && componentsKey(slot) === componentsKey(model)) {+ const { textEncoderFiles: _te, vaeFile: _vae, ...bare } = slot;+ rememberImageModel({ ...bare, ...engagedComponentFiles(slot, status.component_files) });+ }+ const { textEncoderFiles: _te, vaeFile: _vae, ...rest } = model;+ return { ...rest, ...kept };+}++/** Record a finished load's files: a page-started load stores its request; a resumed one keeps or forgets the entry by the build. */+export function rememberLoadedImageComponents(+ load: ImageModelKey & { fieldFiles?: ImageComponentFiles },+ status: { engine?: string | null; component_files?: Record<string, string> | null },+): ImageComponentFiles | null {+ if (!load.fieldFiles) {+ forgetStaleImageComponents(load, status);+ return null;+ }+ rememberImageComponents(load, load.fieldFiles);+ return load.fieldFiles;+}++/** Per-field owner after a load: that load only while the field shows its file; field-ignoring loads (pipelines) leave ownership. */+export function componentFieldsOwnerAfterLoad(+ shown: ImageComponentFiles,+ loaded: ImageComponentFiles,+ owner: ImageComponentFiles,+ kind: RememberedImageModel["kind"],+): ImageComponentFiles {+ if (kind !== "gguf" && kind !== "single_file") return cleanComponentFiles(owner);+ return cleanComponentFiles({+ textEncoderFiles: (sameEncoders(shown, loaded) ? loaded : owner).textEncoderFiles,+ vaeFile: (sameVae(shown, loaded) ? loaded : owner).vaeFile,+ });+}++/** Fields after a load recovered on reopen: untouched fields take the recovered files, edits stay. */+export function recoveredComponentFields(+ shown: ImageComponentFiles,+ owner: ImageComponentFiles,+ loaded: ImageComponentFiles,+ kind: RememberedImageModel["kind"],+): { shown: ImageComponentFiles; replaceEncoders: boolean; replaceVae: boolean } {+ if (kind !== "gguf" && kind !== "single_file") return { shown, replaceEncoders: false, replaceVae: false };+ const replaceEncoders = sameEncoders(shown, owner);+ const replaceVae = sameVae(shown, owner);+ return {+ shown: cleanComponentFiles({+ textEncoderFiles: (replaceEncoders ? loaded : shown).textEncoderFiles,+ vaeFile: (replaceVae ? loaded : shown).vaeFile,+ }),+ replaceEncoders,+ replaceVae,+ };+}++/** Store the paths a load succeeded with; a load with none forgets the model's entry. */+export function rememberImageComponents(model: ImageModelKey, files: ImageComponentFiles): void {+ const key = componentsKey(model);+ const clean = cleanComponentFiles(files);+ const entries = readComponentEntries().filter((e) => e.key !== key);+ if (clean.textEncoderFiles || clean.vaeFile) entries.push({ key, ...clean });+ try {+ localStorage.setItem(COMPONENTS_KEY, JSON.stringify(entries.slice(-COMPONENTS_CAP)));+ } catch {+ // storage can be unavailable in private browsing+ }+}+export function matchesRememberedModel(model: RememberedImageModel,status: {@@ -135,3 +363,52 @@ export function componentFilesMatch(remembered.every((name, i) => name === resident[i]));}++// The pending load and its requested paths: the backend load outlives a page reload and status gives only basenames.+const PENDING_KEY = "unsloth:images:pending-load";++export type PendingImageLoad = RememberedImageModel & { displayRepoId?: string; baseRepo?: string; fieldFiles?: ImageComponentFiles };++export function rememberPendingImageLoad(load: PendingImageLoad): void {+ try {+ localStorage.setItem(PENDING_KEY, JSON.stringify(load));+ } catch {+ // storage can be unavailable in private browsing+ }+}++export function clearPendingImageLoad(): void {+ try {+ localStorage.removeItem(PENDING_KEY);+ } catch {+ // storage can be unavailable in private browsing+ }+}++function readPendingImageLoad(): PendingImageLoad | null {+ try {+ const value = JSON.parse(localStorage.getItem(PENDING_KEY) ?? "null");+ if (!value || typeof value.repoId !== "string" || !value.repoId) return null;+ if (!["gguf", "single_file", "pipeline"].includes(value.kind)) return null;+ return { ...value, fieldFiles: cleanComponentFiles(value.fieldFiles) };+ } catch {+ return null;+ }+}++/** The descriptor a finished load reconciles with, consuming the pending one if the resident build is that load. */+export function finishedLoadTarget<T extends ImageModelKey & { fieldFiles?: ImageComponentFiles }>(+ current: T | null,+ status: Parameters<typeof matchesRememberedModel>[1] & Parameters<typeof forgetStaleImageComponents>[1],+): T | PendingImageLoad | null {+ const pending = readPendingImageLoad();+ clearPendingImageLoad();+ if (current?.fieldFiles) return current;+ if (+ pending &&+ matchesRememberedModel(pending, status) &&+ (status.engine === "sd_cpp" || componentFilesMatch(pending.fieldFiles ?? {}, status.component_files))+ )+ return pending;+ return current;+}diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex d33cf2cc4c1..6b21c4c1efd 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -2,7 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { generationFailureLogsAction } from "@/features/settings/lib/view-logs-action";-import { readImageModel, redirectRetiredImagePick, rememberImageModel, matchesRememberedModel, componentFilesMatch, type RememberedImageModel } from "./image-model-recall";+import { readImageModel, redirectRetiredImagePick, rememberImageModel, matchesRememberedModel, componentFilesMatch, componentFieldsOwnerAfterLoad, componentFilesForModel, forgetStaleImageComponents, forgetStaleResidentComponents, recalledComponentFiles, reconcileRememberedComponents, rememberLoadedImageComponents, recoveredComponentFields, seedImageComponents, rememberPendingImageLoad, clearPendingImageLoad, finishedLoadTarget, type ImageComponentFiles, type ImageModelKey, type RememberedImageModel } from "./image-model-recall";import { componentFileFields, splitComponentFileList } from "./component-files";import type { CompareContext } from "./compare/compare-axes";import type { CompareRun } from "./compare/compare-run";@@ -225,7 +225,7 @@ import { useLoadAnywayPrompt } from "@/components/load-anyway-dialog";import { readAllowOversizedLoad, retryWhileCurrent, shouldOfferLoadAnyway } from "@/lib/unified-memory-load-refusal";import { evictedSlotsFrom, evictedToastOptions, resyncEvicted, type EvictedSlot } from "@/lib/evicted-toast";import { failureMessage, isMultiModelRefusal, MULTI_MODEL_REFUSAL_TITLE, refusalHeadersOf } from "@/lib/multi-model-refusal";-import { watchSavingPhase } from "@/lib/swap-save-phase";+import { isLoadInFlightPhase, watchSavingPhase } from "@/lib/swap-save-phase";import { modelMemorySettingsAction } from "@/features/settings/lib/model-memory-action";import { MAX_UPLOAD_IMAGE_SIDE, blobToDataUrl, fitImageDataUrl } from "@/lib/image-fit";import { loadGalleryUntil } from "@/lib/gallery-deep-link";@@ -1606,7 +1606,9 @@ function reportLoadFailure(failure: unknown, fallback: string): void {type Busy = "loading" | "unloading" | "generating" | null;// baseRepo: only a reload of a resident model the page did not load sends one, to rebuild the same companions.type ImageLoadOptions = { kind: "gguf" | "single_file" | "pipeline"; filename?: string; displayRepoId?: string; baseRepo?: string };-type LastLoad = { repoId: string } & ImageLoadOptions & Pick<RememberedImageModel, "textEncoderFiles" | "vaeFile">;+type LastLoad = { repoId: string } & ImageLoadOptions & Pick<RememberedImageModel, "textEncoderFiles" | "vaeFile"> & {+ fieldFiles?: ImageComponentFiles;+};// What a pick optimistically replaced, so a load that never takes can put it all back. The// quant label and the recipe move together at pick time, so they roll back together.@@ -1907,8 +1909,41 @@ export function ImagesPage({setTextEncoderQuant((v) => nvfp4SelectionFallback(v, nvfp4DiffusionKnown, nvfp4Diffusion));}, [nvfp4Diffusion, nvfp4DiffusionKnown, transformerQuant, textEncoderQuant]);const [memoryMode, setMemoryMode] = useState<"auto" | "fast" | "balanced" | "low_vram">("auto");- const [textEncoderFiles, setTextEncoderFiles] = useState("");- const [vaeFile, setVaeFile] = useState("");+ const [initialComponents] = useState<ImageComponentFiles>(() =>+ rememberedModel ? seedImageComponents(rememberedModel) : {},+ );+ const componentFieldsOwner = useRef(initialComponents);+ const [textEncoderFiles, setTextEncoderFiles] = useState((initialComponents.textEncoderFiles ?? []).join("\n"));+ const [vaeFile, setVaeFile] = useState(initialComponents.vaeFile ?? "");+ const componentFieldsShown = useRef(initialComponents);+ useEffect(() => {+ componentFieldsShown.current = { textEncoderFiles: splitComponentFileList(textEncoderFiles), vaeFile: vaeFile.trim() };+ }, [textEncoderFiles, vaeFile]);+ const pickComponentFiles = useCallback(+ (model: ImageModelKey): ImageComponentFiles => {+ const typed = { textEncoderFiles: splitComponentFileList(textEncoderFiles), vaeFile: vaeFile.trim() };+ const pick = componentFilesForModel(typed, componentFieldsOwner.current, model);+ componentFieldsOwner.current = pick.owner;+ if (pick.replaceEncoders) setTextEncoderFiles((pick.files.textEncoderFiles ?? []).join("\n"));+ if (pick.replaceVae) setVaeFile(pick.files.vaeFile ?? "");+ return pick.files;+ },+ [textEncoderFiles, vaeFile],+ );+ const componentsReconciled = useRef(false);+ const [initialLoadProbe, setInitialLoadProbe] = useState<"pending" | "loading" | "idle">("pending");+ const reconcileInitialComponents = useCallback(+ (loaded: DiffusionStatus) => {+ if (componentsReconciled.current || initialLoadProbe === "pending") return;+ componentsReconciled.current = true;+ if (initialLoadProbe === "loading" || !rememberedModel) return;+ const bare = reconcileRememberedComponents(rememberedModel, loaded);+ if (!bare) return;+ setRememberedModel(bare);+ pickComponentFiles(bare);+ },+ [rememberedModel, pickComponentFiles, initialLoadProbe],+ );// "auto", or the physical index to pin this load to; offered only on a multi-card CUDA/ROCm// host. Persisted, unlike the selects around it: status carries the device a pipeline is on// but not which card, so a refresh would reset it to Auto. A stale id is dropped on send.@@ -1944,6 +1979,22 @@ export function ImagesPage({// setInterval, so returning fires one immediate poll.const genVisibilityListener = useRef<(() => void) | null>(null);const [status, setStatus] = useState<DiffusionStatus | null>(null);+ const residentReconciledFor = useRef<DiffusionStatus | null>(null);+ const reconcileResidentComponents = useCallback(+ (loaded: DiffusionStatus) => {+ if (initialLoadProbe === "pending" || busy === "loading") return;+ if (residentReconciledFor.current === loaded) return;+ residentReconciledFor.current = loaded;+ const bare = forgetStaleResidentComponents(loaded);+ if (bare) setRememberedModel(bare);+ },+ [initialLoadProbe, busy],+ );+ useEffect(() => {+ if (!status?.loaded) return;+ reconcileInitialComponents(status);+ reconcileResidentComponents(status);+ }, [status, reconcileInitialComponents, reconcileResidentComponents]);const { familyOverride, setFamilyOverride, familySelect, opaqueKind, selectorModelId } = useFamilyOverride(status, status?.supported_families);// A connection is not bound by the resident model's size grid or presets.const conditioning = !external && status?.loaded ? (status.conditioning ?? null) : null;@@ -2198,6 +2249,7 @@ export function ImagesPage({lastLoadSig.current = null;// Leaving this set would let Reapply reload the model that was just freed.lastLoad.current = null;+ clearPendingImageLoad();setCanReapply(false);// Stopping the poll also stops its "cancelled or evicted" branch, which is what hands back a// pick that never became resident, so do it here exactly as that branch would.@@ -3408,6 +3460,21 @@ export function ImagesPage({);// Poll load-progress until the background load reaches "ready" or "error", updating the persistent toast in place.+ const rememberFinishedLoad = useCallback((target: LastLoad, loaded: DiffusionStatus, recovered = false) => {+ if (!matchesRememberedModel(target, loaded)) return;+ const remembered = withEngagedFamily(target, loaded);+ rememberImageModel(remembered);+ setRememberedModel(remembered);+ const files = rememberLoadedImageComponents(target, loaded);+ if (files && recovered) {+ const fill = recoveredComponentFields(componentFieldsShown.current, componentFieldsOwner.current, files, target.kind);+ if (fill.replaceEncoders) setTextEncoderFiles((fill.shown.textEncoderFiles ?? []).join("\n"));+ if (fill.replaceVae) setVaeFile(fill.shown.vaeFile ?? "");+ componentFieldsShown.current = fill.shown;+ }+ if (files) componentFieldsOwner.current = componentFieldsOwnerAfterLoad(componentFieldsShown.current, files, componentFieldsOwner.current, target.kind);+ }, []);+const pollLoadProgress = useCallback(async () => {// This tick's cancellation fence: clearing pollTimer stops the next tick, not the awaits below.const seq = cancelSeq.current;@@ -3431,11 +3498,9 @@ export function ImagesPage({const evicted = pendingEvicted.current;pendingEvicted.current = [];toast.success("Model loaded", evictedToastOptions(evicted));- if (lastLoad.current && matchesRememberedModel(lastLoad.current, loaded)) {- const remembered = withEngagedFamily(lastLoad.current, loaded);- rememberImageModel(remembered);- setRememberedModel(remembered);- }+ const started = lastLoad.current;+ lastLoad.current = finishedLoadTarget(started, loaded);+ if (lastLoad.current) rememberFinishedLoad(lastLoad.current, loaded, lastLoad.current !== started);setBusy(null);// A fallback-recipe pick takes the loaded family recipe on an untouched form (else SDXL runs 9 steps, CFG 0).const loadedRecipe = loadedRecipeFor(@@ -3463,6 +3528,7 @@ export function ImagesPage({return;}if (p.phase === "error") {+ clearPendingImageLoad();pendingRecalledGeneration.current = null;pendingEvicted.current = [];dismissLoadToast();@@ -3488,6 +3554,7 @@ export function ImagesPage({return;}if (p.phase === null) {+ clearPendingImageLoad();pendingRecalledGeneration.current = null;pendingEvicted.current = [];// No load in flight and nothing loaded: the load was cancelled or evicted. Terminal, else this@@ -3519,7 +3586,7 @@ export function ImagesPage({}if (seq !== cancelSeq.current) return;pollTimer.current = setTimeout(() => void pollLoadProgress(), 1000);- }, [dismissLoadToast, refreshStatus, cancelLoadFromToast, offerLoadAnywayFor]);+ }, [dismissLoadToast, refreshStatus, cancelLoadFromToast, offerLoadAnywayFor, rememberFinishedLoad]);// Put back what a teardown removed when the load it was tearing down is still running: the// unload failed, so the poll and toast were stopped for nothing. refreshStatus cannot do@@ -3581,18 +3648,31 @@ export function ImagesPage({void (async () => {await refreshStatus();// A load runs on the backend as a daemon thread that survives navigation, so resume tracking one still in flight.+ let inFlight = false;try {const p = await getDiffusionLoadProgress();- if (p.phase === "downloading" || p.phase === "finalizing") {+ inFlight = isLoadInFlightPhase(p.phase);+ if (inFlight) {setBusy("loading");dismissLoadToast();lastLoadSig.current = null;loadToastId.current = toast(null, loadToastArgs(p, undefined, cancelLoadFromToast));void pollLoadProgress();+ } else if (p.phase === "ready") {+ const ticket = ++statusTicket.current;+ const loaded = await getDiffusionStatus();+ setStatusIfNewest(ticket, loaded);+ const resumed = finishedLoadTarget<LastLoad>(null, loaded);+ if (resumed) {+ lastLoad.current = resumed;+ rememberFinishedLoad(resumed, loaded, true);+ }}} catch {// Resume is best-effort; a failed probe just leaves the idle view.}+ if (!inFlight) clearPendingImageLoad();+ setInitialLoadProbe(inFlight ? "loading" : "idle");// Resume tracking a generation started elsewhere so the page shows the in-flight run. Mirrors the video page.try {const g = await getGenerateProgress();@@ -3616,7 +3696,7 @@ export function ImagesPage({}dismissLoadToast();};- }, [refreshStatus, dismissLoadToast, pollLoadProgress, resumeGeneratePoll, cancelLoadFromToast]);+ }, [refreshStatus, setStatusIfNewest, dismissLoadToast, pollLoadProgress, resumeGeneratePoll, cancelLoadFromToast, rememberFinishedLoad]);// Seed the sliders from a resident model's recipe when the page finds one it did not load,// else a resident flux.1-dev generates garbage at 9 steps. Guarded by a per-repo ref.@@ -3856,6 +3936,7 @@ export function ImagesPage({// Whether THIS load carries the selection into the build, so a quantized load that did not can drop it.bakedLorasOnLoad.current = bakeLoras.length > 0;const componentFiles = componentFileFields(opts.kind, advanced.text_encoder_file, advanced.vae_file);+ const fieldFiles = componentFileFields(opts.kind, picked.text_encoder_file, picked.vae_file);// A retired FLUX.3 full copy (named, or a downloaded snapshot of one) loads the base it copies, as the backend// redirects it, so the load, Reapply and the remembered model all name the id the status will report.const redirected = redirectRetiredImagePick({@@ -3876,7 +3957,9 @@ export function ImagesPage({baseRepo: opts.baseRepo,textEncoderFiles: componentFiles.text_encoder_file,vaeFile: componentFiles.vae_file,+ fieldFiles: { textEncoderFiles: fieldFiles.text_encoder_file, vaeFile: fieldFiles.vae_file },};+ rememberPendingImageLoad(lastLoad.current);setCanReapply(true);// Carry the prior target so the async poll can restore it if the background load fails after starting.lastLoadRevert.current = { prev: prevLastLoad };@@ -3884,7 +3967,7 @@ export function ImagesPage({const retryPick = pickSeq.current;const retryOversized = retryWhileCurrent(() => retryPick === pickSeq.current && startLoad === loadSeq.current,- () => void retryLoadRef.current?.(repoId, opts, { ...advanced, allow_oversized_load: true }),+ () => void retryLoadRef.current?.(repoId, opts, { ...picked, allow_oversized_load: true }),);lastLoadAttempt.current = { overrideSent, retry: retryOversized };// The POST may first save the chat model's context; show that on this load's toast meanwhile.@@ -3925,6 +4008,7 @@ export function ImagesPage({resyncEvicted(pendingEvicted.current, "image");} catch (err) {pendingEvicted.current = [];+ clearPendingImageLoad();lastLoad.current = prevLastLoad;setCanReapply(prevLastLoad != null);lastLoadRevert.current = null;@@ -4279,8 +4363,17 @@ export function ImagesPage({pickToast.dismissAll();if (!owns()) return true;}+ const picked = downloadSnapshot || downloadOnly ? null : pickComponentFiles({ repoId, ...opts });+ const withPicked = (a: LoadAdvanced): LoadAdvanced =>+ picked+ ? {+ ...a,+ text_encoder_file: picked.textEncoderFiles?.length ? picked.textEncoderFiles : undefined,+ vae_file: picked.vaeFile || undefined,+ }+ : a;// ONE snapshot for the plan and the load it fires: the download runs for minutes without setting `busy`.- let advanced = downloadSnapshot ?? currentLoadAdvanced(repoId, familyOverrideRequired);+ let advanced = downloadSnapshot ?? withPicked(currentLoadAdvanced(repoId, familyOverrideRequired));// A retired FLUX.3 full copy is planned, staged and loaded as the base it copies, so the staged// checkpoint is the one the load opens (the backend redirects the same picks).const component = componentFileFields(opts.kind, advanced.text_encoder_file, advanced.vae_file);@@ -4293,7 +4386,7 @@ export function ImagesPage({if (redirected.repoId !== repoId) {repoId = redirected.repoId;opts = { kind: redirected.kind, filename: redirected.filename, displayRepoId: redirected.displayRepoId };- advanced = downloadSnapshot ?? currentLoadAdvanced(repoId, familyOverrideRequired);+ advanced = downloadSnapshot ?? withPicked(currentLoadAdvanced(repoId, familyOverrideRequired));// A local snapshot of the copy is now a Hub load of the base: plan and stage it like one.source = "hub";}@@ -4406,7 +4499,7 @@ export function ImagesPage({}return handleLoadRef.current(repoId, opts, advanced, pickToastId);},- [stage, currentLoadAdvanced, requestDownloadPlan, modelSelectionAction, pickGuard, revertPick, pickToast, engineFor, offerLoadAnyway, dismissLoadAnyway],+ [stage, currentLoadAdvanced, pickComponentFiles, requestDownloadPlan, modelSelectionAction, pickGuard, revertPick, pickToast, engineFor, offerLoadAnyway, dismissLoadAnyway],);const loadOrStageRef = useRef(loadOrStage);useEffect(() => {@@ -4416,10 +4509,23 @@ export function ImagesPage({const resolveDownloadFootprint = useCallback(async (repoId: string, meta: ModelSelectorChangeMeta) => {if (!meta.ggufFilename) return null;+ const opts = { kind: "gguf", filename: meta.ggufFilename } as const;+ const advanced = currentLoadAdvanced(repoId, false);+ const { files } = componentFilesForModel(+ { textEncoderFiles: splitComponentFileList(textEncoderFiles), vaeFile: vaeFile.trim() },+ componentFieldsOwner.current,+ { repoId, ...opts },+ );const plan = await requestDownloadPlan(repoId,- { kind: "gguf", filename: meta.ggufFilename },- currentLoadAdvanced(repoId, false),+ opts,+ modelSelectionAction === "download"+ ? advanced+ : {+ ...advanced,+ text_encoder_file: files.textEncoderFiles?.length ? files.textEncoderFiles : undefined,+ vae_file: files.vaeFile || undefined,+ },);const requiredBytes = plan.required_bytes ?? 0;if (requiredBytes <= 0) return null;@@ -4429,7 +4535,7 @@ export function ImagesPage({plan.checkpoint_bytes ?? meta.expectedBytes ?? 0,};},- [currentLoadAdvanced, requestDownloadPlan, pickGuard, stage],+ [currentLoadAdvanced, requestDownloadPlan, pickGuard, stage, modelSelectionAction, textEncoderFiles, vaeFile],);const beginPick = useCallback(() => {@@ -4638,8 +4744,13 @@ export function ImagesPage({void loadOrStage(l.repoId, opts, reloadSource(l.repoId), undefined, true, undefined, true);return;}- void handleLoad(l.repoId, opts);- }, [engineChoice, handleLoad, loadOrStage, status]);+ const files = pickComponentFiles({ repoId: l.repoId, kind: l.kind, filename: l.filename });+ void handleLoad(l.repoId, opts, {+ ...currentLoadAdvanced(l.repoId),+ text_encoder_file: files.textEncoderFiles?.length ? files.textEncoderFiles : undefined,+ vae_file: files.vaeFile || undefined,+ });+ }, [currentLoadAdvanced, engineChoice, handleLoad, loadOrStage, pickComponentFiles, status]);// The LoRA note's action: the same GGUF pick, on the native engine. A resident model the page did not load// reloads from its status, which names the checkpoint.@@ -5731,6 +5842,7 @@ export function ImagesPage({: { repoId: status.repo_id, kind, filename: status.gguf_filename ?? undefined },status,);+ forgetStaleImageComponents(model, status);rememberImageModel(model);setRememberedModel(model);}@@ -5752,6 +5864,7 @@ export function ImagesPage({// "Generate anyway" on an unloaded model: the retry's finally clears the one-shot before this runs.allowOversized: oversizedOnce.current,};+ const recalled = recalledComponentFiles(rememberedModel);const started = await handleLoad(rememberedModel.repoId,{ kind: rememberedModel.kind, filename: rememberedModel.filename },@@ -5760,8 +5873,8 @@ export function ImagesPage({...currentLoadAdvanced(rememberedModel.repoId, false, true),family_override: rememberedModel.familyOverride,// The recalled build's own encoder / VAE files, not whatever the fields hold now.- text_encoder_file: rememberedModel.textEncoderFiles,- vae_file: rememberedModel.vaeFile,+ text_encoder_file: recalled.textEncoderFiles,+ vae_file: recalled.vaeFile,},);if (!started) pendingRecalledGeneration.current = null;diff --git a/studio/frontend/src/lib/swap-save-phase.ts b/studio/frontend/src/lib/swap-save-phase.tsindex e29ae950055..72dda68253b 100644--- a/studio/frontend/src/lib/swap-save-phase.ts+++ b/studio/frontend/src/lib/swap-save-phase.ts@@ -44,3 +44,8 @@ export function watchSavingPhase(},};}++/** Whether a load-progress phase is a load still running (every nonterminal phase, the chat-context save included). */+export function isLoadInFlightPhase(phase: unknown): boolean {+ return phase === "downloading" || phase === "finalizing" || phase === SAVING_CHAT_CONTEXT;+}diff --git a/studio/frontend/tests/image-component-recall.test.ts b/studio/frontend/tests/image-component-recall.test.tsnew file mode 100644index 00000000000..213c36bf20c--- /dev/null+++ b/studio/frontend/tests/image-component-recall.test.ts@@ -0,0 +1,733 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import ts from "@typescript/typescript6";+import {+ componentFieldsOwnerAfterLoad,+ componentFilesForModel,+ forgetStaleImageComponents,+ forgetStaleResidentComponents,+ readImageComponents,+ readImageModel,+ recalledComponentFiles,+ recoveredComponentFields,+ reconcileRememberedComponents,+ rememberImageComponents,+ rememberLoadedImageComponents,+ rememberImageModel,+ sameComponentFiles,+ seedImageComponents,+} from "../src/features/images/image-model-recall.ts";+import { splitComponentFileList } from "../src/features/images/component-files.ts";+import { reapplyTarget } from "../src/features/images/lib/engine-choice.ts";+import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";++const { store } = installLocalStorageFake();++const zImage = { repoId: "/comfy/models/diffusion_models", kind: "gguf", filename: "z.gguf" } as const;+const flux = { repoId: "/comfy/models/diffusion_models", kind: "single_file", filename: "flux.safetensors" } as const;+const zFiles = { textEncoderFiles: ["../text_encoders/qwen_3_4b.safetensors"], vaeFile: "../vae/ae.safetensors" };++test("component files are stored per model and a load with none forgets them", () => {+ store.clear();+ rememberImageComponents(zImage, zFiles);+ rememberImageComponents(flux, { textEncoderFiles: ["clip_l.safetensors", "t5xxl.safetensors"] });+ assert.deepEqual(readImageComponents(zImage), zFiles);+ assert.deepEqual(readImageComponents(flux), { textEncoderFiles: ["clip_l.safetensors", "t5xxl.safetensors"] });+ assert.equal(readImageComponents({ ...zImage, filename: "z-Q8_0.gguf" }), null);+ rememberImageComponents(zImage, {});+ assert.equal(readImageComponents(zImage), null);+ assert.ok(readImageComponents(flux));+});++test("the component map keeps the 50 most recent models and survives bad storage", () => {+ store.clear();+ for (let i = 0; i < 60; i++)+ rememberImageComponents({ repoId: `org/m${i}`, kind: "gguf", filename: "m.gguf" }, { vaeFile: `vae${i}` });+ assert.equal(JSON.parse(store.get("unsloth:images:component-files") ?? "[]").length, 50);+ assert.equal(readImageComponents({ repoId: "org/m9", kind: "gguf", filename: "m.gguf" }), null);+ rememberImageComponents({ repoId: "org/m10", kind: "gguf", filename: "m.gguf" }, { vaeFile: "vae10" });+ rememberImageComponents({ repoId: "org/new", kind: "gguf", filename: "m.gguf" }, { vaeFile: "new" });+ assert.deepEqual(readImageComponents({ repoId: "org/m10", kind: "gguf", filename: "m.gguf" }), { vaeFile: "vae10" });+ assert.equal(readImageComponents({ repoId: "org/m11", kind: "gguf", filename: "m.gguf" }), null);++ store.set("unsloth:images:component-files", "{not json");+ assert.equal(readImageComponents(zImage), null);+ rememberImageComponents(zImage, zFiles);+ assert.deepEqual(readImageComponents(zImage), zFiles);+});++test("the map leaves the last-model slot alone", () => {+ store.clear();+ rememberImageModel({ ...zImage, ...zFiles });+ rememberImageComponents(flux, { vaeFile: "ae.safetensors" });+ assert.deepEqual(readImageModel(), { ...zImage, ...zFiles });+});++test("sameComponentFiles ignores formatting and empty fields", () => {+ assert.ok(sameComponentFiles({}, { textEncoderFiles: [], vaeFile: "" }));+ assert.ok(sameComponentFiles({ textEncoderFiles: ["a"], vaeFile: " v " }, { textEncoderFiles: ["a"], vaeFile: "v" }));+ assert.ok(!sameComponentFiles({ textEncoderFiles: ["a", "b"] }, { textEncoderFiles: ["b", "a"] }));+ assert.ok(!sameComponentFiles(zFiles, {}));+});++test("a model pick fills the Advanced fields from that model, clears another model's, and keeps the user's edits", () => {+ const source = readSrc("features/images/images-page.tsx");+ const tree = ts.createSourceFile("images-page.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let declaration = "";+ const visit = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === "pickComponentFiles")+ declaration = `const ${node.getText(tree)};`;+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(declaration);+ const { outputText } = ts.transpileModule(`${declaration}\nreturn pickComponentFiles;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ });+ const page = (fields: { te: string; vae: string }, owner: object) => {+ const state = { ...fields };+ const scope = {+ useCallback: (fn: unknown) => fn,+ textEncoderFiles: fields.te,+ vaeFile: fields.vae,+ componentFieldsOwner: { current: owner },+ splitComponentFileList,+ sameComponentFiles,+ readImageComponents,+ componentFilesForModel,+ setTextEncoderFiles: (v: string) => (state.te = v),+ setVaeFile: (v: string) => (state.vae = v),+ };+ const pick = new Function(...Object.keys(scope), outputText)(...Object.values(scope));+ return { state, scope, pick };+ };++ store.clear();+ rememberImageComponents(zImage, zFiles);+ const fluxFields = { te: "clip_l.safetensors", vae: "flux_vae.safetensors" };+ const fluxOwner = { textEncoderFiles: ["clip_l.safetensors"], vaeFile: "flux_vae.safetensors" };+ const toZ = page(fluxFields, fluxOwner);+ assert.deepEqual(toZ.pick(zImage), zFiles);+ assert.deepEqual(toZ.state, { te: zFiles.textEncoderFiles.join("\n"), vae: zFiles.vaeFile });+ assert.deepEqual(toZ.scope.componentFieldsOwner.current, zFiles);++ const toFlux = page({ te: zFiles.textEncoderFiles[0], vae: zFiles.vaeFile }, zFiles);+ assert.deepEqual(toFlux.pick(flux), {});+ assert.deepEqual(toFlux.state, { te: "", vae: "" });++ const typed = page({ te: "a.safetensors, b.safetensors", vae: "" }, zFiles);+ assert.deepEqual(typed.pick(zImage), { textEncoderFiles: ["a.safetensors", "b.safetensors"], vaeFile: "" });+ assert.deepEqual(typed.state, { te: "a.safetensors, b.safetensors", vae: "" });+});++test("a successful load stores the requested files per model and the page starts on them", () => {+ const source = readSrc("features/images/images-page.tsx");+ assert.match(+ source,+ /rememberImageModel\(remembered\);\s*setRememberedModel\(remembered\);\s*const files = rememberLoadedImageComponents\(target, loaded\);/,+ );+ assert.match(source, /const fieldFiles = componentFileFields\(opts\.kind, picked\.text_encoder_file, picked\.vae_file\);/);+ assert.match(source, /recalledComponentFiles\(rememberedModel\)/);+ assert.match(source, /downloadSnapshot \|\| downloadOnly \? null : pickComponentFiles\(\{ repoId, \.\.\.opts \}\)/);+});++test("Reapply of a resident model sends that model's files, never the fields another model filled in", () => {+ const source = readSrc("features/images/images-page.tsx");+ const tree = ts.createSourceFile("images-page.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const declarations: Record<string, string> = {};+ const visit = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && ["pickComponentFiles", "handleReapply"].includes(node.name.getText(tree)))+ declarations[node.name.getText(tree)] = `const ${node.getText(tree)};`;+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(declarations.pickComponentFiles && declarations.handleReapply);+ const { outputText } = ts.transpileModule(+ `${declarations.pickComponentFiles}\n${declarations.handleReapply}\nreturn handleReapply;`,+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+ );+ const reapply = (fields: { te: string; vae: string }, owner: object, status: object) => {+ const loads: { repoId: string; advanced: Record<string, unknown> }[] = [];+ const state = { ...fields };+ const currentLoadAdvanced = () => ({+ cpu_offload: false,+ text_encoder_file: splitComponentFileList(state.te).length ? splitComponentFileList(state.te) : undefined,+ vae_file: state.vae.trim() || undefined,+ });+ const scope = {+ useCallback: (fn: unknown) => fn,+ textEncoderFiles: fields.te,+ vaeFile: fields.vae,+ componentFieldsOwner: { current: owner },+ splitComponentFileList,+ sameComponentFiles,+ readImageComponents,+ componentFilesForModel,+ setTextEncoderFiles: (v: string) => (state.te = v),+ setVaeFile: (v: string) => (state.vae = v),+ lastLoad: { current: null },+ status,+ engineChoice: "auto",+ reapplyTarget,+ reapplyChangesEngine: () => false,+ reloadSource: () => "hub",+ loadOrStage: () => assert.fail("no engine change here"),+ currentLoadAdvanced,+ handleLoad: (repoId: string, _opts: unknown, pinned?: Record<string, unknown>) => {+ loads.push({ repoId, advanced: pinned ?? currentLoadAdvanced() });+ return Promise.resolve(true);+ },+ };+ new Function(...Object.keys(scope), outputText)(...Object.values(scope))();+ return { loads, state };+ };++ store.clear();+ rememberImageComponents(zImage, zFiles);+ const other = { loaded: true, repo_id: "org/other-GGUF", model_kind: "gguf", gguf_filename: "o.gguf", component_files: {} };+ const toOther = reapply({ te: zFiles.textEncoderFiles.join("\n"), vae: zFiles.vaeFile }, zFiles, other);+ assert.equal(toOther.loads.length, 1);+ assert.equal(toOther.loads[0].repoId, "org/other-GGUF");+ assert.equal(toOther.loads[0].advanced.text_encoder_file, undefined);+ assert.equal(toOther.loads[0].advanced.vae_file, undefined);+ assert.deepEqual(toOther.state, { te: "", vae: "" });++ const resident = { loaded: true, repo_id: zImage.repoId, model_kind: "gguf", gguf_filename: zImage.filename, component_files: {} };+ const toZ = reapply({ te: zFiles.textEncoderFiles.join("\n"), vae: zFiles.vaeFile }, zFiles, resident);+ assert.deepEqual(toZ.loads[0].advanced.text_encoder_file, zFiles.textEncoderFiles);+ assert.equal(toZ.loads[0].advanced.vae_file, zFiles.vaeFile);+ const typed = reapply({ te: "mine.safetensors", vae: "" }, zFiles, other);+ assert.deepEqual(typed.loads[0].advanced.text_encoder_file, ["mine.safetensors"]);+});++test("a Load-mode footprint plans the shown model with its own files, a Download-mode one with the fields", async () => {+ const source = readSrc("features/images/images-page.tsx");+ const tree = ts.createSourceFile("images-page.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let declaration = "";+ const visit = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === "resolveDownloadFootprint")+ declaration = `const ${node.getText(tree)};`;+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(declaration);+ const { outputText } = ts.transpileModule(`${declaration}\nreturn resolveDownloadFootprint;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ });+ const footprint = async (action: "load" | "download") => {+ const fields = { te: zFiles.textEncoderFiles.join("\n"), vae: zFiles.vaeFile };+ const planned: Record<string, unknown>[] = [];+ const scope = {+ useCallback: (fn: unknown) => fn,+ textEncoderFiles: fields.te,+ vaeFile: fields.vae,+ componentFieldsOwner: { current: zFiles },+ modelSelectionAction: action,+ splitComponentFileList,+ readImageComponents,+ componentFilesForModel,+ currentLoadAdvanced: () => ({+ cpu_offload: false,+ text_encoder_file: splitComponentFileList(fields.te),+ vae_file: fields.vae,+ }),+ requestDownloadPlan: (_repo: string, _opts: unknown, picked: Record<string, unknown>) => {+ planned.push(picked);+ return Promise.resolve({ required_bytes: 1, checkpoint_bytes: 1 });+ },+ pickGuard: null,+ stage: null,+ };+ const resolve = new Function(...Object.keys(scope), outputText)(...Object.values(scope));+ await resolve("org/other-GGUF", { ggufFilename: "o.gguf" });+ return planned[0];+ };++ store.clear();+ rememberImageComponents(zImage, zFiles);+ const load = await footprint("load");+ assert.equal(load.text_encoder_file, undefined);+ assert.equal(load.vae_file, undefined);+ assert.equal(load.cpu_offload, false);+ const download = await footprint("download");+ assert.deepEqual(download.text_encoder_file, zFiles.textEncoderFiles);+});++test("a recalled model's files come from the per-model map, the last-model slot only as a fallback", () => {+ store.clear();+ rememberImageComponents(zImage, zFiles);+ assert.deepEqual(recalledComponentFiles({ ...zImage }), zFiles);+ assert.deepEqual(recalledComponentFiles({ ...flux, vaeFile: "ae.safetensors" }), { vaeFile: "ae.safetensors" });+ assert.deepEqual(recalledComponentFiles({ ...flux }), {});++ const source = readSrc("features/images/images-page.tsx");+ const recall = source.slice(source.indexOf("const handleGenerateWithRecall = useCallback"));+ const pinnedFiles = recall.slice(0, recall.indexOf("if (!started) pendingRecalledGeneration.current = null;"));+ assert.match(pinnedFiles, /const recalled = recalledComponentFiles\(rememberedModel\);/);+ assert.match(pinnedFiles, /text_encoder_file: recalled\.textEncoderFiles,\s*vae_file: recalled\.vaeFile,/);+});++test("a finished load owns the fields only while they show its files", () => {+ assert.deepEqual(componentFieldsOwnerAfterLoad(zFiles, zFiles, {}, "gguf"), zFiles);+ assert.deepEqual(componentFieldsOwnerAfterLoad(zFiles, {}, zFiles, "pipeline"), zFiles);+ assert.deepEqual(componentFieldsOwnerAfterLoad(zFiles, {}, zFiles, "single_file"), zFiles);+ const source = readSrc("features/images/images-page.tsx");+ assert.match(+ source,+ /componentFieldsOwner\.current = componentFieldsOwnerAfterLoad\(componentFieldsShown\.current, files, componentFieldsOwner\.current, target\.kind\);/,+ );+});++test("a load that ignores the fields keeps a cleared field the user's edit", () => {+ const shown = { vaeFile: zFiles.vaeFile };+ assert.deepEqual(componentFieldsOwnerAfterLoad(shown, {}, zFiles, "pipeline"), zFiles);+ rememberImageComponents(flux, { textEncoderFiles: ["../text_encoders/t5.safetensors"], vaeFile: "../vae/flux_ae.safetensors" });+ const owner = componentFieldsOwnerAfterLoad(shown, {}, zFiles, "pipeline");+ assert.deepEqual(componentFilesForModel(shown, owner, flux).files, { vaeFile: "../vae/flux_ae.safetensors" });+ assert.deepEqual(componentFieldsOwnerAfterLoad(shown, {}, zFiles, "single_file"), { vaeFile: zFiles.vaeFile });+});++test("a Load anyway retry keeps the requested files, which a native load strips from what it sends", () => {+ const source = readSrc("features/images/images-page.tsx");+ const start = source.indexOf("const retryOversized = retryWhileCurrent(");+ const retry = source.slice(start, source.indexOf("lastLoadAttempt.current = {", start));+ assert.match(retry, /retryLoadRef\.current\?\.\(repoId, opts, \{ \.\.\.picked, allow_oversized_load: true \}\)/);+});++test("an upgrade seeds the map from the last-model slot, so picking that model keeps its paths", () => {+ store.clear();+ rememberImageModel({ ...zImage, ...zFiles });+ const remembered = readImageModel()!;+ const initial = seedImageComponents(remembered);+ assert.deepEqual(initial, zFiles);+ assert.deepEqual(readImageComponents(zImage), zFiles);+ assert.deepEqual(componentFilesForModel(zFiles, initial, zImage).files, zFiles);+ assert.deepEqual(componentFilesForModel(zFiles, initial, flux).files, {});+ rememberImageComponents(zImage, { vaeFile: "newer.safetensors" });+ assert.deepEqual(seedImageComponents(remembered), { vaeFile: "newer.safetensors" });+ assert.deepEqual(readImageComponents(zImage), { vaeFile: "newer.safetensors" });+ store.clear();+ assert.deepEqual(seedImageComponents({ ...flux }), {});+ assert.equal(store.get("unsloth:images:component-files"), undefined);++ const source = readSrc("features/images/images-page.tsx");+ assert.match(source, /useState<ImageComponentFiles>\(\(\) =>\s*rememberedModel \? seedImageComponents\(rememberedModel\) : \{\},/);+});++test("a resident build with other components than the map's forgets the entry; a matching one keeps it", () => {+ store.clear();+ rememberImageComponents(zImage, zFiles);+ rememberImageComponents(flux, { vaeFile: "../vae/flux_ae.safetensors" });+ forgetStaleImageComponents(zImage, { engine: "sd_cpp", component_files: null });+ assert.deepEqual(readImageComponents(zImage), zFiles);+ forgetStaleImageComponents(zImage, { engine: "diffusers", component_files: {} });+ assert.equal(readImageComponents(zImage), null);+ forgetStaleImageComponents(flux, { component_files: { vae: "flux_ae.safetensors" } });+ assert.deepEqual(readImageComponents(flux), { vaeFile: "../vae/flux_ae.safetensors" });+ forgetStaleImageComponents(flux, { component_files: { vae: "other.safetensors" } });+ assert.equal(readImageComponents(flux), null);++ const source = readSrc("features/images/images-page.tsx");+ const recall = source.slice(source.indexOf("const handleGenerateWithRecall = useCallback"));+ assert.ok(recall.slice(0, recall.indexOf("if (!rememberedModel || !prompt.trim())")).includes("forgetStaleImageComponents(model, status);"));+});++test("a resumed load the page did not start keeps the saved files it engages; a page load stores its request", () => {+ store.clear();+ rememberImageComponents(zImage, zFiles);+ const resumed = { ...zImage, kind: "gguf" as const };+ const engaged = { engine: "diffusers", component_files: { text_encoder: "qwen_3_4b.safetensors", vae: "ae.safetensors" } };+ assert.equal(rememberLoadedImageComponents(resumed, engaged), null);+ assert.deepEqual(readImageComponents(zImage), zFiles);+ assert.equal(rememberLoadedImageComponents(resumed, { engine: "sd_cpp", component_files: null }), null);+ assert.deepEqual(readImageComponents(zImage), zFiles);+ assert.equal(rememberLoadedImageComponents(resumed, { engine: "diffusers", component_files: {} }), null);+ assert.equal(readImageComponents(zImage), null);+ assert.deepEqual(rememberLoadedImageComponents({ ...zImage, fieldFiles: zFiles }, { component_files: {} }), zFiles);+ assert.deepEqual(readImageComponents(zImage), zFiles);+ assert.deepEqual(rememberLoadedImageComponents({ ...zImage, fieldFiles: {} }, { component_files: {} }), {});+ assert.equal(readImageComponents(zImage), null);++ const source = readSrc("features/images/images-page.tsx");+ assert.match(+ source,+ /const files = rememberLoadedImageComponents\(target, loaded\);\s*if \(files && recovered\) \{[\s\S]*?\}\s*if \(files\) componentFieldsOwner\.current = componentFieldsOwnerAfterLoad\(/,+ );+});++test("the encoder and VAE fields are owned separately, so editing one does not carry the other to another model", () => {+ store.clear();+ const fluxFiles = { textEncoderFiles: ["clip_l.safetensors", "t5xxl.safetensors"], vaeFile: "flux_ae.safetensors" };+ rememberImageComponents(flux, fluxFiles);+ rememberImageComponents(zImage, zFiles);+ const typed = { textEncoderFiles: zFiles.textEncoderFiles, vaeFile: "mine.safetensors" };+ const pick = componentFilesForModel(typed, zFiles, flux);+ assert.deepEqual(pick.files, { textEncoderFiles: fluxFiles.textEncoderFiles, vaeFile: "mine.safetensors" });+ assert.deepEqual(pick.owner, { textEncoderFiles: fluxFiles.textEncoderFiles, vaeFile: zFiles.vaeFile });+ assert.deepEqual(componentFilesForModel(pick.files, pick.owner, zImage).files, {+ textEncoderFiles: zFiles.textEncoderFiles,+ vaeFile: "mine.safetensors",+ });+ assert.deepEqual(componentFilesForModel(zFiles, zFiles, flux).files, fluxFiles);+ assert.deepEqual(componentFilesForModel({ textEncoderFiles: ["a"], vaeFile: "b" }, zFiles, flux).files, {+ textEncoderFiles: ["a"],+ vaeFile: "b",+ });+ assert.deepEqual(+ componentFieldsOwnerAfterLoad(+ { textEncoderFiles: zFiles.textEncoderFiles, vaeFile: "edited-during-load" },+ zFiles,+ { vaeFile: "old" },+ "gguf",+ ),+ { textEncoderFiles: zFiles.textEncoderFiles, vaeFile: "old" },+ );+});++test("the first loaded status forgets the remembered model's stale files and clears the untouched fields", () => {+ store.clear();+ rememberImageComponents(zImage, zFiles);+ const resident = { loaded: true, repo_id: zImage.repoId, model_kind: "gguf", gguf_filename: zImage.filename };+ rememberImageModel({ ...zImage, ...zFiles, familyOverride: "z-image" });+ assert.deepEqual(reconcileRememberedComponents({ ...zImage, ...zFiles, familyOverride: "z-image" }, { ...resident, engine: "diffusers", component_files: {} }), {+ ...zImage,+ familyOverride: "z-image",+ });+ assert.equal(readImageComponents(zImage), null);+ assert.deepEqual(readImageModel(), { ...zImage, familyOverride: "z-image" });+ assert.deepEqual(seedImageComponents(readImageModel()!), {});+ assert.deepEqual(recalledComponentFiles(readImageModel()!), {});+ rememberImageComponents(zImage, zFiles);+ rememberImageModel({ ...flux, vaeFile: "flux_ae.safetensors" });+ assert.ok(reconcileRememberedComponents(zImage, { ...resident, engine: "diffusers", component_files: {} }));+ assert.deepEqual(readImageModel(), { ...flux, vaeFile: "flux_ae.safetensors" });+ const kept: Parameters<typeof reconcileRememberedComponents>[1][] = [+ { ...resident, component_files: { text_encoder: "qwen_3_4b.safetensors", vae: "ae.safetensors" } },+ { ...resident, engine: "sd_cpp", component_files: null },+ { ...resident, gguf_filename: "z-Q8_0.gguf", component_files: {} },+ { loaded: false },+ ];+ for (const status of kept) {+ rememberImageComponents(zImage, zFiles);+ assert.equal(reconcileRememberedComponents(zImage, status), null);+ assert.deepEqual(readImageComponents(zImage), zFiles);+ }++ const source = readSrc("features/images/images-page.tsx");+ const tree = ts.createSourceFile("images-page.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const declarations: Record<string, string> = {};+ const visit = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && ["pickComponentFiles", "reconcileInitialComponents"].includes(node.name.getText(tree)))+ declarations[node.name.getText(tree)] = `const ${node.getText(tree)};`;+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(declarations.reconcileInitialComponents);+ const { outputText } = ts.transpileModule(+ `${declarations.pickComponentFiles}\n${declarations.reconcileInitialComponents}\nreturn reconcileInitialComponents;`,+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+ );+ const open = (fields: { te: string; vae: string }, status: object, initialLoadProbe = "idle") => {+ const state: { te: string; vae: string; remembered?: unknown } = { ...fields };+ const scope = {+ useCallback: (fn: unknown) => fn,+ textEncoderFiles: fields.te,+ vaeFile: fields.vae,+ componentFieldsOwner: { current: zFiles },+ componentsReconciled: { current: false },+ rememberedModel: { ...zImage, ...zFiles },+ initialLoadProbe,+ setRememberedModel: (m: unknown) => (state.remembered = m),+ splitComponentFileList,+ componentFilesForModel,+ reconcileRememberedComponents,+ setTextEncoderFiles: (v: string) => (state.te = v),+ setVaeFile: (v: string) => (state.vae = v),+ };+ const reconcile = new Function(...Object.keys(scope), outputText)(...Object.values(scope));+ reconcile(status);+ reconcile(status);+ return { state, scope };+ };+ const stale = { ...resident, engine: "diffusers", component_files: {} };+ store.clear();+ rememberImageComponents(zImage, zFiles);+ const untouched = open({ te: zFiles.textEncoderFiles[0], vae: zFiles.vaeFile }, stale);+ assert.deepEqual(untouched.state, { te: "", vae: "", remembered: { ...zImage } });+ assert.deepEqual(untouched.scope.componentFieldsOwner.current, {});+ assert.equal(untouched.scope.componentsReconciled.current, true);+ rememberImageComponents(zImage, zFiles);+ const edited = open({ te: zFiles.textEncoderFiles[0], vae: "mine.safetensors" }, stale);+ assert.deepEqual(edited.state, { te: "", vae: "mine.safetensors", remembered: { ...zImage } });+ rememberImageComponents(zImage, zFiles);+ const midReload = open({ te: zFiles.textEncoderFiles[0], vae: zFiles.vaeFile }, stale, "loading");+ assert.deepEqual(midReload.state, { te: zFiles.textEncoderFiles[0], vae: zFiles.vaeFile });+ assert.deepEqual(readImageComponents(zImage), zFiles);+ assert.equal(midReload.scope.componentsReconciled.current, true);+ const pending = open({ te: zFiles.textEncoderFiles[0], vae: zFiles.vaeFile }, stale, "pending");+ assert.deepEqual(readImageComponents(zImage), zFiles);+ assert.equal(pending.scope.componentsReconciled.current, false);+ assert.match(source, /setInitialLoadProbe\(inFlight \? "loading" : "idle"\)/);+ assert.match(+ source,+ /useEffect\(\(\) => \{\s*if \(!status\?\.loaded\) return;\s*reconcileInitialComponents\(status\);\s*reconcileResidentComponents\(status\);\s*\}, \[status, reconcileInitialComponents, reconcileResidentComponents\]\);/,+ );+});++test("every settled loaded status forgets the resident model's stale files, not only the remembered model's", () => {+ store.clear();+ rememberImageModel({ ...zImage, ...zFiles });+ rememberImageComponents(zImage, zFiles);+ rememberImageComponents(flux, { vaeFile: "../vae/flux_ae.safetensors" });+ const fluxResident = {+ loaded: true,+ repo_id: flux.repoId,+ model_kind: "single_file",+ gguf_filename: flux.filename,+ engine: "diffusers",+ component_files: {},+ };+ assert.equal(reconcileRememberedComponents(zImage, fluxResident), null);+ assert.deepEqual(readImageComponents(flux), { vaeFile: "../vae/flux_ae.safetensors" });+ forgetStaleResidentComponents(fluxResident);+ assert.equal(readImageComponents(flux), null);+ assert.deepEqual(componentFilesForModel(zFiles, zFiles, flux).files, {});+ assert.deepEqual(readImageComponents(zImage), zFiles);+ assert.deepEqual(readImageModel(), { ...zImage, ...zFiles });+ rememberImageModel({ ...flux, vaeFile: "../vae/flux_ae.safetensors", familyOverride: "flux" });+ rememberImageComponents(flux, { vaeFile: "../vae/flux_ae.safetensors" });+ assert.deepEqual(forgetStaleResidentComponents(fluxResident), { ...flux, familyOverride: "flux" });+ assert.deepEqual(readImageModel(), { ...flux, familyOverride: "flux" });+ assert.deepEqual(recalledComponentFiles(readImageModel()!), {});+ rememberImageModel({ ...flux, vaeFile: "../vae/flux_ae.safetensors" });+ assert.ok(forgetStaleResidentComponents(fluxResident));+ assert.deepEqual(readImageModel(), { ...flux });+ for (const status of [+ { ...fluxResident, component_files: { vae: "flux_ae.safetensors" } },+ { ...fluxResident, engine: "sd_cpp", component_files: null },+ ]) {+ rememberImageModel({ ...flux, vaeFile: "../vae/flux_ae.safetensors" });+ assert.equal(forgetStaleResidentComponents(status), null);+ assert.deepEqual(readImageModel(), { ...flux, vaeFile: "../vae/flux_ae.safetensors" });+ }+ rememberImageModel({ ...zImage, ...zFiles });+ const kept = [+ { ...fluxResident, component_files: { vae: "flux_ae.safetensors" } },+ { ...fluxResident, engine: "sd_cpp", component_files: null },+ { loaded: false },+ ];+ for (const status of kept) {+ rememberImageComponents(flux, { vaeFile: "../vae/flux_ae.safetensors" });+ forgetStaleResidentComponents(status);+ assert.deepEqual(readImageComponents(flux), { vaeFile: "../vae/flux_ae.safetensors" });+ }+ const pipe = { repoId: "black-forest-labs/FLUX.1-dev", kind: "pipeline" } as const;+ rememberImageComponents(pipe, { vaeFile: "/vae/ae.safetensors" });+ forgetStaleResidentComponents({ loaded: true, repo_id: pipe.repoId, model_kind: "pipeline", engine: "diffusers", component_files: {} });+ assert.equal(readImageComponents(pipe), null);++ const source = readSrc("features/images/images-page.tsx");+ const tree = ts.createSourceFile("images-page.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let declaration = "";+ const visit = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === "reconcileResidentComponents")+ declaration = `const ${node.getText(tree)};`;+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(declaration);+ const { outputText } = ts.transpileModule(`${declaration}\nreturn reconcileResidentComponents;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ });+ let remembered: unknown;+ const run = (initialLoadProbe: string, busy: string | null) => {+ rememberImageComponents(flux, { vaeFile: "../vae/flux_ae.safetensors" });+ const setRememberedModel = (m: unknown) => (remembered = m);+ const scope = {+ useCallback: (fn: unknown) => fn,+ residentReconciledFor: { current: null },+ initialLoadProbe,+ busy,+ forgetStaleResidentComponents,+ setRememberedModel,+ };+ new Function(...Object.keys(scope), outputText)(...Object.values(scope))(fluxResident);+ return readImageComponents(flux);+ };+ rememberImageModel({ ...flux, vaeFile: "../vae/flux_ae.safetensors" });+ assert.equal(run("idle", null), null);+ assert.deepEqual(remembered, { ...flux });+ remembered = undefined;+ rememberImageModel({ ...zImage, ...zFiles });+ assert.equal(run("idle", null), null);+ assert.equal(run("loading", null), null);+ assert.equal(run("idle", "generating"), null);+ assert.deepEqual(run("pending", null), { vaeFile: "../vae/flux_ae.safetensors" });+ assert.deepEqual(run("idle", "loading"), { vaeFile: "../vae/flux_ae.safetensors" });+ assert.equal(remembered, undefined);+});++test("a field edit reruns no resident cleanup against a cached status, so another tab's newer files survive", () => {+ const source = readSrc("features/images/images-page.tsx");+ const tree = ts.createSourceFile("images-page.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const names = new Set(["pickComponentFiles", "reconcileInitialComponents", "residentReconciledFor", "reconcileResidentComponents"]);+ const declarations: string[] = [];+ let effect = "";+ const visit = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && names.has(node.name.getText(tree))) declarations.push(`const ${node.getText(tree)};`);+ if (ts.isExpressionStatement(node) && /^useEffect\(/.test(node.getText(tree)) && node.getText(tree).includes("reconcileResidentComponents(status)"))+ effect = node.getText(tree);+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(declarations.length >= 3 && effect);+ const { outputText } = ts.transpileModule([...declarations, effect].join("\n"), {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ });+ store.clear();+ const old = { vaeFile: "/files/old-ae.safetensors" };+ rememberImageModel({ ...zImage, ...old });+ rememberImageComponents(zImage, old);+ const statusFor = (component_files: Record<string, string>) => ({+ loaded: true,+ repo_id: zImage.repoId,+ model_kind: zImage.kind,+ gguf_filename: zImage.filename,+ engine: "diffusers",+ component_files,+ });+ const hooks: { value: unknown; deps?: unknown[] }[] = [];+ let hook = 0;+ let effectDeps: unknown[] | undefined;+ const same = (a: unknown[] | undefined, b: unknown[]) => !!a && a.length === b.length && a.every((v, i) => Object.is(v, b[i]));+ const scope = {+ useRef: (value: unknown) => {+ const i = hook++;+ hooks[i] ??= { value: { current: value } };+ return hooks[i].value;+ },+ useCallback: (fn: unknown, deps: unknown[]) => {+ const i = hook++;+ if (!same(hooks[i]?.deps, deps)) hooks[i] = { value: fn, deps };+ return hooks[i].value;+ },+ useEffect: (fn: () => void, deps: unknown[]) => {+ if (same(effectDeps, deps)) return;+ effectDeps = deps;+ fn();+ },+ textEncoderFiles: "",+ vaeFile: old.vaeFile,+ componentFieldsOwner: { current: old },+ splitComponentFileList,+ componentFilesForModel,+ setTextEncoderFiles: () => {},+ setVaeFile: () => {},+ componentsReconciled: { current: false },+ initialLoadProbe: "idle",+ busy: null,+ rememberedModel: { ...zImage, ...old },+ setRememberedModel: () => {},+ reconcileRememberedComponents,+ forgetStaleResidentComponents,+ status: statusFor({ vae: "old-ae.safetensors" }) as object,+ };+ const render = () => {+ hook = 0;+ new Function(...Object.keys(scope), outputText)(...Object.values(scope));+ };+ render();+ assert.deepEqual(readImageComponents(zImage), old);+ const newer = { vaeFile: "/files/new-ae.safetensors" };+ rememberImageModel({ ...zImage, ...newer });+ rememberLoadedImageComponents({ ...zImage, fieldFiles: newer }, statusFor({ vae: "new-ae.safetensors" }));+ scope.textEncoderFiles = "/files/encoder.safetensors";+ render();+ assert.deepEqual(readImageComponents(zImage), newer);+ assert.equal(readImageModel()?.vaeFile, newer.vaeFile);+ scope.status = statusFor({ vae: "other-ae.safetensors" });+ render();+ assert.equal(readImageComponents(zImage), null);+ assert.equal(readImageModel()?.vaeFile, undefined);+});++test("a reload that changed one override keeps the other's saved path", () => {+ const resident = { loaded: true, repo_id: zImage.repoId, model_kind: "gguf", gguf_filename: zImage.filename, engine: "diffusers" };+ const vaeOnly = { ...resident, component_files: { vae: "ae.safetensors" } };+ store.clear();+ rememberImageComponents(zImage, zFiles);+ forgetStaleImageComponents(zImage, vaeOnly);+ assert.deepEqual(readImageComponents(zImage), { vaeFile: zFiles.vaeFile });+ rememberImageComponents(zImage, zFiles);+ forgetStaleImageComponents(zImage, { ...resident, component_files: { text_encoder: "qwen_3_4b.safetensors", vae: "x.safetensors" } });+ assert.deepEqual(readImageComponents(zImage), { textEncoderFiles: zFiles.textEncoderFiles });++ store.clear();+ rememberImageComponents(zImage, zFiles);+ rememberImageModel({ ...zImage, ...zFiles });+ assert.deepEqual(reconcileRememberedComponents({ ...zImage, ...zFiles }, vaeOnly), { ...zImage, vaeFile: zFiles.vaeFile });+ assert.deepEqual(readImageModel(), { ...zImage, vaeFile: zFiles.vaeFile });+ assert.deepEqual(recalledComponentFiles(readImageModel()!), { vaeFile: zFiles.vaeFile });++ store.clear();+ rememberImageModel({ ...zImage, ...zFiles });+ assert.deepEqual(forgetStaleResidentComponents(vaeOnly), { ...zImage, vaeFile: zFiles.vaeFile });+ assert.deepEqual(readImageModel(), { ...zImage, vaeFile: zFiles.vaeFile });+});++test("a recovered pending load refills the Advanced fields the user has not touched since reopening", () => {+ const source = readSrc("features/images/images-page.tsx");+ const tree = ts.createSourceFile("images-page.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let declaration = "";+ const visit = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === "rememberFinishedLoad")+ declaration = `const ${node.getText(tree)};`;+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(declaration);+ const { outputText } = ts.transpileModule(`${declaration}\nreturn rememberFinishedLoad;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ });+ const loaded = {+ loaded: true,+ repo_id: zImage.repoId,+ model_kind: zImage.kind,+ gguf_filename: zImage.filename,+ engine: "diffusers",+ component_files: { text_encoder: "qwen_3_4b.safetensors", vae: "ae.safetensors" },+ };+ const reopen = (shown: { textEncoderFiles?: string[]; vaeFile?: string }, owner: object, recovered = true) => {+ const state = { te: (shown.textEncoderFiles ?? []).join("\n"), vae: shown.vaeFile ?? "" };+ const scope = {+ useCallback: (fn: unknown) => fn,+ matchesRememberedModel: () => true,+ withEngagedFamily: (target: object) => target,+ rememberImageModel,+ setRememberedModel: () => {},+ rememberLoadedImageComponents,+ componentFieldsOwnerAfterLoad,+ recoveredComponentFields,+ componentFieldsShown: { current: shown },+ componentFieldsOwner: { current: owner },+ setTextEncoderFiles: (v: string) => (state.te = v),+ setVaeFile: (v: string) => (state.vae = v),+ };+ const remember = new Function(...Object.keys(scope), outputText)(...Object.values(scope));+ remember({ ...zImage, ...zFiles, fieldFiles: zFiles }, loaded, recovered);+ return { state, scope };+ };+ store.clear();+ const fresh = reopen({}, {});+ assert.deepEqual(fresh.state, { te: zFiles.textEncoderFiles.join("\n"), vae: zFiles.vaeFile });+ assert.deepEqual(fresh.scope.componentFieldsOwner.current, zFiles);+ const old = { textEncoderFiles: ["old-te.safetensors"], vaeFile: "old-ae.safetensors" };+ assert.deepEqual(reopen(old, old).state, { te: zFiles.textEncoderFiles.join("\n"), vae: zFiles.vaeFile });+ const edited = reopen({ textEncoderFiles: old.textEncoderFiles, vaeFile: "mine.safetensors" }, old);+ assert.deepEqual(edited.state, { te: zFiles.textEncoderFiles.join("\n"), vae: "mine.safetensors" });+ assert.deepEqual(edited.scope.componentFieldsOwner.current, { textEncoderFiles: zFiles.textEncoderFiles, vaeFile: old.vaeFile });+ assert.deepEqual(reopen({}, {}, false).state, { te: "", vae: "" });+});diff --git a/studio/frontend/tests/image-load-resume.test.ts b/studio/frontend/tests/image-load-resume.test.tsnew file mode 100644index 00000000000..240476804ba--- /dev/null+++ b/studio/frontend/tests/image-load-resume.test.ts@@ -0,0 +1,151 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import {+ clearPendingImageLoad,+ finishedLoadTarget,+ forgetStaleResidentComponents,+ readImageComponents,+ readImageModel,+ rememberImageModel,+ rememberLoadedImageComponents,+ rememberPendingImageLoad,+} from "../src/features/images/image-model-recall.ts";+import { isLoadInFlightPhase } from "../src/lib/swap-save-phase.ts";+import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";++const { store } = installLocalStorageFake();++const zImage = { repoId: "/comfy/models/diffusion_models", kind: "gguf", filename: "z.gguf" } as const;+const zFiles = { textEncoderFiles: ["../text_encoders/qwen_3_4b.safetensors"], vaeFile: "../vae/ae.safetensors" };+const ready = {+ loaded: true,+ repo_id: zImage.repoId,+ model_kind: "gguf",+ gguf_filename: zImage.filename,+ engine: "diffusers",+ component_files: { text_encoder: "qwen_3_4b.safetensors", vae: "ae.safetensors" },+};++test("every nonterminal backend load phase counts as in flight on page open", () => {+ const models = readFileSync(new URL("../../backend/models/inference.py", import.meta.url), "utf8");+ const response = models.slice(models.indexOf("class DiffusionLoadProgressResponse"));+ const phases = [.../Literal\[([^\]]+)\]/.exec(response)![1].matchAll(/"([^"]+)"/g)].map((m) => m[1]);+ const nonterminal = phases.filter((p) => p !== "ready" && p !== "error");+ assert.ok(nonterminal.includes("saving_chat_context"));+ for (const phase of nonterminal) assert.equal(isLoadInFlightPhase(phase), true, phase);+ for (const phase of ["ready", "error", null, undefined]) assert.equal(isLoadInFlightPhase(phase), false, String(phase));+ const source = readSrc("features/images/images-page.tsx");+ assert.match(source, /inFlight = isLoadInFlightPhase\(p\.phase\);/);+});++test("a load resumed after a page reload records the paths it was started with", () => {+ store.clear();+ rememberPendingImageLoad({ ...zImage, ...zFiles, fieldFiles: zFiles });+ const resident = { repoId: "org/old", kind: "pipeline" } as const;+ const target = finishedLoadTarget<typeof resident>(resident, ready);+ assert.deepEqual(target, { ...zImage, ...zFiles, fieldFiles: zFiles });+ assert.deepEqual(rememberLoadedImageComponents(target!, ready), zFiles);+ assert.deepEqual(readImageComponents(zImage), zFiles);+ assert.equal(finishedLoadTarget(null, ready), null);++ rememberPendingImageLoad({ ...zImage, fieldFiles: zFiles });+ assert.deepEqual(finishedLoadTarget(null, ready)?.fieldFiles, zFiles);++ rememberPendingImageLoad({ ...zImage, fieldFiles: zFiles });+ assert.equal(finishedLoadTarget(null, { ...ready, gguf_filename: "other.gguf" }), null);+ const own = { ...zImage, fieldFiles: { vaeFile: "mine.safetensors" } };+ rememberPendingImageLoad({ ...zImage, fieldFiles: zFiles });+ assert.equal(finishedLoadTarget(own, ready), own);+ rememberPendingImageLoad({ ...zImage, fieldFiles: zFiles });+ clearPendingImageLoad();+ assert.equal(finishedLoadTarget(null, ready), null);+});++test("the page stores the pending load at start and clears it on every way a load ends", () => {+ const source = readSrc("features/images/images-page.tsx");+ assert.match(source, /lastLoad\.current = \{[\s\S]*?fieldFiles: \{[^}]*\},\s*\};[\s\S]{0,200}rememberPendingImageLoad\(lastLoad\.current\);/);+ assert.match(source, /const started = lastLoad\.current;\s*lastLoad\.current = finishedLoadTarget\(started, loaded\);\s*if \(lastLoad\.current\) rememberFinishedLoad\(lastLoad\.current, loaded, lastLoad\.current !== started\);/);+ assert.match(source, /if \(p\.phase === "error"\) \{\s*clearPendingImageLoad\(\);/);+ assert.match(source, /if \(p\.phase === null\) \{\s*clearPendingImageLoad\(\);/);+ assert.match(source, /\} catch \(err\) \{\s*pendingEvicted\.current = \[\];\s*clearPendingImageLoad\(\);/);+ const drop = source.slice(source.indexOf("const dropResidentState = useCallback"));+ assert.ok(drop.slice(0, drop.indexOf("}, [dismissLoadToast")).includes("clearPendingImageLoad();"));+ assert.match(source, /if \(!inFlight\) clearPendingImageLoad\(\);/);+});++test("a load that finished while the page was closed records its paths before the descriptor is cleared", () => {+ const source = readSrc("features/images/images-page.tsx");+ const mount = source.slice(source.indexOf("inFlight = isLoadInFlightPhase(p.phase);"));+ const probe = mount.slice(0, mount.indexOf("if (!inFlight) clearPendingImageLoad();"));+ assert.match(+ probe,+ /\} else if \(p\.phase === "ready"\) \{[\s\S]*?const loaded = await getDiffusionStatus\(\);\s*setStatusIfNewest\(ticket, loaded\);\s*const resumed = finishedLoadTarget<LastLoad>\(null, loaded\);\s*if \(resumed\) \{\s*lastLoad\.current = resumed;\s*rememberFinishedLoad\(resumed, loaded, true\);/,+ );+ const recorder = source.slice(source.indexOf("const rememberFinishedLoad = useCallback"));+ const body = recorder.slice(0, recorder.indexOf("}, []);"));+ assert.match(body, /if \(!matchesRememberedModel\(target, loaded\)\) return;/);+ assert.match(body, /rememberImageModel\(remembered\);\s*setRememberedModel\(remembered\);/);+ assert.match(body, /rememberLoadedImageComponents\(target, loaded\)/);++ store.clear();+ rememberPendingImageLoad({ ...zImage, fieldFiles: zFiles });+ const resumed = finishedLoadTarget(null, ready);+ assert.deepEqual(resumed?.fieldFiles, zFiles);+ assert.deepEqual(rememberLoadedImageComponents(resumed!, ready), zFiles);+ assert.deepEqual(readImageComponents(zImage), zFiles);+});++test("the mount probe publishes the finished build's status before the reconcilers run", () => {+ const source = readSrc("features/images/images-page.tsx");+ const mount = source.slice(source.indexOf("inFlight = isLoadInFlightPhase(p.phase);"));+ const probe = mount.slice(0, mount.indexOf('setInitialLoadProbe(inFlight ? "loading" : "idle");'));+ assert.match(+ probe,+ /\} else if \(p\.phase === "ready"\) \{[\s\S]*?const ticket = \+\+statusTicket\.current;\s*const loaded = await getDiffusionStatus\(\);\s*setStatusIfNewest\(ticket, loaded\);/,+ );++ const newFiles = { vaeFile: "/models/new-vae.safetensors" };+ const oldBuild = { ...ready, component_files: { vae: "old-vae.safetensors" } };+ const newBuild = { ...ready, component_files: { vae: "new-vae.safetensors" } };+ store.clear();+ rememberPendingImageLoad({ ...zImage, fieldFiles: newFiles });+ const resumed = finishedLoadTarget(null, newBuild)!;+ rememberLoadedImageComponents(resumed, newBuild);+ rememberImageModel({ ...zImage, ...newFiles });+ forgetStaleResidentComponents(newBuild);+ assert.deepEqual(readImageComponents(zImage), newFiles);+ assert.equal(readImageModel()?.vaeFile, newFiles.vaeFile);+ forgetStaleResidentComponents(oldBuild);+ assert.equal(readImageComponents(zImage), null);+});++test("a pending load whose files the resident build does not use keeps the saved entry", () => {+ const working = { vaeFile: "/models/working-ae.safetensors" };+ const other = { vaeFile: "/models/other-ae.safetensors" };+ const resident = { ...ready, component_files: { vae: "working-ae.safetensors" } };+ store.clear();+ rememberLoadedImageComponents({ ...zImage, fieldFiles: working }, resident);+ rememberPendingImageLoad({ ...zImage, ...other, fieldFiles: other });+ const resumed = finishedLoadTarget(null, resident);+ assert.equal(resumed, null);+ assert.equal(finishedLoadTarget(null, resident), null, "consumed");+ forgetStaleResidentComponents(resident);+ assert.deepEqual(readImageComponents(zImage), working);++ const own = { ...zImage };+ rememberPendingImageLoad({ ...zImage, fieldFiles: other });+ assert.equal(finishedLoadTarget(own, resident), own);+ assert.equal(rememberLoadedImageComponents(own, resident), null);+ assert.deepEqual(readImageComponents(zImage), working);++ rememberPendingImageLoad({ ...zImage, fieldFiles: working });+ assert.deepEqual(finishedLoadTarget(null, resident)?.fieldFiles, working);+ const native = { ...ready, engine: "sd_cpp", component_files: {} };+ rememberPendingImageLoad({ ...zImage, fieldFiles: other });+ assert.deepEqual(finishedLoadTarget(null, native)?.fieldFiles, other);+});diff --git a/studio/frontend/tests/image-model-recall.test.ts b/studio/frontend/tests/image-model-recall.test.tsindex c3516f550ac..af9e14d99fc 100644--- a/studio/frontend/tests/image-model-recall.test.ts+++ b/studio/frontend/tests/image-model-recall.test.ts@@ -8,7 +8,9 @@ import { explicitFamily } from "../src/features/model-picker/components/model-seimport {componentFilesMatch,matchesRememberedModel,+ forgetStaleImageComponents,readImageModel,+ recalledComponentFiles,rememberImageModel,} from "../src/features/images/image-model-recall.ts";import { splitComponentFileList } from "../src/features/images/component-files.ts";@@ -64,6 +66,8 @@ test("recalling a quantized model carries the selected adapters into its load",textEncoderFiles: "",vaeFile: "",splitComponentFileList,+ recalledComponentFiles,+ forgetStaleImageComponents,busy: null,external: null,imagePresets: { hydrated: true },diff --git a/studio/frontend/tests/media-status-sequencing.test.ts b/studio/frontend/tests/media-status-sequencing.test.tsindex e306d40ab18..7a9a02b5eb6 100644--- a/studio/frontend/tests/media-status-sequencing.test.ts+++ b/studio/frontend/tests/media-status-sequencing.test.ts@@ -9,8 +9,9 @@ import test from "node:test";import { readSrc } from "./helpers/kit.ts";const PAGES = [- ["images", "features/images/images-page.tsx", "getDiffusionStatus", "unloadDiffusionModel"],- ["video", "features/video/video-page.tsx", "getVideoStatus", "unloadVideoModel"],+ // Images also publishes the finished build's status from its mount probe.+ ["images", "features/images/images-page.tsx", "getDiffusionStatus", "unloadDiffusionModel", 4],+ ["video", "features/video/video-page.tsx", "getVideoStatus", "unloadVideoModel", 3],] as const;function callbackBody(source: string, name: string): string {@@ -29,7 +30,7 @@ function callbackBody(source: string, name: string): string {assert.fail(`${name}'s callback never closes`);}-for (const [name, path, read, unload] of PAGES) {+for (const [name, path, read, unload, writes] of PAGES) {test(`the ${name} page lets only the newest status read write`, () => {const page = readSrc(path);assert.match(page, /const statusTicket = useRef\(0\);/);@@ -83,8 +84,8 @@ for (const [name, path, read, unload] of PAGES) {);assert.equal((page.match(/setStatusIfNewest\(/g) ?? []).length,- 3,- "the refresh, the load-progress read and the unload all go through it",+ writes,+ "every status read (refresh, load-progress, unload) goes through it",);});