Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Unsloth Studio / Desktop: queue image generations from the Images page and the API (#15005)
Leo Borcherding3c51fdc874c7
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 7d4cfa32c9e..c20ea121d19 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -68,6 +68,7 @@ from .diffusion_families import (LUMINA2_FAMILY_NAME,DiffusionFamily,DiffusionModelReplacedError, # re-exported: callers import it from either module+ require_pinned_checkpoint,LoadIdentity,load_identity,local_pipeline_components_are_complete,@@ -14274,6 +14275,7 @@ class DiffusionBackend:loaded_id = load_identity(state.repo_id, state.base_repo, state.family.name)if expected_load is not None and expected_load != loaded_id:raise DiffusionModelReplacedError(expected_load, loaded_id)+ require_pinned_checkpoint(loaded_id, getattr(state, "gguf_filename", None))# Publish active step-0 state before slow setup, so a reload's mount probe does not read idle.self._gen = _GenState(total_steps = steps)begin_attention_run(state)diff --git a/studio/backend/core/inference/diffusion_detailer.py b/studio/backend/core/inference/diffusion_detailer.pyindex 923d5ea4da8..ede2721b71f 100644--- a/studio/backend/core/inference/diffusion_detailer.py+++ b/studio/backend/core/inference/diffusion_detailer.py@@ -645,6 +645,9 @@ def detail_result(renders = list(images)placement = result.get("denoiser_offload")stop_event = threading.Event()+ from core.inference.generation_ticket import bind_generation_cancel++ bind_generation_cancel(stop_event)with _active_lock:_active[stop_event] = accountfinished = Falsediff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 4b879749416..88f3d5a6f4d 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport importlib.utilimport json+import contextlibimport contextvarsimport osimport re@@ -58,6 +59,28 @@ def load_identity(repo_id, base_repo, family) -> LoadIdentity:return LoadIdentity(str(repo_id or ""), str(base_repo or ""), str(family or ""))+# The image queue pins the checkpoint file too: another quant of the same repo is the same LoadIdentity.+_pinned_checkpoint: contextvars.ContextVar = contextvars.ContextVar(+ "pinned_checkpoint", default = None+)+++def pin_checkpoint(filename):+ token = _pinned_checkpoint.set((filename,))+ try:+ yield+ finally:+ _pinned_checkpoint.reset(token)+++def require_pinned_checkpoint(loaded_id: LoadIdentity, loaded_filename) -> None:+ """Called by each engine beside its expected_load check, under the same lock."""+ pin = _pinned_checkpoint.get()+ if pin is not None and pin[0] != loaded_filename:+ raise DiffusionModelReplacedError(loaded_id, loaded_id)++class DiffusionModelReplacedError(RuntimeError):"""Both engines' ``generate`` refusing a ``LoadIdentity`` that is no longer loaded. Keeps acaller's per-model steps/guidance and workflow verdict, taken from an earlier ``status()``diff --git a/studio/backend/core/inference/flux3_prompt_upsampler.py b/studio/backend/core/inference/flux3_prompt_upsampler.pyindex 82f6cfd2793..3f0041de40b 100644--- a/studio/backend/core/inference/flux3_prompt_upsampler.py+++ b/studio/backend/core/inference/flux3_prompt_upsampler.py@@ -2161,6 +2161,10 @@ def enhance_for_generation(variant = variant_for_family(family_name)distinct = list(dict.fromkeys(p for p in prompts if isinstance(p, str)))cancel_event = cancel_event or threading.Event()+ from core.inference.generation_ticket import bind_generation_cancel++ # A queued job's or chat image's own Stop reaches its captioning too, not only the denoise.+ bind_generation_cancel(cancel_event)outcome = EnhanceOutcome(status = STATUS_APPLIED)sidecar = get_sidecar()# On every exit, a Stop included: a retry with enhancement off must not denoise beside a tight server.diff --git a/studio/backend/core/inference/image_queue.py b/studio/backend/core/inference/image_queue.pynew file mode 100644index 00000000000..f9b5eeb485e--- /dev/null+++ b/studio/backend/core/inference/image_queue.py@@ -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++"""Image generation queue: full generate requests wait here and run one at a time through the normal generate path.++In-process only, so it survives a page reload but not a server restart. Every call happens on the event loop, so+the job list needs no lock. Each account sees and edits only its own jobs."""++from __future__ import annotations++import asyncio+import time+import uuid+from dataclasses import dataclass, field+from typing import Any, Awaitable, Callable, Optional++from core.inference.generation_ticket import GenerationTicket+from loggers import get_logger++logger = get_logger(__name__)++QUEUED = "queued"+RUNNING = "running"+DONE = "done"+FAILED = "failed"+CANCELLED = "cancelled"+FINISHED = (DONE, FAILED, CANCELLED)++# Requests can carry base64 source images, so neither list grows without bound.+MAX_QUEUED_PER_ACCOUNT = 100+MAX_FINISHED_PER_ACCOUNT = 20+++class JobCancelled(Exception):+ """The running job was stopped."""+++class QueueFull(Exception):+ pass+++@dataclass+class ImageJob:+ id: str+ account_id: str+ account: Any+ request: Any+ # The resident model when the job was queued; a job never runs on another one.+ load: Any = None+ status: str = QUEUED+ created_at: float = field(default_factory = time.time)+ started_at: Optional[float] = None+ finished_at: Optional[float] = None+ error: Optional[str] = None+ image_ids: list[str] = field(default_factory = list)+ seed_used: Optional[int] = None+ cancel_requested: bool = False+ # Stops this job's render only, queued behind another or running; never whichever render holds the engine.+ ticket: GenerationTicket = field(default_factory = GenerationTicket)+++class ImageGenerationQueue:+ def __init__(+ self,+ runner: Callable[[ImageJob], Awaitable[list[str]]],+ wait_idle: Optional[Callable[[], Awaitable[None]]] = None,+ ) -> None:+ self._runner = runner+ self._wait_idle = wait_idle+ self._jobs: list[ImageJob] = []+ self._worker: Optional[asyncio.Task] = None+ self.loop: Optional[asyncio.AbstractEventLoop] = None++ def jobs(self, account_id: str) -> list[ImageJob]:+ return [job for job in self._jobs if job.account_id == account_id]++ def get(self, account_id: str, job_id: str) -> Optional[ImageJob]:+ return next((job for job in self.jobs(account_id) if job.id == job_id), None)++ def enqueue(+ self,+ account,+ request,+ load = None,+ ) -> ImageJob:+ account_id = account.account_id+ if (+ sum(1 for job in self.jobs(account_id) if job.status == QUEUED)+ >= MAX_QUEUED_PER_ACCOUNT+ ):+ raise QueueFull(f"The image queue is full ({MAX_QUEUED_PER_ACCOUNT} jobs).")+ job = ImageJob(+ id = uuid.uuid4().hex[:12],+ account_id = account_id,+ account = account,+ request = request,+ load = load,+ )+ self._jobs.append(job)+ self._ensure_worker()+ return job++ def cancel(self, account_id: str, job_id: str) -> Optional[ImageJob]:+ """A queued job is cancelled here; a running one has its own render stopped and ends when that unwinds."""+ job = self.get(account_id, job_id)+ if job is None:+ return None+ if job.status == QUEUED:+ self._finish(job, CANCELLED)+ elif job.status == RUNNING:+ job.cancel_requested = True+ job.ticket.stop()+ return job++ def move(self, account_id: str, job_id: str, index: int) -> Optional[ImageJob]:+ """Move a queued job to ``index`` among this account's queued jobs, clamped to the ends."""+ mine = [job for job in self.jobs(account_id) if job.status == QUEUED]+ job = next((j for j in mine if j.id == job_id), None)+ if job is None:+ return None+ mine.remove(job)+ index = max(0, min(index, len(mine)))+ self._jobs.remove(job)+ if index < len(mine):+ self._jobs.insert(self._jobs.index(mine[index]), job)+ elif mine:+ self._jobs.insert(self._jobs.index(mine[-1]) + 1, job)+ else:+ self._jobs.append(job)+ return job++ def retire(self, account_id: str) -> None:+ """A disabled or deleted account: nothing of its waits, its running render stops."""+ for job in self.jobs(account_id):+ self.cancel(account_id, job.id)++ def clear(self, account_id: str) -> int:+ """Drop this account's queued and finished jobs; a running job is left to finish."""+ removed = 0+ for job in self.jobs(account_id):+ if job.status == RUNNING:+ continue+ self._jobs.remove(job)+ removed += 1+ return removed++ def position(self, job: ImageJob) -> Optional[int]:+ if job.status != QUEUED:+ return None+ queued = [j for j in self.jobs(job.account_id) if j.status == QUEUED]+ return queued.index(job)++ def _finish(+ self,+ job: ImageJob,+ status: str,+ error: Optional[str] = None,+ ) -> None:+ job.status = status+ job.error = error+ job.finished_at = time.time()+ # Finished jobs move behind everything still pending, newest last, and the oldest fall off.+ self._jobs.remove(job)+ self._jobs.append(job)+ finished = [j for j in self.jobs(job.account_id) if j.status in FINISHED]+ for stale in finished[:-MAX_FINISHED_PER_ACCOUNT]:+ self._jobs.remove(stale)++ def _next(self) -> Optional[ImageJob]:+ return next((job for job in self._jobs if job.status == QUEUED), None)++ def _ensure_worker(self) -> None:+ if self._worker is None or self._worker.done():+ self.loop = asyncio.get_running_loop()+ self._worker = self.loop.create_task(self._drain())++ async def _drain(self) -> None:+ while True:+ if self._next() is None:+ return+ if self._wait_idle is not None:+ await self._wait_idle()+ # Re-read: the head may have been cancelled or reordered while a direct run finished.+ job = self._next()+ if job is None:+ return+ job.status = RUNNING+ job.started_at = time.time()+ try:+ job.image_ids = list(await self._runner(job))+ except JobCancelled:+ self._finish(job, CANCELLED)+ except asyncio.CancelledError:+ self._finish(job, CANCELLED)+ raise+ except Exception as exc: # noqa: BLE001 -- one bad job must not stop the queue+ logger.warning("image_queue.job_failed: %s", exc)+ self._finish(+ job,+ CANCELLED if job.cancel_requested else FAILED,+ str(exc) or type(exc).__name__,+ )+ else:+ self._finish(job, DONE)diff --git a/studio/backend/core/inference/mlx_diffusion_backend.py b/studio/backend/core/inference/mlx_diffusion_backend.pyindex b9f7e64c004..8e24d687816 100644--- a/studio/backend/core/inference/mlx_diffusion_backend.py+++ b/studio/backend/core/inference/mlx_diffusion_backend.py@@ -26,6 +26,7 @@ from core.inference.diffusion_families import (DIFFUSION_NOT_LOADED_MSG,DiffusionFamily,DiffusionModelReplacedError,+ require_pinned_checkpoint,LoadIdentity,_is_local_path,canonical_base,@@ -1379,6 +1380,7 @@ class MlxDiffusionBackend:loaded_id = load_identity(state.repo_id, state.base_repo, state.family.name)if expected_load is not None and expected_load != loaded_id:raise DiffusionModelReplacedError(expected_load, loaded_id)+ require_pinned_checkpoint(loaded_id, getattr(state, "gguf_filename", None))self._active_generate_cancel = cancelself._active_generate_account = current_account_id()self._gen = _MlxGen(total_steps = steps * batch)diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 025e475ce72..bae0715f870 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -50,6 +50,7 @@ from core.inference.diffusion_families import (DIFFUSION_NOT_LOADED_MSG,DiffusionFamily,DiffusionModelReplacedError,+ require_pinned_checkpoint,family_for_checkpoint,LoadIdentity,detect_family_for_pick,@@ -4619,6 +4620,7 @@ class SdCppDiffusionBackend:loaded_id = load_identity(state.repo_id, state.base_repo, state.family.name)if expected_load is not None and expected_load != loaded_id:raise DiffusionModelReplacedError(expected_load, loaded_id)+ require_pinned_checkpoint(loaded_id, getattr(state, "gguf_filename", None))self._active_generate_cancel = cancelself._active_generate_account = current_account_id()# Publish step 0 before slow setup so a reload probe does not read idle.diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.pyindex 6053f1e3a2f..d4b57419652 100644--- a/studio/backend/loggers/handlers.py+++ b/studio/backend/loggers/handlers.py@@ -108,6 +108,8 @@ _QUIET_SUCCESS_PATHS = {"/api/inference/video/load-progress","/api/inference/images/generate-progress","/api/inference/video/generate-progress",+ # The Images queue panel's list; enqueue, move, cancel and clear are not GETs and still log.+ "/api/inference/images/queue",# Polled by the Images page while the FLUX.3 prompt upsampler downloads."/api/inference/images/prompt-upsampler/status","/api/llama/update-status",diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 5122741fe2f..adf33153dce 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -5904,6 +5904,50 @@ class GalleryListResponse(BaseModel):has_more: bool = Field(False, description = "Whether older images remain past this page")+class ImageQueueJob(BaseModel):+ """One job in the image generation queue: the settings that tell it apart, its state and, once done, its images."""++ id: str+ status: Literal["queued", "running", "done", "failed", "cancelled"]+ position: Optional[int] = Field(+ None, description = "0-based place among your queued jobs; null once started"+ )+ prompt: str+ width: int+ height: int+ steps: Optional[int] = Field(+ None, description = "Requested steps; null follows the loaded model's default"+ )+ seed: Optional[int] = Field(+ None, description = "Requested seed; null draws one when the job runs"+ )+ batch_size: int+ workflow: Optional[str] = None+ loras: list[str] = Field(default_factory = list, description = "Applied adapters as id:weight")+ created_at: float+ started_at: Optional[float] = None+ finished_at: Optional[float] = None+ error: Optional[str] = None+ image_ids: list[str] = Field(+ default_factory = list, description = "Gallery ids of the finished images"+ )+ seed_used: Optional[int] = Field(+ None, description = "The run's base seed once done, for Reuse last seed"+ )+++class ImageQueueResponse(BaseModel):+ """Your image jobs in run order: running first, then queued, then the most recent finished ones."""++ jobs: list[ImageQueueJob] = Field(default_factory = list)+++class ImageQueueMoveRequest(BaseModel):+ """Body of POST /images/queue/{job_id}/move."""++ index: int = Field(..., ge = 0, description = "New 0-based place among your queued jobs (clamped)")++class PromptUpsamplerDownloadRequest(BaseModel):"""Body of POST /images/prompt-upsampler/download (optional)."""diff --git a/studio/backend/routes/accounts.py b/studio/backend/routes/accounts.pyindex b2163dddb4b..c014e7bb04e 100644--- a/studio/backend/routes/accounts.py+++ b/studio/backend/routes/accounts.py@@ -82,6 +82,9 @@ def retire_account_roots(account: AccountContext):video_active = generation_account_in_flight() == account.account_idif video_active:get_video_backend().cancel_generate(expected_account = account.account_id)+ from routes.inference import retire_account_image_jobs++ retire_account_image_jobs(account.account_id)image_active = cancel_generation_for_account(account.account_id)if video_active or image_active:raise AccountRetirementError("Media generation is still active; retry deletion")@@ -217,6 +220,9 @@ def set_account_active(account_id: str, payload: AccountActiveRequest):# Fence first, so a request registering after the sweep is cancelled too.active_generations.fence(account_id)active_generations.cancel_all(account_id)+ from routes.inference import retire_account_image_jobs++ retire_account_image_jobs(account_id)# A scheduled run still waiting for the model gate has not registered yet.cancel_account_runs(account_id)retire_account_loads(account_id)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 4f0943321bd..5cd67a41c88 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -51,6 +51,7 @@ from hub.services.models.account_access import media_link_account, media_link_tafrom utils.account_context import (OWNER_ACCOUNT_ID,account_thread,+ arun_as,current_account,current_account_id,is_owner_context,@@ -3434,6 +3435,9 @@ from models.inference import (GalleryImage,GalleryListResponse,ImageGenerationRequest,+ ImageQueueJob,+ ImageQueueMoveRequest,+ ImageQueueResponse,ImageGenerationData,ImageGenerationResponse,AudioSpeechRequest,@@ -49535,9 +49539,28 @@ async def generate_diffusion_image():if request.provider_id:return await _external_image_generation(request, http_request)- if request.xy is not None:- return await _generate_xy_grid(request)- return await _generate_diffusion_image_core(request)+ global _direct_image_runs, _direct_image_last_end+ _direct_image_runs += 1+ headers = http_request.headers if http_request is not None else {}+ more = headers.get("x-unsloth-more-runs") == "1"+ sequence = headers.get("x-unsloth-run-sequence") or ""+ # This run is the continuation its sequence was holding the queue for.+ _direct_sequences.pop(sequence, None)+ stops = _direct_stops+ finished = False+ try:+ if request.xy is not None:+ response = await _generate_xy_grid(request)+ else:+ response = await _generate_diffusion_image_core(request)+ finished = True+ return response+ finally:+ _direct_image_runs -= 1+ _direct_image_last_end = time.monotonic()+ # A stopped or failed run ends the sequence: the page sends no more.+ if more and finished and stops == _direct_stops:+ _direct_sequences[sequence] = _direct_image_last_end + _DIRECT_SEQUENCE_HOLD_S# Running grids by account: a Stop between cells or before a queued cell finds no denoise to land on.@@ -49645,7 +49668,7 @@ async def _generate_xy_grid(request: DiffusionGenerateRequest) -> DiffusionGenerasync def _generate_diffusion_image_core(- request: DiffusionGenerateRequest,+ request: DiffusionGenerateRequest, pinned_load = None) -> DiffusionGenerateResponse:"""The local-engine image run, shared by the route and the chat generate_image tool."""from core.inference.diffusion_segment import render_fence@@ -49653,11 +49676,13 @@ async def _generate_diffusion_image_core(# From before the run releases the mask segmenter until it ends: a Find cannot reload SAM 3 in the gap before the# render takes the engine's generation slot.with render_fence():- return await _generate_diffusion_image_run(request)+ return await _generate_diffusion_image_run(request, pinned_load = pinned_load)async def _generate_diffusion_image_run(- request: DiffusionGenerateRequest, captured: Optional[list] = None+ request: DiffusionGenerateRequest,+ captured: Optional[list] = None,+ pinned_load = None,) -> DiffusionGenerateResponse:from core.inference import image_galleryfrom core.inference.diffusion_engine_router import get_active_diffusion_engine@@ -49740,6 +49765,8 @@ async def _generate_diffusion_image_run(if enhancement.load is not None:# Captions are written for one family: a model swapped in since then retries with fresh ones.expected_load = enhancement.load+ if pinned_load is not None:+ expected_load = pinned_load# Ahead of the run: milestones key off the previous poll, so a resumed range logs nothing.reset_media_generation_progress("image")try:@@ -49805,8 +49832,8 @@ async def _generate_diffusion_image_run(except FallbackLoadRefusedError as exc:raise exc.http from excexcept DiffusionModelReplacedError as exc:- if attempt > 0:- raise HTTPException(status_code = 409, detail = str(exc))+ if attempt > 0 or pinned_load is not None:+ raise HTTPException(status_code = 409, detail = str(exc)) from exc# The caption was written for the replaced model's family.enhancement = await _enhance_generate_prompts(backend, request)continue@@ -51018,6 +51045,11 @@ async def cancel_diffusion_generation():return {"cancelled": grids}+ # Past the account checks: a refused Stop must not end someone else's multi-run sequence.+ global _direct_stops+ _direct_sequences.clear()+ _direct_stops += 1+# A run still upsampling its prompt has not reached the engine yet.from core.inference.flux3_prompt_upsampler import cancel_active as cancel_upsampling@@ -51035,6 +51067,252 @@ async def cancel_diffusion_generation(return {"cancelled": bool(cancelled or upsampling or detailing or grids)}+# Direct /images/generate runs in flight: the queue waits them out, so a job queued behind one starts after it.+_direct_image_runs = 0+_direct_image_last_end = 0.0+# The page sends a multi-run Generate one request at a time: a queued job must not slip into the gap between two.+# A request marked X-Unsloth-More-Runs holds the queue until the next run of its X-Unsloth-Run-Sequence arrives (or+# Stop, or the hold lapses); holds are per sequence, so another client's run never releases one.+_DIRECT_RUN_SETTLE_S = 1.5+_DIRECT_SEQUENCE_HOLD_S = 60.0+_direct_sequences: dict[str, float] = {}+# Bumped by Stop: a run that still returns (a Detailer keeps its render) must not re-arm the hold.+_direct_stops = 0+_image_queue = None+_QUEUE_MODEL_CHANGED_MSG = (+ "The image model changed since this job was queued. Queue it again on the loaded model."+)+++def _resident_load(status: dict):+ """(load identity, checkpoint file): a GGUF swapped for another quant of the same repo is a different model."""+ from core.inference.diffusion_families import load_identity++ if not status.get("loaded"):+ return None+ return (+ load_identity(status.get("repo_id"), status.get("base_repo"), status.get("family")),+ status.get("gguf_filename"),+ )+++def _engine_rendering() -> bool:+ """Any render on the engine, a chat image included, so a job only reports running once it can render."""+ from core.inference.gpu_arbiter import DIFFUSION+ from core.inference.media_keepwarm import engine_if_imported++ progress = getattr(engine_if_imported(DIFFUSION), "generate_progress", None)+ try:+ return bool(progress is not None and progress().get("active"))+ except Exception: # noqa: BLE001 -- no progress reading: do not hold the queue on it+ return False+++def _sequence_held() -> bool:+ now = time.monotonic()+ for sequence, until in list(_direct_sequences.items()):+ if until <= now:+ _direct_sequences.pop(sequence, None)+ return bool(_direct_sequences)+++async def _wait_for_direct_image_runs() -> None:+ while (+ _direct_image_runs > 0+ or _diffusion_persist_active > 0+ or time.monotonic() - _direct_image_last_end < _DIRECT_RUN_SETTLE_S+ or _sequence_held()+ or _engine_rendering()+ ):+ await asyncio.sleep(0.25)+++async def _run_queued_image_job(job) -> list[str]:+ from core.inference.diffusion_engine_router import get_active_diffusion_engine+ from core.inference.diffusion_families import (+ DIFFUSION_CANCELLED_MSG,+ DiffusionModelReplacedError,+ pin_checkpoint,+ )+ from core.inference import media_keepwarm+ from core.inference.generation_ticket import generation_ticket+ from core.inference.gpu_arbiter import DIFFUSION+ from core.inference.image_queue import JobCancelled+ from core.inference.llama_keepwarm import InferenceActivityReservation++ async def _run() -> list[str]:+ # v1 never reloads: a job runs only on the model that was resident when it was queued.+ status = await asyncio.to_thread(get_active_diffusion_engine().status)+ if _resident_load(status) != job.load:+ raise RuntimeError(_QUEUE_MODEL_CHANGED_MSG)+ if job.ticket.cancelled():+ raise JobCancelled()+ # No HTTP request carries a queued job: keep-warm, training guards and account checks need it (as video's queue).+ activity = InferenceActivityReservation()+ activity.reserve()+ try:+ await activity.start()+ await media_keepwarm.begin_request(DIFFUSION)+ except BaseException:+ activity.finish()+ raise+ try:+ account_access.require_live_account()+ with generation_ticket(job.ticket), pin_checkpoint(job.load[1]):+ response = await _generate_diffusion_image_core(job.request, job.load[0])+ except HTTPException as exc:+ if exc.status_code == 409 and exc.detail == DIFFUSION_CANCELLED_MSG:+ raise JobCancelled() from exc+ if exc.status_code == 409 and isinstance(exc.__cause__, DiffusionModelReplacedError):+ raise RuntimeError(_QUEUE_MODEL_CHANGED_MSG) from exc+ detail = exc.detail+ if isinstance(detail, dict):+ detail = detail.get("message") or detail.get("detail") or json.dumps(detail)+ raise RuntimeError(str(detail)) from exc+ finally:+ media_keepwarm.end_request(DIFFUSION)+ activity.finish()+ job.seed_used = next(+ (+ image.batch_seed if image.batch_seed is not None else image.seed+ for image in response.images+ ),+ None,+ )+ return [image.id for image in response.images]++ return await arun_as(job.account, _run())+++def retire_account_image_jobs(account_id: str) -> None:+ """Called from a worker thread by account disable / delete; the queue lives on the event loop."""+ queue = _image_queue+ if queue is not None and queue.loop is not None and not queue.loop.is_closed():+ queue.loop.call_soon_threadsafe(queue.retire, account_id)+++def _get_image_queue():+ global _image_queue+ if _image_queue is None:+ from core.inference.image_queue import ImageGenerationQueue+ _image_queue = ImageGenerationQueue(_run_queued_image_job, _wait_for_direct_image_runs)+ return _image_queue+++def _image_queue_job(queue, job) -> ImageQueueJob:+ request = job.request+ return ImageQueueJob(+ id = job.id,+ status = job.status,+ position = queue.position(job),+ prompt = request.prompt,+ width = request.width,+ height = request.height,+ steps = request.steps if "steps" in request.model_fields_set else None,+ seed = request.seed,+ batch_size = request.batch_size,+ workflow = request.workflow,+ loras = [f"{l.id}:{l.weight:g}" for l in request.loras or []],+ created_at = job.created_at,+ started_at = job.started_at,+ finished_at = job.finished_at,+ error = job.error,+ image_ids = job.image_ids,+ seed_used = job.seed_used,+ )+++def _image_queue_response(queue) -> ImageQueueResponse:+ from core.inference.image_queue import FINISHED, QUEUED, RUNNING++ jobs = queue.jobs(current_account_id())+ ordered = (+ [job for job in jobs if job.status == RUNNING]+ + [job for job in jobs if job.status == QUEUED]+ + [job for job in reversed(jobs) if job.status in FINISHED]+ )+ return ImageQueueResponse(jobs = [_image_queue_job(queue, job) for job in ordered])+++def _queued_job_or_404(queue, job_id: str):+ job = queue.get(current_account_id(), job_id)+ if job is None:+ raise HTTPException(status_code = 404, detail = "Queued image job not found.")+ return job+++@studio_router.post("/images/queue", response_model = ImageQueueJob)+async def enqueue_diffusion_image(+ request: DiffusionGenerateRequest, current_subject: str = Depends(get_current_subject)+):+ """Add a generate request to the queue. Jobs run one at a time, in queue order, through the same path as+ POST /images/generate, and their images land in the gallery. A job runs only on the model loaded when it was+ queued: nothing loaded is a 409 here, and a model swapped in meanwhile fails the job instead of reloading."""+ from core.inference.diffusion_engine_router import get_active_diffusion_engine+ from core.inference.diffusion_families import DIFFUSION_NOT_LOADED_MSG+ from core.inference.image_queue import QueueFull++ if request.provider_id:+ raise HTTPException(+ status_code = 400,+ detail = "The queue runs on the loaded image model; a saved connection generates directly.",+ )+ if request.xy is not None:+ raise HTTPException(+ status_code = 400, detail = "An XY grid generates directly; it cannot be queued."+ )+ status = await asyncio.to_thread(get_active_diffusion_engine().status)+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_media_generation_access, status, "diffusion")+ await asyncio.to_thread(account_access.require_media_adapters, request)+ load = _resident_load(status)+ if load is None:+ raise HTTPException(status_code = 409, detail = DIFFUSION_NOT_LOADED_MSG)+ queue = _get_image_queue()+ try:+ job = queue.enqueue(current_account(), request, load)+ except QueueFull as exc:+ raise HTTPException(status_code = 409, detail = str(exc))+ return _image_queue_job(queue, job)+++@studio_router.get("/images/queue", response_model = ImageQueueResponse)+async def list_diffusion_queue(current_subject: str = Depends(get_current_subject)):+ return _image_queue_response(_get_image_queue())+++@studio_router.post("/images/queue/{job_id}/cancel", response_model = ImageQueueJob)+async def cancel_diffusion_queue_job(+ job_id: str, current_subject: str = Depends(get_current_subject)+):+ """Cancel one job. A queued job never runs; the running one stops its own render, and the queue moves on."""+ queue = _get_image_queue()+ job = _queued_job_or_404(queue, job_id)+ queue.cancel(job.account_id, job.id)+ return _image_queue_job(queue, job)+++@studio_router.post("/images/queue/{job_id}/move", response_model = ImageQueueResponse)+async def move_diffusion_queue_job(+ job_id: str,+ payload: ImageQueueMoveRequest,+ current_subject: str = Depends(get_current_subject),+):+ queue = _get_image_queue()+ job = _queued_job_or_404(queue, job_id)+ if queue.move(job.account_id, job.id, payload.index) is None:+ raise HTTPException(status_code = 409, detail = "Only a queued job can be moved.")+ return _image_queue_response(queue)+++@studio_router.delete("/images/queue", response_model = ImageQueueResponse)+async def clear_diffusion_queue(current_subject: str = Depends(get_current_subject)):+ """Drop your queued and finished jobs. A running job finishes; Stop it to end it early."""+ queue = _get_image_queue()+ queue.clear(current_account_id())+ return _image_queue_response(queue)++# ── FLUX.3 prompt upsampler (llama.cpp sidecar) ──────────────────────────────────────────────────────────diff --git a/studio/backend/tests/log_budget/session.py b/studio/backend/tests/log_budget/session.pyindex 94b9a20352a..fe6adf8838b 100644--- a/studio/backend/tests/log_budget/session.py+++ b/studio/backend/tests/log_budget/session.py@@ -35,6 +35,8 @@ IDLE_POLLS: dict[str, tuple[float, str]] = {# Hub's 5s vLLM availability retry while the GPU probe still answers "Checking...". A path sits in one scenario# only, and every 2xx read is dropped by _QUIET_SUCCESS_PATHS, so the faster cadences cost no lines either."/api/engines": (30.0, "declared"),+ # The Images page's queue panel: every 5s idle, every 1s while jobs wait (use-image-queue.ts).+ "/api/inference/images/queue": (5.0, "declared"),}# Polls only while an operation is in flight; separate so the idle envelope is not averaged.diff --git a/studio/backend/tests/multi_account/factories_media.py b/studio/backend/tests/multi_account/factories_media.pyindex dc23ccd5ee2..f4ba89180ab 100644--- a/studio/backend/tests/multi_account/factories_media.py+++ b/studio/backend/tests/multi_account/factories_media.py@@ -343,6 +343,25 @@ def seed_model(account) -> dict[str, str]:return {"model_id": MODEL_ID}+@seeder("media-queue-job")+def seed_queue_job(account) -> dict[str, str]:+ """A waiting image job, placed straight in the queue so no worker renders it."""+ import uuid++ from core.inference.image_queue import ImageJob+ from models.inference import DiffusionGenerateRequest+ from routes import inference++ job = ImageJob(+ id = uuid.uuid4().hex[:12],+ account_id = account.account_id,+ account = account,+ request = DiffusionGenerateRequest(prompt = SENTINEL),+ )+ inference._get_image_queue()._jobs.append(job)+ return {"job_id": job.id}++_LINK_IS_THE_CREDENTIAL = ("the signed link is the credential rather than the bearer, so every holder of it is served ""while the minting account is active"@@ -368,6 +387,12 @@ FACTORIES = {"media-image", {"archived": True}, fragment = SENTINEL),"routes.inference:DELETE:/images/gallery/{image_id}": Factory("media-image"),+ "routes.inference:POST:/images/queue/{job_id}/cancel": Factory(+ "media-queue-job", fragment = "cancelled"+ ),+ "routes.inference:POST:/images/queue/{job_id}/move": Factory(+ "media-queue-job", body = {"index": 0}, fragment = SENTINEL+ ),"routes.inference:POST:/images/gallery/{image_id}/move": Factory("media-image", {"after_id": None}, fragment = SENTINEL),diff --git a/studio/backend/tests/test_diffusion_detailer.py b/studio/backend/tests/test_diffusion_detailer.pyindex 8996d033246..699eeef0f3f 100644--- a/studio/backend/tests/test_diffusion_detailer.py+++ b/studio/backend/tests/test_diffusion_detailer.py@@ -1447,3 +1447,30 @@ def test_a_kept_crop_reconciles_the_recorded_placement(monkeypatch, crop, expectgenerate_kwargs = {},)assert result["denoiser_offload"] == expected+++def test_a_queued_jobs_ticket_reaches_its_detailer_pass(monkeypatch):+ """Stopping one queued job ends its Detailer pass without cancelling anyone else's."""+ from core.inference.generation_ticket import GenerationTicket, generation_ticket++ seen = []+ monkeypatch.setattr(+ det,+ "_detail_images",+ lambda generate, result, images, settings, stop, **k: seen.append(stop),+ )+ ticket = GenerationTicket()+ with generation_ticket(ticket):+ det.detail_result(+ lambda **k: None,+ {"images": [object()]},+ det.DetailerSettings(),+ prompt_for = lambda i: "p",+ negative_prompt = None,+ steps = 4,+ guidance = 1.0,+ generate_kwargs = {},+ )+ assert len(seen) == 1 and not seen[0].is_set()+ ticket.stop()+ assert seen[0].is_set()diff --git a/studio/backend/tests/test_diffusion_segment.py b/studio/backend/tests/test_diffusion_segment.pyindex 666bdbfca45..b040acb1f7f 100644--- a/studio/backend/tests/test_diffusion_segment.py+++ b/studio/backend/tests/test_diffusion_segment.py@@ -1729,7 +1729,7 @@ def test_no_find_starts_while_a_render_is_on_its_way(monkeypatch):)seen = []- async def _run(request):+ async def _run(request, pinned_load = None):# The render released SAM 3 and has not taken the slot yet: a Find is refused, and frees the slot it took.with pytest.raises(seg.SegmenterBusyError, match = "generating"):seg.segment_image(_png_b64(), "sofa")diff --git a/studio/backend/tests/test_flux3_prompt_upsampler.py b/studio/backend/tests/test_flux3_prompt_upsampler.pyindex 5d68df163b4..286afa5bee7 100644--- a/studio/backend/tests/test_flux3_prompt_upsampler.py+++ b/studio/backend/tests/test_flux3_prompt_upsampler.py@@ -341,6 +341,18 @@ def test_cancel_propagates(runnable):assert pup.progress() is None+def test_a_stopped_ticket_cancels_its_own_enhancement(runnable):+ """A queued job's Stop reaches its captioning, not only the denoise after it."""+ from core.inference.generation_ticket import GenerationTicket, generation_ticket++ ticket = GenerationTicket()+ ticket.stop()+ with generation_ticket(ticket), pytest.raises(pup.UpsamplerCancelledError):+ pup.enhance_for_generation(["a"], family_name = "flux.3-klein", enhance_prompt = None)+ out = pup.enhance_for_generation(["a"], family_name = "flux.3-klein", enhance_prompt = None)+ assert out.status == "applied"++def _png_url(size = (640, 480)):from PIL import Imagediff --git a/studio/backend/tests/test_image_queue.py b/studio/backend/tests/test_image_queue.pynew file mode 100644index 00000000000..ba452c21b8c--- /dev/null+++ b/studio/backend/tests/test_image_queue.py@@ -0,0 +1,244 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Image generation queue: run order, reorder, cancel and clear, with the generator replaced by a gated fake."""++from __future__ import annotations++import asyncio+import types++import pytest++from core.inference import image_queue+from core.inference.image_queue import ImageGenerationQueue, JobCancelled++OWNER = types.SimpleNamespace(account_id = "owner")+OTHER = types.SimpleNamespace(account_id = "other")+++class _GatedRunner:+ """Each job runs until the test releases it, so the queue can be edited mid-run."""++ def __init__(self) -> None:+ self.started: list[str] = []+ self.gates: dict[str, asyncio.Event] = {}+ self.outcomes: dict[str, Exception] = {}++ def gate(self, prompt: str) -> asyncio.Event:+ return self.gates.setdefault(prompt, asyncio.Event())++ async def __call__(self, job) -> list[str]:+ prompt = job.request.prompt+ self.started.append(prompt)+ await self.gate(prompt).wait()+ if prompt in self.outcomes:+ raise self.outcomes[prompt]+ return [f"img-{prompt}"]+++def _request(prompt: str):+ return types.SimpleNamespace(prompt = prompt)+++async def _settle():+ for _ in range(5):+ await asyncio.sleep(0)+++def _statuses(queue, account = OWNER):+ return {job.request.prompt: job.status for job in queue.jobs(account.account_id)}+++def test_jobs_run_one_at_a_time_in_order():+ async def scenario():+ runner = _GatedRunner()+ queue = ImageGenerationQueue(runner)+ for prompt in ("a", "b", "c"):+ queue.enqueue(OWNER, _request(prompt))+ await _settle()+ assert runner.started == ["a"]+ assert _statuses(queue) == {"a": "running", "b": "queued", "c": "queued"}+ for prompt in ("a", "b", "c"):+ runner.gate(prompt).set()+ await _settle()+ assert runner.started == ["a", "b", "c"]+ assert _statuses(queue) == {"a": "done", "b": "done", "c": "done"}+ assert [job.image_ids for job in queue.jobs("owner")] == [["img-a"], ["img-b"], ["img-c"]]++ asyncio.run(scenario())+++def test_reorder_and_cancel_change_what_runs_next():+ async def scenario():+ runner = _GatedRunner()+ queue = ImageGenerationQueue(runner)+ jobs = {p: queue.enqueue(OWNER, _request(p)) for p in ("a", "b", "c", "d")}+ await _settle()+ queue.move("owner", jobs["d"].id, 0)+ assert [queue.position(jobs[p]) for p in ("d", "b", "c")] == [0, 1, 2]+ assert queue.cancel("owner", jobs["b"].id).status == "cancelled"+ for prompt in ("a", "d", "c"):+ runner.gate(prompt).set()+ await _settle()+ assert runner.started == ["a", "d", "c"]+ assert _statuses(queue) == {"a": "done", "b": "cancelled", "c": "done", "d": "done"}++ asyncio.run(scenario())+++def test_move_clamps_and_refuses_a_running_job():+ async def scenario():+ runner = _GatedRunner()+ queue = ImageGenerationQueue(runner)+ a, b, c = (queue.enqueue(OWNER, _request(p)) for p in ("a", "b", "c"))+ await _settle()+ assert queue.move("owner", a.id, 0) is None+ queue.move("owner", b.id, 99)+ assert [queue.position(j) for j in (c, b)] == [0, 1]+ for gate in ("a", "b", "c"):+ runner.gate(gate).set()+ await _settle()++ asyncio.run(scenario())+++def test_cancelling_the_running_job_only_flags_it_and_the_queue_moves_on():+ async def scenario():+ runner = _GatedRunner()+ queue = ImageGenerationQueue(runner)+ a = queue.enqueue(OWNER, _request("a"))+ queue.enqueue(OWNER, _request("b"))+ await _settle()+ assert queue.cancel("owner", a.id).status == "running"+ assert a.cancel_requested+ # The engine's stop surfaces as the run raising.+ runner.outcomes["a"] = RuntimeError("Generation cancelled.")+ runner.gate("a").set()+ await _settle()+ assert _statuses(queue) == {"a": "cancelled", "b": "running"}+ runner.gate("b").set()+ await _settle()++ asyncio.run(scenario())+++def test_a_failed_job_records_its_error_and_the_next_one_still_runs():+ async def scenario():+ runner = _GatedRunner()+ queue = ImageGenerationQueue(runner)+ a = queue.enqueue(OWNER, _request("a"))+ queue.enqueue(OWNER, _request("b"))+ runner.outcomes["a"] = RuntimeError("out of memory")+ runner.outcomes["b"] = JobCancelled()+ runner.gate("a").set()+ runner.gate("b").set()+ await _settle()+ assert a.status == "failed" and a.error == "out of memory"+ assert _statuses(queue)["b"] == "cancelled"++ asyncio.run(scenario())+++def test_accounts_see_and_edit_only_their_own_jobs():+ async def scenario():+ runner = _GatedRunner()+ queue = ImageGenerationQueue(runner)+ mine = queue.enqueue(OWNER, _request("a"))+ theirs = queue.enqueue(OTHER, _request("b"))+ await _settle()+ assert [j.id for j in queue.jobs("owner")] == [mine.id]+ assert queue.cancel("owner", theirs.id) is None+ assert queue.move("owner", theirs.id, 0) is None+ assert queue.clear("owner") == 0 # its only job is running+ assert theirs.status == "queued"+ runner.gate("a").set()+ runner.gate("b").set()+ await _settle()++ asyncio.run(scenario())+++def test_clear_keeps_the_running_job_and_drops_the_rest():+ async def scenario():+ runner = _GatedRunner()+ queue = ImageGenerationQueue(runner)+ a = queue.enqueue(OWNER, _request("a"))+ queue.enqueue(OWNER, _request("b"))+ queue.enqueue(OWNER, _request("c"))+ await _settle()+ assert queue.clear("owner") == 2+ assert queue.jobs("owner") == [a]+ runner.gate("a").set()+ await _settle()+ assert runner.started == ["a"]++ asyncio.run(scenario())+++def test_the_worker_waits_for_a_direct_run_before_starting(monkeypatch):+ async def scenario():+ runner = _GatedRunner()+ idle = asyncio.Event()++ async def wait_idle():+ await idle.wait()++ queue = ImageGenerationQueue(runner, wait_idle)+ a = queue.enqueue(OWNER, _request("a"))+ await _settle()+ assert runner.started == [] and a.status == "queued"+ idle.set()+ runner.gate("a").set()+ await _settle()+ assert a.status == "done"++ asyncio.run(scenario())+++def test_queue_is_capped_and_finished_history_trimmed(monkeypatch):+ monkeypatch.setattr(image_queue, "MAX_QUEUED_PER_ACCOUNT", 2)+ monkeypatch.setattr(image_queue, "MAX_FINISHED_PER_ACCOUNT", 1)++ async def scenario():+ runner = _GatedRunner()+ queue = ImageGenerationQueue(runner)+ queue.enqueue(OWNER, _request("a"))+ await _settle()+ queue.enqueue(OWNER, _request("b"))+ queue.enqueue(OWNER, _request("c"))+ with pytest.raises(image_queue.QueueFull):+ queue.enqueue(OWNER, _request("d"))+ for gate in ("a", "b", "c"):+ runner.gate(gate).set()+ await _settle()+ assert [j.request.prompt for j in queue.jobs("owner")] == ["c"]++ asyncio.run(scenario())+++def test_retire_cancels_waiting_jobs_and_stops_the_running_render():+ async def scenario():+ started = asyncio.Event()++ async def runner(job):+ started.set()+ while not job.ticket.cancelled():+ await asyncio.sleep(0.01)+ raise JobCancelled()++ queue = ImageGenerationQueue(runner)+ running = queue.enqueue(OWNER, _request("running"))+ waiting = queue.enqueue(OWNER, _request("waiting"))+ other = queue.enqueue(OTHER, _request("other"))+ await asyncio.wait_for(started.wait(), 5)+ queue.retire("owner")+ assert waiting.status == image_queue.CANCELLED and other.status == image_queue.QUEUED+ for _ in range(200):+ if running.status == image_queue.CANCELLED:+ break+ await asyncio.sleep(0.01)+ assert running.status == image_queue.CANCELLED+ assert queue.loop is asyncio.get_running_loop()++ asyncio.run(scenario())diff --git a/studio/backend/tests/test_image_queue_routes.py b/studio/backend/tests/test_image_queue_routes.pynew file mode 100644index 00000000000..a954fd64303--- /dev/null+++ b/studio/backend/tests/test_image_queue_routes.py@@ -0,0 +1,630 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The /images/queue routes end to end against the fake diffusion backend: enqueue, list, reorder, cancel, clear."""++from __future__ import annotations++import sys+import threading+import time+from pathlib import Path++import pytest++import core.inference.diffusion as diffusion_module+import routes.inference as inference_routes++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++from test_diffusion_routes import client # noqa: E402,F401 (fixture)++QUEUE = "/api/inference/images/queue"+++def gated(client, monkeypatch):+ """A loaded fake model whose generate blocks on a per-prompt gate, inside a live TestClient portal."""+ monkeypatch.setattr(inference_routes, "_image_queue", None)+ backend = diffusion_module.get_diffusion_backend()+ gates: dict[str, threading.Event] = {}+ order: list[str] = []+ real_generate = backend.generate++ def generate(*, prompt = None, **kwargs):+ order.append(prompt)+ stop = threading.Event()+ bind_generation_cancel(stop)+ gate = gates.setdefault(prompt, threading.Event())+ deadline = time.monotonic() + 10+ while not gate.wait(0.02) and time.monotonic() < deadline:+ if stop.is_set():+ raise RuntimeError(cancelled_msg)+ if backend.cancel_next:+ backend.cancel_next = False+ raise RuntimeError(cancelled_msg)+ return real_generate(prompt = prompt, **kwargs)++ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG as cancelled_msg+ from core.inference.generation_ticket import bind_generation_cancel++ backend.cancel_next = False++ def cancel_generate(**kwargs):+ backend.cancel_next = True+ gates[order[-1]].set()+ return True++ monkeypatch.setattr(backend, "generate", generate)+ monkeypatch.setattr(backend, "cancel_generate", cancel_generate)+ with client:+ assert (+ client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-turbo-Q4_K_S.gguf",+ "base_repo": "unsloth/Z-Image-base",+ },+ ).status_code+ == 200+ )+ yield client, gates, order, backend+++def _gate(gates, prompt):+ return gates.setdefault(prompt, threading.Event())+++def _jobs(client):+ return client.get(QUEUE).json()["jobs"]+++def _wait(+ client,+ predicate,+ timeout = 5.0,+):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ jobs = _jobs(client)+ if predicate(jobs):+ return jobs+ time.sleep(0.02)+ raise AssertionError(f"queue never settled: {_jobs(client)}")+++def _by_prompt(jobs):+ return {job["prompt"]: job for job in jobs}+++def test_queued_jobs_run_in_order_after_a_reorder_and_a_cancel(gated):+ client, gates, order, _ = gated+ ids = {}+ for prompt in ("one", "two", "three", "four"):+ response = client.post(+ QUEUE, json = {"prompt": prompt, "seed": 5, "width": 512, "height": 768}+ )+ assert response.status_code == 200+ ids[prompt] = response.json()["id"]+ _wait(client, lambda jobs: _by_prompt(jobs)["one"]["status"] == "running")++ listed = _jobs(client)+ assert [job["prompt"] for job in listed] == ["one", "two", "three", "four"]+ assert [job["position"] for job in listed] == [None, 0, 1, 2]+ assert listed[1]["width"] == 512 and listed[1]["height"] == 768 and listed[1]["seed"] == 5+ # Omitted steps follow the model, so the job does not claim the schema default.+ assert listed[1]["steps"] is None++ moved = client.post(f"{QUEUE}/{ids['four']}/move", json = {"index": 0}).json()["jobs"]+ assert [job["prompt"] for job in moved] == ["one", "four", "two", "three"]+ assert client.post(f"{QUEUE}/{ids['two']}/cancel").json()["status"] == "cancelled"++ for prompt in ("one", "four", "three"):+ _gate(gates, prompt).set()+ jobs = _wait(client, lambda jobs: all(job["status"] in ("done", "cancelled") for job in jobs))+ assert order == ["one", "four", "three"]+ states = _by_prompt(jobs)+ assert states["two"]["status"] == "cancelled"+ assert all(len(states[p]["image_ids"]) == 1 for p in ("one", "four", "three"))+ # Finished images are in the gallery like a direct generate's.+ gallery = {+ image["id"] for image in client.get("/api/inference/images/gallery").json()["images"]+ }+ assert {states[p]["image_ids"][0] for p in ("one", "four", "three")} <= gallery+++def test_cancelling_the_running_job_stops_it_and_the_next_one_runs(gated):+ client, gates, order, _ = gated+ first = client.post(QUEUE, json = {"prompt": "first"}).json()["id"]+ client.post(QUEUE, json = {"prompt": "second"})+ _wait(client, lambda jobs: _by_prompt(jobs)["first"]["status"] == "running")+ assert client.post(f"{QUEUE}/{first}/cancel").status_code == 200+ _gate(gates, "second").set()+ jobs = _wait(client, lambda jobs: _by_prompt(jobs)["second"]["status"] == "done")+ assert _by_prompt(jobs)["first"]["status"] == "cancelled"+ assert _by_prompt(jobs)["first"]["image_ids"] == []+++def test_clear_drops_queued_jobs_but_not_the_running_one(gated):+ client, gates, order, _ = gated+ client.post(QUEUE, json = {"prompt": "running"})+ client.post(QUEUE, json = {"prompt": "waiting"})+ _wait(client, lambda jobs: _by_prompt(jobs)["running"]["status"] == "running")+ jobs = client.delete(QUEUE).json()["jobs"]+ assert [job["prompt"] for job in jobs] == ["running"]+ _gate(gates, "running").set()+ _wait(client, lambda jobs: jobs and jobs[0]["status"] == "done")+ assert order == ["running"]+++def test_a_model_swapped_in_after_queueing_fails_the_job(gated):+ client, gates, order, backend = gated+ real_status = backend.status+ client.post(QUEUE, json = {"prompt": "blocker"})+ client.post(QUEUE, json = {"prompt": "stale"})+ _wait(client, lambda jobs: _by_prompt(jobs)["blocker"]["status"] == "running")+ backend.status = lambda: {**real_status(), "repo_id": "unsloth/another-model"}+ _gate(gates, "blocker").set()+ jobs = _wait(client, lambda jobs: _by_prompt(jobs)["stale"]["status"] == "failed")+ assert "model changed" in _by_prompt(jobs)["stale"]["error"]+ assert order == ["blocker"]+++def test_enqueue_refuses_with_nothing_loaded_or_a_connection(client, monkeypatch):+ monkeypatch.setattr(inference_routes, "_image_queue", None)+ refused = client.post(QUEUE, json = {"prompt": "x"})+ assert refused.status_code == 409 and "No diffusion model is loaded" in refused.json()["detail"]+ connection = client.post(QUEUE, json = {"prompt": "x", "provider_id": "p1", "model": "m"})+ assert connection.status_code == 400+ assert client.get(QUEUE).json() == {"jobs": []}+++def test_unknown_job_is_a_404_and_a_running_job_cannot_move(gated):+ client, gates, order, _ = gated+ running = client.post(QUEUE, json = {"prompt": "a"}).json()["id"]+ _wait(client, lambda jobs: jobs[0]["status"] == "running")+ assert client.post(f"{QUEUE}/nope/cancel").status_code == 404+ assert client.post(f"{QUEUE}/{running}/move", json = {"index": 0}).status_code == 409+ assert client.post(f"{QUEUE}/{running}/move", json = {"index": -1}).status_code == 422+ _gate(gates, "a").set()+ _wait(client, lambda jobs: jobs[0]["status"] == "done")+++def test_cancelling_a_queued_job_waiting_for_the_engine_leaves_the_render_ahead_alone(+ client, monkeypatch+):+ """A chat image holds the engine; Stop on the queued job behind it must not stop the chat image."""+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG+ from core.inference.generation_ticket import bind_generation_cancel+ from models.inference import DiffusionGenerateRequest++ monkeypatch.setattr(inference_routes, "_image_queue", None)+ backend = diffusion_module.get_diffusion_backend()+ real_generate = backend.generate+ slot = threading.Lock()+ active: list[threading.Event] = []+ chat_gate = threading.Event()+ ran: list[str] = []++ def generate(*, prompt = None, **kwargs):+ cancel = threading.Event()+ bind_generation_cancel(cancel)+ while True:+ if cancel.is_set():+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ if slot.acquire(timeout = 0.02):+ break+ try:+ # Admission rechecks under the slot, as the engine does.+ if cancel.is_set():+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ active.append(cancel)+ ran.append(prompt)+ while prompt == "chat" and not chat_gate.is_set():+ if cancel.is_set():+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ time.sleep(0.02)+ return real_generate(prompt = prompt, **kwargs)+ finally:+ active.pop()+ slot.release()++ def cancel_generate(**kwargs):+ # Like the engine: Stop reaches the generation holding the slot, not a waiter.+ if not active:+ return False+ active[-1].set()+ return True++ monkeypatch.setattr(backend, "generate", generate)+ monkeypatch.setattr(backend, "cancel_generate", cancel_generate)+ with client:+ assert (+ client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-turbo-Q4_K_S.gguf",+ "base_repo": "unsloth/Z-Image-base",+ },+ ).status_code+ == 200+ )+ chat = client.portal.start_task_soon(+ inference_routes._generate_diffusion_image_core,+ DiffusionGenerateRequest(prompt = "chat"),+ )+ deadline = time.monotonic() + 5+ while ran != ["chat"] and time.monotonic() < deadline:+ time.sleep(0.02)+ queued = client.post(QUEUE, json = {"prompt": "queued"}).json()["id"]+ _wait(client, lambda jobs: jobs[0]["status"] == "running")+ assert client.post(f"{QUEUE}/{queued}/cancel").status_code == 200+ chat_gate.set()+ assert len(chat.result(timeout = 10).images) == 1+ jobs = _wait(client, lambda jobs: jobs[0]["status"] in ("done", "failed", "cancelled"))+ assert ran == ["chat"]+ assert jobs[0]["status"] == "cancelled"+++def test_a_queued_job_is_pinned_to_its_model_and_never_retries_on_a_replacement(+ client, monkeypatch+):+ """A swap between the queue's model check and the render must fail the job, not run it on the new model."""+ from core.inference.diffusion_families import DiffusionModelReplacedError, load_identity+ from fastapi import HTTPException+ from models.inference import DiffusionGenerateRequest++ backend = diffusion_module.get_diffusion_backend()+ real_generate = backend.generate+ seen: list = []+ queued_for = load_identity("unsloth/queued-model", None, None)++ def generate(*, expected_load = None, **kwargs):+ seen.append(expected_load)+ loaded = load_identity("unsloth/swapped-in", None, None)+ if expected_load is not None and expected_load != loaded:+ raise DiffusionModelReplacedError(expected_load, loaded)+ return real_generate(**kwargs)++ monkeypatch.setattr(backend, "generate", generate)+ with client:+ assert (+ client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-turbo-Q4_K_S.gguf",+ "base_repo": "unsloth/Z-Image-base",+ },+ ).status_code+ == 200+ )+ with pytest.raises(HTTPException) as refused:+ client.portal.call(+ inference_routes._generate_diffusion_image_core,+ DiffusionGenerateRequest(prompt = "p", steps = 4, guidance = 1.0),+ queued_for,+ )+ assert refused.value.status_code == 409+ assert isinstance(refused.value.__cause__, DiffusionModelReplacedError)+ assert seen == [queued_for]+++def test_a_queued_job_waits_out_the_gap_between_two_direct_runs(client, monkeypatch):+ """Generate x2 sends two requests back to back; a job queued meanwhile runs after both."""+ monkeypatch.setattr(inference_routes, "_image_queue", None)+ backend = diffusion_module.get_diffusion_backend()+ real_generate = backend.generate+ order: list[str] = []++ def generate(*, prompt = None, **kwargs):+ order.append(prompt)+ if prompt == "direct-1":+ time.sleep(0.3)+ return real_generate(prompt = prompt, **kwargs)++ monkeypatch.setattr(backend, "generate", generate)+ with client:+ assert (+ client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-turbo-Q4_K_S.gguf",+ "base_repo": "unsloth/Z-Image-base",+ },+ ).status_code+ == 200+ )+ first = client.portal.start_task_soon(+ lambda: inference_routes.generate_diffusion_image(+ inference_routes.DiffusionGenerateRequest(prompt = "direct-1"), None+ )+ )+ deadline = time.monotonic() + 5+ while "direct-1" not in order and time.monotonic() < deadline:+ time.sleep(0.01)+ assert client.post(QUEUE, json = {"prompt": "queued"}).status_code == 200+ first.result(timeout = 10)+ time.sleep(0.3)+ assert (+ client.post("/api/inference/images/generate", json = {"prompt": "direct-2"}).status_code+ == 200+ )+ _wait(client, lambda jobs: jobs[0]["status"] == "done")+ assert order == ["direct-1", "direct-2", "queued"]+++def test_another_quant_of_the_same_repo_fails_the_waiting_job(gated):+ client, gates, order, backend = gated+ real_status = backend.status+ client.post(QUEUE, json = {"prompt": "blocker"})+ client.post(QUEUE, json = {"prompt": "stale"})+ _wait(client, lambda jobs: _by_prompt(jobs)["blocker"]["status"] == "running")+ backend.status = lambda: {**real_status(), "gguf_filename": "z-image-turbo-Q8_0.gguf"}+ _gate(gates, "blocker").set()+ jobs = _wait(client, lambda jobs: _by_prompt(jobs)["stale"]["status"] == "failed")+ assert "model changed" in _by_prompt(jobs)["stale"]["error"]+ assert order == ["blocker"]+++def test_a_multi_run_generate_holds_the_queue_across_a_long_gap(client, monkeypatch):+ """Run 1 says another follows: a job queued meanwhile waits past the settle window for run 2."""+ monkeypatch.setattr(inference_routes, "_image_queue", None)+ monkeypatch.setattr(inference_routes, "_DIRECT_RUN_SETTLE_S", 0.2)+ backend = diffusion_module.get_diffusion_backend()+ real_generate = backend.generate+ order: list[str] = []++ def generate(*, prompt = None, **kwargs):+ order.append(prompt)+ if prompt == "direct-1":+ time.sleep(0.3)+ return real_generate(prompt = prompt, **kwargs)++ monkeypatch.setattr(backend, "generate", generate)+ with client:+ assert (+ client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-turbo-Q4_K_S.gguf",+ "base_repo": "unsloth/Z-Image-base",+ },+ ).status_code+ == 200+ )+ first = threading.Thread(+ target = client.post,+ args = ("/api/inference/images/generate",),+ kwargs = {"json": {"prompt": "direct-1"}, "headers": {"X-Unsloth-More-Runs": "1"}},+ )+ first.start()+ deadline = time.monotonic() + 5+ while "direct-1" not in order and time.monotonic() < deadline:+ time.sleep(0.01)+ assert client.post(QUEUE, json = {"prompt": "queued"}).status_code == 200+ first.join(10)+ # Far past the settle window, as behind a slow proxy.+ time.sleep(1.0)+ assert order == ["direct-1"]+ assert (+ client.post("/api/inference/images/generate", json = {"prompt": "direct-2"}).status_code+ == 200+ )+ _wait(client, lambda jobs: jobs[0]["status"] == "done")+ assert order == ["direct-1", "direct-2", "queued"]+++def test_a_failed_run_marked_more_runs_does_not_hold_the_queue(client, monkeypatch):+ monkeypatch.setattr(inference_routes, "_image_queue", None)+ monkeypatch.setattr(inference_routes, "_DIRECT_RUN_SETTLE_S", 0.2)+ backend = diffusion_module.get_diffusion_backend()+ real_generate = backend.generate+ order: list[str] = []+ started = threading.Event()++ def generate(*, prompt = None, **kwargs):+ order.append(prompt)+ if prompt == "direct-1":+ started.set()+ time.sleep(0.3)+ raise RuntimeError("boom")+ return real_generate(prompt = prompt, **kwargs)++ monkeypatch.setattr(backend, "generate", generate)+ with client:+ assert (+ client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-turbo-Q4_K_S.gguf",+ "base_repo": "unsloth/Z-Image-base",+ },+ ).status_code+ == 200+ )+ first = threading.Thread(+ target = client.post,+ args = ("/api/inference/images/generate",),+ kwargs = {"json": {"prompt": "direct-1"}, "headers": {"X-Unsloth-More-Runs": "1"}},+ )+ first.start()+ started.wait(5)+ assert client.post(QUEUE, json = {"prompt": "queued"}).status_code == 200+ first.join(10)+ _wait(client, lambda jobs: jobs[0]["status"] == "done", timeout = 5)+ assert order == ["direct-1", "queued"]+++def test_a_checkpoint_pin_refuses_another_quant_at_engine_admission():+ from core.inference.diffusion_families import (+ DiffusionModelReplacedError,+ load_identity,+ pin_checkpoint,+ require_pinned_checkpoint,+ )++ loaded = load_identity("unsloth/Z-Image-Turbo-GGUF", "unsloth/Z-Image-base", "z-image")+ require_pinned_checkpoint(loaded, "z-image-turbo-Q8_0.gguf") # no pin: any checkpoint+ with pin_checkpoint("z-image-turbo-Q4_K_S.gguf"):+ require_pinned_checkpoint(loaded, "z-image-turbo-Q4_K_S.gguf")+ with pytest.raises(DiffusionModelReplacedError):+ require_pinned_checkpoint(loaded, "z-image-turbo-Q8_0.gguf")+ # Every engine checks the pin beside its expected_load admission.+ for module in ("diffusion", "sd_cpp_backend", "mlx_diffusion_backend"):+ source = (+ Path(__file__).resolve().parents[1] / "core" / "inference" / f"{module}.py"+ ).read_text(encoding = "utf-8")+ assert "require_pinned_checkpoint(loaded_id, " in source, module+++def test_stop_during_a_run_that_still_returns_does_not_hold_the_queue(client, monkeypatch):+ """A Detailer keeps its render on Stop, so the run returns; the page sends no next run."""+ monkeypatch.setattr(inference_routes, "_image_queue", None)+ monkeypatch.setattr(inference_routes, "_DIRECT_RUN_SETTLE_S", 0.2)+ backend = diffusion_module.get_diffusion_backend()+ real_generate = backend.generate+ order: list[str] = []+ started = threading.Event()+ release = threading.Event()++ def generate(*, prompt = None, **kwargs):+ order.append(prompt)+ if prompt == "direct-1":+ started.set()+ release.wait(5)+ return real_generate(prompt = prompt, **kwargs)++ monkeypatch.setattr(backend, "generate", generate)+ # The render keeps going and returns, as a Detailer pass does after Stop.+ monkeypatch.setattr(backend, "cancel_generate", lambda **kwargs: True)+ with client:+ assert (+ client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-turbo-Q4_K_S.gguf",+ "base_repo": "unsloth/Z-Image-base",+ },+ ).status_code+ == 200+ )+ first = threading.Thread(+ target = client.post,+ args = ("/api/inference/images/generate",),+ kwargs = {"json": {"prompt": "direct-1"}, "headers": {"X-Unsloth-More-Runs": "1"}},+ )+ first.start()+ started.wait(5)+ assert client.post(QUEUE, json = {"prompt": "queued"}).status_code == 200+ client.post("/api/inference/images/generate/cancel")+ release.set()+ first.join(10)+ _wait(client, lambda jobs: jobs[0]["status"] == "done", timeout = 5)+ assert order == ["direct-1", "queued"]+++def test_a_refused_stop_leaves_another_accounts_sequence_hold(client, monkeypatch):+ monkeypatch.setattr(inference_routes, "_direct_sequences", {"a": time.monotonic() + 60})+ monkeypatch.setattr(inference_routes, "_direct_stops", 7)+ monkeypatch.setattr(+ inference_routes.account_access, "generation_is_foreign", lambda modality: True+ )+ with client:+ assert client.post("/api/inference/images/generate/cancel").json() == {"cancelled": False}+ assert inference_routes._direct_stops == 7+ assert inference_routes._sequence_held()+++def test_a_running_queued_job_counts_as_inference_for_the_training_guards(gated):+ from core.inference import llama_keepwarm++ client, gates, order, _ = gated+ before = llama_keepwarm._inflight+ client.post(QUEUE, json = {"prompt": "busy"})+ _wait(client, lambda jobs: jobs[0]["status"] == "running")+ deadline = time.monotonic() + 5+ while order != ["busy"] and time.monotonic() < deadline:+ time.sleep(0.02)+ assert llama_keepwarm._inflight == before + 1+ _gate(gates, "busy").set()+ jobs = _wait(client, lambda jobs: jobs[0]["status"] == "done")+ assert llama_keepwarm._inflight == before+ assert isinstance(jobs[0]["seed_used"], int)+++def test_a_job_waits_for_a_render_it_did_not_start(gated, monkeypatch):+ """A chat image holds the engine: the queued job stays queued, so its Stop never targets that render."""+ client, gates, order, backend = gated+ rendering = {"active": True}+ monkeypatch.setattr(inference_routes, "_engine_rendering", lambda: rendering["active"])+ client.post(QUEUE, json = {"prompt": "after-chat"})+ time.sleep(0.8)+ assert _jobs(client)[0]["status"] == "queued" and order == []+ rendering["active"] = False+ _gate(gates, "after-chat").set()+ _wait(client, lambda jobs: jobs[0]["status"] == "done")+++def test_another_clients_run_does_not_release_a_sequence_hold(client, monkeypatch):+ """A1 says more follow; an unrelated B1 ends after it; the queued job still waits for A2."""+ monkeypatch.setattr(inference_routes, "_image_queue", None)+ monkeypatch.setattr(inference_routes, "_DIRECT_RUN_SETTLE_S", 0.2)+ monkeypatch.setattr(inference_routes, "_direct_sequences", {})+ backend = diffusion_module.get_diffusion_backend()+ real_generate = backend.generate+ order: list[str] = []+ started = threading.Event()++ def generate(*, prompt = None, **kwargs):+ order.append(prompt)+ if prompt == "a1":+ started.set()+ time.sleep(0.3)+ return real_generate(prompt = prompt, **kwargs)++ monkeypatch.setattr(backend, "generate", generate)+ generate_url = "/api/inference/images/generate"+ with client:+ assert (+ client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-turbo-Q4_K_S.gguf",+ "base_repo": "unsloth/Z-Image-base",+ },+ ).status_code+ == 200+ )+ first = threading.Thread(+ target = client.post,+ args = (generate_url,),+ kwargs = {+ "json": {"prompt": "a1"},+ "headers": {"X-Unsloth-Run-Sequence": "a", "X-Unsloth-More-Runs": "1"},+ },+ )+ first.start()+ started.wait(5)+ assert client.post(QUEUE, json = {"prompt": "queued"}).status_code == 200+ first.join(10)+ assert client.post(generate_url, json = {"prompt": "b1"}).status_code == 200+ time.sleep(0.8)+ assert order == ["a1", "b1"]+ assert (+ client.post(+ generate_url, json = {"prompt": "a2"}, headers = {"X-Unsloth-Run-Sequence": "a"}+ ).status_code+ == 200+ )+ _wait(client, lambda jobs: jobs[0]["status"] == "done")+ assert order == ["a1", "b1", "a2", "queued"]diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 9bc1553270e..d5d5065c29d 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -506,8 +506,11 @@ export class GenerateResponseLostError extends Error {const RESPONSE_LOST_STATUSES = new Set([408, 502, 503, 504, 522, 524]);/** A run past the proxy window throws GenerateResponseLostError; settle it, do not retry. */+/** `sequence`: this run belongs to a multi-run Generate; while `more` runs follow, the server queue holds its next job+ * until this sequence's next request arrives. */export async function generateDiffusionImage(body: DiffusionGenerateRequest,+ sequence?: { id: string; more: boolean },): Promise<DiffusionGenerateResponse> {let response: Response;try {@@ -516,7 +519,11 @@ export async function generateDiffusionImage("/api/inference/images/generate",{method: "POST",- headers: { "Content-Type": "application/json" },+ headers: {+ "Content-Type": "application/json",+ ...(sequence && { "X-Unsloth-Run-Sequence": sequence.id }),+ ...(sequence?.more && { "X-Unsloth-More-Runs": "1" }),+ },body: JSON.stringify(body),},{ retryNetworkErrors: false },@@ -559,6 +566,75 @@ export async function cancelDiffusionGeneration();}+export type ImageQueueStatus = "queued" | "running" | "done" | "failed" | "cancelled";++export interface ImageQueueJob {+ id: string;+ status: ImageQueueStatus;+ /** 0-based place among the queued jobs; null once started. */+ position: number | null;+ prompt: string;+ width: number;+ height: number;+ /** null follows the loaded model's default. */+ steps: number | null;+ seed: number | null;+ batch_size: number;+ workflow: string | null;+ loras: string[];+ created_at: number;+ started_at: number | null;+ finished_at: number | null;+ error: string | null;+ image_ids: string[];+ seed_used: number | null;+}++// A server without the queue (older Studio, proxy, test double) answers without a list: no jobs, not a crash.+function queueJobs(body: unknown): ImageQueueJob[] {+ const jobs = (body as { jobs?: unknown } | null)?.jobs;+ return Array.isArray(jobs) ? (jobs as ImageQueueJob[]) : [];+}++export async function enqueueDiffusionImage(body: DiffusionGenerateRequest): Promise<ImageQueueJob> {+ // No retry: a re-sent POST queues the run twice.+ return parseJson(+ await authFetch(+ "/api/inference/images/queue",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ },+ { retryNetworkErrors: false },+ ),+ );+}++export async function listDiffusionQueue(): Promise<ImageQueueJob[]> {+ return queueJobs(await parseJson(await authFetch("/api/inference/images/queue")));+}++export async function cancelDiffusionQueueJob(id: string): Promise<ImageQueueJob> {+ return parseJson(+ await authFetch(`/api/inference/images/queue/${encodeURIComponent(id)}/cancel`, { method: "POST" }),+ );+}++export async function moveDiffusionQueueJob(id: string, index: number): Promise<ImageQueueJob[]> {+ const res = await authFetch(`/api/inference/images/queue/${encodeURIComponent(id)}/move`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ index }),+ });+ return queueJobs(await parseJson(res));+}++export async function clearDiffusionQueue(): Promise<ImageQueueJob[]> {+ const res = await authFetch("/api/inference/images/queue", { method: "DELETE" });+ return queueJobs(await parseJson(res));+}+export async function unloadDiffusionModel(): Promise<DiffusionStatus> {return parseJson(await authFetch("/api/inference/images/unload", { method: "POST" }));}diff --git a/studio/frontend/src/features/images/generation-queue-panel.tsx b/studio/frontend/src/features/images/generation-queue-panel.tsxnew file mode 100644index 00000000000..05101fb866c--- /dev/null+++ b/studio/frontend/src/features/images/generation-queue-panel.tsx@@ -0,0 +1,114 @@+// 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 { ArrowDown, ArrowUp, X } from "lucide-react";+import type { ReactNode } from "react";++import { Button } from "@/components/ui/button";+import { Spinner } from "@/components/ui/spinner";++import type { ImageQueueJob } from "./api";+import { promptSnippet, queueJobSummary, queuedJobs, runningJob } from "./lib/generation-queue";++export function GenerationQueuePanel({+ jobs,+ onCancel,+ onMove,+ onClear,+}: {+ jobs: ImageQueueJob[];+ onCancel: (job: ImageQueueJob) => void;+ onMove: (job: ImageQueueJob, index: number) => void;+ onClear: () => void;+}) {+ const running = runningJob(jobs);+ const queued = queuedJobs(jobs);+ if (!running && queued.length === 0) return null;+ return (+ <div className="mx-4 mb-2 rounded-lg border bg-muted/30 text-xs" data-testid="images-queue-panel">+ <div className="flex items-center justify-between px-3 pt-2 pb-1">+ <span className="font-medium">Queue · {queued.length} waiting</span>+ {queued.length > 0 && (+ <Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={onClear}>+ Clear+ </Button>+ )}+ </div>+ <ol className="max-h-48 overflow-y-auto pb-1">+ {running && (+ <QueueRow job={running} label={<Spinner className="size-3" />}>+ <RowButton label="Stop this job" onClick={() => onCancel(running)}>+ <X className="size-3.5" />+ </RowButton>+ </QueueRow>+ )}+ {queued.map((job, index) => (+ <QueueRow key={job.id} job={job} label={index + 1}>+ <RowButton label="Move up" disabled={index === 0} onClick={() => onMove(job, index - 1)}>+ <ArrowUp className="size-3.5" />+ </RowButton>+ <RowButton+ label="Move down"+ disabled={index === queued.length - 1}+ onClick={() => onMove(job, index + 1)}+ >+ <ArrowDown className="size-3.5" />+ </RowButton>+ <RowButton label="Remove from queue" onClick={() => onCancel(job)}>+ <X className="size-3.5" />+ </RowButton>+ </QueueRow>+ ))}+ </ol>+ </div>+ );+}++function QueueRow({+ job,+ label,+ children,+}: {+ job: ImageQueueJob;+ label: ReactNode;+ children: ReactNode;+}) {+ return (+ <li className="flex items-center gap-2 px-3 py-1" data-status={job.status}>+ <span className="flex w-4 shrink-0 justify-center text-muted-foreground tabular-nums">{label}</span>+ <div className="min-w-0 flex-1">+ <div className="truncate" title={job.prompt}>+ {promptSnippet(job.prompt)}+ </div>+ <div className="text-muted-foreground">{queueJobSummary(job)}</div>+ </div>+ <div className="flex shrink-0 items-center">{children}</div>+ </li>+ );+}++function RowButton({+ label,+ disabled,+ onClick,+ children,+}: {+ label: string;+ disabled?: boolean;+ onClick: () => void;+ children: ReactNode;+}) {+ return (+ <Button+ variant="ghost"+ size="icon"+ className="size-6"+ aria-label={label}+ title={label}+ disabled={disabled}+ onClick={onClick}+ >+ {children}+ </Button>+ );+}diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 1a129e3c3e7..7572df8799e 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -307,7 +307,10 @@ import {type LoraSpecInput,GenerateResponseLostError,cancelDiffusionGeneration,+ cancelDiffusionQueueJob,+ clearDiffusionQueue,deleteGalleryImage,+ enqueueDiffusionImage,fetchGalleryBlob,fetchGalleryResponse,fetchGalleryObjectUrl,@@ -321,8 +324,13 @@ import {setGalleryImageFlags,getDiffusionDownloadPlan,loadDiffusionModel,+ moveDiffusionQueueJob,+ type ImageQueueJob,unloadDiffusionModel,} from "./api";+import { GenerationQueuePanel } from "./generation-queue-panel";+import { queuedJobs, runningJob } from "./lib/generation-queue";+import { useImageQueue } from "./use-image-queue";import {shouldContinueGenerating,shouldReportGenerateError,@@ -1966,6 +1974,12 @@ export function ImagesPage({const oversizedOnce = useRef(false);// The compare grid run handleGenerate is to send instead of the form's runs (compare/).const compareOnce = useRef<CompareRun | null>(null);+ // The queued job this page is following, so Stop ends that job and never the one the queue starts next.+ const followingJob = useRef<string | null>(null);+ const localRun = useRef(false);+ const queuedHere = useRef(new Set<string>());+ // Server time of the run behind sessionSeed, so a late queue poll never replaces a newer direct run's seed.+ const sessionSeedAt = useRef(0);const [sdChoice, setSdChoice] = useState<SdControlsChoice>(DEFAULT_SD_CONTROLS);// Set by Vary for the next Generate only: the seed to keep and the variation seed to slerp toward.const varyOnce = useRef<{ seed: number; variationSeed: number; strength: number } | null>(null);@@ -2149,6 +2163,14 @@ export function ImagesPage({const cancelInFlight = useRef<number | null>(null);// A pending cancel can outlive its run via 401 refresh-and-replay and hit a newer run.const cancelAbort = useRef<AbortController | null>(null);+ const resetStopState = useCallback(() => {+ cancelRequested.current = cancelAcked.current = false;+ cancelInFlight.current = null;+ cancelAbort.current?.abort();+ cancelAbort.current = null;+ runToken.current += 1;+ setStopping(false);+ }, []);const pollTimer = useRef<ReturnType<typeof setTimeout> | null>(null);const loadToastId = useRef<string | number | null>(null);// What the load POST unloaded to make room, shown on the "Model loaded" toast it ends with.@@ -3626,6 +3648,65 @@ export function ImagesPage({genPollTimer.current = setInterval(() => void pollGenerateOnce(), 300);}, [loadGallery, refreshStatus]);+ const imageQueue = useImageQueue(active, (finished) => {+ if (finished.some((job) => job.status === "done")) {+ // Fences an earlier refresh still in flight, so it refetches instead of landing after this one.+ stripEpoch.current += 1;+ void loadGallery();+ }+ let latest: ImageQueueJob | null = null;+ for (const job of finished) {+ if (job.status === "failed") toast.error(job.error ?? "A queued generation failed");+ if (job.status === "done" && queuedHere.current.delete(job.id) && typeof job.seed_used === "number") {+ if (!latest || (job.finished_at ?? 0) > (latest.finished_at ?? 0)) latest = job;+ }+ }+ // Newer than the session seed's run (server clock both sides), as a direct Generate's would be, for Reuse last seed.+ if (latest && (latest.finished_at ?? 0) > sessionSeedAt.current) {+ sessionSeedAt.current = latest.finished_at ?? 0;+ setSessionSeed(latest.seed_used);+ }+ });+ const queueRunningId = runningJob(imageQueue.jobs)?.id ?? null;+ const queueWaiting = queuedJobs(imageQueue.jobs).length > 0;+ useEffect(() => {+ if (busy !== null) return;+ followingJob.current = null;+ localRun.current = false;+ }, [busy]);+ useEffect(() => {+ // Busy on a run this page did not start: it is the queue's running job, so Stop targets it by id.+ if (queueRunningId && busy === "generating" && !localRun.current && followingJob.current !== queueRunningId) {+ // A different job: the previous one's Stop state and in-flight acknowledgement do not carry over.+ if (followingJob.current !== null) resetStopState();+ followingJob.current = queueRunningId;+ return;+ }+ // The followed job ended while another render keeps the page busy: Stop goes back to that render.+ if (!queueRunningId && followingJob.current) followingJob.current = null;+ // Idle with a job running (also after a gap in its progress, e.g. captioning): follow it once it denoises.+ if (!queueRunningId || busy !== null) return;+ let cancelled = false;+ void (async () => {+ try {+ const p = await getGenerateProgress();+ // Not denoising yet: the next queue poll (a new jobs array) asks again.+ if (cancelled || !p.active || !isMounted.current) return;+ resetStopState();+ followingJob.current = queueRunningId;+ runTarget.current = undefined;+ setBusy("generating");+ setGenStep(p);+ resumeGeneratePoll();+ } catch {+ // best-effort, like the mount probe+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [queueRunningId, busy, resumeGeneratePoll, imageQueue.jobs, resetStopState]);+useEffect(() => {void (async () => {await refreshStatus();@@ -5175,7 +5256,8 @@ export function ImagesPage({</>);- const handleGenerate = useCallback(async () => {+ // toQueue: the runs go to the server queue instead of running here.+ const handleGenerate = useCallback(async (toQueue = false) => {const allowOversizedSent = allowOversizedField(allowOversized, oversizedOnce.current) === true;oversizedOnce.current = false;const vary = sdCaps?.variation_seed ? varyOnce.current : null;@@ -5337,7 +5419,79 @@ export function ImagesPage({return;}+ // One run's request; Generate sends them here one by one, Queue hands them all to the server queue.+ const requestFor = (i: number): DiffusionGenerateRequest => {+ const runBaseSeed = varying ? baseSeed : baseSeed + i * batchSize;+ return compareRequest(compare, i, baseSeed, {+ prompt: prompt.trim(),+ // Only send a negative prompt when guidance uses it, so the recipe does not record one the model ignored.+ negative_prompt: negativeEngaged ? negativePrompt.trim() || undefined : undefined,+ width: w,+ height: h,+ steps,+ guidance: effectiveGuidance,+ seed: runBaseSeed,+ batch_size: batchSize,+ // Transform/Inpaint/Extend send the source image (and mask) with a strength; the backend+ // derives output size from the image.+ init_image: condInit,+ mask_image: condMask,+ strength: condStrength,+ ...condInpaint,+ upscale: condUpscale,+ upscale_model: isUpscale ? upscaleModelRequest(upscaleModel, upscaleModels) : undefined,+ hires: hiresRequest(hires, hiresCapability, workflow),+ allow_oversized: allowOversizedSent ? true : undefined,+ live_preview: livePreview,+ ...samplerRequestFields(samplerOptions, samplerChoice),+ ...sdControlsRequestFields(+ sdCaps,+ runChoice,+ // A compare grid keeps the form's variation seed for every cell (its axis, if any, replaces it), so+ // only the swept setting differs between cells.+ baseVariationSeed !== null ? (baseVariationSeed + (compare ? 0 : i * batchSize)) % 2 ** 32 : null,+ varying,+ !controlnetEngaged,+ ),+ ...shiftRequestFields(shiftControl, shiftValue),+ ...enhancePromptRequestField(upsamplerCapability, enhanceOn),+ ...condFields,+ ...detailerRequestField(detailerOn, detailerReady, detailerOptions),+ // Drop empty and zero-weight rows and trim hand-typed repo ids, so the recipe records only+ // adapters that applied. Gated on loraCapable, since a restore can leave adapters in state.+ loras: (() => {+ if (!loraCapable) return undefined;+ const active = loras+ .map((l) => ({ id: l.id.trim(), weight: l.weight }))+ .filter((l) => l.id && l.weight > 0);+ return active.length ? active : undefined;+ })(),+ // ControlNet: sent only when a model + control image are chosen; v1 conditions plain text-to-image only.+ controlnet:+ controlnetCapable && controlnetId && controlImage && workflow === "create"+ ? {+ id: controlnetId,+ image: controlImage,+ control_type: controlType,+ strength: controlStrength,+ }+ : undefined,+ ...(external && { provider_id: external.providerId, model: external.modelId }),+ });+ };++ // Saved only once the request passes validation, so a rejected attempt is not kept.saveLastPrompt(`images:${workflow}`, prompt);+ if (toQueue && !compare && !external) {+ try {+ for (let i = 0; i < runs; i++) queuedHere.current.add((await enqueueDiffusionImage(requestFor(i))).id);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Could not queue the generation");+ }+ return;+ }+ followingJob.current = null;+ localRun.current = true;setBusy("generating");setGenDone(0);setGenStep(null);@@ -5378,6 +5532,8 @@ export function ImagesPage({// Captured BEFORE the first POST: settleLostGeneration needs a record outside it as proof.const knownIds = new Set(galleryCache.images.map((image) => image.id));try {+ // Not crypto.randomUUID: a LAN Studio over plain http is not a secure context.+ const sequenceId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;for (let i = 0; i < runTotal; i++) {// Stop issuing more GPU generations once the page unmounted or Stop was pressed: the backend// cancel only reaches the denoise in flight, so a count > 1 request would run on.@@ -5399,59 +5555,7 @@ export function ImagesPage({const runBaseSeed = varying ? baseSeed : baseSeed + i * batchSize;let res: DiffusionGenerateResponse;try {- res = await generateDiffusionImage(compareRequest(compare, i, baseSeed, {- prompt: prompt.trim(),- // Only send a negative prompt when guidance uses it, so the recipe does not record one the model ignored.- negative_prompt: negativeEngaged ? negativePrompt.trim() || undefined : undefined,- width: w,- height: h,- steps,- guidance: effectiveGuidance,- seed: runBaseSeed,- batch_size: batchSize,- init_image: condInit,- mask_image: condMask,- strength: condStrength,- ...condInpaint,- upscale: condUpscale,- upscale_model: isUpscale ? upscaleModelRequest(upscaleModel, upscaleModels) : undefined,- hires: hiresRequest(hires, hiresCapability, workflow),- allow_oversized: allowOversizedSent ? true : undefined,- live_preview: livePreview,- ...samplerRequestFields(samplerOptions, samplerChoice),- ...sdControlsRequestFields(- sdCaps,- runChoice,- // A compare grid keeps the form's variation seed for every cell (its axis, if any, replaces it), so- // only the swept setting differs between cells.- baseVariationSeed !== null ? (baseVariationSeed + (compare ? 0 : i * batchSize)) % 2 ** 32 : null,- varying,- !controlnetEngaged,- ),- ...shiftRequestFields(shiftControl, shiftValue),- ...enhancePromptRequestField(upsamplerCapability, enhanceOn),- ...condFields,- ...detailerRequestField(detailerOn, detailerReady, detailerOptions),- // Drop empty and zero-weight rows and trim hand-typed repo ids, so the recipe records only- // adapters that applied. Gated on loraCapable, since a restore can leave adapters in state.- loras: (() => {- if (!loraCapable) return undefined;- const active = loras- .map((l) => ({ id: l.id.trim(), weight: l.weight }))- .filter((l) => l.id && l.weight > 0);- return active.length ? active : undefined;- })(),- controlnet:- controlnetCapable && controlnetId && controlImage && workflow === "create"- ? {- id: controlnetId,- image: controlImage,- control_type: controlType,- strength: controlStrength,- }- : undefined,- ...(external && { provider_id: external.providerId, model: external.modelId }),- }));+ res = await generateDiffusionImage(requestFor(i), { id: sequenceId, more: i < runTotal - 1 });} catch (err) {// The tunnel caps the response near 100s; retrying would duplicate the work.if (!(err instanceof GenerateResponseLostError)) throw err;@@ -5459,12 +5563,17 @@ export function ImagesPage({if (!isMounted.current) break;await loadGallery();// A compare cell takes its record from what the gallery gained (matched by seed in compare/).- compare?.onImages(i, galleryCache.images.filter((image) => !knownIds.has(image.id)));+ const gained = galleryCache.images.filter((image) => !knownIds.has(image.id));+ compare?.onImages(i, gained);// loadGallery refreshes the module cache synchronously, so this run's records are folded in// before the next run.galleryCache.images.forEach((image) => knownIds.add(image.id));- // The run landed without its records, so Reuse last seed takes the seed it was sent.- if (!external) setSessionSeed(compare?.sentSeed(i) ?? runBaseSeed);+ // No records came back: Reuse last seed takes the sent seed, unless a later queued run already set one.+ const gainedAt = Math.max(0, ...gained.map((image) => image.created_at));+ if (!external && gainedAt >= sessionSeedAt.current) {+ sessionSeedAt.current = gainedAt;+ setSessionSeed(compare?.sentSeed(i) ?? runBaseSeed);+ }setGenDone(i + 1);continue;}@@ -5476,7 +5585,12 @@ export function ImagesPage({res.images.forEach((image) => knownIds.add(image.id));if (res.images[0]) setSelectedId(res.images[0].id);const runSeed = lastSeedOf(res.images);- if (runSeed !== null) setSessionSeed(runSeed);+ const runAt = Math.max(0, ...res.images.map((image) => image.created_at));+ // A late reply never replaces the seed of a queued run that finished after it.+ if (runSeed !== null && runAt >= sessionSeedAt.current) {+ sessionSeedAt.current = runAt;+ setSessionSeed(runSeed);+ }// Asked for enhancement and did not get it: say so once, without blocking the result.if (enhanceOn && upsamplerCapability.supported) {const notice = enhancementNotice(res.images[0]?.prompt_enhancement);@@ -5549,13 +5663,18 @@ export function ImagesPage({const abort = new AbortController();cancelAbort.current = abort;try {- const { cancelled } = runTarget.current- ? await cancelConnectionImageGeneration(abort.signal)- : await cancelDiffusionGeneration(abort.signal);+ const followed = followingJob.current;+ const { cancelled } = followed+ ? { cancelled: (await cancelDiffusionQueueJob(followed)).status !== "done" }+ : runTarget.current+ ? await cancelConnectionImageGeneration(abort.signal)+ : await cancelDiffusionGeneration(abort.signal);+ // The page moved on to another job meanwhile: this answer is about the old one.+ if (runToken.current !== token) return;cancelAcked.current = Boolean(cancelled);if (!cancelled) setStopping(false);} catch {- if (!abort.signal.aborted) {+ if (!abort.signal.aborted && runToken.current === token) {cancelAcked.current = false;setStopping(false);toast.error("Could not reach the server to stop this generation; it is still running");@@ -5566,6 +5685,32 @@ export function ImagesPage({}}, []);+ const handleQueue = useCallback(async () => {+ if (!imagePresets.hydrated) return;+ await handleGenerate(true);+ await imageQueue.refresh();+ }, [handleGenerate, imagePresets.hydrated, imageQueue.refresh]);+ const queueAction = useCallback(+ async (action: () => Promise<unknown>) => {+ try {+ await action();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Could not update the queue");+ }+ await imageQueue.refresh();+ },+ [imageQueue.refresh],+ );+ const handleCancelQueued = useCallback(+ (job: ImageQueueJob) => void queueAction(() => cancelDiffusionQueueJob(job.id)),+ [queueAction],+ );+ const handleMoveQueued = useCallback(+ (job: ImageQueueJob, index: number) => void queueAction(() => moveDiffusionQueueJob(job.id, index)),+ [queueAction],+ );+ const handleClearQueue = useCallback(() => void queueAction(clearDiffusionQueue), [queueAction]);+// Compare grid: handleGenerate reads the run from compareOnce, so a grid shares Stop, progress and the gallery// merge with Generate. Text-to-image on a loaded local model only.const [compareRun, setCompareRun] = useState<CompareRun | null>(null);@@ -5585,6 +5730,7 @@ export function ImagesPage({[busy, handleGenerate, imagePresets.hydrated],);const compareAvailable = !external && Boolean(status?.loaded) && workflow === "create";+ const canQueue = !external && Boolean(status?.loaded);const compareSdControls = sdCaps;const compareContext = useMemo<CompareContext>(() => ({@@ -7096,6 +7242,12 @@ export function ImagesPage({)}</div>+ <GenerationQueuePanel+ jobs={imageQueue.jobs}+ onCancel={handleCancelQueued}+ onMove={handleMoveQueued}+ onClear={handleClearQueue}+ />{/* The scroll mask provides the fade; leave the footer unpainted to avoid dark-mode banding. */}<div className="relative z-10 flex shrink-0 flex-wrap justify-center gap-2 px-4 pt-0.5 pb-3">{!external && busy === null && heldByOtherAccount(status) && (@@ -7104,22 +7256,32 @@ export function ImagesPage({</p>)}{busy === "generating" ? (- <Button- className="relative z-10 text-ui-13 hover:bg-muted dark:hover:bg-muted"- variant="outline"- onClick={handleCancelGenerate}- >- <Spinner className="mr-2 size-4" />- {stopButtonLabel({ stopping, done: genDone, count })}- </Button>+ /* Replaces Generate while a run is in flight. Every workflow funnels through the same+ handler, so one control stops all of them. */+ <>+ <Button+ className="relative z-10 text-ui-13 hover:bg-muted dark:hover:bg-muted"+ variant="outline"+ onClick={handleCancelGenerate}+ >+ <Spinner className="mr-2 size-4" />+ {stopButtonLabel({ stopping, done: genDone, count })}+ </Button>+ {canQueue && compareRun === null && (+ <Button className="relative z-10 text-ui-13" onClick={handleQueue} disabled={!imagePresets.hydrated}>+ Queue+ </Button>+ )}+ </>) : (<><Button variant="primary"className="relative z-10 h-11 px-8 text-ui-14 bg-control-accent text-control-accent-foreground hover:bg-control-accent/85 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100"- onClick={handleGenerateWithRecall}+ // Jobs still waiting: a new one lines up behind them instead of jumping the queue.+ onClick={queueWaiting && canQueue ? handleQueue : handleGenerateWithRecall}disabled={busy !== null || !imagePresets.hydrated || (!status?.loaded && !rememberedModel && !external)}>- Generate+ {queueWaiting && canQueue ? "Queue" : "Generate"}</Button>{canVary && (<Tooltip>diff --git a/studio/frontend/src/features/images/lib/generation-queue.ts b/studio/frontend/src/features/images/lib/generation-queue.tsnew file mode 100644index 00000000000..5a5783359bf--- /dev/null+++ b/studio/frontend/src/features/images/lib/generation-queue.ts@@ -0,0 +1,47 @@+// 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 { ImageQueueJob } from "../api.ts";++const FINISHED = new Set(["done", "failed", "cancelled"]);++export function queuedJobs(jobs: readonly ImageQueueJob[]): ImageQueueJob[] {+ return jobs.filter((job) => job.status === "queued");+}++export function runningJob(jobs: readonly ImageQueueJob[]): ImageQueueJob | null {+ return jobs.find((job) => job.status === "running") ?? null;+}++/** Whether the queue still has work, so the page keeps polling and Generate keeps lining up behind it. */+export function queueBusy(jobs: readonly ImageQueueJob[]): boolean {+ return jobs.some((job) => job.status === "queued" || job.status === "running");+}++/** Jobs that finished between two polls, including one queued and finished in between. `prev` null is the first+ * poll (a reload): what already finished then is not news. */+export function newlyFinished(+ prev: readonly ImageQueueJob[] | null,+ next: readonly ImageQueueJob[],+): ImageQueueJob[] {+ if (prev === null) return [];+ const before = new Map(prev.map((job) => [job.id, job.status]));+ return next.filter((job) => {+ const was = before.get(job.id);+ return FINISHED.has(job.status) && (was === undefined || !FINISHED.has(was));+ });+}++export function promptSnippet(prompt: string, max = 60): string {+ const flat = prompt.replace(/\s+/g, " ").trim();+ return flat.length > max ? `${flat.slice(0, max - 1).trimEnd()}…` : flat;+}++export function queueJobSummary(job: ImageQueueJob): string {+ return [+ `${job.width}×${job.height}`,+ job.steps === null ? "model steps" : `${job.steps} steps`,+ job.seed === null ? "random seed" : `seed ${job.seed}`,+ ...(job.batch_size > 1 ? [`×${job.batch_size}`] : []),+ ].join(" · ");+}diff --git a/studio/frontend/src/features/images/use-image-queue.ts b/studio/frontend/src/features/images/use-image-queue.tsnew file mode 100644index 00000000000..ebc8d563446--- /dev/null+++ b/studio/frontend/src/features/images/use-image-queue.ts@@ -0,0 +1,50 @@+// 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 { useCallback, useEffect, useRef, useState } from "react";++import { type ImageQueueJob, listDiffusionQueue } from "./api";+import { newlyFinished, queueBusy } from "./lib/generation-queue";++const BUSY_POLL_MS = 1000;+// Idle, the page still notices jobs queued over the API.+const IDLE_POLL_MS = 5000;++export function useImageQueue(active: boolean, onFinished: (jobs: ImageQueueJob[]) => void) {+ const [jobs, setJobs] = useState<ImageQueueJob[]>([]);+ const jobsRef = useRef<ImageQueueJob[] | null>(null);+ const finishedRef = useRef(onFinished);+ finishedRef.current = onFinished;++ const apply = useCallback((next: ImageQueueJob[]) => {+ const finished = newlyFinished(jobsRef.current, next);+ jobsRef.current = next;+ setJobs(next);+ if (finished.length) finishedRef.current(finished);+ }, []);++ // Polls and action refreshes overlap on a slow link: an answer older than one already applied is dropped.+ const issued = useRef(0);+ const applied = useRef(0);+ const refresh = useCallback(async () => {+ const id = ++issued.current;+ try {+ const jobs = await listDiffusionQueue();+ if (id < applied.current) return;+ applied.current = id;+ apply(jobs);+ } catch {+ // transient; the next poll retries+ }+ }, [apply]);++ const busy = queueBusy(jobs);+ useEffect(() => {+ if (!active) return;+ void refresh();+ const timer = setInterval(() => void refresh(), busy ? BUSY_POLL_MS : IDLE_POLL_MS);+ return () => clearInterval(timer);+ }, [active, busy, refresh]);++ return { jobs, refresh, apply };+}diff --git a/studio/frontend/tests/image-generation-queue.test.ts b/studio/frontend/tests/image-generation-queue.test.tsnew file mode 100644index 00000000000..6e5aeca37bc--- /dev/null+++ b/studio/frontend/tests/image-generation-queue.test.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import type { ImageQueueJob } from "../src/features/images/api.ts";+import {+ newlyFinished,+ promptSnippet,+ queueBusy,+ queuedJobs,+ queueJobSummary,+ runningJob,+} from "../src/features/images/lib/generation-queue.ts";+import { readSrc } from "./helpers/kit.ts";++function job(id: string, status: ImageQueueJob["status"], extra: Partial<ImageQueueJob> = {}): ImageQueueJob {+ return {+ id,+ status,+ position: null,+ prompt: `prompt ${id}`,+ width: 1024,+ height: 768,+ steps: 9,+ seed: 42,+ batch_size: 1,+ workflow: null,+ loras: [],+ created_at: 0,+ started_at: null,+ finished_at: null,+ error: null,+ image_ids: [],+ seed_used: null,+ ...extra,+ };+}++test("the running job and the waiting ones are told apart; finished jobs are neither", () => {+ const jobs = [job("a", "running"), job("b", "queued"), job("c", "queued"), job("d", "done")];+ assert.equal(runningJob(jobs)?.id, "a");+ assert.deepEqual(queuedJobs(jobs).map((j) => j.id), ["b", "c"]);+ assert.equal(queueBusy(jobs), true);+ assert.equal(queueBusy([job("d", "done"), job("e", "cancelled")]), false);+ assert.equal(runningJob([job("b", "queued")]), null);+});++test("a job pending on the last poll, or queued and finished since, counts as newly finished", () => {+ const prev = [job("a", "running"), job("b", "queued"), job("old", "done")];+ const next = [job("b", "running"), job("a", "done"), job("api", "failed"), job("old", "done")];+ assert.deepEqual(newlyFinished(prev, next).map((j) => j.id), ["a", "api"]);+ // The first poll after a reload reports history, not news.+ assert.deepEqual(newlyFinished(null, next), []);+ assert.deepEqual(+ newlyFinished([job("b", "queued")], [job("b", "cancelled")]).map((j) => j.status),+ ["cancelled"],+ );+});++test("a row shows a one-line prompt snippet and the settings that tell jobs apart", () => {+ assert.equal(promptSnippet("a red\n fox"), "a red fox");+ const long = promptSnippet("x".repeat(100), 20);+ assert.equal(long.length, 20);+ assert.ok(long.endsWith("…"));+ assert.equal(queueJobSummary(job("a", "queued")), "1024×768 · 9 steps · seed 42");+ assert.equal(+ queueJobSummary(job("a", "queued", { steps: null, seed: null, batch_size: 4 })),+ "1024×768 · model steps · random seed · ×4",+ );+});++test("while a render runs the page offers Queue beside Stop, and Generate queues behind waiting jobs", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /\{canQueue && compareRun === null && \(\s*<Button[^>]*onClick=\{handleQueue\}/);+ assert.match(page, /onClick=\{queueWaiting && canQueue \? handleQueue : handleGenerateWithRecall\}/);+ // Queue reuses Generate's validation and request, then hands the runs to the server.+ assert.match(page, /if \(toQueue && !compare && !external\) \{[\s\S]*?enqueueDiffusionImage\(requestFor\(i\)\)/);+ assert.match(page, /res = await generateDiffusionImage\(requestFor\(i\), { id: sequenceId, more: i < runTotal - 1 }\);/);+});diff --git a/studio/frontend/tests/image-prompt-enhance.test.ts b/studio/frontend/tests/image-prompt-enhance.test.tsindex 8bd4b74f403..5bb445efc49 100644--- a/studio/frontend/tests/image-prompt-enhance.test.ts+++ b/studio/frontend/tests/image-prompt-enhance.test.ts@@ -86,7 +86,7 @@ test("enhance_prompt is sent only when the loaded family supports it", () => {assert.deepEqual(enhancePromptRequestField(promptUpsamplerCapability(null), true), {});// Wired into the generate request.const page = readSrc("features/images/images-page.tsx");- const call = page.slice(page.indexOf("res = await generateDiffusionImage("));+ const call = page.slice(page.indexOf("const requestFor = (i: number)"));assert.match(call.slice(0, 4000), /\.\.\.enhancePromptRequestField\(upsamplerCapability, enhanceOn\)/);});diff --git a/studio/frontend/tests/image-seed-inpaint-steps.test.ts b/studio/frontend/tests/image-seed-inpaint-steps.test.tsindex e062ec5afbb..974f9597ea9 100644--- a/studio/frontend/tests/image-seed-inpaint-steps.test.ts+++ b/studio/frontend/tests/image-seed-inpaint-steps.test.ts@@ -92,7 +92,7 @@ test("the Seed field has Random and Reuse last seed buttons", () => {);assert.match(page,- /const runSeed = lastSeedOf\(res\.images\);\n\s+if \(runSeed !== null\) setSessionSeed\(runSeed\);/,+ /const runSeed = lastSeedOf\(res\.images\);[\s\S]{0,300}if \(runSeed !== null && runAt >= sessionSeedAt\.current\) \{[\s\S]{0,120}setSessionSeed\(runSeed\);/,);assert.match(page, /<Shuffle className="size-4" strokeWidth=\{1\.5\} \/>/);assert.match(page, /<HugeiconsIcon icon=\{HistoryIcon\} className="size-4" strokeWidth=\{1\.5\} \/>/);@@ -179,7 +179,7 @@ test("a run whose response was lost still becomes the seed Reuse last seed picksassert.match(page, /seed: runBaseSeed,/);assert.match(page,- /if \(!\(err instanceof GenerateResponseLostError\)\) throw err;[\s\S]*?if \(!external\) setSessionSeed\((?:compare\?\.sentSeed\(i\) \?\? )?runBaseSeed\);\n\s+setGenDone\(i \+ 1\);\n\s+continue;/,+ /if \(!\(err instanceof GenerateResponseLostError\)\) throw err;[\s\S]*?if \(!external && gainedAt >= sessionSeedAt\.current\) \{[\s\S]{0,120}setSessionSeed\(compare\?\.sentSeed\(i\) \?\? runBaseSeed\);\n\s+\}\n\s+setGenDone\(i \+ 1\);\n\s+continue;/,);});diff --git a/studio/frontend/tests/images-compare-grid.test.ts b/studio/frontend/tests/images-compare-grid.test.tsindex 3b8e4e0e590..6ad4a7e905f 100644--- a/studio/frontend/tests/images-compare-grid.test.ts+++ b/studio/frontend/tests/images-compare-grid.test.ts@@ -431,10 +431,14 @@ test("the Images page (its own lazy chunk) renders the panel and loops cells thrconst root = readSrc("app/routes/__root.tsx");assert.match(root, /lazy\(\(\) =>\s*import\("@\/features\/images"\)/);assert.match(page, /for \(let i = 0; i < runTotal; i\+\+\)/);- assert.match(page, /generateDiffusionImage\(compareRequest\(compare, i, baseSeed, \{/);+ assert.match(page, /return compareRequest\(compare, i, baseSeed, \{/);+ assert.match(page, /generateDiffusionImage\(requestFor\(i\), { id: sequenceId, more: i < runTotal - 1 }\)/);assert.match(page, /compare\?\.onImages\(i, res\.images\)/);// The lost-response branch also reports the cell, from the records the gallery gained.- assert.match(page, /compare\?\.onImages\(i, galleryCache\.images\.filter\(\(image\) => !knownIds\.has\(image\.id\)\)\)/);+ assert.match(+ page,+ /const gained = galleryCache\.images\.filter\(\(image\) => !knownIds\.has\(image\.id\)\);\s+compare\?\.onImages\(i, gained\)/,+ );assert.match(page, /workflow === "create"/);});