Skip to content

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.

Studio: free chat model VRAM at training start only when the GPU is tight (#6243)

Daniel Hanc42c1d56e891
diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.py
index a9694bb8e98..636fe1a759c 100644
--- a/studio/backend/core/export/orchestrator.py
+++ b/studio/backend/core/export/orchestrator.py
@@ -63,6 +63,19 @@ class ExportOrchestrator:
self._run_start_seq: int = 0
# True while an export op runs; SSE ends the stream 1s after this flips False.
self._export_active: bool = False
+ # Set by cancel_export(); reset when a new load/export run starts. Lets the
+ # caller distinguish a user cancel from a genuine subprocess crash.
+ self._cancel_requested: bool = False
+
+ # Last finished operation, so a client whose blocking POST was cut off by a
+ # Cloudflare tunnel timeout (524 at ~100s, while the op runs for minutes) can
+ # poll /api/export/status and still learn the real outcome. Guarded by
+ # _op_lock. `_op_seq` is a monotonic counter the client uses as a baseline to
+ # tell "my op finished" (seq grew) from a stale previous result.
+ self._op_lock = threading.Lock()
+ self._op_seq: int = 0
+ self._active_op_kind: Optional[str] = None
+ self._last_op: Optional[Dict[str, Any]] = None
atexit.register(self._cleanup)
logger.info("ExportOrchestrator initialized (subprocess mode)")
@@ -119,6 +132,72 @@ class ExportOrchestrator:
"""True while an export / load / cleanup command is running."""
return self._export_active
+ def was_cancelled(self) -> bool:
+ """True if the in-flight (or most recent) run was cancelled by the user."""
+ return self._cancel_requested
+
+ def _record_op_finished(self, success: bool, message: str, output_path: Optional[str]) -> None:
+ """Snapshot the just-finished op so status pollers can recover its outcome.
+
+ Called from each op's ``finally`` (with ``_active_op_kind`` still set) BEFORE
+ ``_export_active`` is cleared, so a status read that observes the op as
+ inactive is guaranteed to also see this matching result.
+ """
+ with self._op_lock:
+ self._op_seq += 1
+ status = "cancelled" if self._cancel_requested else ("success" if success else "error")
+ self._last_op = {
+ "seq": self._op_seq,
+ "kind": self._active_op_kind,
+ "status": status,
+ "output_path": output_path if success else None,
+ "error": None if success else (message or None),
+ }
+
+ def get_last_op(self) -> Optional[Dict[str, Any]]:
+ """Return the last finished op record (or None), for status recovery."""
+ with self._op_lock:
+ return dict(self._last_op) if self._last_op is not None else None
+
+ def get_active_op_kind(self) -> Optional[str]:
+ """Return the kind of the currently running op (or None when idle)."""
+ return self._active_op_kind
+
+ def cancel_export(self) -> bool:
+ """Terminate the in-flight export subprocess immediately.
+
+ An export op holds ``self._lock`` for its whole duration (blocked in
+ ``_wait_response``), so we deliberately do NOT take the lock here -- we
+ kill the worker process directly, which unblocks that wait and makes the
+ in-flight op return a failure the caller surfaces as "cancelled".
+
+ Only the export subprocess is touched; training and inference run in
+ their own subprocesses and are left untouched.
+
+ Returns True if a live subprocess was terminated, False if none ran.
+ """
+ self._cancel_requested = True
+ proc = self._proc
+ if proc is None or not proc.is_alive():
+ return False
+ logger.info(
+ "Export cancel requested: terminating export subprocess (pid=%s)",
+ proc.pid,
+ )
+ try:
+ proc.terminate()
+ proc.join(timeout = 5)
+ except Exception:
+ pass
+ if proc.is_alive():
+ logger.warning("Export subprocess survived terminate, killing")
+ try:
+ proc.kill()
+ proc.join(timeout = 3)
+ except Exception:
+ pass
+ return True
+
# ------------------------------------------------------------------
# Subprocess lifecycle
# ------------------------------------------------------------------
@@ -323,7 +402,10 @@ class ExportOrchestrator:
with self._lock:
# Fresh log buffer so the UI sees only this run's output.
self.clear_logs()
+ self._cancel_requested = False
+ self._active_op_kind = "load_checkpoint"
self._export_active = True
+ op_success, op_message = False, ""
try:
# Always kill any existing subprocess and spawn fresh.
if self._ensure_subprocess_alive():
@@ -341,6 +423,7 @@ class ExportOrchestrator:
self.current_checkpoint = None
self.is_vision = False
self.is_peft = False
+ op_success, op_message = False, str(exc)
return False, str(exc)
if resp.get("success"):
@@ -348,15 +431,19 @@ class ExportOrchestrator:
self.is_vision = resp.get("is_vision", False)
self.is_peft = resp.get("is_peft", False)
logger.info("Checkpoint '%s' loaded in subprocess", checkpoint_path)
- return True, resp.get("message", "Loaded successfully")
+ op_success, op_message = True, resp.get("message", "Loaded successfully")
+ return True, op_message
else:
error = resp.get("message", "Failed to load checkpoint")
logger.error("Failed to load checkpoint: %s", error)
self.current_checkpoint = None
self.is_vision = False
self.is_peft = False
+ op_success, op_message = False, error
return False, error
finally:
+ self._record_op_finished(op_success, op_message, None)
+ self._active_op_kind = None
self._export_active = False
def export_merged_model(
@@ -458,7 +545,10 @@ class ExportOrchestrator:
)
self.clear_logs()
+ self._cancel_requested = False
+ self._active_op_kind = f"export_{export_type}"
self._export_active = True
+ op_success, op_message, op_output_path = False, "", None
try:
cmd = {"type": "export", "export_type": export_type, **params}
try:
@@ -467,14 +557,16 @@ class ExportOrchestrator:
f"export_{export_type}_done",
timeout = 3600, # GGUF for 30B+ models can take 30+ min
)
- return (
- resp.get("success", False),
- resp.get("message", ""),
- resp.get("output_path"),
- )
+ op_success = resp.get("success", False)
+ op_message = resp.get("message", "")
+ op_output_path = resp.get("output_path")
+ return op_success, op_message, op_output_path
except RuntimeError as exc:
+ op_success, op_message = False, str(exc)
return False, str(exc), None
finally:
+ self._record_op_finished(op_success, op_message, op_output_path)
+ self._active_op_kind = None
self._export_active = False
def cleanup_memory(self) -> bool:
@@ -486,7 +578,9 @@ class ExportOrchestrator:
self.is_peft = False
return True
+ self._active_op_kind = "cleanup"
self._export_active = True
+ success = False
try:
try:
self._send_cmd({"type": "cleanup"})
@@ -503,6 +597,8 @@ class ExportOrchestrator:
self.is_peft = False
return success
finally:
+ self._record_op_finished(success, "", None)
+ self._active_op_kind = None
self._export_active = False
def scan_checkpoints(self, outputs_dir: str = str(outputs_root())) -> List[Tuple[str, list]]:
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 197ecf1a9fb..16a401d1156 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -1230,6 +1230,9 @@ class LlamaCppBackend:
# coexist as two llama-server processes (#5401). RLock so MTP-crash
# recovery can re-acquire it for its nested load_model.
self._serial_load_lock = threading.RLock()
+ # Serialises mid-session respawns so many generations hitting a killed
+ # server trigger at most one reload (see _respawn_if_dead).
+ self._respawn_lock = threading.Lock()
# Set by the in-app updater while it swaps prebuilt binaries; load_model()
# rejects fast so no server starts from a half-swapped binary.
self._llama_update_in_progress = False
@@ -7058,6 +7061,38 @@ class LlamaCppBackend:
finally:
_cancel_closed.set()
+ def _respawn_if_dead(self) -> bool:
+ """Relaunch the llama-server if its process has exited.
+
+ A loaded chat model can be SIGKILL'd mid-session (usually GPU/RAM pressure
+ from a training run on the same box), leaving a defunct process while
+ ``is_loaded`` still reads True. Replay the last ``load_model`` call to
+ recover, returning True once healthy. Serialised on ``_respawn_lock`` so
+ many generations hitting the dead server trigger at most one reload.
+ """
+ with self._respawn_lock:
+ proc = self._process
+ if proc is None:
+ return False
+ if proc.poll() is None:
+ # Process is alive: either a concurrent caller already respawned
+ # it (healthy), or this connection error wasn't a dead server.
+ return self._healthy
+ kwargs = self._last_load_kwargs
+ if not kwargs:
+ return False
+ logger.warning(
+ f"llama-server for '{self._model_identifier}' exited "
+ f"(code {proc.returncode}); respawning to recover the session"
+ )
+ with self._lock:
+ self._healthy = False
+ try:
+ return bool(self.load_model(**kwargs))
+ except Exception as exc:
+ logger.error(f"Failed to respawn llama-server: {exc}")
+ return False
+
def generate_chat_completion(
self,
messages: list[dict],
@@ -7075,6 +7110,7 @@ class LlamaCppBackend:
reasoning_effort: Optional[str] = None,
preserve_thinking: Optional[bool] = None,
seed: Optional[int] = None,
+ _allow_respawn_retry: bool = True,
) -> Generator[Union[str, dict], None, None]:
"""
Send a chat completion to llama-server and stream tokens back.
@@ -7241,8 +7277,36 @@ class LlamaCppBackend:
}
except httpx.ConnectError as e:
- # Server already down (e.g. crashed on a prior request): recover MTP.
- self._maybe_recover_from_mtp_crash(e)
+ # Server already down. If this was an MTP+tensor crash, recover by
+ # reloading without MTP (scheduled in the background) and fail this
+ # request. Otherwise the server was likely SIGKILL'd by GPU pressure
+ # from a concurrent training run: respawn the same config and retry the
+ # generation once (bounded by the private flag, no duplicate output).
+ if self._maybe_recover_from_mtp_crash(e):
+ raise RuntimeError("Lost connection to llama-server")
+ if _allow_respawn_retry and not cumulative and self._respawn_if_dead():
+ logger.warning(
+ "llama-server was unreachable; respawned it and retrying the generation"
+ )
+ yield from self.generate_chat_completion(
+ messages,
+ image_b64 = image_b64,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ max_tokens = max_tokens,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ stop = stop,
+ cancel_event = cancel_event,
+ enable_thinking = enable_thinking,
+ reasoning_effort = reasoning_effort,
+ preserve_thinking = preserve_thinking,
+ seed = seed,
+ _allow_respawn_retry = False,
+ )
+ return
raise RuntimeError("Lost connection to llama-server")
except Exception as e:
if cancel_event is not None and cancel_event.is_set():
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index 73744466b6b..5a1f40d82f2 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -229,11 +229,24 @@ class TrainingBackend:
# Public API (called by routes/training.py)
# ------------------------------------------------------------------
- def start_training(self, job_id: str, **kwargs) -> bool:
+ def start_training(
+ self,
+ job_id: str,
+ *,
+ before_spawn = None,
+ **kwargs,
+ ) -> bool:
"""Spawn a subprocess to run the full training pipeline.
All kwargs are serialized into a config dict and sent to the worker.
Returns True if the subprocess started successfully.
+
+ ``before_spawn`` is an optional no-arg callable run after synchronous
+ validation (start guards, config build, explicit gpu_ids) passes but
+ before VRAM-dependent auto GPU-selection and the spawn -- used to free
+ VRAM (e.g. unload chat) without tearing it down on a refused start, while
+ still letting auto-selection place training against the freed memory.
+ Hook failures never block the start.
"""
with self._lock:
if self._proc is not None and self._proc.is_alive():
@@ -326,26 +339,50 @@ class TrainingBackend:
if config["training_type"] == "Full Finetuning":
config["load_in_4bit"] = False
- # Spawn into locals so state is untouched on failure.
+ # Split GPU validation from placement around the VRAM hook:
+ # * Explicit gpu_ids are validated here (raises -> the route returns 400
+ # before any teardown) and their placement is VRAM-independent, so it
+ # stays correct after the hook frees memory.
+ # * Auto-selection ranks GPUs by *free* VRAM, so it is deferred until
+ # after the hook frees export/chat -- otherwise it could pin training
+ # onto a GPU the hook is about to clear (and onto a kept chat model).
from utils.hardware import hardware as _hw
+ gpu_ids = kwargs.get("gpu_ids")
+ gpu_selection_kwargs = dict(
+ model_name = config["model_name"],
+ hf_token = config["hf_token"] or None,
+ training_type = config["training_type"],
+ load_in_4bit = config["load_in_4bit"],
+ batch_size = config.get("batch_size", 4),
+ max_seq_length = config.get("max_seq_length", 2048),
+ lora_rank = config.get("lora_r", 16),
+ target_modules = config.get("target_modules"),
+ gradient_checkpointing = config.get("gradient_checkpointing", "unsloth"),
+ optimizer = config.get("optim", "adamw_8bit"),
+ )
+
+ defer_auto_selection = False
if _hw.DEVICE == _hw.DeviceType.MLX:
config["resolved_gpu_ids"] = None
config["gpu_selection"] = None
+ elif gpu_ids:
+ resolved_gpu_ids, gpu_selection = prepare_gpu_selection(gpu_ids, **gpu_selection_kwargs)
+ config["resolved_gpu_ids"] = resolved_gpu_ids
+ config["gpu_selection"] = gpu_selection
else:
- resolved_gpu_ids, gpu_selection = prepare_gpu_selection(
- kwargs.get("gpu_ids"),
- model_name = config["model_name"],
- hf_token = config["hf_token"] or None,
- training_type = config["training_type"],
- load_in_4bit = config["load_in_4bit"],
- batch_size = config.get("batch_size", 4),
- max_seq_length = config.get("max_seq_length", 2048),
- lora_rank = config.get("lora_r", 16),
- target_modules = config.get("target_modules"),
- gradient_checkpointing = config.get("gradient_checkpointing", "unsloth"),
- optimizer = config.get("optim", "adamw_8bit"),
- )
+ defer_auto_selection = True
+
+ # Synchronous validation passed -> free VRAM (export + chat) now, before
+ # auto-selection and the spawn, so placement sees the freed memory.
+ if before_spawn is not None:
+ try:
+ before_spawn()
+ except Exception:
+ logger.warning("before_spawn hook failed; continuing", exc_info = True)
+
+ if defer_auto_selection:
+ resolved_gpu_ids, gpu_selection = prepare_gpu_selection(None, **gpu_selection_kwargs)
config["resolved_gpu_ids"] = resolved_gpu_ids
config["gpu_selection"] = gpu_selection
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
index 6e6a28b9198..94e0913ac92 100644
--- a/studio/backend/hub/services/models/local_inventory.py
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -177,6 +177,17 @@ def _scan_models_dir(
return found
+def _safe_is_dir(path: Path) -> bool:
+ """``Path.is_dir()`` treating an unreadable path (``PermissionError`` /
+ ``OSError`` on a restricted ``~/.cache/huggingface/hub``) as "not a
+ directory", so the inventory skips that source instead of 500ing the Hub page.
+ """
+ try:
+ return path.is_dir()
+ except OSError:
+ return False
+
+
def _hf_repo_dir_has_content(repo_dir: Path) -> bool:
blobs_dir = repo_dir / "blobs"
if not blobs_dir.is_dir():
@@ -191,7 +202,7 @@ def _hf_repo_dir_has_content(repo_dir: Path) -> bool:
def _scan_hf_cache(cache_dir: Path, *, entry_limit: int | None = None) -> List[LocalModelInfo]:
- if not cache_dir.exists() or not cache_dir.is_dir():
+ if not _safe_is_dir(cache_dir):
return []
discovered: List[tuple[Path, str, Optional[float]]] = []
@@ -502,11 +513,11 @@ async def _collect_models_from_default_sources(
local_models = await _scan_source("models directory", _scan_models_dir, models_root)
local_models += await _scan_source("HF cache", _scan_hf_cache, hf_cache_dir)
- if legacy_hf.is_dir() and legacy_hf.resolve() != hf_cache_dir.resolve():
+ if _safe_is_dir(legacy_hf) and legacy_hf.resolve() != hf_cache_dir.resolve():
local_models += await _scan_source("legacy HF cache", _scan_hf_cache, legacy_hf)
if (
- hf_default.is_dir()
+ _safe_is_dir(hf_default)
and hf_default.resolve() != hf_cache_dir.resolve()
and hf_default.resolve() != legacy_hf.resolve()
):
@@ -621,9 +632,9 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModel
ollama_dirs = ollama_model_dirs()
allowed_roots: list[Path] = [Path("./models").resolve(), hf_cache_dir]
- if legacy_hf.is_dir():
+ if _safe_is_dir(legacy_hf):
allowed_roots.append(legacy_hf)
- if hf_default.is_dir():
+ if _safe_is_dir(hf_default):
allowed_roots.append(hf_default)
allowed_roots.extend([studio_root(), outputs_root()])
diff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.py
index a1ac372abbf..22c948b6830 100644
--- a/studio/backend/hub/utils/hf_cache_state.py
+++ b/studio/backend/hub/utils/hf_cache_state.py
@@ -19,6 +19,16 @@ TRANSPORT_MARKER_NAME = ".transport"
INCOMPLETE_SUFFIX = ".incomplete"
+def _safe_is_dir(path: Path) -> bool:
+ """``Path.is_dir()`` returning False instead of raising when the path or a
+ parent is unreadable (e.g. a restricted ``~/.cache/huggingface/hub``), so
+ cache enumeration skips that root rather than 500ing."""
+ try:
+ return path.is_dir()
+ except OSError:
+ return False
+
+
def hf_cache_root(*, create: bool = False) -> Optional[Path]:
try:
from huggingface_hub import constants as hf_constants
@@ -31,7 +41,7 @@ def hf_cache_root(*, create: bool = False) -> Optional[Path]:
except OSError:
return None
return root
- return root if root.is_dir() else None
+ return root if _safe_is_dir(root) else None
def hf_cache_roots() -> list[Path]:
@@ -41,7 +51,7 @@ def hf_cache_roots() -> list[Path]:
seen: set[str] = set()
def _add(path: Optional[Path]) -> None:
- if path is None or not path.is_dir():
+ if path is None or not _safe_is_dir(path):
return
try:
key = str(path.resolve())
diff --git a/studio/backend/models/export.py b/studio/backend/models/export.py
index 62371970723..1e8e3c4792b 100644
--- a/studio/backend/models/export.py
+++ b/studio/backend/models/export.py
@@ -76,6 +76,37 @@ class ExportStatusResponse(BaseModel):
False,
description = "True if the loaded checkpoint is a PEFT (LoRA) model",
)
+ is_export_active: bool = Field(
+ False,
+ description = "True while a load / export / cleanup operation is running",
+ )
+ # Recovery fields: when a blocking export POST is cut off by a Cloudflare tunnel
+ # timeout (524 at ~100s), the client polls this endpoint to learn the real
+ # outcome of the operation that kept running on the backend.
+ active_op_kind: Optional[str] = Field(
+ None,
+ description = "Kind of the currently running op (load_checkpoint / export_* / cleanup)",
+ )
+ last_op_seq: int = Field(
+ 0,
+ description = "Monotonic counter of finished ops; client baseline to detect 'my op finished'",
+ )
+ last_op_kind: Optional[str] = Field(
+ None,
+ description = "Kind of the most recently finished op",
+ )
+ last_op_status: Optional[str] = Field(
+ None,
+ description = "Outcome of the most recently finished op: success / error / cancelled",
+ )
+ last_op_output_path: Optional[str] = Field(
+ None,
+ description = "Output path of the most recently finished op, if it produced one",
+ )
+ last_op_error: Optional[str] = Field(
+ None,
+ description = "Error message of the most recently finished op, if it failed",
+ )
class ExportOperationResponse(BaseModel):
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 88799604e08..3c6ccd70a85 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -129,6 +129,11 @@ class ValidateModelRequest(BaseModel):
gguf_variant: Optional[str] = Field(
None, description = "GGUF quantization variant (e.g. 'Q4_K_M')"
)
+ # Intended load settings so validate's coexistence check matches the follow-up
+ # /load; defaults preserve old behavior for callers that omit them.
+ max_seq_length: int = Field(0, ge = 0, le = 1048576)
+ load_in_4bit: bool = Field(True)
+ gpu_ids: Optional[List[int]] = Field(None)
include_context_length: bool = Field(
False,
description = "Also read the native context length from the local GGUF header. "
diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.py
index 1b71cf5f57a..122f530013a 100644
--- a/studio/backend/routes/export.py
+++ b/studio/backend/routes/export.py
@@ -50,40 +50,14 @@ logger = get_logger(__name__)
async def load_checkpoint(
request: LoadCheckpointRequest, current_subject: str = Depends(get_current_subject)
):
- """Load a checkpoint into the export backend (ExportBackend.load_checkpoint)."""
- try:
- # Free GPU memory: shut down running inference/training subprocesses
- # before loading the export checkpoint (they'd compete for VRAM).
- try:
- from core.inference import get_inference_backend
- inf = get_inference_backend()
- if inf.active_model_name:
- logger.info(
- "Unloading inference model '%s' to free GPU memory for export",
- inf.active_model_name,
- )
- inf._shutdown_subprocess()
- inf.active_model_name = None
- inf.models.clear()
- except Exception as e:
- logger.warning("Could not unload inference model: %s", e)
-
- try:
- from core.training import get_training_backend
- trn = get_training_backend()
- if trn.is_training_active():
- logger.info("Stopping active training to free GPU memory for export")
- trn.stop_training()
- # Wait for the training subprocess to exit, else it may still hold GPU memory.
- for _ in range(60): # up to 30s
- if not trn.is_training_active():
- break
- await asyncio.sleep(0.5)
- else:
- logger.warning("Training subprocess did not exit within 30s, proceeding anyway")
- except Exception as e:
- logger.warning("Could not stop training: %s", e)
+ """Load a checkpoint into the export backend (ExportBackend.load_checkpoint).
+ Export runs in its own subprocess and is allowed to run in parallel with
+ training and inference. We deliberately do NOT stop training or unload the
+ chat model here -- if the GPU runs out of memory the load/export fails with
+ a clear error instead of tearing down the user's other running workloads.
+ """
+ try:
backend = get_export_backend()
# Run in a worker thread (spawns and waits on a subprocess, can take
# minutes) so the event loop stays free to serve the live log SSE stream.
@@ -138,15 +112,51 @@ async def cleanup_export_memory(current_subject: str = Depends(get_current_subje
)
[email protected]("/cancel", response_model = ExportOperationResponse)
+async def cancel_export(current_subject: str = Depends(get_current_subject)):
+ """Cancel the in-flight export by terminating its worker subprocess.
+
+ Only the export subprocess is killed; training and inference run in their
+ own subprocesses and keep going.
+ """
+ try:
+ backend = get_export_backend()
+ cancelled = await asyncio.to_thread(backend.cancel_export)
+ return ExportOperationResponse(
+ success = True,
+ message = "Export cancelled" if cancelled else "No active export to cancel",
+ )
+ except Exception as e:
+ logger.error(f"Error cancelling export: {e}", exc_info = True)
+ raise HTTPException(
+ status_code = 500,
+ detail = "Failed to cancel export",
+ )
+
+
@router.get("/status", response_model = ExportStatusResponse)
async def get_export_status(current_subject: str = Depends(get_current_subject)):
"""Get export backend status (loaded checkpoint, model type, PEFT flag)."""
try:
backend = get_export_backend()
+ last_op = backend.get_last_op()
+ # Relativise the recovered output path the same way the per-op POST response
+ # does, so the success banner shows an identical path on either route.
+ last_op_output_path = None
+ if last_op and last_op.get("output_path"):
+ details = _export_details(last_op["output_path"])
+ last_op_output_path = (details or {}).get("output_path")
return ExportStatusResponse(
current_checkpoint = backend.current_checkpoint,
is_vision = bool(getattr(backend, "is_vision", False)),
is_peft = bool(getattr(backend, "is_peft", False)),
+ is_export_active = bool(backend.is_export_active()),
+ active_op_kind = backend.get_active_op_kind(),
+ last_op_seq = int(last_op["seq"]) if last_op else 0,
+ last_op_kind = last_op.get("kind") if last_op else None,
+ last_op_status = last_op.get("status") if last_op else None,
+ last_op_output_path = last_op_output_path,
+ last_op_error = last_op.get("error") if last_op else None,
)
except Exception as e:
logger.error(f"Error getting export status: {e}", exc_info = True)
@@ -156,6 +166,59 @@ async def get_export_status(current_subject: str = Depends(get_current_subject))
)
+async def get_export_logs(
+ since: Optional[int] = Query(
+ None,
+ description = "Return log entries with seq strictly greater than this cursor.",
+ ),
+ current_subject: str = Depends(get_current_subject),
+):
+ """Tunnel-safe JSON fallback for the live export log stream.
+
+ The SSE endpoint (`/logs/stream`) is the low-latency path, but some reverse
+ proxies -- notably Cloudflare quick tunnels (`*.trycloudflare.com`) used by
+ `--secure` mode -- buffer `text/event-stream` responses and only flush when
+ the stream closes, so over the tunnel the browser sees nothing for the whole
+ export ("connecting..." with no logs). This endpoint returns the same
+ ring-buffer lines as a short, complete JSON response that no proxy buffers,
+ so the frontend can poll it and still show logs in near real time.
+
+ Shares the orchestrator's monotonic `seq` cursor with the SSE stream, so the
+ two transports can run together and the client de-dupes by seq.
+ """
+ try:
+ backend = get_export_backend()
+ # No cursor on the first poll of a run: start from the run-start snapshot
+ # so the client gets every line since the run began (matches the SSE
+ # default), not the entire historical ring buffer.
+ if since is None:
+ cursor = backend.get_run_start_seq()
+ else:
+ cursor = max(0, int(since))
+
+ entries, new_cursor = backend.get_logs_since(cursor)
+ return {
+ "entries": [
+ {
+ "seq": int(entry.get("seq", 0)),
+ "stream": entry.get("stream", "stdout"),
+ "line": entry.get("line", ""),
+ "ts": entry.get("ts"),
+ }
+ for entry in entries
+ ],
+ "cursor": new_cursor,
+ "active": bool(backend.is_export_active()),
+ }
+ except Exception as e:
+ logger.error(f"Error getting export logs: {e}", exc_info = True)
+ raise HTTPException(
+ status_code = 500,
+ detail = "Failed to get export logs",
+ )
+
+
def _try_register_external_export(path: Path) -> tuple[bool, Optional[str]]:
"""Best-effort registration so absolute exports show up in local scans."""
try:
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 52540a5a720..b4a098eaf44 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -12,7 +12,7 @@ import uuid
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.responses import StreamingResponse, JSONResponse, Response
-from typing import Any, Optional, Union
+from typing import Any, List, Optional, Union
import json
import httpx
import structlog
@@ -1923,6 +1923,203 @@ def get_llama_cpp_backend() -> LlamaCppBackend:
return _llama_cpp_backend
+def _effective_load_in_4bit(config: ModelConfig, requested: bool) -> bool:
+ """Effective quantization the loader will use: a LoRA adapter can flip 4-bit to
+ 16-bit via adapter_config.json, so the guard sizes this, not the raw request."""
+ load_in_4bit = requested
+ if not getattr(config, "is_lora", False) or not getattr(config, "path", None):
+ return load_in_4bit
+ adapter_cfg_path = Path(config.path) / "adapter_config.json"
+ if not adapter_cfg_path.exists():
+ return load_in_4bit
+ try:
+ with open(adapter_cfg_path) as f:
+ adapter_cfg = json.load(f)
+ if not isinstance(adapter_cfg, dict): # malformed -> keep requested
+ return load_in_4bit
+ except Exception as e:
+ logger.warning(f"Could not read adapter_config.json: {e}")
+ return load_in_4bit
+ training_method = adapter_cfg.get("unsloth_training_method")
+ if training_method == "lora":
+ return False
+ if training_method == "qlora":
+ return True
+ if not training_method and config.base_model and "-bnb-4bit" not in config.base_model.lower():
+ return False
+ return load_in_4bit
+
+
+def _remote_gguf_companion_bytes(
+ repo: str, *, hf_token: Optional[str], include_mmproj: bool
+) -> int:
+ """Bytes of MTP/mmproj companion GGUFs llama-server auto-downloads. 0 on error,
+ so it can only add headroom, never refuse a load by itself."""
+ try:
+ from huggingface_hub import model_info
+
+ info = model_info(repo, token = hf_token, files_metadata = True)
+ total = 0
+ for sibling in info.siblings or []:
+ base = Path(sibling.rfilename or "").name.lower()
+ if not base.endswith(".gguf"):
+ continue
+ if base.startswith("mtp-") or (include_mmproj and "mmproj" in base):
+ total += getattr(sibling, "size", 0) or 0
+ return total
+ except Exception as e:
+ logger.warning(f"Could not size GGUF companions for {repo}: {e}")
+ return 0
+
+
+def _estimate_gguf_kv_gb(
+ gguf_path: str,
+ max_seq_length: int,
+ llama_extra_args: Optional[list[str]] = None,
+ n_parallel: int = 1,
+) -> float:
+ """KV-cache VRAM (GB) at the larger of max_seq_length and any `--ctx-size`/`-c`
+ override, over n_parallel slots, with the default f16 cache so the estimate is
+ never below what the server allocates. 0 if metadata is unreadable."""
+ try:
+ from core.inference.llama_server_args import parse_ctx_override
+
+ probe = LlamaCppBackend()
+ probe._read_gguf_metadata(gguf_path)
+ if not probe._can_estimate_kv():
+ return 0.0
+ try:
+ ctx_override = parse_ctx_override(llama_extra_args) or 0
+ except Exception:
+ ctx_override = 0 # malformed extras are rejected upstream; fall back
+ ctx = max(max_seq_length or 0, ctx_override) or (probe._context_length or 0)
+ if ctx <= 0:
+ return 0.0
+ kv = probe._estimate_kv_cache_bytes(ctx, n_parallel = max(1, n_parallel or 1))
+ return kv / (1024**3)
+ except Exception as e:
+ logger.warning(f"Could not size GGUF KV cache for training guard: {e}")
+ return 0.0
+
+
+def _estimate_gguf_required_gb(
+ config: ModelConfig,
+ hf_token: Optional[str] = None,
+ max_seq_length: int = 0,
+ llama_extra_args: Optional[list[str]] = None,
+ n_parallel: int = 1,
+) -> Optional[float]:
+ """Approximate GGUF VRAM (GB): quantized weights + companions, plus the KV
+ cache for local files (unreadable pre-download for remote). None when nothing
+ resolves so the caller default-denies."""
+ try:
+ total_bytes = 0
+ main = getattr(config, "gguf_file", None)
+ if main and Path(main).is_file():
+ total_bytes += LlamaCppBackend._get_gguf_size_bytes(str(main))
+ for attr in ("gguf_mmproj_file", "gguf_mtp_file"):
+ f = getattr(config, attr, None)
+ if f and Path(f).is_file():
+ total_bytes += Path(f).stat().st_size
+ if total_bytes > 0:
+ return total_bytes / (1024**3) + _estimate_gguf_kv_gb(
+ main, max_seq_length, llama_extra_args, n_parallel
+ )
+
+ repo = getattr(config, "gguf_hf_repo", None)
+ variant = getattr(config, "gguf_variant", None)
+ if repo and variant:
+ from utils.models.model_config import list_gguf_variants
+
+ variants, has_vision = list_gguf_variants(repo, hf_token = hf_token)
+ main_bytes = next(
+ (v.size_bytes for v in variants if v.quant.lower() == variant.lower()), None
+ )
+ if main_bytes is None:
+ return None
+ companions = _remote_gguf_companion_bytes(
+ repo, hf_token = hf_token, include_mmproj = bool(has_vision)
+ )
+ return (main_bytes + companions) / (1024**3)
+ return None
+ except Exception as e:
+ logger.warning(f"Could not size GGUF model for training guard: {e}")
+ return None
+
+
+def _guard_chat_load_against_training(
+ config: ModelConfig,
+ *,
+ model_identifier: str,
+ hf_token: Optional[str],
+ load_in_4bit: bool,
+ max_seq_length: int,
+ requested_gpu_ids: Optional[List[int]],
+ llama_extra_args: Optional[list[str]] = None,
+ n_parallel: int = 1,
+) -> None:
+ """Refuse loading a local chat model that would OOM an active training run.
+ No-op when training is inactive or unknown. `load_in_4bit` must be the
+ effective quantization (see _effective_load_in_4bit). Raises HTTP 409 when the
+ model would not fit alongside training."""
+ from core.training import get_training_backend
+ from routes.training_vram import can_load_chat_during_training
+
+ try:
+ if not get_training_backend().is_training_active():
+ return
+ except Exception as e:
+ logger.warning("Could not check training state for chat-load guard: %s", e)
+ return
+
+ is_gguf = bool(getattr(config, "is_gguf", False))
+ required_override_gb = (
+ _estimate_gguf_required_gb(
+ config,
+ hf_token = hf_token,
+ max_seq_length = max_seq_length,
+ llama_extra_args = llama_extra_args,
+ n_parallel = n_parallel,
+ )
+ if is_gguf
+ else None
+ )
+
+ ok, info = can_load_chat_during_training(
+ model_name = model_identifier,
+ hf_token = hf_token,
+ load_in_4bit = load_in_4bit,
+ max_seq_length = max_seq_length,
+ requested_gpu_ids = requested_gpu_ids,
+ is_gguf = is_gguf,
+ required_override_gb = required_override_gb,
+ )
+ if ok:
+ return
+
+ usable = info.get("usable_gb")
+ needed = info.get("needed_gb")
+ if needed is None:
+ needed = info.get("required_gb")
+ if needed is not None and usable is not None:
+ detail = (
+ f"Not enough free GPU memory to load this model while training is "
+ f"running (needs ~{needed:.0f} GB including safety headroom, "
+ f"~{usable:.0f} GB free). Training was left untouched. Use an external "
+ f"provider, a smaller or more quantized model, or try again after "
+ f"training finishes."
+ )
+ else:
+ detail = (
+ "Can't load this model while training is running: its GPU memory use "
+ "could not be verified, so the load was refused to protect the "
+ "training run. Use an external provider or try again after training "
+ "finishes."
+ )
+ logger.info("Refusing chat-model load during training: %s", info)
+ raise HTTPException(status_code = 409, detail = detail)
+
+
def _model_json_response(model, status_code: int = 200) -> Response:
"""Serialize a pydantic response once via pydantic-core.
@@ -2118,14 +2315,37 @@ async def load_model(
# Normalize gpu_ids: empty list means auto-selection, same as None
effective_gpu_ids = request.gpu_ids if request.gpu_ids else None
+ # Reject GGUF + gpu_ids first so the guard can't mask it with a VRAM 409.
+ if config.is_gguf and effective_gpu_ids is not None:
+ raise HTTPException(
+ status_code = 400,
+ detail = "gpu_ids is not supported for GGUF models yet.",
+ )
+
+ # Effective quantization (LoRA can flip 4-bit -> 16-bit); guard + load reuse it.
+ effective_load_in_4bit = _effective_load_in_4bit(config, request.load_in_4bit)
+ if effective_load_in_4bit != request.load_in_4bit:
+ logger.info(
+ f"Resolved load_in_4bit={effective_load_in_4bit} for '{model_log_label}' "
+ f"from adapter_config.json / base model (requested {request.load_in_4bit})"
+ )
+
+ # Refuse a load that would OOM active training, before the unload step below
+ # frees the resident model. Off-loop: guard does sync nvidia-smi / HF work.
+ await asyncio.to_thread(
+ _guard_chat_load_against_training,
+ config,
+ model_identifier = model_identifier,
+ hf_token = request.hf_token,
+ load_in_4bit = effective_load_in_4bit,
+ max_seq_length = request.max_seq_length,
+ requested_gpu_ids = effective_gpu_ids,
+ llama_extra_args = extra_llama_args,
+ n_parallel = getattr(fastapi_request.app.state, "llama_parallel_slots", 1),
+ )
+
# ── GGUF path: load via llama-server ──────────────────────
if config.is_gguf:
- if effective_gpu_ids is not None:
- raise HTTPException(
- status_code = 400,
- detail = "gpu_ids is not supported for GGUF models yet.",
- )
-
llama_backend = get_llama_cpp_backend()
unsloth_backend = get_inference_backend()
@@ -2365,51 +2585,8 @@ async def load_model(
except Exception as e:
logger.warning("Could not shut down export subprocess: %s", e)
- # Auto-detect quantization for LoRA adapters from adapter_config.json.
- # The training pipeline writes "unsloth_training_method" ('qlora' or
- # 'lora'); only LoRA (16-bit) needs load_in_4bit=False.
- load_in_4bit = request.load_in_4bit
- if config.is_lora and config.path:
- import json
- from pathlib import Path
-
- adapter_cfg_path = Path(config.path) / "adapter_config.json"
- if adapter_cfg_path.exists():
- try:
- with open(adapter_cfg_path) as f:
- adapter_cfg = json.load(f)
- training_method = adapter_cfg.get("unsloth_training_method")
- if training_method == "lora" and load_in_4bit:
- logger.info(
- f"adapter_config.json says unsloth_training_method='lora' — "
- f"setting load_in_4bit=False to match 16-bit training"
- )
- load_in_4bit = False
- elif training_method == "qlora" and not load_in_4bit:
- logger.info(
- f"adapter_config.json says unsloth_training_method='qlora' — "
- f"setting load_in_4bit=True to match QLoRA training"
- )
- load_in_4bit = True
- elif training_method:
- logger.info(
- f"Training method: {training_method}, load_in_4bit={load_in_4bit}"
- )
- else:
- # No unsloth_training_method -- fall back to base model name
- if (
- config.base_model
- and "-bnb-4bit" not in config.base_model.lower()
- and load_in_4bit
- ):
- logger.info(
- f"No unsloth_training_method in adapter_config.json. "
- f"Base model '{config.base_model}' has no -bnb-4bit suffix — "
- f"setting load_in_4bit=False"
- )
- load_in_4bit = False
- except Exception as e:
- logger.warning(f"Could not read adapter_config.json: {e}")
+ # Resolved before the guard so both size the same load.
+ load_in_4bit = effective_load_in_4bit
# Load in a thread so the event loop stays free for download progress
# polling and other requests.
@@ -2646,6 +2823,27 @@ async def validate_model(
detail = f"Invalid model identifier: {model_log_label}",
)
+ # Refuse early (before the frontend unloads to load this) if it can't fit
+ # alongside training, using the same settings /load uses so they agree.
+ effective_gpu_ids = request.gpu_ids if request.gpu_ids else None
+ # Mirror /load: reject GGUF + gpu_ids before the guard so both return 400.
+ if config.is_gguf and effective_gpu_ids is not None:
+ raise HTTPException(
+ status_code = 400,
+ detail = "gpu_ids is not supported for GGUF models yet.",
+ )
+ effective_load_in_4bit = _effective_load_in_4bit(config, request.load_in_4bit)
+ # Off-loop: guard does sync nvidia-smi / HF work.
+ await asyncio.to_thread(
+ _guard_chat_load_against_training,
+ config,
+ model_identifier = model_identifier,
+ hf_token = request.hf_token,
+ load_in_4bit = effective_load_in_4bit,
+ max_seq_length = request.max_seq_length,
+ requested_gpu_ids = effective_gpu_ids,
+ )
+
# Both checks cover the [adapter, base] set (matching the scan route and workers):
# either repo can ship auto_map code or a poisoned pickle.
security_targets = [config.identifier]
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 5860b395d57..64b64c0e97d 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -273,36 +273,74 @@ async def start_training(
request.model_name,
)
- # Free GPU memory: shut down any running inference/export subprocesses
- # before training (they'd compete for VRAM otherwise).
- try:
- from core.inference import get_inference_backend
- inf_backend = get_inference_backend()
- if inf_backend.active_model_name:
- logger.info(
- "Unloading inference model '%s' to free GPU memory for training",
- inf_backend.active_model_name,
+ # Free VRAM for training: stop export, unload chat unless it can coexist.
+ # A before_spawn hook -> runs only after start_training's guards pass, so
+ # we never tear down chat/export VRAM for a start that is then refused.
+ def _free_vram_for_training() -> None:
+ try:
+ from core.export import get_export_backend
+ exp_backend = get_export_backend()
+ # Tear down the export subprocess whenever an export is in flight,
+ # not just once a checkpoint is loaded: during the load phase
+ # current_checkpoint is still unset while the worker is already
+ # allocating GPU memory, so gate on is_export_active() too.
+ if exp_backend.current_checkpoint or exp_backend.is_export_active():
+ logger.info("Shutting down export subprocess to free GPU memory for training")
+ exp_backend._shutdown_subprocess()
+ exp_backend.current_checkpoint = None
+ exp_backend.is_vision = False
+ exp_backend.is_peft = False
+ except Exception as e:
+ logger.warning("Could not shut down export subprocess: %s", e)
+
+ try:
+ from routes.training_vram import (
+ can_keep_chat_during_training,
+ free_chat_models_for_training,
+ summarize_resident_chat,
)
- inf_backend._shutdown_subprocess()
- inf_backend.active_model_name = None
- inf_backend.models.clear()
- except Exception as e:
- logger.warning("Could not unload inference model: %s", e)
- try:
- from core.export import get_export_backend
- exp_backend = get_export_backend()
- if exp_backend.current_checkpoint:
- logger.info("Shutting down export subprocess to free GPU memory for training")
- exp_backend._shutdown_subprocess()
- exp_backend.current_checkpoint = None
- exp_backend.is_vision = False
- exp_backend.is_peft = False
- except Exception as e:
- logger.warning("Could not shut down export subprocess: %s", e)
-
- # start_training spawns a subprocess (non-blocking).
- success = backend.start_training(job_id = job_id, **training_kwargs)
+ resident = summarize_resident_chat()
+ if not resident["any"]:
+ return
+ if resident.get("loading"):
+ # In-flight load can't be sized -> free rather than risk OOM.
+ freed = free_chat_models_for_training(reason = "chat model still loading")
+ logger.info("Freed in-flight chat load for training: %s", freed)
+ return
+ keep, info = can_keep_chat_during_training(
+ model_name = training_kwargs["model_name"],
+ hf_token = training_kwargs["hf_token"],
+ training_type = training_kwargs["training_type"],
+ load_in_4bit = training_kwargs["load_in_4bit"],
+ batch_size = training_kwargs["batch_size"],
+ max_seq_length = training_kwargs["max_seq_length"],
+ lora_rank = training_kwargs["lora_r"],
+ target_modules = training_kwargs["target_modules"],
+ gradient_checkpointing = training_kwargs["gradient_checkpointing"],
+ optimizer = training_kwargs["optim"],
+ gpu_ids = training_kwargs["gpu_ids"],
+ )
+ if keep:
+ logger.info(
+ "Keeping chat model(s) loaded during training "
+ "(free ~%s GB, needs ~%s GB): %s",
+ info.get("usable_gb"),
+ info.get("required_gb"),
+ resident,
+ )
+ else:
+ freed = free_chat_models_for_training(
+ reason = "insufficient VRAM to run training alongside chat",
+ )
+ logger.info("Freed chat model(s) for training: %s", freed)
+ except Exception as e:
+ logger.warning("Chat/training VRAM coordination failed; proceeding: %s", e)
+
+ # The hook runs only once start guards pass -> VRAM freed iff training starts.
+ success = backend.start_training(
+ job_id = job_id, before_spawn = _free_vram_for_training, **training_kwargs
+ )
if not success:
progress_error = backend.trainer.training_progress.error
diff --git a/studio/backend/routes/training_vram.py b/studio/backend/routes/training_vram.py
new file mode 100644
index 00000000000..fb361d33597
--- /dev/null
+++ b/studio/backend/routes/training_vram.py
@@ -0,0 +1,342 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""VRAM coordination between chat/inference and training.
+
+Decides, from live free VRAM, whether a resident chat model can stay loaded
+during training or must be unloaded, and unloads it across all backends
+(HF/MLX orchestrator + llama.cpp GGUF server). In the route layer because the
+GGUF accessor lives in routes/inference.py; backends are imported lazily.
+"""
+
+from typing import Any, Dict, List, Optional, Tuple
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+# keep iff usable_gb >= required_gb * SAFETY_MARGIN + KEEP_FLOOR_GB. Conservative:
+# the probe sees only the chat model's current footprint, so reserve headroom for
+# estimate error + KV-cache growth (KEEP_FLOOR_GB ~= 2 GB load buffer + 2 GB chat).
+SAFETY_MARGIN = 1.15
+KEEP_FLOOR_GB = 4.0
+
+# Each extra GPU contributes less than its raw free memory (sharding overhead).
+_MULTI_GPU_OVERHEAD = 0.85
+
+
+def _free_vram_by_index(devices: List[Dict[str, Any]]) -> Dict[int, float]:
+ """Map GPU index -> free VRAM (GB) from a get_visible_gpu_utilization() device list."""
+ free_by_index: Dict[int, float] = {}
+ for device in devices:
+ total_gb = device.get("vram_total_gb")
+ used_gb = device.get("vram_used_gb")
+ if total_gb is None or used_gb is None:
+ continue
+ free_by_index[device["index"]] = max(total_gb - used_gb, 0.0)
+ return free_by_index
+
+
+def summarize_resident_chat() -> Dict[str, Any]:
+ """Report which chat models hold GPU memory (resident even while loading). Never raises."""
+ hf_name: Optional[str] = None
+ gguf_name: Optional[str] = None
+ loading: bool = False
+
+ try:
+ from core.inference import get_inference_backend
+ inf = get_inference_backend()
+ # active_model_name is set only on success; a mid-load model sits in
+ # loading_models while already holding VRAM -> both count as resident.
+ if inf.active_model_name or inf.loading_models:
+ hf_name = inf.active_model_name or next(iter(inf.loading_models), None)
+ # Any in-flight load (incl. a replacement while the old model is still
+ # active) can't be sized -> flag it so the caller frees instead of keeps.
+ if inf.loading_models:
+ loading = True
+ except Exception as e:
+ logger.warning("Could not inspect inference backend: %s", e)
+
+ try:
+ from routes.inference import get_llama_cpp_backend
+ llama = get_llama_cpp_backend()
+ # is_active (not is_loaded): a mid-start server already allocates VRAM.
+ # A confirmed CPU-only server (_gpu_offload_active is False) holds no VRAM.
+ if llama.is_active and getattr(llama, "_gpu_offload_active", None) is not False:
+ gguf_name = llama.model_identifier or "gguf"
+ if not getattr(llama, "is_loaded", False): # still loading -> size unknown
+ loading = True
+ except Exception as e:
+ logger.warning("Could not inspect GGUF backend: %s", e)
+
+ return {
+ "hf": hf_name,
+ "gguf": gguf_name,
+ "loading": loading,
+ "any": bool(hf_name or gguf_name),
+ }
+
+
+def can_keep_chat_during_training(
+ *,
+ model_name: str,
+ hf_token: Optional[str],
+ training_type: str,
+ load_in_4bit: bool,
+ batch_size: int,
+ max_seq_length: int,
+ lora_rank: int,
+ target_modules: Optional[List[str]],
+ gradient_checkpointing: str,
+ optimizer: str,
+ gpu_ids: Optional[List[int]],
+) -> Tuple[bool, Dict[str, Any]]:
+ """Decide if a resident chat model can coexist with training given free VRAM.
+
+ Reuses training's own estimator/selector so the decision matches later
+ placement. Default-deny: anything we can't size returns False (unload).
+ """
+ try:
+ from utils.hardware import (
+ DeviceType,
+ auto_select_gpu_ids,
+ estimate_required_model_memory_gb,
+ get_device,
+ get_visible_gpu_utilization,
+ resolve_requested_gpu_ids,
+ )
+
+ if get_device() != DeviceType.CUDA:
+ return False, {"mode": "non_cuda", "reason": "non_cuda"}
+
+ # Full finetuning runs in 16-bit, so ignore the 4-bit request or we under-count.
+ effective_4bit = False if training_type == "Full Finetuning" else load_in_4bit
+ hf_token_arg = hf_token or None
+
+ est_kwargs = dict(
+ hf_token = hf_token_arg,
+ training_type = training_type,
+ load_in_4bit = effective_4bit,
+ batch_size = batch_size,
+ max_seq_length = max_seq_length,
+ lora_rank = lora_rank,
+ target_modules = target_modules,
+ gradient_checkpointing = gradient_checkpointing,
+ optimizer = optimizer,
+ )
+
+ if gpu_ids:
+ # Explicit GPUs: the selector does no VRAM math, so size it here.
+ try:
+ resolved = resolve_requested_gpu_ids(gpu_ids)
+ except ValueError:
+ # Invalid ids -> start_training will 400 first, so don't unload.
+ return True, {"mode": "explicit", "reason": "invalid_gpu_ids"}
+
+ required_gb, est_meta = estimate_required_model_memory_gb(model_name, **est_kwargs)
+ if required_gb is None:
+ return False, {"mode": "explicit", "reason": "estimate_unavailable"}
+
+ free_by_index = _free_vram_by_index(get_visible_gpu_utilization().get("devices", []))
+
+ # A requested GPU missing from the device list contributes 0.
+ free_vals = [free_by_index.get(i, 0.0) for i in resolved]
+ ranked = sorted(free_vals, reverse = True)
+ usable_gb = (
+ ranked[0] + sum(f * _MULTI_GPU_OVERHEAD for f in ranked[1:]) if ranked else 0.0
+ )
+ aggregate_fits = usable_gb >= required_gb * SAFETY_MARGIN + KEEP_FLOOR_GB
+
+ # Activations don't shard: enforce a per-GPU floor so an uneven split
+ # (e.g. free [45, 10]) can't be kept into an OOM the aggregate misses.
+ per_gpu_fits = True
+ min_free_gb = min(free_vals) if free_vals else 0.0
+ if len(resolved) > 1:
+ min_per_gpu_gb = est_meta.get("vram_breakdown", {}).get(
+ f"min_per_gpu_{len(resolved)}"
+ )
+ if min_per_gpu_gb is not None:
+ per_gpu_fits = min_free_gb >= min_per_gpu_gb
+
+ keep = aggregate_fits and per_gpu_fits
+ return keep, {
+ "mode": "explicit",
+ "required_gb": required_gb,
+ "usable_gb": round(usable_gb, 3),
+ "min_free_gb": round(min_free_gb, 3),
+ }
+
+ # Auto: same call start_training makes later; reuse its sizing metadata.
+ _selected, meta = auto_select_gpu_ids(model_name, **est_kwargs)
+ mode = meta.get("selection_mode")
+ required_gb = meta.get("required_gb")
+ usable_gb = meta.get("usable_gb")
+ keep = (
+ mode == "auto"
+ and required_gb is not None
+ and usable_gb is not None
+ and usable_gb >= required_gb * SAFETY_MARGIN + KEEP_FLOOR_GB
+ )
+ return keep, {
+ "mode": mode,
+ "required_gb": required_gb,
+ "usable_gb": usable_gb,
+ }
+ except Exception as e:
+ # Never let a sizing failure keep a chat model loaded into a training OOM.
+ logger.warning("Chat-coexistence probe failed; will unload: %s", e)
+ return False, {"reason": "probe_error", "error": str(e)}
+
+
+def can_load_chat_during_training(
+ *,
+ model_name: str,
+ hf_token: Optional[str],
+ load_in_4bit: bool,
+ max_seq_length: int,
+ requested_gpu_ids: Optional[List[int]],
+ is_gguf: bool = False,
+ required_override_gb: Optional[float] = None,
+) -> Tuple[bool, Dict[str, Any]]:
+ """Decide if a NEW chat model can load without OOMing active training (inverse
+ of can_keep_chat_during_training: training is already resident, so size the
+ chat model against the free VRAM that remains). Sizes/places it the same way
+ the loader will: HF auto reuses auto_select_gpu_ids; HF explicit requires an
+ even-share per-GPU floor for device_map="balanced"; GGUF sizes from
+ required_override_gb over the visible pool. `load_in_4bit` must be effective
+ (LoRA can flip 4-bit -> 16-bit). Non-CUDA allows the load; default-deny on any
+ CUDA case it can't size, so a load never OOMs training."""
+ try:
+ from utils.hardware import (
+ DeviceType,
+ auto_select_gpu_ids,
+ estimate_required_model_memory_gb,
+ get_device,
+ get_visible_gpu_utilization,
+ resolve_requested_gpu_ids,
+ )
+
+ if get_device() != DeviceType.CUDA:
+ return True, {"mode": "non_cuda", "reason": "non_cuda"}
+
+ est_kwargs = dict(
+ hf_token = hf_token or None,
+ training_type = None, # inference sizing of the chat model itself
+ load_in_4bit = load_in_4bit,
+ max_seq_length = max_seq_length or 2048,
+ )
+
+ # HF auto: reuse the loader's selector; fits iff its pick clears the margin.
+ if not requested_gpu_ids and not is_gguf:
+ _selected, meta = auto_select_gpu_ids(model_name, **est_kwargs)
+ mode = meta.get("selection_mode")
+ required_gb = meta.get("required_gb")
+ usable_gb = meta.get("usable_gb")
+ needed_gb = (
+ round(required_gb * SAFETY_MARGIN + KEEP_FLOOR_GB, 3)
+ if required_gb is not None
+ else None
+ )
+ fits = (
+ mode == "auto"
+ and required_gb is not None
+ and usable_gb is not None
+ and usable_gb >= needed_gb
+ )
+ return fits, {
+ "mode": mode,
+ "required_gb": required_gb,
+ "usable_gb": usable_gb,
+ "needed_gb": needed_gb,
+ }
+
+ # Explicit GPUs, or GGUF: size directly and check live free VRAM.
+ required_gb = required_override_gb
+ if required_gb is None:
+ required_gb, _meta = estimate_required_model_memory_gb(model_name, **est_kwargs)
+ if required_gb is None:
+ mode = "explicit" if requested_gpu_ids else "gguf"
+ return False, {"mode": mode, "reason": "estimate_unavailable"}
+
+ free_by_index = _free_vram_by_index(get_visible_gpu_utilization().get("devices", []))
+ if requested_gpu_ids:
+ # Invalid ids -> load_model 400s first, so don't block; missing id = 0.
+ try:
+ resolved = resolve_requested_gpu_ids(requested_gpu_ids)
+ except ValueError:
+ return True, {"mode": "explicit", "reason": "invalid_gpu_ids"}
+ free_vals = [free_by_index.get(i, 0.0) for i in resolved]
+ mode = "explicit"
+ else:
+ # GGUF: llama.cpp picks the GPU(s); any visible GPU is a candidate.
+ free_vals = list(free_by_index.values())
+ mode = "gguf"
+
+ if not free_vals:
+ return False, {"mode": mode, "reason": "no_visible_gpus"}
+
+ ranked = sorted(free_vals, reverse = True)
+ usable_gb = ranked[0] + sum(f * _MULTI_GPU_OVERHEAD for f in ranked[1:])
+ needed_gb = required_gb * SAFETY_MARGIN + KEEP_FLOOR_GB
+ aggregate_fits = usable_gb >= needed_gb
+
+ # device_map="balanced" shards across GPUs: an even-share floor stops one
+ # near-full GPU hiding behind aggregate capacity. GGUF self-places, no floor.
+ min_free_gb = min(free_vals)
+ per_gpu_fits = True
+ if mode == "explicit" and len(free_vals) > 1:
+ per_gpu_fits = min_free_gb >= needed_gb / len(free_vals)
+
+ return aggregate_fits and per_gpu_fits, {
+ "mode": mode,
+ "required_gb": round(required_gb, 3),
+ "usable_gb": round(usable_gb, 3),
+ "needed_gb": round(needed_gb, 3),
+ "min_free_gb": round(min_free_gb, 3),
+ }
+ except Exception as e:
+ # Never let a sizing failure load a chat model into a training OOM.
+ logger.warning("Chat-load coexistence probe failed; will refuse: %s", e)
+ return False, {"reason": "probe_error", "error": str(e)}
+
+
+def free_chat_models_for_training(reason: str) -> List[str]:
+ """Unload every resident chat model (HF/MLX orchestrator + GGUF server) to free
+ VRAM for training. Each backend isolated. Returns labels of what was freed."""
+ freed: List[str] = []
+
+ try:
+ from core.inference import get_inference_backend
+ inf = get_inference_backend()
+ if inf.active_model_name or inf.loading_models:
+ name = inf.active_model_name or next(iter(inf.loading_models), None)
+ logger.info(
+ "Unloading inference model '%s' to free GPU memory for training (%s)",
+ name,
+ reason,
+ )
+ inf._shutdown_subprocess()
+ inf.active_model_name = None
+ inf.models.clear()
+ inf.loading_models.clear()
+ freed.append(f"hf:{name}")
+ except Exception as e:
+ logger.warning("Could not unload inference model: %s", e)
+
+ try:
+ from routes.inference import get_llama_cpp_backend
+ llama = get_llama_cpp_backend()
+ # CPU-only GGUF holds no VRAM, so killing it can't help (see summarize).
+ if llama.is_active and getattr(llama, "_gpu_offload_active", None) is not False:
+ name = llama.model_identifier or "gguf"
+ logger.info(
+ "Unloading GGUF chat model '%s' to free GPU memory for training (%s)",
+ name,
+ reason,
+ )
+ llama.unload_model()
+ freed.append(f"gguf:{name}")
+ except Exception as e:
+ logger.warning("Could not unload GGUF chat model: %s", e)
+
+ return freed
diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.py
new file mode 100644
index 00000000000..487c3c7ce0d
--- /dev/null
+++ b/studio/backend/tests/test_chat_load_during_training.py
@@ -0,0 +1,685 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Loading a NEW chat model while training runs: can_load_chat_during_training
+(VRAM fit check), _guard_chat_load_against_training and _effective_load_in_4bit
+(409 + sizing wiring). The guard sizes the same effective load the backend will
+perform (HF auto reuses the loader's selector, HF explicit applies a per-GPU
+floor, GGUF sizes from on-disk weights, LoRA 4-bit->16-bit flips resolved first)
+and leaves non-training/external loads untouched."""
+
+import asyncio
+import importlib.util
+import sys
+import types
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from fastapi import HTTPException
+
+from utils.hardware import DeviceType
+import utils.hardware.hardware as _hw_module
+
+_BACKEND_ROOT = Path(__file__).resolve().parent.parent
+
+# Load training_vram.py standalone (avoids the heavy routes/__init__.py); its
+# lazy hardware imports still resolve against the patched utils.hardware names.
+_spec = importlib.util.spec_from_file_location(
+ "training_vram_load_test", _BACKEND_ROOT / "routes" / "training_vram.py"
+)
+tv = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(tv)
+
+
+class _GpuCacheResetMixin:
+ def tearDown(self):
+ _hw_module._physical_gpu_count = None
+ _hw_module._visible_gpu_count = None
+
+
+def _devices(*free_specs):
+ """Build a device list from (index, total, used) tuples."""
+ return [
+ {"index": i, "vram_total_gb": total, "vram_used_gb": used}
+ for (i, total, used) in free_specs
+ ]
+
+
+# ── can_load_chat_during_training: HF auto (reuses auto_select_gpu_ids) ───────
+
+
+class TestCanLoadAutoHF(_GpuCacheResetMixin, unittest.TestCase):
+ def _run(self, *, selection_mode, required, usable):
+ meta = {"selection_mode": selection_mode, "required_gb": required, "usable_gb": usable}
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch("utils.hardware.auto_select_gpu_ids", return_value = ([0], meta)) as auto_mock,
+ ):
+ ok, info = tv.can_load_chat_during_training(
+ model_name = "unsloth/Qwen3-1.7B",
+ hf_token = None,
+ load_in_4bit = True,
+ max_seq_length = 0,
+ requested_gpu_ids = None,
+ is_gguf = False,
+ )
+ return ok, info, auto_mock
+
+ def test_fits_with_margin(self):
+ # free 60 >= 8*1.15+4 = 13.2
+ ok, info, auto_mock = self._run(selection_mode = "auto", required = 8.0, usable = 60.0)
+ self.assertTrue(ok)
+ self.assertEqual(info["mode"], "auto")
+ self.assertAlmostEqual(info["needed_gb"], 13.2, places = 3)
+ auto_mock.assert_called_once() # mirrors the loader's own selection
+
+ def test_too_tight_refuses(self):
+ # free 10 < 8*1.15+4 = 13.2 -> refuse even though raw 10 > 8
+ ok, _, _ = self._run(selection_mode = "auto", required = 8.0, usable = 10.0)
+ self.assertFalse(ok)
+
+ def test_fallback_all_refuses(self):
+ # Selector couldn't confirm placement -> default-deny to protect training.
+ ok, info = self._run(selection_mode = "fallback_all", required = 8.0, usable = 999.0)[:2]
+ self.assertFalse(ok)
+
+
+# ── can_load_chat_during_training: HF explicit (per-GPU floor) ────────────────
+
+
+class TestCanLoadExplicitHF(_GpuCacheResetMixin, unittest.TestCase):
+ def _run(
+ self,
+ *,
+ required,
+ devices,
+ gpu_ids,
+ resolved = None,
+ resolve_side_effect = None,
+ ):
+ resolve_kwargs = (
+ {"side_effect": resolve_side_effect}
+ if resolve_side_effect
+ else {"return_value": resolved if resolved is not None else gpu_ids}
+ )
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch("utils.hardware.estimate_required_model_memory_gb", return_value = (required, {})),
+ patch("utils.hardware.get_visible_gpu_utilization", return_value = {"devices": devices}),
+ patch("utils.hardware.resolve_requested_gpu_ids", **resolve_kwargs),
+ patch("utils.hardware.auto_select_gpu_ids") as auto_mock,
+ ):
+ ok, info = tv.can_load_chat_during_training(
+ model_name = "m",
+ hf_token = None,
+ load_in_4bit = True,
+ max_seq_length = 0,
+ requested_gpu_ids = gpu_ids,
+ is_gguf = False,
+ )
+ return ok, info, auto_mock
+
+ def test_single_gpu_fits(self):
+ ok, info, auto_mock = self._run(required = 8.0, devices = _devices((0, 80, 20)), gpu_ids = [0])
+ self.assertTrue(ok)
+ self.assertEqual(info["mode"], "explicit")
+ auto_mock.assert_not_called() # explicit never calls the auto selector
+
+ def test_per_gpu_floor_blocks_uneven_split(self):
+ # free [45, 10]; aggregate 45 + 10*0.85 = 53.5 >= needed 27, but the 10 GB
+ # GPU is below the even-share floor 27/2 = 13.5 -> refuse (would OOM it).
+ ok, info, _ = self._run(
+ required = 20.0, devices = _devices((0, 80, 35), (1, 80, 70)), gpu_ids = [0, 1]
+ )
+ self.assertFalse(ok)
+ self.assertAlmostEqual(info["min_free_gb"], 10.0, places = 3)
+
+ def test_per_gpu_floor_passes_when_even(self):
+ # free [30, 30]; both clear the 13.5 even-share floor -> allow.
+ ok, _, _ = self._run(
+ required = 20.0, devices = _devices((0, 80, 50), (1, 80, 50)), gpu_ids = [0, 1]
+ )
+ self.assertTrue(ok)
+
+ def test_missing_gpu_counts_as_zero(self):
+ ok, _, _ = self._run(required = 5.0, devices = _devices((0, 80, 5)), gpu_ids = [3], resolved = [3])
+ self.assertFalse(ok)
+
+ def test_invalid_ids_does_not_block(self):
+ ok, info, _ = self._run(
+ required = 5.0,
+ devices = [],
+ gpu_ids = [99],
+ resolve_side_effect = ValueError("Invalid gpu_ids [99]"),
+ )
+ self.assertTrue(ok)
+ self.assertEqual(info["reason"], "invalid_gpu_ids")
+
+
+# ── can_load_chat_during_training: GGUF (sized from on-disk weights) ──────────
+
+
+class TestCanLoadGGUF(_GpuCacheResetMixin, unittest.TestCase):
+ def _run(
+ self,
+ *,
+ devices,
+ required_override = None,
+ estimate = None,
+ ):
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch("utils.hardware.estimate_required_model_memory_gb", return_value = (estimate, {})),
+ patch("utils.hardware.get_visible_gpu_utilization", return_value = {"devices": devices}),
+ patch("utils.hardware.auto_select_gpu_ids") as auto_mock,
+ ):
+ ok, info = tv.can_load_chat_during_training(
+ model_name = "unsloth/gemma-GGUF",
+ hf_token = None,
+ load_in_4bit = True,
+ max_seq_length = 0,
+ requested_gpu_ids = None,
+ is_gguf = True,
+ required_override_gb = required_override,
+ )
+ return ok, info, auto_mock
+
+ def test_override_fits(self):
+ ok, info, auto_mock = self._run(devices = _devices((0, 80, 20)), required_override = 10.0)
+ self.assertTrue(ok)
+ self.assertEqual(info["mode"], "gguf")
+ auto_mock.assert_not_called() # GGUF never uses the HF auto selector
+
+ def test_no_per_gpu_floor_for_gguf(self):
+ # free [45, 10], override 20 -> needed 27, aggregate 53.5 >= 27. GGUF self-
+ # places, so the per-GPU floor that would block HF doesn't apply -> allow.
+ ok, _, _ = self._run(devices = _devices((0, 80, 35), (1, 80, 70)), required_override = 20.0)
+ self.assertTrue(ok)
+
+ def test_estimate_unavailable_refuses(self):
+ # No override and the estimator can't size it -> default-deny.
+ ok, info, _ = self._run(devices = _devices((0, 80, 0)), required_override = None, estimate = None)
+ self.assertFalse(ok)
+ self.assertEqual(info["reason"], "estimate_unavailable")
+
+
+# ── can_load_chat_during_training: device-independent paths ──────────────────
+
+
+class TestCanLoadMisc(_GpuCacheResetMixin, unittest.TestCase):
+ def test_non_cuda_allows(self):
+ with patch("utils.hardware.get_device", return_value = DeviceType.MLX):
+ ok, info = tv.can_load_chat_during_training(
+ model_name = "m",
+ hf_token = None,
+ load_in_4bit = True,
+ max_seq_length = 0,
+ requested_gpu_ids = None,
+ )
+ self.assertTrue(ok)
+ self.assertEqual(info["mode"], "non_cuda")
+
+ def test_no_visible_gpus_refuses(self):
+ # GGUF with an empty device list -> no candidate GPU -> default-deny.
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch("utils.hardware.get_visible_gpu_utilization", return_value = {"devices": []}),
+ patch("utils.hardware.auto_select_gpu_ids"),
+ ):
+ ok, info = tv.can_load_chat_during_training(
+ model_name = "m",
+ hf_token = None,
+ load_in_4bit = True,
+ max_seq_length = 0,
+ requested_gpu_ids = None,
+ is_gguf = True,
+ required_override_gb = 8.0,
+ )
+ self.assertFalse(ok)
+ self.assertEqual(info["reason"], "no_visible_gpus")
+
+ def test_probe_exception_refuses(self):
+ with patch("utils.hardware.get_device", side_effect = RuntimeError("boom")):
+ ok, info = tv.can_load_chat_during_training(
+ model_name = "m",
+ hf_token = None,
+ load_in_4bit = True,
+ max_seq_length = 0,
+ requested_gpu_ids = None,
+ )
+ self.assertFalse(ok)
+ self.assertEqual(info["reason"], "probe_error")
+
+
+# ── _guard_chat_load_against_training + _effective_load_in_4bit (route) ───────
+
+
+def _load_inference_route():
+ spec = importlib.util.spec_from_file_location(
+ "inference_route_chatload_test", _BACKEND_ROOT / "routes" / "inference.py"
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _stub_guard_deps(
+ *,
+ training_active,
+ decision,
+ captured = None,
+):
+ """Inject the guard's two lazy imports (get_training_backend, can_load_chat_
+ during_training); `captured` records the can_load kwargs for assertions."""
+ core_training = types.ModuleType("core.training")
+ if isinstance(training_active, Exception):
+
+ def _raise():
+ raise training_active
+
+ core_training.get_training_backend = _raise
+ else:
+ core_training.get_training_backend = lambda: SimpleNamespace(
+ is_training_active = lambda: training_active
+ )
+
+ def _can_load(**kwargs):
+ if captured is not None:
+ captured.append(kwargs)
+ return decision
+
+ tv_stub = types.ModuleType("routes.training_vram")
+ tv_stub.can_load_chat_during_training = _can_load
+ return patch.dict(
+ sys.modules, {"core.training": core_training, "routes.training_vram": tv_stub}
+ )
+
+
+class TestChatLoadGuardRoute(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.route = _load_inference_route()
+
+ def _guard(
+ self,
+ *,
+ config = None,
+ captured = None,
+ training_active,
+ decision,
+ ):
+ config = config or SimpleNamespace(is_gguf = False, is_lora = False, path = None)
+ with _stub_guard_deps(
+ training_active = training_active, decision = decision, captured = captured
+ ):
+ self.route._guard_chat_load_against_training(
+ config,
+ model_identifier = "unsloth/Qwen3-1.7B",
+ hf_token = None,
+ load_in_4bit = True,
+ max_seq_length = 0,
+ requested_gpu_ids = None,
+ )
+
+ def test_noop_when_training_inactive(self):
+ self._guard(training_active = False, decision = (False, {})) # must not raise
+
+ def test_noop_when_training_state_unknown(self):
+ self._guard(training_active = RuntimeError("no backend"), decision = (False, {}))
+
+ def test_allows_when_fits(self):
+ self._guard(training_active = True, decision = (True, {"mode": "auto"}))
+
+ def test_refuses_with_headroom_number(self):
+ info = {"required_gb": 30.0, "usable_gb": 6.0, "needed_gb": 39.0, "mode": "auto"}
+ with self.assertRaises(HTTPException) as exc:
+ self._guard(training_active = True, decision = (False, info))
+ self.assertEqual(exc.exception.status_code, 409)
+ self.assertIn("39 GB", exc.exception.detail) # reports needed_gb, not required_gb 30
+ self.assertNotIn("30 GB", exc.exception.detail)
+ self.assertIn("including safety headroom", exc.exception.detail)
+ self.assertNotIn("chat is disabled", exc.exception.detail.lower())
+
+ def test_refuses_generic_when_unsizable(self):
+ with self.assertRaises(HTTPException) as exc:
+ self._guard(training_active = True, decision = (False, {"reason": "estimate_unavailable"}))
+ self.assertEqual(exc.exception.status_code, 409)
+ self.assertIn("could not be verified", exc.exception.detail)
+
+ def test_gguf_config_passes_is_gguf_and_override(self):
+ captured = []
+ config = SimpleNamespace(is_gguf = True)
+ with patch.object(self.route, "_estimate_gguf_required_gb", return_value = 12.5):
+ self._guard(
+ config = config,
+ captured = captured,
+ training_active = True,
+ decision = (True, {}),
+ )
+ self.assertEqual(captured[0]["is_gguf"], True)
+ self.assertEqual(captured[0]["required_override_gb"], 12.5)
+
+
+class TestEffectiveLoadIn4bit(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.route = _load_inference_route()
+
+ def _write_adapter(self, tmpdir, payload):
+ import json
+ (Path(tmpdir) / "adapter_config.json").write_text(json.dumps(payload))
+
+ def test_non_lora_returns_request(self):
+ cfg = SimpleNamespace(is_lora = False, path = None, base_model = None)
+ self.assertTrue(self.route._effective_load_in_4bit(cfg, True))
+
+ def test_lora_method_flips_to_16bit(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ self._write_adapter(d, {"unsloth_training_method": "lora"})
+ cfg = SimpleNamespace(is_lora = True, path = d, base_model = "x")
+ # requested 4-bit, but a 'lora' adapter loads 16-bit
+ self.assertFalse(self.route._effective_load_in_4bit(cfg, True))
+
+ def test_qlora_method_keeps_4bit(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ self._write_adapter(d, {"unsloth_training_method": "qlora"})
+ cfg = SimpleNamespace(is_lora = True, path = d, base_model = "x")
+ self.assertTrue(self.route._effective_load_in_4bit(cfg, True))
+
+ def test_no_method_non_bnb_base_flips_to_16bit(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ self._write_adapter(d, {})
+ cfg = SimpleNamespace(is_lora = True, path = d, base_model = "meta/Llama-3-8B")
+ self.assertFalse(self.route._effective_load_in_4bit(cfg, True))
+
+ def test_malformed_adapter_config_returns_request(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ (Path(d) / "adapter_config.json").write_text("[1, 2, 3]") # not a dict
+ cfg = SimpleNamespace(is_lora = True, path = d, base_model = "x")
+ self.assertTrue(self.route._effective_load_in_4bit(cfg, True)) # no crash
+
+
+# ── validate_model integration (early refusal, real settings) ────────────────
+
+
+class TestValidateRefusesDuringTraining(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.route = _load_inference_route()
+
+ def _validate(
+ self,
+ *,
+ training_active,
+ decision,
+ captured = None,
+ load_in_4bit = True,
+ ):
+ from models.inference import ValidateModelRequest
+
+ request = ValidateModelRequest(
+ model_path = "unsloth/Qwen3-1.7B", load_in_4bit = load_in_4bit, max_seq_length = 4096
+ )
+ cfg = SimpleNamespace(
+ identifier = "unsloth/Qwen3-1.7B",
+ display_name = "Qwen3-1.7B",
+ is_gguf = False,
+ is_lora = False,
+ is_vision = False,
+ path = None,
+ base_model = None,
+ )
+ with (
+ patch.object(
+ self.route,
+ "_resolve_model_identifier_for_request",
+ return_value = ("unsloth/Qwen3-1.7B", "unsloth/Qwen3-1.7B", False),
+ ),
+ patch.object(self.route.ModelConfig, "from_identifier", return_value = cfg),
+ patch.object(self.route, "load_inference_config", return_value = {}),
+ _stub_guard_deps(training_active = training_active, decision = decision, captured = captured),
+ ):
+ return asyncio.run(self.route.validate_model(request, current_subject = "test-user"))
+
+ def test_ok_when_training_inactive(self):
+ resp = self._validate(training_active = False, decision = (False, {}))
+ self.assertTrue(resp.valid)
+
+ def test_refuses_when_wont_fit(self):
+ info = {"required_gb": 40.0, "usable_gb": 5.0, "needed_gb": 50.0}
+ with self.assertRaises(HTTPException) as exc:
+ self._validate(training_active = True, decision = (False, info))
+ self.assertEqual(exc.exception.status_code, 409)
+ self.assertIn("training is running", exc.exception.detail)
+
+ def test_passes_real_load_settings_to_guard(self):
+ # validate must size with the request's settings, not hardcoded defaults.
+ captured = []
+ self._validate(
+ training_active = True, decision = (True, {}), captured = captured, load_in_4bit = False
+ )
+ self.assertEqual(captured[0]["load_in_4bit"], False)
+ self.assertEqual(captured[0]["max_seq_length"], 4096)
+
+ def test_rejects_gguf_with_gpu_ids_before_guard(self):
+ # /validate must mirror /load's GGUF + gpu_ids 400, before the VRAM guard.
+ from models.inference import ValidateModelRequest
+
+ request = ValidateModelRequest(model_path = "x.gguf", gpu_ids = [0])
+ cfg = SimpleNamespace(
+ identifier = "x.gguf",
+ display_name = "x",
+ is_gguf = True,
+ is_lora = False,
+ is_vision = False,
+ path = None,
+ base_model = None,
+ )
+ captured = []
+ with (
+ patch.object(
+ self.route,
+ "_resolve_model_identifier_for_request",
+ return_value = ("x.gguf", "x.gguf", False),
+ ),
+ patch.object(self.route.ModelConfig, "from_identifier", return_value = cfg),
+ patch.object(self.route, "load_inference_config", return_value = {}),
+ _stub_guard_deps(training_active = True, decision = (True, {}), captured = captured),
+ ):
+ with self.assertRaises(HTTPException) as exc:
+ asyncio.run(self.route.validate_model(request, current_subject = "u"))
+ self.assertEqual(exc.exception.status_code, 400)
+ self.assertIn("gpu_ids is not supported for GGUF", exc.exception.detail)
+ self.assertEqual(captured, []) # guard never reached
+
+
+# ── _estimate_gguf_required_gb (sizes the same weights the loader loads) ──────
+
+
+class TestEstimateGgufRequiredGb(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.route = _load_inference_route()
+
+ def test_local_sums_split_shards(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ p = Path(d)
+ (p / "model-00001-of-00002.gguf").write_bytes(b"x" * 1000)
+ (p / "model-00002-of-00002.gguf").write_bytes(b"y" * 2000)
+ cfg = SimpleNamespace(
+ gguf_file = str(p / "model-00001-of-00002.gguf"),
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_hf_repo = None,
+ gguf_variant = None,
+ )
+ gb = self.route._estimate_gguf_required_gb(cfg)
+ self.assertAlmostEqual(gb, 3000 / (1024**3), places = 9) # both shards
+
+ def test_remote_threads_token_and_adds_companions(self):
+ import utils.models.model_config as mc
+
+ cfg = SimpleNamespace(
+ gguf_file = None,
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_hf_repo = "org/repo",
+ gguf_variant = "Q4_K_M",
+ )
+ variant = SimpleNamespace(quant = "Q4_K_M", size_bytes = 10 * 1024**3)
+ captured = {}
+
+ def fake_list(repo, hf_token = None):
+ captured["token"] = hf_token
+ return ([variant], True) # has_vision -> include mmproj
+
+ with (
+ patch.object(mc, "list_gguf_variants", fake_list),
+ patch.object(
+ self.route, "_remote_gguf_companion_bytes", return_value = 2 * 1024**3
+ ) as comp,
+ ):
+ gb = self.route._estimate_gguf_required_gb(cfg, hf_token = "tok")
+ self.assertEqual(captured["token"], "tok") # token threaded for gated repos
+ self.assertAlmostEqual(gb, 12.0, places = 6) # 10 GB variant + 2 GB companions
+ self.assertTrue(comp.call_args.kwargs["include_mmproj"])
+
+ def test_remote_unknown_variant_returns_none(self):
+ import utils.models.model_config as mc
+ cfg = SimpleNamespace(
+ gguf_file = None,
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_hf_repo = "org/repo",
+ gguf_variant = "Q8_0",
+ )
+ with patch.object(
+ mc,
+ "list_gguf_variants",
+ return_value = ([SimpleNamespace(quant = "Q4_K_M", size_bytes = 1)], False),
+ ):
+ self.assertIsNone(self.route._estimate_gguf_required_gb(cfg))
+
+ def test_local_adds_kv_cache(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ p = Path(d) / "model.gguf"
+ p.write_bytes(b"x" * 1000)
+ cfg = SimpleNamespace(
+ gguf_file = str(p),
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_hf_repo = None,
+ gguf_variant = None,
+ )
+ with patch.object(self.route, "_estimate_gguf_kv_gb", return_value = 2.0):
+ gb = self.route._estimate_gguf_required_gb(cfg, max_seq_length = 8192)
+ self.assertAlmostEqual(gb, 1000 / (1024**3) + 2.0, places = 6) # weights + KV
+
+ def test_kv_helper_graceful_on_non_gguf(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ p = Path(d) / "not-a.gguf"
+ p.write_bytes(b"not a gguf")
+ self.assertEqual(self.route._estimate_gguf_kv_gb(str(p), 4096), 0.0)
+
+ def test_kv_sizes_at_larger_of_max_seq_len_and_ctx_override(self):
+ # KV sized at the larger of max_seq_length and --ctx-size, else native.
+ seen = {}
+
+ class _FakeBackend:
+ _context_length = 2048
+
+ def _read_gguf_metadata(self, path):
+ pass
+
+ def _can_estimate_kv(self):
+ return True
+
+ def _estimate_kv_cache_bytes(
+ self,
+ ctx,
+ n_parallel = 1,
+ ):
+ seen["ctx"] = ctx
+ seen["n_parallel"] = n_parallel
+ return ctx * n_parallel * (1024**2) # 1 MiB per ctx unit per slot
+
+ with patch.object(self.route, "LlamaCppBackend", _FakeBackend):
+ r = self.route
+ # --ctx-size override above max_seq_length -> override wins
+ self.assertAlmostEqual(
+ r._estimate_gguf_kv_gb("m", 4096, ["--ctx-size", "131072"]), 128.0
+ )
+ self.assertEqual(seen["ctx"], 131072)
+ self.assertEqual(seen["n_parallel"], 1) # default single slot
+ # override below max_seq_length -> larger (max_seq_length) wins
+ self.assertAlmostEqual(r._estimate_gguf_kv_gb("m", 4096, ["--ctx-size", "1024"]), 4.0)
+ self.assertEqual(seen["ctx"], 4096)
+ # no override, no max_seq_length -> native context fallback
+ self.assertAlmostEqual(r._estimate_gguf_kv_gb("m", 0, None), 2.0)
+ self.assertEqual(seen["ctx"], 2048)
+ # malformed extras are ignored (fall back to max_seq_length)
+ self.assertAlmostEqual(r._estimate_gguf_kv_gb("m", 4096, ["--ctx-size", "oops"]), 4.0)
+ # --parallel slots scale the cache the same way the launcher does
+ self.assertAlmostEqual(r._estimate_gguf_kv_gb("m", 4096, None, 4), 16.0)
+ self.assertEqual(seen["n_parallel"], 4)
+
+
+# ── load_model integration: authoritative 409, and no unload before refusal ──
+
+
+class TestLoadModelGuardIntegration(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.route = _load_inference_route()
+
+ def test_refusal_409_and_no_unload(self):
+ import contextlib
+ from unittest.mock import MagicMock
+ from models.inference import LoadRequest
+
+ inf = SimpleNamespace(active_model_name = None)
+ inf.unload_model = MagicMock()
+ inf._shutdown_subprocess = MagicMock()
+ llama = SimpleNamespace(is_loaded = False, model_identifier = None, hf_variant = None)
+ llama.unload_model = MagicMock()
+ cfg = SimpleNamespace(is_gguf = False, is_lora = False, path = None, base_model = None)
+ request = LoadRequest(model_path = "unsloth/Qwen3-1.7B")
+ info = {"required_gb": 40.0, "usable_gb": 5.0, "needed_gb": 50.0, "mode": "auto"}
+
+ with (
+ patch.object(self.route, "validate_extra_args", return_value = None),
+ patch.object(
+ self.route,
+ "_resolve_model_identifier_for_request",
+ return_value = ("unsloth/Qwen3-1.7B", "unsloth/Qwen3-1.7B", False),
+ ),
+ patch.object(self.route, "resolve_effective_chat_template_override", return_value = None),
+ patch.object(self.route, "get_inference_backend", return_value = inf),
+ patch.object(self.route, "get_llama_cpp_backend", return_value = llama),
+ patch.object(self.route, "_hf_offline_if_dns_dead", lambda: contextlib.nullcontext()),
+ patch.object(self.route.ModelConfig, "from_identifier", return_value = cfg),
+ _stub_guard_deps(training_active = True, decision = (False, info)),
+ ):
+ with self.assertRaises(HTTPException) as exc:
+ asyncio.run(
+ self.route.load_model(request, fastapi_request = MagicMock(), current_subject = "u")
+ )
+
+ self.assertEqual(exc.exception.status_code, 409)
+ # Guard runs before the unload step, so a refused load tears down nothing.
+ inf.unload_model.assert_not_called()
+ inf._shutdown_subprocess.assert_not_called()
+ llama.unload_model.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/studio/backend/tests/test_gpu_selection.py b/studio/backend/tests/test_gpu_selection.py
index cb26330ed05..d96f88e4a65 100644
--- a/studio/backend/tests/test_gpu_selection.py
+++ b/studio/backend/tests/test_gpu_selection.py
@@ -754,8 +754,8 @@ class TestRouteErrors(unittest.TestCase):
with (
patch.object(training_route, "get_training_backend", return_value = DummyBackend()),
patch(
- "core.inference.get_inference_backend",
- return_value = SimpleNamespace(active_model_name = None),
+ "routes.training_vram.summarize_resident_chat",
+ return_value = {"any": False, "hf": None, "gguf": None},
),
patch(
"core.export.get_export_backend",
@@ -794,8 +794,8 @@ class TestRouteErrors(unittest.TestCase):
with (
patch.object(training_route, "get_training_backend", return_value = DummyBackend()),
patch(
- "core.inference.get_inference_backend",
- return_value = SimpleNamespace(active_model_name = None),
+ "routes.training_vram.summarize_resident_chat",
+ return_value = {"any": False, "hf": None, "gguf": None},
),
patch(
"core.export.get_export_backend",
diff --git a/studio/backend/tests/test_training_before_spawn.py b/studio/backend/tests/test_training_before_spawn.py
new file mode 100644
index 00000000000..efd96aeda3e
--- /dev/null
+++ b/studio/backend/tests/test_training_before_spawn.py
@@ -0,0 +1,163 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""
+start_training()'s before_spawn hook must run iff a training subprocess is
+actually spawned -- i.e. only after ALL synchronous validation (start guards,
+config build, GPU-selection) passes. This protects the chat-VRAM unload from
+firing for a start that is then refused (e.g. invalid gpu_ids -> 400).
+"""
+
+import unittest
+from unittest.mock import MagicMock, patch
+
+from core.training.training import TrainingBackend
+from utils.hardware import DeviceType
+
+
+class _DummyProcess:
+ pid = 4321
+
+ def start(self):
+ return None
+
+
+class _DummyThread:
+ def start(self):
+ return None
+
+
+def _start(backend, hook):
+ dummy_queue = object()
+ with (
+ patch("core.training.training.prepare_gpu_selection", return_value = ([0], {})),
+ patch("core.training.training._CTX.Queue", side_effect = [dummy_queue, dummy_queue]),
+ patch("core.training.training._CTX.Process", return_value = _DummyProcess()),
+ patch("core.training.training.threading.Thread", return_value = _DummyThread()),
+ ):
+ return backend.start_training(
+ job_id = "before-spawn-test",
+ before_spawn = hook,
+ model_name = "unsloth/test",
+ training_type = "LoRA/QLoRA",
+ )
+
+
+class TestBeforeSpawnHook(unittest.TestCase):
+ def test_hook_runs_when_training_starts(self):
+ backend = TrainingBackend()
+ hook = MagicMock()
+ ok = _start(backend, hook)
+ self.assertTrue(ok)
+ hook.assert_called_once()
+
+ def test_hook_skipped_when_subprocess_already_alive(self):
+ backend = TrainingBackend()
+ backend._proc = MagicMock()
+ backend._proc.is_alive.return_value = True
+ hook = MagicMock()
+ ok = _start(backend, hook)
+ self.assertFalse(ok)
+ hook.assert_not_called() # never free chat VRAM for a refused start
+
+ def test_hook_skipped_when_pump_thread_will_not_die(self):
+ backend = TrainingBackend()
+ stuck = MagicMock()
+ stuck.is_alive.return_value = True
+ stuck.join.return_value = None
+ backend._pump_thread = stuck
+ hook = MagicMock()
+ ok = _start(backend, hook)
+ self.assertFalse(ok)
+ hook.assert_not_called()
+
+ def test_hook_failure_does_not_block_start(self):
+ backend = TrainingBackend()
+ hook = MagicMock(side_effect = RuntimeError("boom"))
+ ok = _start(backend, hook)
+ self.assertTrue(ok) # training still starts despite a hook error
+ hook.assert_called_once()
+
+ def test_hook_skipped_when_gpu_selection_rejects(self):
+ # Invalid gpu_ids raise in prepare_gpu_selection (before the spawn), so the
+ # hook must NOT run -- a refused start frees no chat/export VRAM.
+ backend = TrainingBackend()
+ hook = MagicMock()
+ with (
+ patch("utils.hardware.hardware.DEVICE", DeviceType.CUDA),
+ patch(
+ "core.training.training.prepare_gpu_selection",
+ side_effect = ValueError("Invalid gpu_ids [99]"),
+ ),
+ patch("core.training.training._CTX.Process") as process_mock,
+ ):
+ with self.assertRaisesRegex(ValueError, "Invalid gpu_ids"):
+ backend.start_training(
+ job_id = "before-spawn-test",
+ before_spawn = hook,
+ model_name = "unsloth/test",
+ training_type = "LoRA/QLoRA",
+ gpu_ids = [99],
+ )
+ hook.assert_not_called()
+ process_mock.assert_not_called()
+
+ def test_auto_placement_runs_after_hook(self):
+ # Auto-selection ranks GPUs by free VRAM, so it must run AFTER the hook
+ # frees export/chat -- otherwise training could be pinned onto a freed GPU
+ # (or onto a GPU holding a chat model the probe decided to keep).
+ order = []
+ backend = TrainingBackend()
+ hook = MagicMock(side_effect = lambda: order.append("hook"))
+
+ def _placement(gpu_ids, **kwargs):
+ order.append("placement")
+ return ([0], {})
+
+ with (
+ patch("utils.hardware.hardware.DEVICE", DeviceType.CUDA),
+ patch("core.training.training.prepare_gpu_selection", side_effect = _placement),
+ patch("core.training.training._CTX.Queue", side_effect = [object(), object()]),
+ patch("core.training.training._CTX.Process", return_value = _DummyProcess()),
+ patch("core.training.training.threading.Thread", return_value = _DummyThread()),
+ ):
+ ok = backend.start_training(
+ job_id = "before-spawn-test",
+ before_spawn = hook,
+ model_name = "unsloth/test",
+ training_type = "LoRA/QLoRA",
+ ) # gpu_ids omitted -> auto mode
+ self.assertTrue(ok)
+ self.assertEqual(order, ["hook", "placement"])
+
+ def test_explicit_placement_validated_before_hook(self):
+ # Explicit gpu_ids are validated before the hook (so an invalid set 400s
+ # without teardown); explicit placement is VRAM-independent.
+ order = []
+ backend = TrainingBackend()
+ hook = MagicMock(side_effect = lambda: order.append("hook"))
+
+ def _placement(gpu_ids, **kwargs):
+ order.append("placement")
+ return (list(gpu_ids), {})
+
+ with (
+ patch("utils.hardware.hardware.DEVICE", DeviceType.CUDA),
+ patch("core.training.training.prepare_gpu_selection", side_effect = _placement),
+ patch("core.training.training._CTX.Queue", side_effect = [object(), object()]),
+ patch("core.training.training._CTX.Process", return_value = _DummyProcess()),
+ patch("core.training.training.threading.Thread", return_value = _DummyThread()),
+ ):
+ ok = backend.start_training(
+ job_id = "before-spawn-test",
+ before_spawn = hook,
+ model_name = "unsloth/test",
+ training_type = "LoRA/QLoRA",
+ gpu_ids = [5],
+ )
+ self.assertTrue(ok)
+ self.assertEqual(order, ["placement", "hook"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/studio/backend/tests/test_training_vram_coexistence.py b/studio/backend/tests/test_training_vram_coexistence.py
new file mode 100644
index 00000000000..2bedc46d1fe
--- /dev/null
+++ b/studio/backend/tests/test_training_vram_coexistence.py
@@ -0,0 +1,442 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""
+Tests for routes/training_vram.py -- the VRAM-aware decision to keep or unload a
+resident chat model when a training run starts.
+"""
+
+import importlib.util
+import sys
+import types
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+from utils.hardware import DeviceType
+import utils.hardware.hardware as _hw_module
+
+# Load training_vram.py standalone so importing it doesn't pull the heavy
+# routes/__init__.py; its lazy backend imports still resolve via sys.modules stubs.
+_BACKEND_ROOT = Path(__file__).resolve().parent.parent
+_spec = importlib.util.spec_from_file_location(
+ "training_vram_under_test", _BACKEND_ROOT / "routes" / "training_vram.py"
+)
+tv = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(tv)
+
+
+class _GpuCacheResetMixin:
+ """Reset module-level GPU caches between tests to prevent state leaks."""
+
+ def tearDown(self):
+ _hw_module._physical_gpu_count = None
+ _hw_module._visible_gpu_count = None
+
+
+def _fake_inference_backend(
+ *,
+ active = None,
+ loading = None,
+ alive = False,
+):
+ inf = SimpleNamespace(
+ active_model_name = active,
+ loading_models = set(loading or []),
+ models = {},
+ )
+ inf._ensure_subprocess_alive = lambda: alive
+ inf._shutdown_subprocess = MagicMock()
+ # Bind the MagicMock so assertions can reach it.
+ inf._shutdown_subprocess_mock = inf._shutdown_subprocess
+ return inf
+
+
+def _fake_llama_backend(
+ *,
+ active = False,
+ identifier = "model.gguf",
+ gpu_offload = None,
+ loaded = None,
+):
+ # A healthy active server is loaded; pass loaded=False for a mid-start one.
+ is_loaded = active if loaded is None else loaded
+ llama = SimpleNamespace(
+ is_active = active,
+ is_loaded = is_loaded,
+ model_identifier = identifier,
+ _gpu_offload_active = gpu_offload,
+ )
+ llama.unload_model = MagicMock()
+ return llama
+
+
+def _patch_backends(inf, llama):
+ """Stub core.inference + routes.inference modules so the lazy imports inside
+ training_vram resolve to fakes (avoids importing torch-heavy backends)."""
+ core_inf = types.ModuleType("core.inference")
+ core_inf.get_inference_backend = lambda: inf
+ routes_inf = types.ModuleType("routes.inference")
+ routes_inf.get_llama_cpp_backend = lambda: llama
+ return patch.dict(sys.modules, {"core.inference": core_inf, "routes.inference": routes_inf})
+
+
+# ── summarize_resident_chat ──────────────────────────────────────────────────
+
+
+class TestSummarizeResidentChat(_GpuCacheResetMixin, unittest.TestCase):
+ def test_nothing_resident(self):
+ with _patch_backends(_fake_inference_backend(), _fake_llama_backend(active = False)):
+ self.assertEqual(
+ tv.summarize_resident_chat(),
+ {"hf": None, "gguf": None, "loading": False, "any": False},
+ )
+
+ def test_hf_resident_via_active_model(self):
+ with _patch_backends(
+ _fake_inference_backend(active = "unsloth/Qwen3-4B"), _fake_llama_backend(active = False)
+ ):
+ out = tv.summarize_resident_chat()
+ self.assertEqual(out["hf"], "unsloth/Qwen3-4B")
+ self.assertFalse(out["loading"])
+ self.assertTrue(out["any"])
+
+ def test_hf_resident_while_still_loading(self):
+ # Mid-load: no active model yet but VRAM is held -> flag in-flight.
+ with _patch_backends(
+ _fake_inference_backend(active = None, loading = ["unsloth/Qwen3-4B"]),
+ _fake_llama_backend(active = False),
+ ):
+ out = tv.summarize_resident_chat()
+ self.assertEqual(out["hf"], "unsloth/Qwen3-4B")
+ self.assertTrue(out["loading"])
+ self.assertTrue(out["any"])
+
+ def test_replacement_hf_load_is_in_flight(self):
+ # Swap: new model loading while old still active -> unsafe to keep.
+ with _patch_backends(
+ _fake_inference_backend(active = "unsloth/old", loading = ["unsloth/new"]),
+ _fake_llama_backend(active = False),
+ ):
+ out = tv.summarize_resident_chat()
+ self.assertEqual(out["hf"], "unsloth/old")
+ self.assertTrue(out["loading"])
+
+ def test_cpu_only_gguf_is_not_a_vram_resident(self):
+ # A llama-server confirmed to run entirely on CPU holds no VRAM.
+ with _patch_backends(
+ _fake_inference_backend(),
+ _fake_llama_backend(active = True, identifier = "cpu.gguf", gpu_offload = False),
+ ):
+ out = tv.summarize_resident_chat()
+ self.assertIsNone(out["gguf"])
+ self.assertFalse(out["any"])
+
+ def test_mid_start_gguf_is_in_flight(self):
+ # Active but not yet healthy -- still allocating, so unsafe to size.
+ with _patch_backends(
+ _fake_inference_backend(),
+ _fake_llama_backend(active = True, loaded = False, identifier = "starting.gguf"),
+ ):
+ out = tv.summarize_resident_chat()
+ self.assertEqual(out["gguf"], "starting.gguf")
+ self.assertTrue(out["loading"])
+
+ def test_bare_alive_subprocess_without_model_is_not_resident(self):
+ # Bare-alive subprocess (no model, only CUDA context) must NOT count.
+ with _patch_backends(
+ _fake_inference_backend(active = None, alive = True), _fake_llama_backend(active = False)
+ ):
+ out = tv.summarize_resident_chat()
+ self.assertIsNone(out["hf"])
+ self.assertFalse(out["any"])
+
+ def test_gguf_resident(self):
+ with _patch_backends(
+ _fake_inference_backend(), _fake_llama_backend(active = True, identifier = "gemma.gguf")
+ ):
+ out = tv.summarize_resident_chat()
+ self.assertEqual(out["gguf"], "gemma.gguf")
+ self.assertFalse(out["loading"]) # healthy/loaded -> safe to size
+ self.assertTrue(out["any"])
+
+ def test_one_backend_raising_does_not_break_the_other(self):
+ bad_inf = SimpleNamespace() # missing attributes -> AttributeError
+ with _patch_backends(bad_inf, _fake_llama_backend(active = True)):
+ out = tv.summarize_resident_chat()
+ self.assertIsNone(out["hf"])
+ self.assertTrue(out["any"]) # GGUF still detected
+
+
+# ── can_keep_during_training (auto mode) ─────────────────────────────────────
+
+
+_BASE_KW = dict(
+ model_name = "unsloth/Qwen3-4B",
+ hf_token = None,
+ training_type = "LoRA/QLoRA",
+ load_in_4bit = True,
+ batch_size = 2,
+ max_seq_length = 2048,
+ lora_rank = 16,
+ target_modules = None,
+ gradient_checkpointing = "unsloth",
+ optimizer = "adamw_8bit",
+ gpu_ids = None,
+)
+
+
+class TestCanKeepAuto(_GpuCacheResetMixin, unittest.TestCase):
+ def _run(
+ self,
+ auto_return,
+ *,
+ device = DeviceType.CUDA,
+ **overrides,
+ ):
+ kw = {**_BASE_KW, **overrides}
+ with (
+ patch("utils.hardware.get_device", return_value = device),
+ patch("utils.hardware.auto_select_gpu_ids", return_value = auto_return) as auto_mock,
+ ):
+ keep, info = tv.can_keep_chat_during_training(**kw)
+ return keep, info, auto_mock
+
+ def test_keep_when_abundant(self):
+ # required 10 -> threshold 10*1.15+4 = 15.5; usable 30 >> 15.5.
+ meta = {"selection_mode": "auto", "required_gb": 10.0, "usable_gb": 30.0}
+ keep, info, _ = self._run(([1], meta))
+ self.assertTrue(keep)
+ self.assertEqual(info["mode"], "auto")
+
+ def test_unload_when_within_margin(self):
+ # required 10 -> threshold 15.5; usable 15.0 fits raw but not the margin.
+ meta = {"selection_mode": "auto", "required_gb": 10.0, "usable_gb": 15.0}
+ keep, _, _ = self._run(([0], meta))
+ self.assertFalse(keep)
+
+ def test_unload_on_fallback_all(self):
+ meta = {"selection_mode": "fallback_all", "required_gb": 10.0, "usable_gb": 100.0}
+ keep, _, _ = self._run(([0, 1], meta))
+ self.assertFalse(keep)
+
+ def test_unload_when_estimate_unavailable(self):
+ meta = {"selection_mode": "auto", "required_gb": None, "usable_gb": None}
+ keep, _, _ = self._run((None, meta))
+ self.assertFalse(keep)
+
+ def test_unload_on_non_cuda(self):
+ keep, info, auto_mock = self._run(([0], {}), device = DeviceType.CPU)
+ self.assertFalse(keep)
+ self.assertEqual(info["mode"], "non_cuda")
+ auto_mock.assert_not_called()
+
+ def test_full_finetuning_forces_16bit_in_estimate(self):
+ meta = {"selection_mode": "auto", "required_gb": 10.0, "usable_gb": 30.0}
+ _keep, _info, auto_mock = self._run(
+ ([0], meta), training_type = "Full Finetuning", load_in_4bit = True
+ )
+ self.assertFalse(auto_mock.call_args.kwargs["load_in_4bit"])
+
+ def test_hf_token_forwarded(self):
+ meta = {"selection_mode": "auto", "required_gb": 10.0, "usable_gb": 30.0}
+ _keep, _info, auto_mock = self._run(([0], meta), hf_token = "hf_secret")
+ self.assertEqual(auto_mock.call_args.kwargs["hf_token"], "hf_secret")
+
+ def test_probe_exception_defaults_to_unload(self):
+ kw = {**_BASE_KW}
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch("utils.hardware.auto_select_gpu_ids", side_effect = RuntimeError("boom")),
+ ):
+ keep, info = tv.can_keep_chat_during_training(**kw)
+ self.assertFalse(keep)
+ self.assertEqual(info["reason"], "probe_error")
+
+
+# ── can_keep_during_training (explicit GPU mode) ─────────────────────────────
+
+
+class TestCanKeepExplicit(_GpuCacheResetMixin, unittest.TestCase):
+ def _run(
+ self,
+ *,
+ required,
+ devices,
+ resolved,
+ gpu_ids,
+ est_meta = None,
+ resolve_side_effect = None,
+ ):
+ kw = {**_BASE_KW, "gpu_ids": gpu_ids}
+ resolve_kwargs = (
+ {"side_effect": resolve_side_effect}
+ if resolve_side_effect
+ else {"return_value": resolved}
+ )
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch(
+ "utils.hardware.estimate_required_model_memory_gb",
+ return_value = (required, est_meta or {}),
+ ),
+ patch(
+ "utils.hardware.get_visible_gpu_utilization",
+ return_value = {"devices": devices},
+ ),
+ patch("utils.hardware.resolve_requested_gpu_ids", **resolve_kwargs),
+ patch("utils.hardware.auto_select_gpu_ids") as auto_mock,
+ ):
+ keep, info = tv.can_keep_chat_during_training(**kw)
+ return keep, info, auto_mock
+
+ def test_keep_when_chosen_gpu_has_room(self):
+ devices = [{"index": 0, "vram_total_gb": 80.0, "vram_used_gb": 20.0}]
+ keep, info, auto_mock = self._run(required = 30.0, devices = devices, resolved = [0], gpu_ids = [0])
+ # free 60 >= 30*1.15+4 = 38.5
+ self.assertTrue(keep)
+ self.assertEqual(info["mode"], "explicit")
+ auto_mock.assert_not_called() # explicit mode never calls the selector
+
+ def test_unload_when_chosen_gpu_too_tight(self):
+ devices = [{"index": 0, "vram_total_gb": 24.0, "vram_used_gb": 20.0}]
+ keep, _, _ = self._run(required = 10.0, devices = devices, resolved = [0], gpu_ids = [0])
+ # free 4 < 10*1.15+4 = 15.5
+ self.assertFalse(keep)
+
+ def test_multi_gpu_overhead_applied(self):
+ # frees [20, 10]; without overhead usable=30, with overhead=20+10*0.85=28.5.
+ # required 22 -> threshold 22*1.15+4 = 29.3. 28.5 < 29.3 -> unload, proving
+ # the 0.85 overhead was applied (raw 30 would have kept).
+ devices = [
+ {"index": 0, "vram_total_gb": 24.0, "vram_used_gb": 4.0},
+ {"index": 1, "vram_total_gb": 24.0, "vram_used_gb": 14.0},
+ ]
+ keep, info, _ = self._run(required = 22.0, devices = devices, resolved = [0, 1], gpu_ids = [0, 1])
+ self.assertFalse(keep)
+ self.assertAlmostEqual(info["usable_gb"], 28.5, places = 3)
+
+ def test_requested_gpu_missing_from_devices_counts_as_zero(self):
+ devices = [{"index": 0, "vram_total_gb": 80.0, "vram_used_gb": 5.0}]
+ # resolved [3] is absent -> free 0 -> unload.
+ keep, _, _ = self._run(required = 5.0, devices = devices, resolved = [3], gpu_ids = [3])
+ self.assertFalse(keep)
+
+ def test_unload_when_estimate_none(self):
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch("utils.hardware.estimate_required_model_memory_gb", return_value = (None, {})),
+ patch("utils.hardware.resolve_requested_gpu_ids", return_value = [0]),
+ ):
+ keep, info = tv.can_keep_chat_during_training(**{**_BASE_KW, "gpu_ids": [0]})
+ self.assertFalse(keep)
+ self.assertEqual(info["reason"], "estimate_unavailable")
+
+ def test_per_gpu_floor_blocks_uneven_explicit_split(self):
+ # free [45, 10]: aggregate 53.5 >= 50 passes, but GPU1's 10 < per-GPU
+ # floor 25 -> unload (the tight GPU would OOM).
+ devices = [
+ {"index": 0, "vram_total_gb": 80.0, "vram_used_gb": 35.0}, # 45 free
+ {"index": 1, "vram_total_gb": 80.0, "vram_used_gb": 70.0}, # 10 free
+ ]
+ keep, info, _ = self._run(
+ required = 40.0,
+ devices = devices,
+ resolved = [0, 1],
+ gpu_ids = [0, 1],
+ est_meta = {"vram_breakdown": {"min_per_gpu_2": 25.0}},
+ )
+ self.assertFalse(keep)
+ self.assertAlmostEqual(info["min_free_gb"], 10.0, places = 3)
+
+ def test_per_gpu_floor_passes_when_even(self):
+ # Same aggregate, but both GPUs clear the 25 GB per-GPU floor -> keep.
+ devices = [
+ {"index": 0, "vram_total_gb": 80.0, "vram_used_gb": 45.0}, # 35 free
+ {"index": 1, "vram_total_gb": 80.0, "vram_used_gb": 50.0}, # 30 free
+ ]
+ keep, _, _ = self._run(
+ required = 40.0,
+ devices = devices,
+ resolved = [0, 1],
+ gpu_ids = [0, 1],
+ est_meta = {"vram_breakdown": {"min_per_gpu_2": 25.0}},
+ )
+ self.assertTrue(keep)
+
+ def test_invalid_gpu_ids_keeps_chat_instead_of_unloading(self):
+ # resolve raising -> request will 400 before training, so leave chat alone.
+ keep, info, _ = self._run(
+ required = 5.0,
+ devices = [],
+ resolved = None,
+ gpu_ids = [99],
+ resolve_side_effect = ValueError("Invalid gpu_ids [99]"),
+ )
+ self.assertTrue(keep)
+ self.assertEqual(info["reason"], "invalid_gpu_ids")
+
+
+# ── free_chat_models_for_training ────────────────────────────────────────────
+
+
+class TestFreeChatModels(_GpuCacheResetMixin, unittest.TestCase):
+ def test_unloads_both_backends(self):
+ inf = _fake_inference_backend(active = "unsloth/Qwen3-4B")
+ llama = _fake_llama_backend(active = True, identifier = "gemma.gguf")
+ with _patch_backends(inf, llama):
+ freed = tv.free_chat_models_for_training(reason = "test")
+ inf._shutdown_subprocess.assert_called_once()
+ llama.unload_model.assert_called_once()
+ self.assertIn("hf:unsloth/Qwen3-4B", freed)
+ self.assertIn("gguf:gemma.gguf", freed)
+ # State cleared so a later resident check is accurate.
+ self.assertIsNone(inf.active_model_name)
+ self.assertEqual(inf.models, {})
+ self.assertEqual(inf.loading_models, set())
+
+ def test_unloads_gguf_only(self):
+ inf = _fake_inference_backend() # nothing resident
+ llama = _fake_llama_backend(active = True, identifier = "gemma.gguf")
+ with _patch_backends(inf, llama):
+ freed = tv.free_chat_models_for_training(reason = "test")
+ inf._shutdown_subprocess.assert_not_called()
+ llama.unload_model.assert_called_once()
+ self.assertEqual(freed, ["gguf:gemma.gguf"])
+
+ def test_leaves_cpu_only_gguf_alone(self):
+ # Killing a CPU-only llama-server cannot reclaim VRAM, so don't.
+ inf = _fake_inference_backend()
+ llama = _fake_llama_backend(active = True, identifier = "cpu.gguf", gpu_offload = False)
+ with _patch_backends(inf, llama):
+ freed = tv.free_chat_models_for_training(reason = "test")
+ llama.unload_model.assert_not_called()
+ self.assertEqual(freed, [])
+
+ def test_unloads_inflight_hf_load(self):
+ inf = _fake_inference_backend(active = None, loading = ["unsloth/Qwen3-4B"])
+ llama = _fake_llama_backend(active = False)
+ with _patch_backends(inf, llama):
+ freed = tv.free_chat_models_for_training(reason = "test")
+ inf._shutdown_subprocess.assert_called_once()
+ self.assertEqual(freed, ["hf:unsloth/Qwen3-4B"])
+
+ def test_nothing_to_free(self):
+ inf = _fake_inference_backend()
+ llama = _fake_llama_backend(active = False)
+ with _patch_backends(inf, llama):
+ freed = tv.free_chat_models_for_training(reason = "test")
+ self.assertEqual(freed, [])
+
+ def test_hf_failure_still_unloads_gguf(self):
+ bad_inf = SimpleNamespace() # AttributeError on access
+ llama = _fake_llama_backend(active = True, identifier = "gemma.gguf")
+ with _patch_backends(bad_inf, llama):
+ freed = tv.free_chat_models_for_training(reason = "test")
+ llama.unload_model.assert_called_once()
+ self.assertEqual(freed, ["gguf:gemma.gguf"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 77b819aa63e..f4f40e73f69 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -6,9 +6,15 @@ import { Navbar } from "@/components/navbar";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { SettingsDialog, useSettingsDialogStore } from "@/features/settings";
+import {
+ ChatPage,
+ clearNewChatDraft,
+ useChatRuntimeStore,
+ type ChatSearch,
+} from "@/features/chat";
import { RemoteCodeConsentDialog } from "@/features/security";
-import { clearNewChatDraft, useChatRuntimeStore } from "@/features/chat";
import { useTrainingUnloadGuard } from "@/features/training";
+import { useExportRuntimeLifecycle } from "@/features/export";
import { useSidebarPin } from "@/hooks/use-sidebar-pin";
import { useT, type TranslationKey } from "@/i18n";
import {
@@ -20,7 +26,13 @@ import {
useRouterState,
} from "@tanstack/react-router";
import { AnimatePresence, motion } from "motion/react";
-import { Suspense, useEffect, useLayoutEffect } from "react";
+import {
+ Suspense,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useState,
+} from "react";
import { AppProvider } from "../provider";
declare module "@tanstack/react-router" {
@@ -78,11 +90,51 @@ function RootLayout() {
const t = useT();
const pathname = useRouterState({ select: (s) => s.location.pathname });
const hideNavbar = HIDDEN_NAVBAR_ROUTES.includes(pathname);
- const isChatRoute = pathname.startsWith("/chat");
+ // Exact match: a prefix would treat /chatty as chat, hiding its not-found UI.
+ const isChatRoute = pathname === "/chat";
const { pinned, setPinned, togglePinned } = useSidebarPin();
const navigate = useNavigate();
+ // ChatPage is mounted persistently below (not via the /chat route) so an in-flight
+ // generation survives leaving the tab: it mounts lazily on first /chat visit, then
+ // stays mounted, its search frozen to the last /chat value while off-route.
+ const rawSearch = useRouterState({ select: (s) => s.location.search }) as
+ | Record<string, unknown>
+ | undefined;
+ const rawThread =
+ typeof rawSearch?.thread === "string" ? rawSearch.thread : undefined;
+ const rawCompare =
+ typeof rawSearch?.compare === "string" ? rawSearch.compare : undefined;
+ const rawNew = typeof rawSearch?.new === "string" ? rawSearch.new : undefined;
+ const rawProject =
+ typeof rawSearch?.project === "string" ? rawSearch.project : undefined;
+ const liveChatSearch = useMemo<ChatSearch>(
+ () => ({
+ thread: rawThread,
+ compare: rawCompare,
+ new: rawNew,
+ project: rawProject,
+ }),
+ [rawThread, rawCompare, rawNew, rawProject],
+ );
+ // Freeze the last /chat search and latch "mounted" via render-phase setState
+ // (React's "adjust state during render" pattern), avoiding effects/refs.
+ const [frozenChatSearch, setFrozenChatSearch] =
+ useState<ChatSearch>(liveChatSearch);
+ const [chatMounted, setChatMounted] = useState(isChatRoute);
+ if (isChatRoute && frozenChatSearch !== liveChatSearch) {
+ setFrozenChatSearch(liveChatSearch);
+ }
+ if (isChatRoute && !chatMounted) {
+ setChatMounted(true);
+ }
+ const chatSearch = isChatRoute ? liveChatSearch : frozenChatSearch;
+ const shouldMountChat = isChatRoute || chatMounted;
+
useTrainingUnloadGuard();
+ // Global export driver: streams worker logs and tracks status from any route
+ // so an export keeps running and stays visible while training / chatting.
+ useExportRuntimeLifecycle();
const matchedTitle = useMatches({
select: (matches) => {
@@ -134,6 +186,12 @@ function RootLayout() {
useEffect(() => {
if (isChatRoute) return;
const chatRuntime = useChatRuntimeStore.getState();
+ // A URL-less chat's provider is keyed off the active thread id; clearing it
+ // mid-generation would remount and cancel the stream. Only reset when idle.
+ const anyRunning = Object.values(chatRuntime.runningByThreadId).some(
+ Boolean,
+ );
+ if (anyRunning) return;
chatRuntime.setActiveProjectId(null);
chatRuntime.setActiveThreadId(null);
chatRuntime.setIncognito(false);
@@ -163,25 +221,43 @@ function RootLayout() {
<div
className={`relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col ${isChatRoute ? "overflow-hidden" : "overflow-visible"} ${isChatRoute ? "" : "pt-14 md:pt-0"}`}
>
+ {/* Stays mounted across navigation so an in-flight generation is
+ not cancelled when leaving /chat; hidden (not unmounted) off-route.
+ `active` lets ChatPage close its body-portaled surfaces (model
+ selector, settings sheet, tour) so they don't bleed over other tabs. */}
+ {shouldMountChat && (
+ <div
+ className={
+ isChatRoute
+ ? "flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"
+ : "hidden"
+ }
+ inert={!isChatRoute || undefined}
+ >
+ <ChatPage search={chatSearch} active={isChatRoute} />
+ </div>
+ )}
{/* Use mode="popLayout" instead of "wait" to prevent UI freezes when
switching from heavy pages (like Export with many checkpoints).
"popLayout" allows the new route to mount immediately while the
old one animates out, avoiding blocking on expensive exit renders.
See issue #5850. */}
- <AnimatePresence initial={false} mode="popLayout">
- <motion.div
- key={pathname}
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.15 }}
- className={`flex min-h-0 min-w-0 flex-1 basis-0 flex-col ${isChatRoute ? "overflow-hidden" : "overflow-visible"}`}
- >
- <Suspense fallback={<RouteFallback />}>
- <Outlet />
- </Suspense>
- </motion.div>
- </AnimatePresence>
+ {!isChatRoute && (
+ <AnimatePresence initial={false} mode="popLayout">
+ <motion.div
+ key={pathname}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.15 }}
+ className="flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-visible"
+ >
+ <Suspense fallback={<RouteFallback />}>
+ <Outlet />
+ </Suspense>
+ </motion.div>
+ </AnimatePresence>
+ )}
</div>
</SidebarInset>
</SidebarProvider>
diff --git a/studio/frontend/src/app/routes/chat.tsx b/studio/frontend/src/app/routes/chat.tsx
index a5514cdee18..1e5ce00b79b 100644
--- a/studio/frontend/src/app/routes/chat.tsx
+++ b/studio/frontend/src/app/routes/chat.tsx
@@ -1,28 +1,18 @@
// 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 { ChatPage } from "@/features/chat/chat-page";
+import { validateChatSearch } from "@/features/chat";
import { createRoute } from "@tanstack/react-router";
import { requireAuth } from "../auth-guards";
import { Route as rootRoute } from "./__root";
-export type ChatSearch = {
- thread?: string;
- compare?: string;
- new?: string;
- project?: string;
-};
-
+// RootLayout renders ChatPage persistently (so it survives leaving the tab); this
+// route only owns the URL, auth gate, and search validation.
export const Route = createRoute({
getParentRoute: () => rootRoute,
path: "/chat",
staticData: { title: "Chat" },
beforeLoad: () => requireAuth(),
- validateSearch: (search: Record<string, unknown>): ChatSearch => ({
- thread: typeof search.thread === "string" ? search.thread : undefined,
- compare: typeof search.compare === "string" ? search.compare : undefined,
- new: typeof search.new === "string" ? search.new : undefined,
- project: typeof search.project === "string" ? search.project : undefined,
- }),
- component: ChatPage,
+ validateSearch: (search: Record<string, unknown>) => validateChatSearch(search),
+ component: () => null,
});
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index e15b3a0bdfd..4ca1d466fc2 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -41,6 +41,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
+import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { useAnimatedThemeToggle } from "@/components/ui/animated-theme-toggler";
import { cn } from "@/lib/utils";
@@ -116,10 +117,12 @@ import {
emitTrainingRunUpdated,
removeTrainingUnloadGuard,
renameTrainingRun,
+ useTrainingCompletionWatch,
useTrainingHistorySidebarItems,
useTrainingRuntimeStore,
} from "@/features/training";
import type { TrainingRunSummary } from "@/features/training";
+import { useExportRuntimeStore } from "@/features/export";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { toast } from "@/lib/toast";
import { ShutdownDialog } from "@/components/shutdown-dialog";
@@ -207,6 +210,7 @@ function NavItem({
children,
dataTour,
className,
+ spinner,
}: {
icon: typeof ZapIcon;
label: string;
@@ -216,6 +220,7 @@ function NavItem({
children?: ReactNode;
dataTour?: string;
className?: string;
+ spinner?: boolean;
}) {
return (
<SidebarMenuItem className={className}>
@@ -230,7 +235,14 @@ function NavItem({
>
<HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-icon! shrink-0 group-hover/menu-button:animate-icon-pop" />
<span className="text-[14.5px] leading-[19px] tracking-nav">{label}</span>
+ {spinner && (
+ <Spinner className="ml-auto size-3.5 shrink-0 text-muted-foreground group-data-[collapsible=icon]:hidden" />
+ )}
</SidebarMenuButton>
+ {spinner && (
+ // Collapsed (icon-only) rail: small spinner badge over the icon corner.
+ <Spinner className="pointer-events-none absolute right-1 top-1 hidden size-2.5 text-muted-foreground group-data-[collapsible=icon]:block" />
+ )}
</div>
{children}
</SidebarMenuItem>
@@ -254,7 +266,6 @@ export function AppSidebar() {
if (isMobile) setOpenMobile(false);
};
- const isTrainingRunning = useTrainingRuntimeStore((s) => s.isTrainingRunning);
const chatOnly = usePlatformStore((s) => s.isChatOnly());
const [shutdownOpen, setShutdownOpen] = useState(false);
@@ -328,6 +339,15 @@ export function AppSidebar() {
const [pinnedOpen, setPinnedOpen] = useState(true);
const storeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const setActiveThreadId = useChatRuntimeStore((s) => s.setActiveThreadId);
+ const anyChatRunning = useChatRuntimeStore((s) =>
+ Object.values(s.runningByThreadId).some(Boolean),
+ );
+ // The thread currently generating (if any), so "Return to Chat" lands on the
+ // live chat rather than an empty new-chat draft left active after New Chat.
+ const runningThreadId = useChatRuntimeStore((s) => {
+ const entry = Object.entries(s.runningByThreadId).find(([, on]) => on);
+ return entry ? entry[0] : null;
+ });
const activeThreadId = isChatRoute
? (search.thread as string | undefined) ??
(search.compare as string | undefined) ??
@@ -347,6 +367,20 @@ export function AppSidebar() {
const currentRunViewActive = useTrainingRuntimeStore((s) => s.currentRunViewActive);
const selectedHistoryRunId = useTrainingRuntimeStore((s) => s.selectedHistoryRunId);
const setSelectedHistoryRunId = useTrainingRuntimeStore((s) => s.setSelectedHistoryRunId);
+ // Running or starting up. Drives the Train spinner + New Chat / Return to Chat swap.
+ const trainingInProgress = useTrainingRuntimeStore((s) => s.isTrainingRunning || s.isStarting);
+ // Export runs in the background (parallel with training/inference); reflect it
+ // on the Export nav item so it is visible from any tab.
+ const exportInProgress = useExportRuntimeStore((s) => s.isExporting);
+ // On any non-chat tab (Train, Export, Recipes, Projects, Hub, ...) offer a way
+ // back to the live chat instead of starting a new one, whenever a chat is
+ // running or its thread is still active, or a training / export is in progress.
+ const showReturnToChat =
+ !isChatRoute &&
+ (trainingInProgress || exportInProgress || anyChatRunning || storeThreadId != null);
+ // The Train-page status poll doesn't run off-route; keep state fresh so the spinner
+ // clears even if a run finishes while the user is on another tab.
+ useTrainingCompletionWatch();
// Recompute bottom-fade on mount and whenever list height can change
// (items load, sections toggle, route switch) - onScroll never fires for
@@ -366,8 +400,6 @@ export function AppSidebar() {
isStudioRoute,
]);
- const chatDisabled = isTrainingRunning;
-
function chatSearchForProject(projectId: string | null) {
if (projectId) {
return { project: projectId };
@@ -378,7 +410,6 @@ export function AppSidebar() {
}
function openNewChat(projectId = activeProjectId) {
- if (chatDisabled) return;
clearNewChatDraft();
setActiveThreadId(null);
useChatRuntimeStore.getState().setActiveProjectId(projectId);
@@ -390,7 +421,6 @@ export function AppSidebar() {
}
function openProject(projectId: string) {
- if (chatDisabled) return;
setActiveThreadId(null);
useChatRuntimeStore.getState().setActiveProjectId(projectId);
navigate({ to: "/chat", search: { project: projectId } });
@@ -902,7 +932,6 @@ export function AppSidebar() {
to="/chat"
onClick={(event) => {
event.preventDefault();
- if (chatDisabled) return;
openNewChat(null);
}}
className="flex items-center gap-[6px] select-none"
@@ -975,23 +1004,37 @@ export function AppSidebar() {
<SidebarMenu>
<NavItem
icon={PencilEdit02Icon}
- label={t("shell.navigation.newChat")}
+ label={
+ showReturnToChat
+ ? t("shell.navigation.returnToChat")
+ : t("shell.navigation.newChat")
+ }
active={
isChatRoute &&
!search.thread &&
!search.compare &&
!search.project
}
- disabled={chatDisabled}
- onClick={() => openNewChat(null)}
+ onClick={() => {
+ if (showReturnToChat) {
+ // Prefer the running thread so we return to the live generation,
+ // not the empty new chat that became active after New Chat.
+ if (runningThreadId && runningThreadId !== storeThreadId) {
+ navigate({ to: "/chat", search: { thread: runningThreadId } });
+ } else {
+ navigate({ to: "/chat" });
+ }
+ closeMobileIfOpen();
+ return;
+ }
+ openNewChat(null);
+ }}
/>
<NavItem
icon={Search01Icon}
label={t("shell.navigation.search")}
active={false}
onClick={() => {
- // Search is read-only and never runs inference, so it stays
- // available while training (unlike New chat, gated on chatDisabled).
useChatSearchStore.getState().open();
closeMobileIfOpen();
}}
@@ -1062,6 +1105,7 @@ export function AppSidebar() {
pathname === "/studio" || pathname.startsWith("/studio/")
}
disabled={chatOnly}
+ spinner={trainingInProgress}
onClick={() => {
if (chatOnly) return;
navigate({ to: "/studio" });
@@ -1089,6 +1133,7 @@ export function AppSidebar() {
label={t("shell.navigation.train")}
active={pathname === "/studio" || pathname.startsWith("/studio/")}
disabled={chatOnly}
+ spinner={trainingInProgress}
onClick={() => {
if (chatOnly) return;
navigate({ to: "/studio" });
@@ -1109,6 +1154,7 @@ export function AppSidebar() {
label={t("shell.navigation.export")}
active={pathname === "/export" || pathname.startsWith("/export/")}
disabled={chatOnly}
+ spinner={exportInProgress}
onClick={() => {
if (chatOnly) return;
navigate({ to: "/export" });
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 91bfe56120f..956056b83b1 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -2181,6 +2181,13 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {
// Colab-style proxies can swallow fetch aborts, so also POST
// /inference/cancel explicitly on abort.
const onAbortCancel = () => {
+ // assistant-ui aborts with AbortError(detach=true) when a thread's runtime
+ // unmounts (navigation / background thread switch) and detach=false for an
+ // explicit Stop. Only a real Stop cancels the backend run; a detach must
+ // leave a backgrounded generation streaming.
+ if ((abortSignal.reason as { detach?: boolean } | undefined)?.detach) {
+ return;
+ }
const body: Record<string, string> = { cancel_id: cancelId };
if (sandboxSessionId) body.session_id = sandboxSessionId;
// Plain fetch, not authFetch: authFetch redirects to login on
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index f3235fa4476..5003072903e 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -111,6 +111,10 @@ export async function validateModel(
native_path_lease: payload.nativePathLease ?? null,
hf_token: payload.hf_token,
gguf_variant: payload.gguf_variant ?? null,
+ // Send the intended load settings so validate's VRAM check matches the
+ // follow-up /load and doesn't unload for a load /load would then reject.
+ max_seq_length: payload.max_seq_length,
+ load_in_4bit: payload.load_in_4bit,
}),
});
return parseJsonOrThrow<ValidateModelResponse>(response);
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 5ed834fb9eb..5c1da880227 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -1,7 +1,6 @@
// 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 type { ChatSearch } from "@/app/routes/chat";
import {
type DeletedModelRef,
type ExternalModelOption,
@@ -36,7 +35,7 @@ import {
LayoutAlignRightIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useNavigate, useRouterState, useSearch } from "@tanstack/react-router";
+import { useNavigate } from "@tanstack/react-router";
import { Tooltip as TooltipPrimitive } from "radix-ui";
import type { PanelImperativeHandle } from "react-resizable-panels";
import {
@@ -83,7 +82,11 @@ import {
providerSupportsBuiltinWebFetch,
providerSupportsBuiltinWebSearch,
} from "./provider-capabilities";
-import { ChatRuntimeProvider } from "./runtime-provider";
+import {
+ ChatActiveContext,
+ ChatRuntimeProvider,
+ useChatActive,
+} from "./runtime-provider";
import {
type CompareHandle,
type CompareHandles,
@@ -521,6 +524,7 @@ const LoraCompareContent = memo(function LoraCompareContent({
const handlesRef = useRef<Record<string, CompareHandle>>({});
const [baseThreadId, setBaseThreadId] = useState<string>();
const [loraThreadId, setLoraThreadId] = useState<string>();
+ const active = useChatActive();
const compareRunning = useChatRuntimeStore(
(s) => Object.keys(s.runningByThreadId).length > 0,
@@ -549,12 +553,16 @@ const LoraCompareContent = memo(function LoraCompareContent({
<CompareShell
handlesRef={handlesRef}
composer={
- <SharedComposer
- handlesRef={handlesRef}
- onExitCompare={onExitCompare}
- model1ThreadId={baseThreadId}
- model2ThreadId={loraThreadId}
- />
+ active ? (
+ <SharedComposer
+ handlesRef={handlesRef}
+ onExitCompare={onExitCompare}
+ model1ThreadId={baseThreadId}
+ model2ThreadId={loraThreadId}
+ />
+ ) : (
+ <></>
+ )
}
>
<>
@@ -621,6 +629,9 @@ function GeneralCompareHeader({
deleteDisabled?: boolean;
side: "left" | "right";
}): ReactElement {
+ // Controlled so the body-portaled popover can't linger over another tab off-route.
+ const active = useChatActive();
+ const [selectorOpen, setSelectorOpen] = useState(false);
return (
<div
className={cn(
@@ -639,6 +650,8 @@ function GeneralCompareHeader({
deleteDisabled={deleteDisabled}
variant="ghost"
className="max-w-[80%] !h-[34px]"
+ open={active && selectorOpen}
+ onOpenChange={(open) => setSelectorOpen(active && open)}
/>
</div>
);
@@ -672,6 +685,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
const globalCheckpoint = useChatRuntimeStore((s) => s.params.checkpoint);
const globalGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
+ const active = useChatActive();
const compareRunning = useChatRuntimeStore(
(s) => Object.keys(s.runningByThreadId).length > 0,
);
@@ -729,14 +743,18 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
<CompareShell
handlesRef={handlesRef}
composer={
- <SharedComposer
- handlesRef={handlesRef}
- model1={model1}
- model2={model2}
- onExitCompare={onExitCompare}
- model1ThreadId={model1ThreadId}
- model2ThreadId={model2ThreadId}
- />
+ active ? (
+ <SharedComposer
+ handlesRef={handlesRef}
+ model1={model1}
+ model2={model2}
+ onExitCompare={onExitCompare}
+ model1ThreadId={model1ThreadId}
+ model2ThreadId={model2ThreadId}
+ />
+ ) : (
+ <></>
+ )
}
>
<>
@@ -1020,11 +1038,31 @@ function ProjectLanding({
);
}
-export function ChatPage(): ReactElement {
- const search = useSearch({ from: "/chat" });
+export type ChatSearch = {
+ thread?: string;
+ compare?: string;
+ new?: string;
+ project?: string;
+};
+
+export function validateChatSearch(search: Record<string, unknown>): ChatSearch {
+ return {
+ thread: typeof search.thread === "string" ? search.thread : undefined,
+ compare: typeof search.compare === "string" ? search.compare : undefined,
+ new: typeof search.new === "string" ? search.new : undefined,
+ project: typeof search.project === "string" ? search.project : undefined,
+ };
+}
+
+// `search` comes from RootLayout (not useSearch) so ChatPage stays mounted off-route
+// (keeping an in-flight generation alive), frozen to the last /chat search. `active`
+// is false off-route: close body-portaled surfaces and stop route-specific listeners
+// that would otherwise bleed over the visible tab.
+export function ChatPage({
+ search,
+ active,
+}: { search: ChatSearch; active: boolean }): ReactElement {
const navigate = useNavigate();
- const pathname = useRouterState({ select: (s) => s.location.pathname });
- const isCurrentChatRoute = pathname.startsWith("/chat");
const settingsOpen = useChatRuntimeStore((s) => s.settingsPanelOpen);
const setSettingsOpen = useChatRuntimeStore((s) => s.setSettingsPanelOpen);
@@ -1081,6 +1119,9 @@ export function ChatPage(): ReactElement {
}, [hydratePersistedSettings]);
useEffect(() => {
+ // Skip while off-route: ChatPage stays mounted, and toast+navigate here would
+ // yank the user back to chat from whatever tab they're on.
+ if (!active) return;
const threadId = search.thread;
if (!threadId) return;
@@ -1109,7 +1150,7 @@ export function ChatPage(): ReactElement {
return () => {
canceled = true;
};
- }, [navigate, search.thread]);
+ }, [active, navigate, search.thread]);
const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
const [modelSelectorLocked, setModelSelectorLocked] = useState(false);
@@ -1621,7 +1662,7 @@ export function ChatPage(): ReactElement {
onAutoLoad: handleNativeModelPickerAutoLoad,
});
const nativeModelDropState = useNativeModelDrop({
- enabled: view.mode === "single",
+ enabled: active && view.mode === "single",
nativePathLeasesSupported,
hasActiveModel,
isModelLoading: Boolean(loadingModel) || modelLoading,
@@ -2077,6 +2118,9 @@ export function ChatPage(): ReactElement {
}, [refresh, refreshLocalModels]);
useEffect(() => {
+ // ChatPage no longer remounts on navigation, so re-check the handoff whenever
+ // we return to /chat (e.g. from the training progress "compare in chat" action).
+ if (!active) return;
const handoff = getTrainingCompareHandoff();
if (!handoff) return;
console.info("[chat-handoff] received", handoff);
@@ -2138,7 +2182,7 @@ export function ChatPage(): ReactElement {
return () => {
canceled = true;
};
- }, []);
+ }, [active, navigate]);
const tourSteps = useMemo(
() =>
@@ -2183,15 +2227,14 @@ export function ChatPage(): ReactElement {
(view.mode === "compare" || artifactSurface === "overlay"),
);
- if (!isCurrentChatRoute) {
- return (
- <div className="flex min-h-0 min-w-0 flex-1 basis-0 bg-background" />
- );
- }
-
return (
+ // Provides `active` to ChatRuntimeProvider (drops the message views/composers
+ // while off-route, keeping the runtime alive) and to the compare chrome.
+ <ChatActiveContext.Provider value={active}>
<div className="flex min-h-0 min-w-0 flex-1 basis-0 bg-background overflow-hidden">
- <GuidedTour {...tour.tourProps} />
+ {/* Portaled surfaces render to document.body, escaping the parent's hidden
+ wrapper, so gate them on `active` to keep them off other tabs. */}
+ {active && <GuidedTour {...tour.tourProps} />}
<div className="relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden">
<NativeModelDropOverlay state={nativeModelDropState} />
{/* Fade under the top bar so messages dissolve as they scroll
@@ -2227,7 +2270,7 @@ export function ChatPage(): ReactElement {
onModelsChange={refreshModelLists}
deleteDisabled={modelOperationInProgress}
variant="ghost"
- open={modelSelectorOpen}
+ open={active && modelSelectorOpen}
onOpenChange={handleModelSelectorOpenChange}
triggerDataTour="chat-model-selector"
contentDataTour="chat-model-selector-popover"
@@ -2378,8 +2421,14 @@ export function ChatPage(): ReactElement {
items={currentProjectItems}
/>
) : view.mode === "single" ? (
+ // Keyed by project only (not thread / new-chat nonce) so switching threads or
+ // starting a New Chat reuses the same provider and switches in place. This keeps
+ // an in-flight generation streaming in the background (assistant-ui keeps every
+ // alive thread's runtime mounted) instead of remounting the provider and cutting
+ // it off; returning to that thread reattaches the live run rather than reloading
+ // a half-saved one.
<SingleContent
- key={view.threadId ?? view.newThreadNonce ?? "single"}
+ key={view.projectId ?? "single"}
threadId={view.threadId}
newThreadNonce={view.newThreadNonce}
projectId={view.projectId}
@@ -2402,7 +2451,7 @@ export function ChatPage(): ReactElement {
/>
)}
- {showArtifactOverlay && selectedArtifact ? (
+ {active && showArtifactOverlay && selectedArtifact ? (
<ArtifactSurface
artifact={selectedArtifact}
variant="overlay"
@@ -2412,7 +2461,7 @@ export function ChatPage(): ReactElement {
</div>
<ChatSettingsPanel
- open={settingsOpen}
+ open={active && settingsOpen}
onOpenChange={(open) => {
setSettingsOpen(open);
// Closing the sheet abandons a staged (not-yet-loaded) pick: cancel its
@@ -2488,5 +2537,6 @@ export function ChatPage(): ReactElement {
}
/>
</div>
+ </ChatActiveContext.Provider>
);
}
diff --git a/studio/frontend/src/features/chat/components/project-switcher.tsx b/studio/frontend/src/features/chat/components/project-switcher.tsx
index df0d51f606c..e17a1d139e6 100644
--- a/studio/frontend/src/features/chat/components/project-switcher.tsx
+++ b/studio/frontend/src/features/chat/components/project-switcher.tsx
@@ -12,7 +12,8 @@ import { Folder01Icon } from "@hugeicons/core-free-icons";
import { Tick02Icon } from "@/lib/tick-icon";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import type { ReactElement } from "react";
+import { type ReactElement, useState } from "react";
+import { useChatActive } from "../runtime-provider";
import type { ProjectRecord } from "../types";
export function ProjectSwitcher({
@@ -32,8 +33,12 @@ export function ProjectSwitcher({
const showEmptyRow = !isLoading && projects.length === 0;
const label = currentProject?.name ?? (isLoading ? "Project" : "Projects");
+ // Controlled so the body-portaled dropdown can't linger over another tab off-route.
+ const active = useChatActive();
+ const [open, setOpen] = useState(false);
+
return (
- <DropdownMenu>
+ <DropdownMenu open={active && open} onOpenChange={(o) => setOpen(active && o)}>
<DropdownMenuTrigger asChild={true}>
<button
type="button"
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 7bb8d71a71f..7777fdb7e91 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -513,11 +513,26 @@ export function useChatModelRuntime() {
const validateNativePathLease = nativePathToken
? (await consumeNativePathToken(nativePathToken, "validate-model")).nativePathLease
: undefined;
+ // Validate with the same effective context /load uses: a GGUF native
+ // context can exceed maxSeqLength, so sizing on raw maxSeqLength could
+ // pass, unload, then have /load refuse it. Read pre-unload state; load
+ // recomputes its own value, so this leaves loading untouched.
+ const preUnloadState = useChatRuntimeStore.getState();
+ const validateMaxSeqLength = resolveLoadMaxSeqLength({
+ modelId,
+ ggufVariant,
+ customContextLength: preUnloadState.customContextLength,
+ ggufContextLength: preUnloadState.ggufContextLength,
+ currentCheckpoint,
+ activeGgufVariant: preUnloadState.activeGgufVariant,
+ maxSeqLength,
+ presetSource: preUnloadState.activePresetSource,
+ });
const validation = await validateModel({
model_path: modelId,
nativePathLease: validateNativePathLease,
hf_token: hfToken,
- max_seq_length: maxSeqLength,
+ max_seq_length: validateMaxSeqLength,
load_in_4bit: true,
is_lora: isLora,
gguf_variant: ggufVariant ?? null,
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index dec5f405056..75749b0040b 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-export { ChatPage } from "./chat-page";
+export { ChatPage, validateChatSearch, type ChatSearch } from "./chat-page";
export {
getInferenceStatus,
listGgufVariants,
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 3de3ef6dab7..d08d5ef6aff 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -26,7 +26,9 @@ import mammoth from "mammoth";
import {
type ReactElement,
type ReactNode,
+ createContext,
useCallback,
+ useContext,
useEffect,
useMemo,
useRef,
@@ -1271,6 +1273,15 @@ function ThreadBackendAutosave({
return null;
}
+// True when the chat tab is visible. While false, ChatPage stays mounted (runtime +
+// autosave alive, so the stream survives) but its views/composers unmount, so no
+// body-portaled surface bleeds over the active tab. Defaults true for use elsewhere.
+export const ChatActiveContext = createContext(true);
+
+export function useChatActive(): boolean {
+ return useContext(ChatActiveContext);
+}
+
export function ChatRuntimeProvider({
children,
modelType = "base",
@@ -1319,6 +1330,9 @@ export function ChatRuntimeProvider({
{!initialThreadId && newThreadNonce && (
<ThreadNewChatSwitch nonce={newThreadNonce} />
)}
+ {/* The view stays mounted (only CSS-hidden by RootLayout) while off-route
+ so assistant-ui keeps the run attached and the stream alive. Unmounting
+ it here aborts the in-flight generation. */}
{children}
</AssistantRuntimeProvider>
);
diff --git a/studio/frontend/src/features/export/anim.ts b/studio/frontend/src/features/export/anim.ts
deleted file mode 100644
index e313dc1a6ee..00000000000
--- a/studio/frontend/src/features/export/anim.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-export const collapseAnim = {
- initial: { height: 0, opacity: 0 },
- animate: { height: "auto" as const, opacity: 1 },
- exit: { height: 0, opacity: 0 },
- transition: { duration: 0.3, ease: [0.25, 0.1, 0.25, 1] as const },
-};
diff --git a/studio/frontend/src/features/export/api/export-api.ts b/studio/frontend/src/features/export/api/export-api.ts
index 5cd944e67bd..659dd44f885 100644
--- a/studio/frontend/src/features/export/api/export-api.ts
+++ b/studio/frontend/src/features/export/api/export-api.ts
@@ -6,13 +6,45 @@ import { readFastApiError } from "@/lib/format-fastapi-error";
const readError = (r: Response): Promise<string> => readFastApiError(r);
+/**
+ * Error from an export request that preserves the HTTP status, so callers can
+ * tell an authoritative backend rejection (4xx) from a transport timeout that
+ * the long export may survive (e.g. Cloudflare's 524 over a quick tunnel).
+ */
+export class ExportRequestError extends Error {
+ status: number | null;
+ constructor(message: string, status: number | null) {
+ super(message);
+ this.name = "ExportRequestError";
+ this.status = status;
+ }
+}
+
async function parseJson<T>(response: Response): Promise<T> {
if (!response.ok) {
- throw new Error(await readError(response));
+ throw new ExportRequestError(await readError(response), response.status);
}
return (await response.json()) as T;
}
+/**
+ * Whether an error from an export POST is a recoverable transport failure (the
+ * backend op may still be running and may still succeed) rather than an
+ * authoritative rejection. A Cloudflare quick tunnel returns 524 (and friends
+ * 520/522/523) when a request runs past ~100s; a dropped connection surfaces as
+ * a status-less network error from authFetch. Real 4xx (400/404/409/422) are
+ * the backend saying no and must fail immediately.
+ */
+export function isRecoverableTransportError(err: unknown): boolean {
+ if (err instanceof ExportRequestError) {
+ // 502/503/504 gateway + 520/522/523/524 Cloudflare timeouts are recoverable.
+ return typeof err.status === "number" ? err.status >= 502 : true;
+ }
+ // No HTTP status at all (authFetch threw on a fetch TypeError = network drop /
+ // backend unreachable): indeterminate, so recover by polling status.
+ return err instanceof Error;
+}
+
export interface CheckpointInfo {
display_name: string;
path: string;
@@ -159,6 +191,43 @@ export async function cleanupExport(): Promise<ExportOperationResponse> {
return parseJson<ExportOperationResponse>(response);
}
+/**
+ * Cancel the in-flight export by terminating its worker subprocess. Training
+ * and inference are left running. Always resolves (best-effort) so callers can
+ * fire it without guarding for a missing active run.
+ */
+export async function cancelExport(): Promise<ExportOperationResponse> {
+ const response = await authFetch("/api/export/cancel", { method: "POST" });
+ return parseJson<ExportOperationResponse>(response);
+}
+
+export interface ExportStatus {
+ current_checkpoint: string | null;
+ is_vision: boolean;
+ is_peft: boolean;
+ /** True while a load / export / cleanup operation is running on the backend. */
+ is_export_active: boolean;
+ /** Kind of the currently running op (load_checkpoint / export_* / cleanup). */
+ active_op_kind?: string | null;
+ /** Monotonic counter of finished ops; baseline to detect "my op finished". */
+ last_op_seq?: number;
+ last_op_kind?: string | null;
+ /** Outcome of the most recently finished op. */
+ last_op_status?: "success" | "error" | "cancelled" | null;
+ last_op_output_path?: string | null;
+ last_op_error?: string | null;
+}
+
+/**
+ * Snapshot of the export backend, used to hydrate the runtime store on mount /
+ * page reload so a still-running export (started in another tab, or before a
+ * refresh) is reflected even though the in-memory store reset.
+ */
+export async function getExportStatus(): Promise<ExportStatus> {
+ const response = await authFetch("/api/export/status");
+ return parseJson<ExportStatus>(response);
+}
+
// ─────────────────────────────────────────────────────────────────────
// Live export log stream (Server-Sent Events)
// ─────────────────────────────────────────────────────────────────────
@@ -171,6 +240,37 @@ export interface ExportLogEntry {
ts: number | null;
}
+/** A log line from the JSON poll endpoint, carrying its ring-buffer seq. */
+export interface ExportLogPollEntry extends ExportLogEntry {
+ seq: number;
+}
+
+export interface ExportLogsResponse {
+ entries: ExportLogPollEntry[];
+ /** Highest seq returned; pass back as `since` on the next poll. */
+ cursor: number;
+ /** True while a load / export / cleanup op is running on the backend. */
+ active: boolean;
+}
+
+/**
+ * Tunnel-safe JSON fallback for {@link streamExportLogs}. Cloudflare quick
+ * tunnels (`--secure` mode) buffer `text/event-stream`, so the SSE stream
+ * delivers nothing until it closes; this plain-JSON poll is never buffered and
+ * carries the same ring-buffer lines. Poll it while a run is active and merge
+ * the entries into the store (de-duped by seq), so logs appear over the tunnel.
+ */
+export async function fetchExportLogs(
+ since: number | null,
+): Promise<ExportLogsResponse> {
+ const url =
+ typeof since === "number"
+ ? `/api/export/logs?since=${since}`
+ : "/api/export/logs";
+ const response = await authFetch(url);
+ return parseJson<ExportLogsResponse>(response);
+}
+
export type ExportLogEventName = "log" | "heartbeat" | "complete" | "error";
export interface ExportLogEvent {
diff --git a/studio/frontend/src/features/export/components/export-dialog.tsx b/studio/frontend/src/features/export/components/export-dialog.tsx
deleted file mode 100644
index c366f0cdeb0..00000000000
--- a/studio/frontend/src/features/export/components/export-dialog.tsx
+++ /dev/null
@@ -1,694 +0,0 @@
-// 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 { Button } from "@/components/ui/button";
-import { FolderBrowser } from "@/components/assistant-ui/model-selector/folder-browser";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
-import {
- InputGroup,
- InputGroupAddon,
- InputGroupInput,
-} from "@/components/ui/input-group";
-import { Spinner } from "@/components/ui/spinner";
-import { Switch } from "@/components/ui/switch";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
-import { AlertCircleIcon, ArrowRight01Icon, CheckmarkCircle02Icon, FolderSearchIcon, Key01Icon } from "@hugeicons/core-free-icons";
-import { HugeiconsIcon } from "@hugeicons/react";
-import { AnimatePresence, motion } from "motion/react";
-import { useEffect, useRef, useState } from "react";
-import { streamExportLogs, type ExportLogEntry } from "../api/export-api";
-import { collapseAnim } from "../anim";
-import { EXPORT_METHODS, type ExportMethod } from "../constants";
-
-// Max log lines kept in local state. Matches the backend ring buffer's maxlen
-// so the UI shows the full server-side scrollback.
-const MAX_LOG_LINES = 4000;
-
-interface UseExportLogsResult {
- lines: ExportLogEntry[];
- connected: boolean;
- error: string | null;
-}
-
-/**
- * Subscribe to the live export log SSE stream while `exporting` is true and
- * accumulate lines. Prior-action lines are cleared when a new export starts and
- * when the user switches method / reopens / closes the dialog, so reopening
- * into a different action doesn't show stale output.
- */
-function useExportLogs(
- exporting: boolean,
- exportMethod: ExportMethod | null,
- open: boolean,
-): UseExportLogsResult {
- const [lines, setLines] = useState<ExportLogEntry[]>([]);
- const [connected, setConnected] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- // Reset log state on screen change (method switch or dialog reopen) so each
- // (open × method) shows only its own run history. The streaming effect below
- // additionally clears on new export start.
- useEffect(() => {
- setLines([]);
- setError(null);
- setConnected(false);
- }, [exportMethod, open]);
-
- useEffect(() => {
- if (!exporting) return;
-
- setLines([]);
- setError(null);
-
- const abortCtrl = new AbortController();
- let cancelled = false;
- // Highest seq seen on a `log` event, to resume via `since=` / Last-Event-ID
- // after a drop. The backend's SSE `id:` field carries this as ExportLogEvent.id.
- let lastSeq: number | null = null;
- // Capped exponential backoff with jitter; reset on each successful connect
- // so flaky networks don't accumulate delay.
- let backoffMs = 500;
- const MAX_BACKOFF_MS = 5000;
- // Set by a terminal event (backend `complete` or a non-retryable error) to
- // stop the reconnect loop even while `exporting` is still true.
- let terminated = false;
-
- const run = async () => {
- while (!cancelled && !terminated) {
- try {
- await streamExportLogs({
- signal: abortCtrl.signal,
- since: lastSeq,
- onOpen: () => {
- if (cancelled) return;
- setConnected(true);
- // Reset backoff on every successful connect so later
- // drops don't inherit accumulated delay from earlier ones.
- backoffMs = 500;
- },
- onEvent: (event) => {
- if (cancelled) return;
- if (event.event === "log" && event.entry) {
- if (typeof event.id === "number") {
- lastSeq = event.id;
- }
- const entry = event.entry;
- setLines((prev) => {
- const next = prev.length >= MAX_LOG_LINES
- ? prev.slice(prev.length - MAX_LOG_LINES + 1)
- : prev.slice();
- next.push(entry);
- return next;
- });
- } else if (event.event === "complete") {
- // Run fully drained -- stop reconnecting even if `exporting`
- // hasn't flipped false yet on this tick.
- terminated = true;
- } else if (event.event === "error" && event.error) {
- setError(event.error);
- }
- },
- });
- } catch (err: unknown) {
- if (cancelled) return;
- if (err instanceof DOMException && err.name === "AbortError") return;
- setError(err instanceof Error ? err.message : String(err));
- // Fall through to backoff; a fetch-level failure retries like a clean EOF.
- }
-
- setConnected(false);
- if (cancelled || terminated) return;
-
- // Exponential backoff with jitter before reconnecting. Ring buffer +
- // Last-Event-ID resume means no lines lost across the retry as long as
- // the reconnect lands within the buffer's lifetime (~4000 lines).
- const delay = backoffMs + Math.floor(Math.random() * 250);
- backoffMs = Math.min(backoffMs * 2, MAX_BACKOFF_MS);
- try {
- await new Promise<void>((resolve, reject) => {
- if (abortCtrl.signal.aborted) {
- reject(new DOMException("Aborted", "AbortError"));
- return;
- }
- const timeoutId = window.setTimeout(resolve, delay);
- abortCtrl.signal.addEventListener(
- "abort",
- () => {
- window.clearTimeout(timeoutId);
- reject(new DOMException("Aborted", "AbortError"));
- },
- { once: true },
- );
- });
- } catch {
- return;
- }
- }
- };
-
- // run() handles every failure path; swallow stragglers so React's dev
- // overlay doesn't flag an unhandled rejection on dialog close.
- void run().catch(() => {});
-
- return () => {
- cancelled = true;
- abortCtrl.abort();
- setConnected(false);
- };
- }, [exporting]);
-
- return { lines, connected, error };
-}
-
-/**
- * Tick every second while `exporting` is true and report elapsed seconds.
- * Powers the "Working… 27s" badge so the panel doesn't look frozen during long
- * single-step phases (cache copy, GGUF conversion) with no new lines.
- */
-function useElapsedSeconds(exporting: boolean): number {
- const [elapsed, setElapsed] = useState(0);
- useEffect(() => {
- if (!exporting) {
- setElapsed(0);
- return;
- }
- const startedAt = Date.now();
- setElapsed(0);
- const id = window.setInterval(() => {
- setElapsed(Math.floor((Date.now() - startedAt) / 1000));
- }, 1000);
- return () => window.clearInterval(id);
- }, [exporting]);
- return elapsed;
-}
-
-function formatElapsed(seconds: number): string {
- if (seconds < 60) return `${seconds}s`;
- const m = Math.floor(seconds / 60);
- const s = seconds % 60;
- return `${m}m ${s.toString().padStart(2, "0")}s`;
-}
-
-function formatLogLine(entry: ExportLogEntry): string {
- // Strip trailing CRs from tqdm-style progress so scrollback doesn't render boxes.
- return entry.line.replace(/\r+$/g, "");
-}
-
-function isAbsoluteFolderPath(path: string): boolean {
- return path.startsWith("/") || /^[A-Za-z]:([\\/]|$)/.test(path) || /^\\\\/.test(path);
-}
-
-type Destination = "local" | "hub";
-
-interface ExportDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- checkpoint: string | null;
- exportMethod: ExportMethod | null;
- quantLevels: string[];
- estimatedSize: string;
- baseModelName: string;
- isAdapter: boolean;
- destination: Destination;
- onDestinationChange: (v: Destination) => void;
- saveDirectory: string;
- defaultSaveDirectory: string;
- saveDirectoryOverridden: boolean;
- onSaveDirectoryChange: (v: string | null) => void;
- hfUsername: string;
- onHfUsernameChange: (v: string) => void;
- modelName: string;
- onModelNameChange: (v: string) => void;
- hfToken: string;
- onHfTokenChange: (v: string) => void;
- privateRepo: boolean;
- onPrivateRepoChange: (v: boolean) => void;
- onExport: () => void;
- exporting: boolean;
- exportError: string | null;
- exportSuccess: boolean;
- /**
- * Resolved on-disk realpath of the latest successful export, shown on the
- * Export Complete screen. Null when the export only pushed to the Hub.
- */
- exportOutputPath: string | null;
-}
-
-export function ExportDialog({
- open,
- onOpenChange,
- checkpoint,
- exportMethod,
- quantLevels,
- estimatedSize,
- baseModelName,
- isAdapter,
- destination,
- onDestinationChange,
- saveDirectory,
- defaultSaveDirectory,
- saveDirectoryOverridden,
- onSaveDirectoryChange,
- hfUsername,
- onHfUsernameChange,
- modelName,
- onModelNameChange,
- hfToken,
- onHfTokenChange,
- privateRepo,
- onPrivateRepoChange,
- onExport,
- exporting,
- exportError,
- exportSuccess,
- exportOutputPath,
-}: ExportDialogProps) {
- // Live log capture applies to any backend-worker export path, incl. LoRA-only.
- const showLogPanel =
- exportMethod === "merged" ||
- exportMethod === "gguf" ||
- exportMethod === "lora";
- const showCompletionScreen = exportSuccess && !showLogPanel;
- const [folderBrowserOpen, setFolderBrowserOpen] = useState(false);
-
- const { lines: logLines, connected: logConnected, error: logError } =
- useExportLogs(exporting && showLogPanel, exportMethod, open);
- const elapsedSeconds = useElapsedSeconds(exporting && showLogPanel);
-
- const logScrollRef = useRef<HTMLDivElement | null>(null);
- // Auto-scroll to bottom on each new line, unless the user scrolled up.
- const [followTail, setFollowTail] = useState(true);
-
- useEffect(() => {
- if (!followTail) return;
- const el = logScrollRef.current;
- if (el) el.scrollTop = el.scrollHeight;
- }, [logLines, followTail]);
-
- const handleLogScroll = () => {
- const el = logScrollRef.current;
- if (!el) return;
- const nearBottom =
- el.scrollHeight - el.scrollTop - el.clientHeight < 24;
- setFollowTail(nearBottom);
- };
-
- return (
- <>
- <Dialog
- open={open}
- onOpenChange={(v) => {
- if (exporting) return;
- onOpenChange(v);
- }}
- >
- <DialogContent
- className={showLogPanel ? "sm:max-w-2xl" : "sm:max-w-lg"}
- onInteractOutside={(e) => { if (exporting) e.preventDefault(); }}
- >
- {showCompletionScreen ? (
- <>
- <div className="flex flex-col items-center gap-3 py-6">
- <div className="flex size-12 items-center justify-center rounded-full bg-emerald-500/10">
- <HugeiconsIcon icon={CheckmarkCircle02Icon} className="size-6 text-emerald-500" />
- </div>
- <div className="flex flex-col items-center gap-2 text-center">
- <h3 className="text-lg font-semibold">Export Complete</h3>
- <p className="text-sm text-muted-foreground">
- {destination === "hub"
- ? "Model successfully pushed to Hugging Face Hub."
- : "Model saved locally."}
- </p>
- {exportOutputPath ? (
- <div className="mt-1 flex w-full max-w-md flex-col items-stretch gap-1 rounded-lg border border-border/40 bg-muted/40 px-3 py-2 text-left">
- <span className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
- Saved to
- </span>
- <code
- className="select-all break-all font-mono text-[12px] text-foreground"
- title={exportOutputPath}
- >
- {exportOutputPath}
- </code>
- </div>
- ) : null}
- </div>
- </div>
- <DialogFooter>
- <Button onClick={() => onOpenChange(false)}>Done</Button>
- </DialogFooter>
- </>
- ) : (
- <>
- <DialogHeader>
- <DialogTitle>Export Model</DialogTitle>
- <DialogDescription>
- Choose where to save your exported model.
- </DialogDescription>
- </DialogHeader>
-
- <div className="flex gap-2">
- <Button
- variant={destination === "local" ? "dark" : "outline"}
- onClick={() => onDestinationChange("local")}
- disabled={exporting}
- className="flex-1"
- >
- Save Locally
- </Button>
- <Button
- variant={destination === "hub" ? "dark" : "outline"}
- onClick={() => onDestinationChange("hub")}
- disabled={exporting}
- className="flex-1"
- >
- Push to Hub
- </Button>
- </div>
-
- {destination === "local" && (
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between gap-2">
- <label className="text-xs font-medium text-muted-foreground">
- Save folder
- </label>
- {saveDirectoryOverridden && (
- <Button
- type="button"
- variant="ghost"
- size="xs"
- onClick={() => onSaveDirectoryChange(null)}
- disabled={exporting}
- >
- Use default
- </Button>
- )}
- </div>
- <div className="flex items-stretch gap-2">
- <Input
- className="min-w-0 flex-1 font-mono text-[12px]"
- value={saveDirectory}
- onChange={(e) => onSaveDirectoryChange(e.target.value)}
- disabled={exporting}
- spellCheck={false}
- title={saveDirectory}
- placeholder={defaultSaveDirectory}
- />
- <Tooltip>
- <TooltipTrigger asChild={true}>
- <Button
- type="button"
- variant="outline"
- size="icon"
- onClick={() => setFolderBrowserOpen(true)}
- disabled={exporting}
- aria-label="Browse save folder"
- >
- <HugeiconsIcon icon={FolderSearchIcon} className="size-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- Browse
- </TooltipContent>
- </Tooltip>
- </div>
- <p className="text-[11px] text-muted-foreground/70">
- {saveDirectory !== defaultSaveDirectory ? (
- <>
- Default: {defaultSaveDirectory}
- </>
- ) : (
- <>
- Paste an absolute path if the folder browser cannot reach the drive.
- </>
- )}
- </p>
- </div>
- )}
-
- <AnimatePresence>
- {destination === "hub" && (
- <motion.div {...collapseAnim} className="overflow-hidden">
- <div className="flex flex-col gap-4 px-0.5">
- <div className="grid grid-cols-2 gap-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-xs font-medium text-muted-foreground">
- Username / Org
- </label>
- <Input
- placeholder="your-username"
- value={hfUsername}
- onChange={(e) => onHfUsernameChange(e.target.value)}
- disabled={exporting}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-xs font-medium text-muted-foreground">
- Model Name
- </label>
- <Input
- placeholder="my-model-gguf"
- value={modelName}
- onChange={(e) => onModelNameChange(e.target.value)}
- disabled={exporting}
- />
- </div>
- </div>
-
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <label className="text-xs font-medium text-muted-foreground">
- HF Write Token
- </label>
- <a
- href="https://huggingface.co/settings/tokens"
- target="_blank"
- rel="noopener noreferrer"
- className="flex items-center gap-1 text-[11px] text-emerald-600 hover:text-emerald-700 transition-colors"
- >
- Get token
- <HugeiconsIcon
- icon={ArrowRight01Icon}
- className="size-3"
- />
- </a>
- </div>
- <InputGroup>
- <InputGroupAddon>
- <HugeiconsIcon icon={Key01Icon} className="size-4" />
- </InputGroupAddon>
- <InputGroupInput
- type="password"
- autoComplete="new-password"
- name="hf-token"
- placeholder="hf_..."
- value={hfToken}
- onChange={(e) => onHfTokenChange(e.target.value)}
- disabled={exporting}
- />
- </InputGroup>
- <p className="text-[11px] text-muted-foreground/70">
- Leave empty if already logged in via CLI.
- </p>
- </div>
-
- <div className="flex items-center gap-3">
- <Switch
- id="private-repo"
- size="sm"
- checked={privateRepo}
- onCheckedChange={onPrivateRepoChange}
- disabled={exporting}
- />
- <label
- htmlFor="private-repo"
- className="text-xs font-medium cursor-pointer"
- >
- Private Repository
- </label>
- </div>
- </div>
- </motion.div>
- )}
- </AnimatePresence>
-
- {/* Success banner: keep users on the log screen after completion so
- they can inspect conversion output before closing. */}
- {exportSuccess && showLogPanel && (
- <div className="flex items-start gap-2 rounded-lg bg-emerald-500/10 p-3 text-sm text-emerald-700 dark:text-emerald-300">
- <HugeiconsIcon icon={CheckmarkCircle02Icon} className="mt-0.5 size-4 shrink-0" />
- <div className="flex min-w-0 flex-col gap-1">
- <span>
- {destination === "hub"
- ? "Export finished and pushed to Hugging Face Hub."
- : "Export finished successfully."}
- </span>
- {exportOutputPath ? (
- <code className="select-all break-all font-mono text-[12px] text-foreground/90" title={exportOutputPath}>
- {exportOutputPath}
- </code>
- ) : null}
- </div>
- </div>
- )}
-
- {/* Error banner */}
- {exportError && (
- <div className="flex items-start gap-2 rounded-lg bg-destructive/10 p-3 text-sm text-destructive">
- <HugeiconsIcon icon={AlertCircleIcon} className="size-4 mt-0.5 shrink-0" />
- <span>{exportError}</span>
- </div>
- )}
-
- {/* Summary */}
- <div className="rounded-xl bg-muted/50 p-3 text-xs text-muted-foreground flex flex-col gap-1">
- <div className="flex justify-between">
- <span>Base Model</span>
- <span className="font-medium text-foreground">{baseModelName}</span>
- </div>
- <div className="flex justify-between">
- <span>{isAdapter ? "Checkpoint" : "Model"}</span>
- <span className="font-medium text-foreground">{checkpoint}</span>
- </div>
- <div className="flex justify-between">
- <span>Export Method</span>
- <span className="font-medium text-foreground">
- {EXPORT_METHODS.find((m) => m.value === exportMethod)?.title}
- </span>
- </div>
- {exportMethod === "gguf" && quantLevels.length > 0 && (
- <div className="flex justify-between">
- <span>Quantizations</span>
- <span className="font-medium text-foreground">
- {quantLevels.join(", ")}
- </span>
- </div>
- )}
- {estimatedSize && (
- <div className="flex justify-between">
- <span>Est. size</span>
- <span className="font-medium text-foreground">
- {estimatedSize}
- </span>
- </div>
- )}
- </div>
-
- {/* Live export output panel */}
- <AnimatePresence>
- {showLogPanel && (exporting || logLines.length > 0) && (
- <motion.div {...collapseAnim} className="overflow-hidden">
- <div className="flex flex-col gap-1.5 pt-1">
- <div className="flex items-center justify-between">
- <label className="text-xs font-medium text-muted-foreground">
- Export output
- </label>
- <div className="flex items-center gap-2 text-[11px] text-muted-foreground/80">
- <span
- className={
- logConnected
- ? "inline-block size-1.5 rounded-full bg-emerald-500"
- : "inline-block size-1.5 rounded-full bg-muted-foreground/40"
- }
- />
- <span>
- {logConnected
- ? "streaming"
- : exporting
- ? "connecting..."
- : "idle"}
- </span>
- {exporting && elapsedSeconds > 0 ? (
- <span className="tabular-nums text-muted-foreground/70">
- · {formatElapsed(elapsedSeconds)}
- </span>
- ) : null}
- </div>
- </div>
- <div
- ref={logScrollRef}
- onScroll={handleLogScroll}
- className="h-56 w-full overflow-auto rounded-lg border border-border/40 bg-black/85 p-3 font-mono text-[11px] leading-[1.45] text-emerald-200/90"
- >
- {logLines.length === 0 ? (
- <div className="flex h-full items-center justify-center text-muted-foreground/70">
- <span className="flex items-center gap-2">
- <Spinner className="size-3" />
- Waiting for worker output...
- </span>
- </div>
- ) : (
- <pre className="whitespace-pre-wrap break-words">
- {logLines.map((entry, idx) => (
- <div
- key={idx}
- className={
- entry.stream === "stderr"
- ? "text-rose-300/90"
- : entry.stream === "status"
- ? "text-sky-300/90"
- : ""
- }
- >
- {formatLogLine(entry)}
- </div>
- ))}
- </pre>
- )}
- </div>
- {logError && (
- <p className="text-[11px] text-destructive/80">
- Log stream: {logError}
- </p>
- )}
- </div>
- </motion.div>
- )}
- </AnimatePresence>
-
- <DialogFooter>
- <Button
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={exporting}
- >
- {exportSuccess ? "Done" : "Cancel"}
- </Button>
- <Button onClick={onExport} disabled={exporting || exportSuccess}>
- {exporting ? (
- <span className="flex items-center gap-2">
- <Spinner className="size-4" />
- Exporting…
- </span>
- ) : exportSuccess ? (
- "Export Complete"
- ) : (
- "Start Export"
- )}
- </Button>
- </DialogFooter>
- </>
- )}
- </DialogContent>
- </Dialog>
- <FolderBrowser
- open={folderBrowserOpen}
- onOpenChange={setFolderBrowserOpen}
- initialPath={isAbsoluteFolderPath(saveDirectory) ? saveDirectory : undefined}
- onSelect={(path) => onSaveDirectoryChange(path)}
- />
- </>
- );
-}
diff --git a/studio/frontend/src/features/export/components/export-run-panel.tsx b/studio/frontend/src/features/export/components/export-run-panel.tsx
new file mode 100644
index 00000000000..9a4f0ee1372
--- /dev/null
+++ b/studio/frontend/src/features/export/components/export-run-panel.tsx
@@ -0,0 +1,572 @@
+// 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 { Button } from "@/components/ui/button";
+import { FolderBrowser } from "@/components/assistant-ui/model-selector/folder-browser";
+import { Input } from "@/components/ui/input";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@/components/ui/input-group";
+import { Progress } from "@/components/ui/progress";
+import { Spinner } from "@/components/ui/spinner";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ AlertCircleIcon,
+ ArrowRight01Icon,
+ CancelCircleIcon,
+ CheckmarkCircle02Icon,
+ FolderSearchIcon,
+ Key01Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useEffect, useRef, useState } from "react";
+import { useShallow } from "zustand/react/shallow";
+import { EXPORT_METHODS, type ExportMethod } from "../constants";
+import type { ExportLogEntry } from "../api/export-api";
+import {
+ selectExportProgressPercent,
+ useExportRuntimeStore,
+ type ExportDestination,
+} from "../stores/export-runtime-store";
+
+function useElapsedSeconds(startedAt: number | null, running: boolean): number {
+ // `now` is only advanced by the interval (never set synchronously in the
+ // effect body), so the elapsed value is derived during render. When `running`
+ // flips false the interval stops and `now` freezes, holding the final time.
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!running || startedAt == null) return;
+ const id = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(id);
+ }, [running, startedAt]);
+ if (startedAt == null) return 0;
+ return Math.max(0, Math.floor((now - startedAt) / 1000));
+}
+
+function formatElapsed(seconds: number): string {
+ if (seconds < 60) return `${seconds}s`;
+ const m = Math.floor(seconds / 60);
+ const s = seconds % 60;
+ return `${m}m ${s.toString().padStart(2, "0")}s`;
+}
+
+function formatLogLine(entry: ExportLogEntry): string {
+ return entry.line.replace(/\r+$/g, "");
+}
+
+function isAbsoluteFolderPath(path: string): boolean {
+ return (
+ path.startsWith("/") ||
+ /^[A-Za-z]:([\\/]|$)/.test(path) ||
+ /^\\\\/.test(path)
+ );
+}
+
+const PHASE_LABELS: Record<string, string> = {
+ idle: "Ready",
+ loading: "Loading model",
+ exporting: "Exporting",
+ success: "Complete",
+ error: "Failed",
+ canceled: "Canceled",
+};
+
+// Shown in the terminal before the first worker line arrives (it can lag a few
+// seconds behind, especially over a tunnel). Reflects the phase so the panel
+// never looks stuck while the progress bar is already advancing.
+function waitingMessage(phase: string, stage: string | null): string {
+ if (stage) return stage;
+ if (phase === "loading") return "Loading model into the export worker...";
+ if (phase === "exporting") return "Preparing export...";
+ return "Starting...";
+}
+
+export interface ExportRunPanelProps {
+ exportMethod: ExportMethod | null;
+ quantLevels: string[];
+ checkpoint: string | null;
+ baseModelName: string;
+ isAdapter: boolean;
+ destination: ExportDestination;
+ onDestinationChange: (v: ExportDestination) => void;
+ saveDirectory: string;
+ defaultSaveDirectory: string;
+ saveDirectoryOverridden: boolean;
+ onSaveDirectoryChange: (v: string | null) => void;
+ hfUsername: string;
+ onHfUsernameChange: (v: string) => void;
+ modelName: string;
+ onModelNameChange: (v: string) => void;
+ hfToken: string;
+ onHfTokenChange: (v: string) => void;
+ privateRepo: boolean;
+ onPrivateRepoChange: (v: boolean) => void;
+ /** Kick off the export (the page assembles params and calls the store). */
+ onStart: () => void;
+ /** Collapse the panel; only offered before a run or after a terminal one. */
+ onClose: () => void;
+}
+
+export function ExportRunPanel(props: ExportRunPanelProps) {
+ const {
+ exportMethod,
+ quantLevels,
+ checkpoint,
+ baseModelName,
+ isAdapter,
+ destination,
+ onDestinationChange,
+ saveDirectory,
+ defaultSaveDirectory,
+ saveDirectoryOverridden,
+ onSaveDirectoryChange,
+ hfUsername,
+ onHfUsernameChange,
+ modelName,
+ onModelNameChange,
+ hfToken,
+ onHfTokenChange,
+ privateRepo,
+ onPrivateRepoChange,
+ onStart,
+ onClose,
+ } = props;
+
+ const run = useExportRuntimeStore(
+ useShallow((s) => ({
+ phase: s.phase,
+ isExporting: s.isExporting,
+ logLines: s.logLines,
+ connected: s.connected,
+ reconnecting: s.reconnecting,
+ stage: s.stage,
+ quantIndex: s.quantIndex,
+ quantTotal: s.quantTotal,
+ startedAt: s.startedAt,
+ result: s.result,
+ error: s.error,
+ summary: s.summary,
+ })),
+ );
+ const requestCancel = useExportRuntimeStore((s) => s.requestCancel);
+ const progress = useExportRuntimeStore(selectExportProgressPercent);
+
+ const isExporting = run.isExporting;
+ const isTerminal =
+ run.phase === "success" || run.phase === "error" || run.phase === "canceled";
+ const showConfig = run.phase === "idle";
+ // Gate the log area on the active run's method (from the store) as well as the
+ // local form selection, so it stays visible after navigating away and back
+ // (the form `exportMethod` resets on remount, but the run does not).
+ const panelMethod = run.summary?.method ?? exportMethod;
+ const showLogPanel =
+ isExporting ||
+ run.logLines.length > 0 ||
+ panelMethod === "merged" ||
+ panelMethod === "gguf" ||
+ panelMethod === "lora";
+
+ const elapsedSeconds = useElapsedSeconds(run.startedAt, isExporting);
+
+ const [folderBrowserOpen, setFolderBrowserOpen] = useState(false);
+ const logScrollRef = useRef<HTMLDivElement | null>(null);
+ const [followTail, setFollowTail] = useState(true);
+
+ useEffect(() => {
+ if (!followTail) return;
+ const el = logScrollRef.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ }, [run.logLines, followTail]);
+
+ const handleLogScroll = () => {
+ const el = logScrollRef.current;
+ if (!el) return;
+ const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
+ setFollowTail(nearBottom);
+ };
+
+ const methodTitle = EXPORT_METHODS.find((m) => m.value === exportMethod)?.title;
+ const summary = run.summary;
+ const summaryBaseModel = summary?.baseModelName ?? baseModelName;
+ const summaryCheckpoint = summary?.checkpointLabel ?? checkpoint;
+ const summaryMethodLabel = summary?.methodLabel ?? methodTitle;
+ const summaryQuants = summary?.quantLevels ?? quantLevels;
+ const summaryMethod = summary?.method ?? exportMethod;
+ const showProgress = isExporting || isTerminal;
+
+ return (
+ <div className="flex flex-col gap-4 rounded-2xl border border-border/50 bg-muted/20 p-4">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex flex-col gap-0.5">
+ <h3 className="text-sm font-semibold">
+ {showConfig ? "Export Model" : "Export"}
+ </h3>
+ <p className="text-xs text-muted-foreground">
+ {showConfig
+ ? "Choose where to save your exported model."
+ : "Runs in the background. You can keep training and chatting while it exports."}
+ </p>
+ </div>
+ {(showConfig || isTerminal) && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Close export panel"
+ onClick={onClose}
+ >
+ <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />
+ </Button>
+ )}
+ </div>
+
+ {/* Destination configuration (only before a run starts) */}
+ {showConfig && (
+ <>
+ <div className="flex gap-2">
+ <Button
+ variant={destination === "local" ? "dark" : "outline"}
+ onClick={() => onDestinationChange("local")}
+ className="flex-1"
+ >
+ Save Locally
+ </Button>
+ <Button
+ variant={destination === "hub" ? "dark" : "outline"}
+ onClick={() => onDestinationChange("hub")}
+ className="flex-1"
+ >
+ Push to Hub
+ </Button>
+ </div>
+
+ {destination === "local" && (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between gap-2">
+ <label className="text-xs font-medium text-muted-foreground">
+ Save folder
+ </label>
+ {saveDirectoryOverridden && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() => onSaveDirectoryChange(null)}
+ >
+ Use default
+ </Button>
+ )}
+ </div>
+ <div className="flex items-stretch gap-2">
+ <Input
+ className="min-w-0 flex-1 font-mono text-[12px]"
+ value={saveDirectory}
+ onChange={(e) => onSaveDirectoryChange(e.target.value)}
+ spellCheck={false}
+ title={saveDirectory}
+ placeholder={defaultSaveDirectory}
+ />
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ onClick={() => setFolderBrowserOpen(true)}
+ aria-label="Browse save folder"
+ >
+ <HugeiconsIcon icon={FolderSearchIcon} className="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Browse</TooltipContent>
+ </Tooltip>
+ </div>
+ <p className="text-[11px] text-muted-foreground/70">
+ {saveDirectory !== defaultSaveDirectory ? (
+ <>Default: {defaultSaveDirectory}</>
+ ) : (
+ <>
+ Paste an absolute path if the folder browser cannot reach the
+ drive.
+ </>
+ )}
+ </p>
+ </div>
+ )}
+
+ {destination === "hub" && (
+ <div className="flex flex-col gap-4 px-0.5">
+ <div className="grid grid-cols-2 gap-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-xs font-medium text-muted-foreground">
+ Username / Org
+ </label>
+ <Input
+ placeholder="your-username"
+ value={hfUsername}
+ onChange={(e) => onHfUsernameChange(e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-xs font-medium text-muted-foreground">
+ Model Name
+ </label>
+ <Input
+ placeholder="my-model-gguf"
+ value={modelName}
+ onChange={(e) => onModelNameChange(e.target.value)}
+ />
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <label className="text-xs font-medium text-muted-foreground">
+ HF Write Token
+ </label>
+ <a
+ href="https://huggingface.co/settings/tokens"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex items-center gap-1 text-[11px] text-emerald-600 hover:text-emerald-700 transition-colors"
+ >
+ Get token
+ <HugeiconsIcon icon={ArrowRight01Icon} className="size-3" />
+ </a>
+ </div>
+ <InputGroup>
+ <InputGroupAddon>
+ <HugeiconsIcon icon={Key01Icon} className="size-4" />
+ </InputGroupAddon>
+ <InputGroupInput
+ type="password"
+ autoComplete="new-password"
+ name="hf-token"
+ placeholder="hf_..."
+ value={hfToken}
+ onChange={(e) => onHfTokenChange(e.target.value)}
+ />
+ </InputGroup>
+ <p className="text-[11px] text-muted-foreground/70">
+ Leave empty if already logged in via CLI.
+ </p>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <Switch
+ id="export-private-repo"
+ size="sm"
+ checked={privateRepo}
+ onCheckedChange={onPrivateRepoChange}
+ />
+ <label
+ htmlFor="export-private-repo"
+ className="text-xs font-medium cursor-pointer"
+ >
+ Private Repository
+ </label>
+ </div>
+ </div>
+ )}
+ </>
+ )}
+
+ {/* Result banners */}
+ {run.phase === "success" && (
+ <div className="flex items-start gap-2 rounded-lg bg-emerald-500/10 p-3 text-sm text-emerald-700 dark:text-emerald-300">
+ <HugeiconsIcon
+ icon={CheckmarkCircle02Icon}
+ className="mt-0.5 size-4 shrink-0"
+ />
+ <div className="flex min-w-0 flex-col gap-1">
+ <span>
+ {run.result?.destination === "hub"
+ ? "Export finished and pushed to Hugging Face Hub."
+ : "Export finished successfully."}
+ </span>
+ {run.result?.outputPath ? (
+ <code
+ className="select-all break-all font-mono text-[12px] text-foreground/90"
+ title={run.result.outputPath}
+ >
+ {run.result.outputPath}
+ </code>
+ ) : null}
+ </div>
+ </div>
+ )}
+
+ {run.phase === "canceled" && (
+ <div className="flex items-start gap-2 rounded-lg bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-300">
+ <HugeiconsIcon icon={CancelCircleIcon} className="mt-0.5 size-4 shrink-0" />
+ <span>Export canceled. Training and inference were not affected.</span>
+ </div>
+ )}
+
+ {run.phase === "error" && run.error && (
+ <div className="flex items-start gap-2 rounded-lg bg-destructive/10 p-3 text-sm text-destructive">
+ <HugeiconsIcon icon={AlertCircleIcon} className="size-4 mt-0.5 shrink-0" />
+ <span>{run.error}</span>
+ </div>
+ )}
+
+ {/* Summary */}
+ <div className="rounded-xl bg-muted/50 p-3 text-xs text-muted-foreground flex flex-col gap-1">
+ <div className="flex justify-between">
+ <span>Base Model</span>
+ <span className="font-medium text-foreground">{summaryBaseModel}</span>
+ </div>
+ <div className="flex justify-between">
+ <span>{isAdapter ? "Checkpoint" : "Model"}</span>
+ <span className="font-medium text-foreground">{summaryCheckpoint}</span>
+ </div>
+ <div className="flex justify-between">
+ <span>Export Method</span>
+ <span className="font-medium text-foreground">{summaryMethodLabel}</span>
+ </div>
+ {summaryMethod === "gguf" && summaryQuants.length > 0 && (
+ <div className="flex justify-between">
+ <span>Quantizations</span>
+ <span className="font-medium text-foreground">
+ {summaryQuants.join(", ")}
+ </span>
+ </div>
+ )}
+ </div>
+
+ {/* Progress */}
+ {showProgress && (
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="rounded-full bg-foreground/10 px-2.5 py-1 text-[10px] font-semibold">
+ {PHASE_LABELS[run.phase] ?? run.phase}
+ </span>
+ {summaryMethod === "gguf" && run.quantTotal > 1 && (
+ <span className="text-[10px] tabular-nums text-muted-foreground">
+ Quant {Math.min(run.quantIndex + (isExporting ? 1 : 0), run.quantTotal)} of {run.quantTotal}
+ </span>
+ )}
+ <span className="rounded-full border border-border/60 px-2.5 py-1 text-[10px] font-medium tabular-nums text-muted-foreground">
+ {progress}%
+ </span>
+ <span className="text-[10px] tabular-nums text-muted-foreground/70">
+ {formatElapsed(elapsedSeconds)}
+ </span>
+ </div>
+ <Progress
+ value={progress}
+ className="h-2 bg-foreground/[0.05]"
+ indicatorClassName={
+ run.phase === "error"
+ ? "bg-destructive"
+ : run.phase === "canceled"
+ ? "bg-amber-500"
+ : undefined
+ }
+ />
+ {run.stage && (
+ <p className="truncate text-[11px] text-muted-foreground/80" title={run.stage}>
+ {run.stage}
+ </p>
+ )}
+ </div>
+ )}
+
+ {/* Live export output */}
+ {showLogPanel && (isExporting || run.logLines.length > 0) && (
+ <div className="flex flex-col gap-1.5 pt-1">
+ <div className="flex items-center justify-between">
+ <label className="text-xs font-medium text-muted-foreground">
+ Export output
+ </label>
+ <div className="flex items-center gap-2 text-[11px] text-muted-foreground/80">
+ <span
+ className={
+ run.reconnecting
+ ? "inline-block size-1.5 rounded-full bg-amber-500"
+ : run.connected
+ ? "inline-block size-1.5 rounded-full bg-emerald-500"
+ : "inline-block size-1.5 rounded-full bg-muted-foreground/40"
+ }
+ />
+ <span>
+ {run.reconnecting
+ ? "reconnecting..."
+ : run.connected
+ ? "streaming"
+ : isExporting
+ ? "connecting..."
+ : "idle"}
+ </span>
+ </div>
+ </div>
+ <div
+ ref={logScrollRef}
+ onScroll={handleLogScroll}
+ className="h-56 w-full overflow-auto rounded-lg border border-border/40 bg-black/85 p-3 font-mono text-[11px] leading-[1.45] text-emerald-200/90"
+ >
+ {run.logLines.length === 0 ? (
+ <div className="flex h-full items-center justify-center text-muted-foreground/70">
+ <span className="flex items-center gap-2">
+ <Spinner className="size-3" />
+ {waitingMessage(run.phase, run.stage)}
+ </span>
+ </div>
+ ) : (
+ <pre className="whitespace-pre-wrap break-words">
+ {run.logLines.map((entry, idx) => (
+ <div
+ key={idx}
+ className={
+ entry.stream === "stderr"
+ ? "text-rose-300/90"
+ : entry.stream === "status"
+ ? "text-sky-300/90"
+ : ""
+ }
+ >
+ {formatLogLine(entry)}
+ </div>
+ ))}
+ </pre>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Footer actions */}
+ <div className="flex justify-end gap-2">
+ {showConfig && (
+ <>
+ <Button variant="outline" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button onClick={onStart}>Start Export</Button>
+ </>
+ )}
+ {isExporting && (
+ <Button variant="destructive" onClick={() => void requestCancel()}>
+ Cancel Export
+ </Button>
+ )}
+ {isTerminal && <Button onClick={onClose}>Done</Button>}
+ </div>
+
+ <FolderBrowser
+ open={folderBrowserOpen}
+ onOpenChange={setFolderBrowserOpen}
+ initialPath={
+ isAbsoluteFolderPath(saveDirectory) ? saveDirectory : undefined
+ }
+ onSelect={(path) => onSaveDirectoryChange(path)}
+ />
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/export/components/method-picker.tsx b/studio/frontend/src/features/export/components/method-picker.tsx
index 78cec2cd73d..282b7c99f87 100644
--- a/studio/frontend/src/features/export/components/method-picker.tsx
+++ b/studio/frontend/src/features/export/components/method-picker.tsx
@@ -63,12 +63,12 @@ export function MethodPicker({ value, onChange, disabledMethods = [], disabledRe
disabled={isDisabled}
onClick={() => !isDisabled && onChange(m.value)}
className={cn(
- "flex items-start gap-3 rounded-xl p-4 text-left ring-1 transition-all",
+ "flex items-start gap-3 rounded-xl p-4 text-left ring-1 transition-colors",
isDisabled
? "ring-border opacity-40 cursor-not-allowed"
: selected
? "ring-2 ring-primary bg-primary/5"
- : "ring-border hover:-translate-y-0.5 hover:shadow-sm",
+ : "ring-border hover:bg-muted/40",
)}
>
<div
diff --git a/studio/frontend/src/features/export/components/quant-picker.tsx b/studio/frontend/src/features/export/components/quant-picker.tsx
index 192cbeaeee4..dadc959e55a 100644
--- a/studio/frontend/src/features/export/components/quant-picker.tsx
+++ b/studio/frontend/src/features/export/components/quant-picker.tsx
@@ -75,7 +75,7 @@ export function QuantPicker({ value, onChange, sizes }: QuantPickerProps) {
type="button"
onClick={() => toggle(q.value)}
className={cn(
- "inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium ring-1 transition-all",
+ "inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium ring-1 transition-colors",
active
? "ring-primary bg-primary/10 text-foreground"
: "ring-border text-muted-foreground hover:text-foreground hover:ring-foreground/20",
diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsx
index 72128cb44bd..14022f4d19c 100644
--- a/studio/frontend/src/features/export/export-page.tsx
+++ b/studio/frontend/src/features/export/export-page.tsx
@@ -44,6 +44,7 @@ import {
} from "@/hooks";
import {
AlertCircleIcon,
+ ArrowDown01Icon,
FolderSearchIcon,
InformationCircleIcon,
Key01Icon,
@@ -51,29 +52,24 @@ import {
Search01Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { AnimatePresence, motion } from "motion/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";
-import { collapseAnim } from "./anim";
import type { ModelCheckpoints } from "./api/export-api";
-import {
- cleanupExport,
- exportBase,
- exportGGUF,
- exportLoRA,
- exportMerged,
- fetchCheckpoints,
- loadCheckpoint,
-} from "./api/export-api";
-import { ExportDialog } from "./components/export-dialog";
+import { fetchCheckpoints } from "./api/export-api";
+import { ExportRunPanel } from "./components/export-run-panel";
import { MethodPicker } from "./components/method-picker";
import { QuantPicker } from "./components/quant-picker";
import {
+ EXPORT_METHODS,
type ExportMethod,
GUIDE_STEPS,
buildQuantSizeLabels,
getEstimatedSize,
} from "./constants";
+import {
+ isExportPanelActive,
+ useExportRuntimeStore,
+} from "./stores/export-runtime-store";
import { useExportSizeEstimate } from "./hooks/use-export-size-estimate";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { exportTourSteps } from "./tour";
@@ -142,9 +138,24 @@ export function ExportPage() {
const debouncedModelQuery = useDebouncedValue(modelInput);
const debouncedHfToken = useDebouncedValue(hfToken, 500);
- const [exportMethod, setExportMethod] = useState<ExportMethod | null>(null);
- const [quantLevels, setQuantLevels] = useState<string[]>([]);
- const [dialogOpen, setDialogOpen] = useState(false);
+ // Seed the method + quants from a live run so that navigating away and back
+ // (which remounts this page) keeps the method card selected and the run panel
+ // showing its logs/progress. The run itself lives in the global store; only
+ // this form state is local and would otherwise reset to null on remount.
+ const [exportMethod, setExportMethod] = useState<ExportMethod | null>(() => {
+ const s = useExportRuntimeStore.getState();
+ return isExportPanelActive(s) && s.summary ? s.summary.method : null;
+ });
+ const [quantLevels, setQuantLevels] = useState<string[]>(() => {
+ const s = useExportRuntimeStore.getState();
+ return isExportPanelActive(s) && s.summary?.method === "gguf"
+ ? s.summary.quantLevels
+ : [];
+ });
+ // Whether the inline export panel is expanded. The panel also shows itself
+ // whenever a run is active/terminal (see `panelActive`), so it survives
+ // navigation even though this local flag resets on remount.
+ const [panelOpen, setPanelOpen] = useState(false);
const [destination, setDestination] = useState<"local" | "hub">("local");
const [customSaveDirectory, setCustomSaveDirectory] = useState<string | null>(
@@ -154,12 +165,12 @@ export function ExportPage() {
const [modelName, setModelName] = useState("");
const [privateRepo, setPrivateRepo] = useState(false);
- const [exporting, setExporting] = useState(false);
- const [exportError, setExportError] = useState<string | null>(null);
- const [exportSuccess, setExportSuccess] = useState(false);
- // On-disk path of the last successful export, shown on the Export Complete
- // screen so the user can find their model. Null for Hub-only pushes.
- const [exportOutputPath, setExportOutputPath] = useState<string | null>(null);
+ // Export run state lives in the global runtime store so it keeps running and
+ // streaming in the background, in parallel with training and inference.
+ const runExport = useExportRuntimeStore((s) => s.runExport);
+ const resetExportRun = useExportRuntimeStore((s) => s.reset);
+ const isExporting = useExportRuntimeStore((s) => s.isExporting);
+ const panelActive = useExportRuntimeStore(isExportPanelActive);
const hfComboboxAnchorRef = useRef<HTMLDivElement>(null);
const localComboboxAnchorRef = useRef<HTMLDivElement>(null);
@@ -484,131 +495,86 @@ export function ExportPage() {
[],
);
- // ---- Export handler ----
- const handleExport = useCallback(async () => {
+ // ---- Export handlers ----
+ // Assemble the run params from the current form and hand off to the global
+ // runtime store, which drives load -> export -> cleanup in the background.
+ const handleStart = useCallback(async () => {
const source = sourceMode === "checkpoint" ? checkpoint : selectedSourceModel;
- if (!source) return;
+ if (!source || !exportMethod) return;
+ // A GGUF export with no quant selected runs zero exports yet would still
+ // settle as success with no file; require at least one (mirrors canExport).
+ if (exportMethod === "gguf" && quantLevels.length === 0) return;
const selectedCp = sourceMode === "checkpoint"
? checkpointsForModel.find((cp) => cp.display_name === checkpoint)
: null;
if (sourceMode === "checkpoint" && !selectedCp) return;
- const checkpointPath = selectedCp?.path;
-
- setExporting(true);
- setExportError(null);
- setExportSuccess(false);
- setExportOutputPath(null);
+ const checkpointPath = selectedCp?.path ?? null;
const pushToHub = destination === "hub";
const repoId = pushToHub && hfUsername && modelName
? `${hfUsername}/${modelName}`
: undefined;
const token = pushToHub && hfToken ? hfToken : undefined;
-
- try {
- // 1. Load model source
- if (sourceMode === "checkpoint") {
- if (!checkpointPath) return;
- await loadCheckpoint({
- checkpoint_path: checkpointPath,
- hf_token: hfToken || null,
- });
- } else {
- // Consent gate for an HF source's custom (auto_map) code: the only way to enable
- // trust_remote_code here. A local checkpoint the user exported is trusted by default.
- let trustRemoteCode = modelSource !== "hf";
- let approvedRemoteCodeFingerprint: string | null = null;
- const remoteCodeOk = await confirmRemoteCodeIfNeeded({
- modelName: source,
- hfToken: hfToken || null,
- // An HF source can need trust_remote_code via its YAML default with no auto_map
- // to review; signal it so a YAML-only model does not export with it false.
- requiresTrustRemoteCode: modelSource === "hf",
- onApprove: (fingerprint) => {
- trustRemoteCode = true;
- approvedRemoteCodeFingerprint = fingerprint;
- },
- });
- if (!remoteCodeOk) return;
-
- await loadCheckpoint({
- checkpoint_path: source,
- load_in_4bit: false,
- trust_remote_code: trustRemoteCode,
- approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,
- hf_token: hfToken || null,
- });
- }
-
- // 2. Run export. Capture the resolved output_path (when the backend
- // wrote a local copy) for the success screen. Multi-quant GGUF runs
- // share one directory, so we just keep the last response.
- let lastOutputPath: string | null = null;
- if (exportMethod === "merged") {
- if (isAdapter) {
- const resp = await exportMerged({
- save_directory: saveDirectory,
- push_to_hub: pushToHub,
- repo_id: repoId,
- hf_token: token,
- private: privateRepo,
- });
- lastOutputPath = resp.details?.output_path ?? null;
- } else {
- const resp = await exportBase({
- save_directory: saveDirectory,
- push_to_hub: pushToHub,
- repo_id: repoId,
- hf_token: token,
- private: privateRepo,
- base_model_id: selectedModelData?.base_model,
- });
- lastOutputPath = resp.details?.output_path ?? null;
- }
- } else if (exportMethod === "gguf") {
- for (const quant of quantLevels) {
- const resp = await exportGGUF({
- save_directory: saveDirectory,
- quantization_method: quant,
- push_to_hub: pushToHub,
- repo_id: repoId,
- hf_token: token,
- });
- lastOutputPath = resp.details?.output_path ?? lastOutputPath;
- }
- } else if (exportMethod === "lora") {
- const resp = await exportLoRA({
- save_directory: saveDirectory,
- push_to_hub: pushToHub,
- repo_id: repoId,
- hf_token: token,
- private: privateRepo,
- });
- lastOutputPath = resp.details?.output_path ?? null;
- }
-
- setExportOutputPath(lastOutputPath);
- setExportSuccess(true);
- } catch (err) {
- setExportError(
- err instanceof Error ? err.message : "Export failed",
- );
- } finally {
- try {
- await cleanupExport();
- } catch {
- // cleanup is best-effort
- }
- setExporting(false);
+ const methodLabel =
+ EXPORT_METHODS.find((m) => m.value === exportMethod)?.title ?? exportMethod;
+ const adapterExport = sourceMode === "checkpoint" && isAdapter;
+
+ // Consent gate for an HF source's custom (auto_map) code, run before we hand
+ // off to runExport (which performs the load in the background). A local
+ // checkpoint/model the user exported is trusted by default.
+ let trustRemoteCode = modelSource !== "hf";
+ let approvedRemoteCodeFingerprint: string | null = null;
+ if (sourceMode !== "checkpoint") {
+ const remoteCodeOk = await confirmRemoteCodeIfNeeded({
+ modelName: source,
+ hfToken: hfToken || null,
+ // An HF source can need trust_remote_code via its YAML default with no
+ // auto_map to review; signal it so a YAML-only model does not export
+ // with it false.
+ requiresTrustRemoteCode: modelSource === "hf",
+ onApprove: (fingerprint) => {
+ trustRemoteCode = true;
+ approvedRemoteCodeFingerprint = fingerprint;
+ },
+ });
+ if (!remoteCodeOk) return;
}
+
+ void runExport({
+ sourceMode,
+ checkpointPath,
+ source,
+ modelSource,
+ trustRemoteCode,
+ approvedRemoteCodeFingerprint,
+ loadToken: hfToken || null,
+ exportMethod,
+ isAdapter: adapterExport,
+ quantLevels,
+ saveDirectory,
+ destination,
+ repoId,
+ token,
+ privateRepo,
+ baseModelId: selectedModelData?.base_model ?? undefined,
+ summary: {
+ baseModelName: sourceBaseModelName,
+ checkpointLabel: selectedExportSource,
+ methodLabel,
+ method: exportMethod,
+ quantLevels,
+ destination,
+ },
+ });
}, [
checkpoint,
checkpointsForModel,
sourceMode,
selectedSourceModel,
- selectedModelIdx,
selectedModelData,
+ selectedExportSource,
+ sourceBaseModelName,
exportMethod,
isAdapter,
quantLevels,
@@ -619,8 +585,53 @@ export function ExportPage() {
hfToken,
privateRepo,
modelSource,
+ runExport,
]);
+ // Open the inline panel into a fresh config state. Clears any previous
+ // terminal run (a still-running export cannot be cleared, so it stays).
+ const handleOpenPanel = useCallback(() => {
+ if (!isExporting) {
+ resetExportRun();
+ }
+ setPanelOpen(true);
+ }, [isExporting, resetExportRun]);
+
+ // Collapse the panel. Only reachable from config / terminal states (never
+ // mid-run), so resetting the store back to idle is safe.
+ const handleClosePanel = useCallback(() => {
+ resetExportRun();
+ setPanelOpen(false);
+ }, [resetExportRun]);
+
+ const showPanel = panelOpen || panelActive;
+
+ // Bring the panel into view when it opens and offer a scroll-down affordance
+ // (like Chat) when its end is below the fold.
+ const panelEndRef = useRef<HTMLDivElement>(null);
+ const [panelEndVisible, setPanelEndVisible] = useState(true);
+
+ useEffect(() => {
+ if (!showPanel) return;
+ const id = window.setTimeout(() => {
+ panelEndRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
+ }, 60);
+ return () => window.clearTimeout(id);
+ }, [showPanel]);
+
+ useEffect(() => {
+ const el = panelEndRef.current;
+ if (!showPanel || !el) return;
+ // The scroll-down button is also gated on showPanel, so there is no need to
+ // reset visibility when the panel closes; the observer self-corrects on open.
+ const obs = new IntersectionObserver(
+ ([entry]) => setPanelEndVisible(entry.isIntersecting),
+ { rootMargin: "0px 0px -40px 0px" },
+ );
+ obs.observe(el);
+ return () => obs.disconnect();
+ }, [showPanel]);
+
// ---- Render ----
return (
<div className="min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] bg-background">
@@ -701,16 +712,8 @@ export function ExportPage() {
</button>
</div>
- <AnimatePresence mode="wait" initial={false}>
{sourceMode === "checkpoint" ? (
- <motion.div
- key="checkpoint"
- initial={{ height: 0, opacity: 0 }}
- animate={{ height: "auto", opacity: 1 }}
- exit={{ height: 0, opacity: 0 }}
- transition={{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }}
- className="flex flex-col gap-2 overflow-visible"
- >
+ <div className="flex flex-col gap-2 overflow-visible">
<div data-tour="export-training-run" className="flex flex-col gap-2">
<Select
value={selectedModelIdx ?? ""}
@@ -822,16 +825,9 @@ export function ExportPage() {
</SelectContent>
</Select>
</div>
- </motion.div>
+ </div>
) : (
- <motion.div
- key="model"
- initial={{ height: 0, opacity: 0 }}
- animate={{ height: "auto", opacity: 1 }}
- exit={{ height: 0, opacity: 0 }}
- transition={{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }}
- className="flex flex-col gap-2 overflow-visible"
- >
+ <div className="flex flex-col gap-2 overflow-visible">
<div className="flex gap-2">
<Button
variant={modelSource === "hf" ? "dark" : "outline"}
@@ -1028,9 +1024,8 @@ export function ExportPage() {
Direct model exports currently support GGUF only.
</p>
</div>
- </motion.div>
+ </div>
)}
- </AnimatePresence>
{sourceMode === "checkpoint" && (
<div className="rounded-xl bg-foreground/[0.04] p-3 flex flex-col gap-2">
@@ -1106,75 +1101,84 @@ export function ExportPage() {
}
/>
- <AnimatePresence>
- {exportMethod === "gguf" && (
- <motion.div {...collapseAnim} className="overflow-visible">
- <QuantPicker
- value={quantLevels}
- onChange={setQuantLevels}
- sizes={quantSizeLabels}
- />
- </motion.div>
- )}
- </AnimatePresence>
+ {exportMethod === "gguf" && (
+ <QuantPicker
+ value={quantLevels}
+ onChange={setQuantLevels}
+ sizes={quantSizeLabels}
+ />
+ )}
+ {estimatedSize && (
+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <HugeiconsIcon
+ icon={InformationCircleIcon}
+ className="size-3.5"
+ />
+ <span>Est. size: {estimatedSize}</span>
+ </div>
+ )}
<Separator />
- <div className="flex items-center justify-between">
- {estimatedSize ? (
- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
- <HugeiconsIcon
- icon={InformationCircleIcon}
- className="size-3.5"
+ {showPanel && (
+ <ExportRunPanel
+ exportMethod={exportMethod}
+ quantLevels={quantLevels}
+ checkpoint={selectedExportSource}
+ baseModelName={sourceBaseModelName}
+ isAdapter={sourceMode === "checkpoint" && isAdapter}
+ destination={destination}
+ onDestinationChange={setDestination}
+ saveDirectory={saveDirectory}
+ defaultSaveDirectory={defaultSaveDirectory}
+ saveDirectoryOverridden={!!customSaveDirectory}
+ onSaveDirectoryChange={setCustomSaveDirectory}
+ hfUsername={hfUsername}
+ onHfUsernameChange={setHfUsername}
+ modelName={modelName}
+ onModelNameChange={setModelName}
+ hfToken={hfToken}
+ onHfTokenChange={setHfToken}
+ privateRepo={privateRepo}
+ onPrivateRepoChange={setPrivateRepo}
+ onStart={handleStart}
+ onClose={handleClosePanel}
/>
- <span>Est. size: {estimatedSize}</span>
- </div>
- ) : (
- <span />
)}
- <Button
- data-tour="export-cta"
- disabled={!canExport}
- onClick={() => { setExportSuccess(false); setExportError(null); setDialogOpen(true); }}
+ {showPanel && (
+ <div ref={panelEndRef} aria-hidden="true" className="h-px w-full" />
+ )}
+ {showPanel && !panelEndVisible && (
+ <button
+ type="button"
+ onClick={() =>
+ panelEndRef.current?.scrollIntoView({
+ behavior: "smooth",
+ block: "end",
+ })
+ }
+ aria-label="Scroll to export output"
+ className="fixed bottom-6 right-6 z-30 flex size-10 items-center justify-center rounded-full border border-border/60 bg-background/90 text-foreground shadow-md backdrop-blur transition-colors hover:bg-muted"
>
- Export Model
- </Button>
- </div>
+ <HugeiconsIcon icon={ArrowDown01Icon} className="size-5" />
+ </button>
+ )}
+ {!showPanel && (
+ <div className="flex items-center justify-end">
+ <Button
+ data-tour="export-cta"
+ disabled={!canExport}
+ onClick={handleOpenPanel}
+ >
+ Export Model
+ </Button>
+ </div>
+ )}
</>
)}
</SectionCard>
<RecentTrainingsSection />
</main>
-
- <ExportDialog
- open={dialogOpen}
- onOpenChange={setDialogOpen}
- exportMethod={exportMethod}
- quantLevels={quantLevels}
- estimatedSize={estimatedSize}
- checkpoint={selectedExportSource}
- baseModelName={sourceBaseModelName}
- isAdapter={sourceMode === "checkpoint" && isAdapter}
- destination={destination}
- onDestinationChange={setDestination}
- saveDirectory={saveDirectory}
- defaultSaveDirectory={defaultSaveDirectory}
- saveDirectoryOverridden={!!customSaveDirectory}
- onSaveDirectoryChange={setCustomSaveDirectory}
- hfUsername={hfUsername}
- onHfUsernameChange={setHfUsername}
- modelName={modelName}
- onModelNameChange={setModelName}
- hfToken={hfToken}
- onHfTokenChange={setHfToken}
- privateRepo={privateRepo}
- onPrivateRepoChange={setPrivateRepo}
- onExport={handleExport}
- exporting={exporting}
- exportError={exportError}
- exportSuccess={exportSuccess}
- exportOutputPath={exportOutputPath}
- />
</div>
);
}
diff --git a/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts b/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts
new file mode 100644
index 00000000000..cdf771f2b76
--- /dev/null
+++ b/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts
@@ -0,0 +1,204 @@
+// 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 { hasAuthToken } from "@/features/auth";
+import { useEffect } from "react";
+import {
+ fetchExportLogs,
+ getExportStatus,
+ streamExportLogs,
+} from "../api/export-api";
+import { useExportRuntimeStore } from "../stores/export-runtime-store";
+
+const STATUS_POLL_INTERVAL_MS = 5000;
+const STREAM_RECONNECT_DELAY_MS = 600;
+// JSON log poll cadence. The SSE stream is the low-latency path on localhost,
+// but Cloudflare quick tunnels (`--secure`) buffer `text/event-stream`, so this
+// poll is the transport that actually delivers logs over the tunnel. Short
+// JSON responses are never buffered, so this works through any proxy.
+const LOG_POLL_INTERVAL_MS = 750;
+
+/**
+ * Global export runtime driver, mounted once at the app root so it runs on every
+ * route (the inline export panel lives on /export, but the run must stay live and
+ * visible from any tab). It:
+ * - hydrates `is_export_active` from the backend on mount / reload,
+ * - streams the worker log SSE into the store while a run is active, and
+ * - keeps that stream alive across the load -> export phase boundary so a
+ * transient `complete` between per-phase POSTs does not strand the panel on
+ * "Waiting for worker output..." (the premature-complete bug).
+ *
+ * The actual export sequence is driven by the store's `runExport` action (a
+ * detached promise), so it survives navigation independently of this hook.
+ */
+export function useExportRuntimeLifecycle(): void {
+ useEffect(() => {
+ let disposed = false;
+ let openingStream = false;
+ let streamController: AbortController | null = null;
+ let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ let logPolling = false;
+ let logPollTimer: ReturnType<typeof setTimeout> | null = null;
+
+ const store = useExportRuntimeStore;
+
+ const clearReconnect = () => {
+ if (reconnectTimer) {
+ clearTimeout(reconnectTimer);
+ reconnectTimer = null;
+ }
+ };
+
+ const stopStream = () => {
+ clearReconnect();
+ if (streamController) {
+ streamController.abort();
+ streamController = null;
+ }
+ stopLogPolling();
+ store.getState().setConnected(false);
+ };
+
+ // ── JSON log polling (tunnel-safe fallback) ──────────────────────────
+ // Runs for the whole active run, in parallel with the SSE stream. On
+ // localhost the SSE delivers first and these polls are de-duped away by
+ // seq; over a Cloudflare tunnel the SSE is buffered and these polls are
+ // what actually fill the log panel. A successful poll marks the stream
+ // "connected" so the panel shows "streaming" rather than "connecting...".
+ const pollLogsOnce = async () => {
+ if (disposed || !store.getState().isExporting) return;
+ try {
+ const res = await fetchExportLogs(store.getState().lastSeq);
+ if (disposed) return;
+ store.getState().setConnected(true);
+ if (res.entries.length > 0) {
+ store.getState().appendLogs(res.entries);
+ }
+ } catch {
+ // Transient poll failure: the next poll (or the SSE) will catch up.
+ }
+ };
+
+ const logPollLoop = async () => {
+ if (disposed || !logPolling) return;
+ await pollLogsOnce();
+ if (disposed || !logPolling) return;
+ logPollTimer = setTimeout(() => {
+ void logPollLoop();
+ }, LOG_POLL_INTERVAL_MS);
+ };
+
+ const startLogPolling = () => {
+ if (logPolling || disposed) return;
+ logPolling = true;
+ void logPollLoop();
+ };
+
+ function stopLogPolling() {
+ logPolling = false;
+ if (logPollTimer) {
+ clearTimeout(logPollTimer);
+ logPollTimer = null;
+ }
+ }
+
+ const ensureStream = async () => {
+ if (
+ disposed ||
+ openingStream ||
+ streamController ||
+ !store.getState().isExporting
+ ) {
+ return;
+ }
+
+ clearReconnect();
+ openingStream = true;
+ const controller = new AbortController();
+ streamController = controller;
+
+ try {
+ await streamExportLogs({
+ signal: controller.signal,
+ since: store.getState().lastSeq,
+ onOpen: () => store.getState().setConnected(true),
+ onEvent: (event) => {
+ if (event.event === "log" && event.entry) {
+ store.getState().appendLog(event.entry, event.id ?? undefined);
+ }
+ // `complete` / `error` end this connection (streamExportLogs returns);
+ // the finally block reconnects while the run is still in flight.
+ },
+ });
+ } catch {
+ // fetch-level failure: fall through to the reconnect below.
+ } finally {
+ openingStream = false;
+ if (streamController === controller) {
+ streamController = null;
+ }
+ // Do NOT clear `connected` here: over a Cloudflare tunnel the SSE drops
+ // and reconnects repeatedly (buffered / premature complete), which used
+ // to flap the indicator back to "connecting...". The log poll owns the
+ // connected flag for the duration of the run; stopStream clears it when
+ // the run actually ends.
+
+ if (
+ !disposed &&
+ !controller.signal.aborted &&
+ store.getState().isExporting
+ ) {
+ reconnectTimer = setTimeout(() => {
+ void ensureStream();
+ }, STREAM_RECONNECT_DELAY_MS);
+ }
+ }
+ };
+
+ const pollStatus = async () => {
+ if (!hasAuthToken()) return;
+ try {
+ const status = await getExportStatus();
+ if (disposed) return;
+ store.getState().applyBackendStatus(status);
+ if (store.getState().isExporting) {
+ void ensureStream();
+ startLogPolling();
+ }
+ } catch {
+ // ignore transient status failures
+ }
+ };
+
+ // React to isExporting flipping (run start / terminal) without needing the
+ // subscribeWithSelector middleware: the base subscribe fires on every change.
+ let prevExporting = store.getState().isExporting;
+ const unsubscribe = store.subscribe((state) => {
+ if (state.isExporting === prevExporting) return;
+ prevExporting = state.isExporting;
+ if (state.isExporting) {
+ void ensureStream();
+ startLogPolling();
+ } else {
+ stopStream();
+ }
+ });
+
+ void pollStatus();
+ if (store.getState().isExporting) {
+ void ensureStream();
+ startLogPolling();
+ }
+
+ const statusTimer = setInterval(() => {
+ void pollStatus();
+ }, STATUS_POLL_INTERVAL_MS);
+
+ return () => {
+ disposed = true;
+ clearInterval(statusTimer);
+ unsubscribe();
+ stopStream();
+ };
+ }, []);
+}
diff --git a/studio/frontend/src/features/export/index.ts b/studio/frontend/src/features/export/index.ts
index ba529a842d6..e3323dffa53 100644
--- a/studio/frontend/src/features/export/index.ts
+++ b/studio/frontend/src/features/export/index.ts
@@ -1,4 +1,20 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-export { ExportPage } from "./export-page";
+// The heavy ExportPage is not re-exported here on purpose: the /export route
+// lazy-imports it directly (app/routes/export.tsx) so it stays code-split. This
+// barrel exposes only the lightweight export runtime so the always-mounted root
+// layout and the sidebar can use it without pulling ExportPage into their chunk.
+export {
+ isExportPanelActive,
+ selectExportProgressPercent,
+ useExportRuntimeStore,
+} from "./stores/export-runtime-store";
+export type {
+ ExportDestination,
+ ExportPhase,
+ ExportRunSummary,
+ ExportRuntimeStore,
+ RunExportParams,
+} from "./stores/export-runtime-store";
+export { useExportRuntimeLifecycle } from "./hooks/use-export-runtime-lifecycle";
diff --git a/studio/frontend/src/features/export/stores/export-runtime-store.ts b/studio/frontend/src/features/export/stores/export-runtime-store.ts
new file mode 100644
index 00000000000..307e1ccaabf
--- /dev/null
+++ b/studio/frontend/src/features/export/stores/export-runtime-store.ts
@@ -0,0 +1,566 @@
+// 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 { create } from "zustand";
+import {
+ cancelExport,
+ cleanupExport,
+ exportBase,
+ exportGGUF,
+ exportLoRA,
+ exportMerged,
+ getExportStatus,
+ isRecoverableTransportError,
+ loadCheckpoint,
+ type ExportLogEntry,
+ type ExportLogPollEntry,
+ type ExportOperationResponse,
+ type ExportStatus,
+} from "../api/export-api";
+import type { ExportMethod } from "../constants";
+
+/** Thrown by status recovery when the backend reports the op was cancelled. */
+class ExportCanceledError extends Error {
+ constructor() {
+ super("Export canceled");
+ this.name = "ExportCanceledError";
+ }
+}
+
+// Status-recovery tuning (used when a blocking export POST is cut off by a
+// Cloudflare tunnel 524 while the backend op keeps running).
+const RECOVERY_POLL_INTERVAL_MS = 1500;
+const RECOVERY_GRACE_MS = 15000; // wait this long for the op to appear on status
+const RECOVERY_MAX_MS = 2 * 60 * 60 * 1000; // hard cap (exports can be long)
+const RECOVERY_MAX_STATUS_FAILS = 5; // give up if status itself is unreachable
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Settle an export phase whose blocking POST was cut off by a tunnel timeout, by
+ * polling /api/export/status until the still-running backend op finishes, then
+ * reading its recorded outcome. `baseline` is `last_op_seq` captured before the
+ * POST; a record is "ours" once the op went inactive AND either we observed it
+ * active or its seq advanced past the baseline (single serial driver ⇒ exact).
+ */
+async function recoverViaStatus(
+ baseline: number | null,
+ isCurrent: () => boolean,
+): Promise<{ outputPath: string | null }> {
+ const start = Date.now();
+ let statusFails = 0;
+ let sawActive = false;
+
+ while (Date.now() - start < RECOVERY_MAX_MS) {
+ if (!isCurrent()) throw new Error("Export run superseded");
+ await sleep(RECOVERY_POLL_INTERVAL_MS);
+
+ let st: ExportStatus;
+ try {
+ st = await getExportStatus();
+ statusFails = 0;
+ } catch {
+ // Status itself is transiently unreachable; tolerate a few, then (past the
+ // grace window) give up so a truly-down backend surfaces a real error.
+ statusFails += 1;
+ if (
+ Date.now() - start > RECOVERY_GRACE_MS &&
+ statusFails >= RECOVERY_MAX_STATUS_FAILS
+ ) {
+ throw new Error("Lost connection to the export server.");
+ }
+ continue;
+ }
+
+ if (st.is_export_active) {
+ sawActive = true;
+ continue;
+ }
+
+ const seq = st.last_op_seq ?? 0;
+ const isOurs = sawActive || (baseline !== null && seq > baseline);
+ if (isOurs) {
+ if (st.last_op_status === "success") {
+ return { outputPath: st.last_op_output_path ?? null };
+ }
+ if (st.last_op_status === "cancelled") throw new ExportCanceledError();
+ throw new Error(st.last_op_error || "Export failed");
+ }
+
+ // Inactive but our op was never observed: the POST likely died before the
+ // backend started it. Allow a grace window for the op to appear, then fail.
+ if (Date.now() - start > RECOVERY_GRACE_MS) {
+ throw new Error(
+ "The export request failed before the server started the operation.",
+ );
+ }
+ }
+ throw new Error("Timed out waiting for the export to finish.");
+}
+
+// Keep the same scrollback depth as the backend ring buffer so the inline
+// panel shows the full server-side history.
+const MAX_LOG_LINES = 4000;
+
+export type ExportPhase =
+ | "idle"
+ | "loading"
+ | "exporting"
+ | "success"
+ | "error"
+ | "canceled";
+
+export type ExportDestination = "local" | "hub";
+
+/** Snapshot of what is being exported, captured when a run starts. */
+export interface ExportRunSummary {
+ baseModelName: string;
+ checkpointLabel: string | null;
+ methodLabel: string;
+ method: ExportMethod;
+ quantLevels: string[];
+ destination: ExportDestination;
+}
+
+/** Everything `runExport` needs to drive the load -> export -> cleanup sequence. */
+export interface RunExportParams {
+ sourceMode: "checkpoint" | "model";
+ /** Resolved on-disk checkpoint path (checkpoint mode). */
+ checkpointPath: string | null;
+ /** Raw source id passed to load-checkpoint (model mode: HF id or local path). */
+ source: string;
+ modelSource: "hf" | "local";
+ trustRemoteCode: boolean;
+ /** Consent fingerprint from the load-time remote-code review dialog (HF custom code). */
+ approvedRemoteCodeFingerprint?: string | null;
+ /** HF token for loading a gated/private source model (separate from the Hub upload token). */
+ loadToken?: string | null;
+ exportMethod: ExportMethod;
+ isAdapter: boolean;
+ quantLevels: string[];
+ saveDirectory: string;
+ destination: ExportDestination;
+ repoId?: string;
+ token?: string;
+ privateRepo: boolean;
+ baseModelId?: string | null;
+ summary: ExportRunSummary;
+}
+
+interface ExportRuntimeState {
+ phase: ExportPhase;
+ /** True from the moment a run starts until it reaches a terminal phase. */
+ isExporting: boolean;
+ /** True while this store's own `runExport` drives the sequence (vs a run
+ * recovered from the backend after a reload). Gates status-poll takeovers. */
+ ownsRun: boolean;
+ method: ExportMethod | null;
+ summary: ExportRunSummary | null;
+ quantTotal: number;
+ /** Number of GGUF quants finished so far (0-based current = this value). */
+ quantIndex: number;
+ /** Latest high-level status line surfaced by the worker. */
+ stage: string | null;
+ logLines: ExportLogEntry[];
+ lastSeq: number | null;
+ connected: boolean;
+ /** True while a phase POST's response was lost (tunnel timeout) and we are
+ * settling the run by polling /api/export/status instead. Logs keep streaming. */
+ reconnecting: boolean;
+ startedAt: number | null;
+ result: { outputPath: string | null; destination: ExportDestination } | null;
+ error: string | null;
+ cancelRequested: boolean;
+ hasHydrated: boolean;
+ backendActive: boolean;
+ /** Bumped on every run so stale async callbacks can detect they were superseded. */
+ runId: number;
+}
+
+interface ExportRuntimeActions {
+ runExport: (params: RunExportParams) => Promise<void>;
+ requestCancel: () => Promise<void>;
+ /** Append one streamed line (SSE). De-duped by seq against the poll path. */
+ appendLog: (entry: ExportLogEntry, seq?: number) => void;
+ /** Merge a batch of polled lines (JSON fallback). De-duped by seq. */
+ appendLogs: (entries: ExportLogPollEntry[]) => void;
+ setConnected: (value: boolean) => void;
+ applyBackendStatus: (status: ExportStatus) => void;
+ reset: () => void;
+}
+
+export type ExportRuntimeStore = ExportRuntimeState & ExportRuntimeActions;
+
+const initialState: ExportRuntimeState = {
+ phase: "idle",
+ isExporting: false,
+ ownsRun: false,
+ method: null,
+ summary: null,
+ quantTotal: 1,
+ quantIndex: 0,
+ stage: null,
+ logLines: [],
+ lastSeq: null,
+ connected: false,
+ reconnecting: false,
+ startedAt: null,
+ result: null,
+ error: null,
+ cancelRequested: false,
+ hasHydrated: false,
+ backendActive: false,
+ runId: 0,
+};
+
+export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) => ({
+ ...initialState,
+
+ setConnected: (value) => set({ connected: value }),
+
+ appendLog: (entry, seq) =>
+ set((state) => {
+ // De-dupe by seq: the SSE stream and the JSON poll fallback both feed
+ // logs, so ignore anything at or below the highest seq already seen.
+ if (
+ typeof seq === "number" &&
+ state.lastSeq !== null &&
+ seq <= state.lastSeq
+ ) {
+ return state;
+ }
+ const next =
+ state.logLines.length >= MAX_LOG_LINES
+ ? state.logLines.slice(state.logLines.length - MAX_LOG_LINES + 1)
+ : state.logLines.slice();
+ next.push(entry);
+ return {
+ logLines: next,
+ lastSeq: typeof seq === "number" ? seq : state.lastSeq,
+ // `status` lines are the worker's high-level progress markers; surface
+ // the most recent one as the stage label.
+ stage: entry.stream === "status" ? entry.line : state.stage,
+ };
+ }),
+
+ appendLogs: (entries) =>
+ set((state) => {
+ // Keep only lines newer than the highest seq we've shown (covers overlap
+ // with the SSE stream and with the previous poll batch).
+ const fresh =
+ state.lastSeq === null
+ ? entries
+ : entries.filter((e) => e.seq > (state.lastSeq as number));
+ if (fresh.length === 0) return state;
+
+ const merged = state.logLines.concat(
+ fresh.map((e) => ({ stream: e.stream, line: e.line, ts: e.ts })),
+ );
+ const next =
+ merged.length > MAX_LOG_LINES
+ ? merged.slice(merged.length - MAX_LOG_LINES)
+ : merged;
+
+ // Latest `status` line in the batch becomes the stage label.
+ let stage = state.stage;
+ for (const e of fresh) {
+ if (e.stream === "status") stage = e.line;
+ }
+ return {
+ logLines: next,
+ lastSeq: fresh[fresh.length - 1].seq,
+ stage,
+ };
+ }),
+
+ applyBackendStatus: (status) =>
+ set((state) => {
+ const base = { hasHydrated: true, backendActive: status.is_export_active };
+ // Recover a run started before this store existed (full page reload, or
+ // an export kicked off in another browser tab): show it live.
+ if (status.is_export_active && !state.isExporting && !state.ownsRun) {
+ return {
+ ...base,
+ isExporting: true,
+ phase: "exporting" as const,
+ startedAt: state.startedAt ?? Date.now(),
+ };
+ }
+ // A recovered (not store-owned) run finished on the backend. Settle from
+ // the last-op record when present (accurate success/error/output path),
+ // else fall back to the optimistic guess.
+ if (!status.is_export_active && state.isExporting && !state.ownsRun) {
+ // A standalone load_checkpoint (or no recorded op) is not an export and
+ // must never settle as a finished export. A completed export ends on its
+ // export_* op or the trailing cleanup, both of which count.
+ const wasExport =
+ !!status.last_op_kind && status.last_op_kind !== "load_checkpoint";
+ if (status.last_op_status === "error") {
+ return {
+ ...base,
+ isExporting: false,
+ phase: "error" as const,
+ error: status.last_op_error ?? "Export failed",
+ };
+ }
+ if (status.last_op_status === "cancelled") {
+ return { ...base, isExporting: false, phase: "canceled" as const };
+ }
+ if (status.last_op_status === "success" && wasExport) {
+ return {
+ ...base,
+ isExporting: false,
+ phase: "success" as const,
+ result: {
+ outputPath: status.last_op_output_path ?? null,
+ destination: state.result?.destination ?? "local",
+ },
+ };
+ }
+ // Load-only op, or no clear success record: nothing was exported.
+ return { ...base, isExporting: false, phase: "idle" as const };
+ }
+ return base;
+ }),
+
+ reset: () =>
+ set((state) => ({
+ ...initialState,
+ hasHydrated: state.hasHydrated,
+ backendActive: state.backendActive,
+ runId: state.runId,
+ })),
+
+ requestCancel: async () => {
+ if (!get().isExporting) return;
+ set({ cancelRequested: true });
+ try {
+ await cancelExport();
+ } catch {
+ // Best-effort: the in-flight export POST will still reject when the
+ // worker dies, which runExport turns into the canceled phase.
+ }
+ },
+
+ runExport: async (params) => {
+ const runId = get().runId + 1;
+ const quantTotal =
+ params.exportMethod === "gguf"
+ ? Math.max(1, params.quantLevels.length)
+ : 1;
+
+ set({
+ runId,
+ isExporting: true,
+ ownsRun: true,
+ phase: "loading",
+ method: params.exportMethod,
+ summary: params.summary,
+ quantTotal,
+ quantIndex: 0,
+ stage: null,
+ logLines: [],
+ lastSeq: null,
+ connected: false,
+ reconnecting: false,
+ startedAt: Date.now(),
+ result: null,
+ error: null,
+ cancelRequested: false,
+ });
+
+ const isCurrent = () => get().runId === runId;
+ const pushToHub = params.destination === "hub";
+
+ // Run a phase POST so it survives a Cloudflare tunnel 524: capture the
+ // last-op baseline, fire the POST, and on a recoverable transport failure
+ // settle the still-running backend op via short status polls instead of
+ // failing. Returns the resolved output path (null for load/hub-only).
+ const runRecoverableOp = async (
+ post: () => Promise<ExportOperationResponse>,
+ ): Promise<{ outputPath: string | null }> => {
+ let baseline: number | null = null;
+ try {
+ baseline = (await getExportStatus()).last_op_seq ?? 0;
+ } catch {
+ baseline = null; // pre-read failed; recovery falls back to "saw active"
+ }
+ try {
+ const resp = await post();
+ return { outputPath: resp.details?.output_path ?? null };
+ } catch (err) {
+ if (!isRecoverableTransportError(err)) throw err;
+ set({ reconnecting: true });
+ try {
+ return await recoverViaStatus(baseline, isCurrent);
+ } finally {
+ if (isCurrent()) set({ reconnecting: false });
+ }
+ }
+ };
+
+ try {
+ // 1. Load the model source into a fresh export subprocess.
+ if (params.sourceMode === "checkpoint") {
+ if (!params.checkpointPath) {
+ throw new Error("No checkpoint selected");
+ }
+ const checkpointPath = params.checkpointPath;
+ await runRecoverableOp(() =>
+ loadCheckpoint({
+ checkpoint_path: checkpointPath,
+ hf_token: params.loadToken ?? null,
+ }),
+ );
+ } else {
+ await runRecoverableOp(() =>
+ loadCheckpoint({
+ checkpoint_path: params.source,
+ load_in_4bit: false,
+ trust_remote_code:
+ params.modelSource === "hf" ? params.trustRemoteCode : true,
+ approved_remote_code_fingerprint:
+ params.approvedRemoteCodeFingerprint ?? null,
+ hf_token: params.loadToken ?? null,
+ }),
+ );
+ }
+ if (!isCurrent()) return;
+
+ // 2. Run the export. Capture the resolved output_path for the success
+ // banner; multi-quant GGUF shares one directory, so keep the last.
+ set({ phase: "exporting" });
+ let lastOutputPath: string | null = null;
+
+ if (params.exportMethod === "merged") {
+ if (params.isAdapter) {
+ const { outputPath } = await runRecoverableOp(() =>
+ exportMerged({
+ save_directory: params.saveDirectory,
+ push_to_hub: pushToHub,
+ repo_id: params.repoId,
+ hf_token: params.token,
+ private: params.privateRepo,
+ }),
+ );
+ lastOutputPath = outputPath;
+ } else {
+ const { outputPath } = await runRecoverableOp(() =>
+ exportBase({
+ save_directory: params.saveDirectory,
+ push_to_hub: pushToHub,
+ repo_id: params.repoId,
+ hf_token: params.token,
+ private: params.privateRepo,
+ base_model_id: params.baseModelId,
+ }),
+ );
+ lastOutputPath = outputPath;
+ }
+ } else if (params.exportMethod === "gguf") {
+ for (let i = 0; i < params.quantLevels.length; i += 1) {
+ if (!isCurrent()) return;
+ set({ quantIndex: i });
+ const quant = params.quantLevels[i];
+ const { outputPath } = await runRecoverableOp(() =>
+ exportGGUF({
+ save_directory: params.saveDirectory,
+ quantization_method: quant,
+ push_to_hub: pushToHub,
+ repo_id: params.repoId,
+ hf_token: params.token,
+ }),
+ );
+ lastOutputPath = outputPath ?? lastOutputPath;
+ if (!isCurrent()) return;
+ set({ quantIndex: i + 1 });
+ }
+ } else if (params.exportMethod === "lora") {
+ const { outputPath } = await runRecoverableOp(() =>
+ exportLoRA({
+ save_directory: params.saveDirectory,
+ push_to_hub: pushToHub,
+ repo_id: params.repoId,
+ hf_token: params.token,
+ private: params.privateRepo,
+ }),
+ );
+ lastOutputPath = outputPath;
+ }
+ if (!isCurrent()) return;
+
+ set({
+ phase: "success",
+ isExporting: false,
+ reconnecting: false,
+ result: { outputPath: lastOutputPath, destination: params.destination },
+ });
+ } catch (err) {
+ if (!isCurrent()) return;
+ if (get().cancelRequested || err instanceof ExportCanceledError) {
+ set({
+ phase: "canceled",
+ isExporting: false,
+ reconnecting: false,
+ error: null,
+ });
+ } else {
+ set({
+ phase: "error",
+ isExporting: false,
+ reconnecting: false,
+ error: err instanceof Error ? err.message : "Export failed",
+ });
+ }
+ } finally {
+ // Cleanup is best-effort and runs after the terminal phase is set, so it
+ // does not gate the success banner. Only the run that still owns the
+ // store releases ownership and frees the worker.
+ if (isCurrent()) {
+ try {
+ await cleanupExport();
+ } catch {
+ // ignore
+ }
+ if (isCurrent()) {
+ set({ ownsRun: false });
+ }
+ }
+ }
+ },
+}));
+
+/**
+ * Map the run phase to a 0-100 progress value. There is no byte-level signal
+ * from llama.cpp / the HF uploader, so progress is phase + quant-index based:
+ * loading occupies a small head band, the export body advances per completed
+ * GGUF quant, and success pins to 100.
+ */
+export function selectExportProgressPercent(state: ExportRuntimeStore): number {
+ const total = Math.max(1, state.quantTotal);
+ const exportBand = () => {
+ const done = Math.min(Math.max(state.quantIndex, 0), total);
+ return Math.round(15 + (done / total) * 72); // 15..87
+ };
+ switch (state.phase) {
+ case "idle":
+ return 0;
+ case "loading":
+ return 8;
+ case "exporting":
+ return exportBand();
+ case "success":
+ return 100;
+ case "error":
+ case "canceled":
+ // Freeze near where it stopped so the bar does not snap back to 0.
+ return Math.max(8, exportBand());
+ default:
+ return 0;
+ }
+}
+
+/** Whether the inline run panel should be visible (a run is active or terminal). */
+export function isExportPanelActive(state: ExportRuntimeStore): boolean {
+ return state.isExporting || state.phase !== "idle";
+}
diff --git a/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts b/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts
new file mode 100644
index 00000000000..ab4388d4b93
--- /dev/null
+++ b/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts
@@ -0,0 +1,45 @@
+// 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 { useEffect } from "react";
+
+import { getTrainingStatus } from "../api/train-api";
+import { useTrainingRuntimeStore } from "../stores/training-runtime-store";
+
+const WATCH_INTERVAL_MS = 6000;
+
+/**
+ * Keep training state fresh while a run is active, even off the Train page.
+ *
+ * The lifecycle poll (`useTrainingRuntimeLifecycle`) only runs while Train is
+ * mounted, so a run finishing while the user is on another tab would leave the
+ * sidebar spinner stuck. This polls `/api/train/status` only while a run is in
+ * progress (no traffic when idle). Mount once in an always-rendered shell.
+ */
+export function useTrainingCompletionWatch(): void {
+ const active = useTrainingRuntimeStore(
+ (s) => s.isTrainingRunning || s.isStarting,
+ );
+
+ useEffect(() => {
+ if (!active) return;
+ let cancelled = false;
+
+ const tick = async () => {
+ try {
+ const status = await getTrainingStatus();
+ if (!cancelled) {
+ useTrainingRuntimeStore.getState().applyStatus(status);
+ }
+ } catch {
+ // Transient network/auth hiccup; the next tick retries.
+ }
+ };
+
+ const id = window.setInterval(tick, WATCH_INTERVAL_MS);
+ return () => {
+ cancelled = true;
+ window.clearInterval(id);
+ };
+ }, [active]);
+}
diff --git a/studio/frontend/src/features/training/index.ts b/studio/frontend/src/features/training/index.ts
index 05f882184f2..5157d89582d 100644
--- a/studio/frontend/src/features/training/index.ts
+++ b/studio/frontend/src/features/training/index.ts
@@ -9,6 +9,7 @@ export {
export { useTrainingActions } from "./hooks/use-training-actions";
export { useTrainingHistorySidebarItems } from "./hooks/use-training-history-sidebar";
export { useTrainingRuntimeLifecycle } from "./hooks/use-training-runtime-lifecycle";
+export { useTrainingCompletionWatch } from "./hooks/use-training-completion-watch";
export {
removeTrainingUnloadGuard,
useTrainingUnloadGuard,
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 9b32c22dde7..5f7e5b6644a 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -32,6 +32,7 @@ export const en = {
},
navigation: {
newChat: "New Chat",
+ returnToChat: "Return to Chat",
compare: "Compare",
search: "Search",
hub: "Hub",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index c98ff794bd7..c87ea1b3127 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -32,6 +32,7 @@ export const zhCN = {
},
navigation: {
newChat: "新聊天",
+ returnToChat: "返回聊天",
compare: "对比",
search: "搜索",
hub: "Hub",