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
Studio: let image generation be stopped (#8219)
Daniel Hanf9656fd6cc7d
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex f1387def963..cd7e0bbbac2 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -4491,6 +4491,20 @@ class DiffusionBackend:compile_cache.save(state.compile_cache_ctx, logger = logger)except Exception: # noqa: BLE001 — cache persistence is best-effortpass+ # Last word on cancellation, AFTER the post-denoise work: the event stays+ # registered through the compile-cache save (a static compile writes a fresh+ # artifact per shape, so that save is not instant) and the page still shows Stop+ # for as long as progress reads active, so a Stop landing there was answered+ # cancelled = true and then contradicted by the image the route persisted.+ # Check and deregister under _lock, which is the lock cancel_generate takes, so the+ # two cannot interleave: a cancel that saw this event registered ran strictly+ # before the check, and one that arrives after finds nothing to set and answers+ # false. The finally below repeats the clear for every other exit.+ with self._lock:+ if cancel.is_set():+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ if self._active_generate_cancel is cancel:+ self._active_generate_cancel = None# Count the finished generation (drives deferred speed); a batch is one generation.object.__setattr__(state, "generation_count", state.generation_count + 1)# Return the PIL images unencoded; the route embeds recipes and persists them. ``seeds`` records each image's own seed.@@ -4542,6 +4556,24 @@ class DiffusionBackend:"eta_seconds": gen.eta_seconds,}+ def cancel_generate(self) -> bool:+ """Signal the in-flight generation to stop at its next step boundary.++ The denoise loop already watches this event (``_on_step`` sets diffusers'+ ``_interrupt``, and the per-chunk check discards a partial batch), but until now only+ unload() and a superseding load could set it. Returns False when nothing is running,+ which the route reports so the UI can settle its button back to Generate.++ Best effort by construction: the sampler stops at the NEXT step callback, so a cancel+ during the VAE decode or the encode that precedes step 0 lands when that finishes.+ Same contract as the video backend."""+ with self._lock:+ cancel = self._active_generate_cancel+ if cancel is None:+ return False+ cancel.set()+ return True+def unload(self) -> dict[str, Any]:with self._lock:# Abort an in-flight (lock-free) download so unload returns promptly. Under the lock, like video.py: begin_loaddiff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex a04d0a555eb..8ccfb05f9c3 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -1152,8 +1152,17 @@ class SdCppDiffusionBackend:lora_resolved = lora_resolved,cancel = cancel,)- if cancel.is_set():- raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ # Check and deregister under _lock, the lock cancel_generate takes, so the two+ # cannot interleave: a cancel that saw this event registered ran strictly before+ # the check and the run unwinds as cancelled, and one arriving after finds nothing+ # to set and answers false. Same critical section as DiffusionBackend.generate;+ # /images/generate/cancel resolves through the engine router, so a native host has+ # to give the same answer. The finally repeats the clear for every other exit.+ with self._lock:+ if cancel.is_set():+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ if self._active_generate_cancel is cancel:+ self._active_generate_cancel = None# ``seeds`` is the per-image seed (image i used seed+i) for the route to persist.return {"images": images,@@ -1469,6 +1478,19 @@ class SdCppDiffusionBackend:"eta_seconds": gen.eta_seconds,}+ def cancel_generate(self) -> bool:+ """Signal the in-flight generation to stop, matching DiffusionBackend.cancel_generate.++ The native engine is stricter than best-effort: the runner polls this event and kills+ the sd-cli process tree, so the stop lands within the poll interval rather than at the+ next step boundary. Returns False when nothing is running."""+ with self._lock:+ cancel = self._active_generate_cancel+ if cancel is None:+ return False+ cancel.set()+ return True+# ── Unload / status ──────────────────────────────────────────────────────def unload(self) -> dict[str, Any]:diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex aad36820d40..e237db9eca4 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -155,6 +155,14 @@ _install_httpcore_asyncgen_silencer()# that bounded work out of the default executor, which drives local token streaming._STATUS_PROBE_EXECUTOR = ThreadPoolExecutor(max_workers = 2, thread_name_prefix = "inference-status")+# Stop has to preempt exactly when the box is busy, so it gets its own workers for the same reason+# the probes above do. Every /images/generate sits in the default executor for the whole run (it+# blocks on the backend's serial _generate_lock), so concurrent generations can occupy that pool+# and leave a cancel queued until the run it was meant to stop has already finished. Off the+# default executor rather than on the event loop: cancelling a native sd.cpp run kills a process+# tree, which is not a short call.+_CANCEL_EXECUTOR = ThreadPoolExecutor(max_workers = 2, thread_name_prefix = "inference-cancel")+def _loaded_chat_template() -> Optional[str]:"""Chat template of the currently loaded GGUF model, if any."""@@ -20700,6 +20708,24 @@ async def diffusion_generate_progress(current_subject: str = Depends(get_currentreturn DiffusionGenerateProgressResponse(**progress)+@studio_router.post("/images/generate/cancel")+async def cancel_diffusion_generation(current_subject: str = Depends(get_current_subject)):+ """Stop the in-flight image generation, mirroring POST /video/generate/cancel.++ Resolved through the engine router, so it stops a diffusers denoise (at its next step+ boundary) and a native sd.cpp run (which kills the sd-cli process tree) alike. The+ generation's OWN request is what reports the outcome: it unwinds with the cancelled+ sentinel, which this module already maps to a 409. ``cancelled`` is False when nothing was+ running, so the page can settle its button back to Generate rather than wait for a+ generation that already finished."""+ from core.inference.diffusion_engine_router import get_active_diffusion_engine++ cancelled = await asyncio.get_running_loop().run_in_executor(+ _CANCEL_EXECUTOR, get_active_diffusion_engine().cancel_generate+ )+ return {"cancelled": cancelled}++# ──────────────────────────────────────────────────────────────────────────# OpenAI-compatible images API (POST /v1/images/generations). The inference router is mounted at both /api/inference and /v1, so this# also answers /v1/images/generations for OpenAI clients. The Studio Image tab uses the richer /images/generate above; this is the spec shape.diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 2a4bd9e8183..41f386e9cf7 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -6789,3 +6789,206 @@ def test_download_plan_skips_nothing_when_the_hub_reports_no_commit(monkeypatch)"unsloth/FLUX.1-dev-GGUF","unsloth/FLUX.1-dev",}+++# ── generate cancellation (issue #8187) ──────────────────────────────────────+#+# The denoise loop already honoured the per-generation cancel event, but only unload() and a+# superseding load could set it, so there was no way for a user to stop a run. These cover the+# public cancel_generate() across EVERY image workflow, since all five UI surfaces (Create,+# Transform, Inpaint, Extend, Upscale) funnel through the same generate() and would otherwise+# be assumed to work from a Create-only test.+++def _stepping_call(record):+ """A pipeline __call__ that actually steps, so a cancel can be observed mid-denoise.++ The fake pipes return immediately, which cannot distinguish "the sampler stopped" from+ "the sampler finished". This mirrors diffusers: invoke callback_on_step_end each step and+ break out when the callback sets ``_interrupt``, exactly as the real denoise loop does."""++ def _call(+ self,+ *,+ callback_on_step_end = None,+ **kwargs,+ ):+ record["steps_run"] = 0+ self._interrupt = False+ for index in range(record["total_steps"]):+ if callback_on_step_end is not None:+ callback_on_step_end(self, index, index, {})+ record["steps_run"] = index + 1+ record["reached"].set()+ if getattr(self, "_interrupt", False):+ break+ record["resume"].wait(5)+ n = kwargs.get("num_images_per_prompt", 1)+ return types.SimpleNamespace(images = [_FakeImage() for _ in range(n)])++ return _call+++ "surface,gen_kwargs",+ [+ ("create", {}),+ ("transform", {"init_image": _tiny_png_b64(), "strength": 0.5}),+ # Extend is the Images page's outpaint tab: it pads the canvas client-side and sends the+ # result down the SAME inpaint path, so inpaint covers both surfaces.+ ("inpaint", {"init_image": _tiny_png_b64(), "mask_image": _mask_b64(64)}),+ ("extend", {"init_image": _tiny_png_b64(), "mask_image": _mask_b64(64)}),+ ("upscale", {"init_image": _tiny_png_b64(), "upscale": 2.0}),+ ],+)+def test_cancel_generate_stops_every_workflow(+ fake_runtime, tmp_path, monkeypatch, surface, gen_kwargs+):+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG++ (tmp_path / "model.gguf").write_bytes(b"x")+ backend = DiffusionBackend()+ backend.load_pipeline(+ str(tmp_path), gguf_filename = "model.gguf", base_repo = "base/repo", family_override = "z-image"+ )++ record = {+ "total_steps": 8,+ "steps_run": 0,+ "reached": threading.Event(),+ "resume": threading.Event(),+ }+ stepping = _stepping_call(record)+ for cls in (_FakePipe, _FakeImg2ImgPipe, _FakeInpaintPipe):+ monkeypatch.setattr(cls, "__call__", stepping)++ # Nothing in flight yet, so there is nothing to stop.+ assert backend.cancel_generate() is False++ outcome: dict = {}++ def _run():+ try:+ outcome["result"] = backend.generate(+ prompt = "a sloth", steps = record["total_steps"], **gen_kwargs+ )+ except BaseException as exc: # noqa: BLE001 -- the test asserts on the exact type/text+ outcome["error"] = exc++ worker = threading.Thread(target = _run, daemon = True)+ worker.start()+ assert record["reached"].wait(5), f"{surface}: the denoise never started"++ assert backend.cancel_generate() is True+ record["resume"].set()+ worker.join(10)+ assert not worker.is_alive(), f"{surface}: the denoise did not unwind"++ # The sampler stopped rather than ran to completion, and nothing was returned to persist.+ assert "result" not in outcome, f"{surface}: a cancelled run still produced images"+ assert isinstance(outcome["error"], RuntimeError)+ assert str(outcome["error"]) == DIFFUSION_CANCELLED_MSG+ assert record["steps_run"] < record["total_steps"], (+ f"{surface}: ran {record['steps_run']}/{record['total_steps']} steps, so the cancel "+ "never reached the sampler"+ )+ # The progress state is cleared on every exit, so the page does not stay stuck at "generating".+ assert backend.generate_progress()["active"] is False+ # Deregistered, so a second cancel does not poke a finished generation.+ assert backend.cancel_generate() is False+++def test_cancel_generate_lands_at_the_next_step_boundary(fake_runtime, tmp_path, monkeypatch):+ # The contract is best-effort at the NEXT step boundary, the same one the video backend+ # documents. Pin it: a cancel raised during step 1 must not let step 3 run.+ (tmp_path / "model.gguf").write_bytes(b"x")+ backend = DiffusionBackend()+ backend.load_pipeline(+ str(tmp_path), gguf_filename = "model.gguf", base_repo = "base/repo", family_override = "z-image"+ )++ seen: list[int] = []++ def _call(+ self,+ *,+ callback_on_step_end = None,+ **kwargs,+ ):+ self._interrupt = False+ for index in range(20):+ if callback_on_step_end is not None:+ callback_on_step_end(self, index, index, {})+ seen.append(index)+ if getattr(self, "_interrupt", False):+ break+ if index == 1:+ backend.cancel_generate()+ return types.SimpleNamespace(images = [_FakeImage()])++ monkeypatch.setattr(_FakePipe, "__call__", _call)++ with pytest.raises(RuntimeError):+ backend.generate(prompt = "x", steps = 20)+ # Cancelled during step index 1: index 2 is the step whose callback observes it, and nothing runs after.+ assert seen == [0, 1, 2]+++def test_cancel_generate_during_the_post_denoise_save_still_cancels(+ fake_runtime, tmp_path, monkeypatch+):+ # The cancel event stays registered through the compile-cache save, and progress still reads+ # active, so the page still shows Stop. Before the final recheck, a Stop landing there was+ # answered cancelled = true and then contradicted: generate() returned the images and the+ # route persisted them. The two answers have to agree, so the run unwinds as cancelled.+ from core.inference import diffusion_compile_cache as compile_cache++ (tmp_path / "model.gguf").write_bytes(b"x")+ backend = DiffusionBackend()+ backend.load_pipeline(+ str(tmp_path), gguf_filename = "model.gguf", base_repo = "base/repo", family_override = "z-image"+ )++ def _save(ctx, logger = None):+ # Stop pressed while the bundle is being written: the route's cancel reaches the SAME+ # event, and it must still be registered here or the button would have reported False.+ assert backend.cancel_generate() is True++ monkeypatch.setattr(compile_cache, "save", _save)++ with pytest.raises(RuntimeError, match = "cancelled"):+ backend.generate(prompt = "x", steps = 2)+++def test_a_completed_generation_stops_advertising_itself_as_cancellable(+ fake_runtime, tmp_path, monkeypatch+):+ # The final check and the deregistration are one critical section under the same lock+ # cancel_generate takes, so there is no sliver between "the result is committed" and "the+ # event is gone" in which Stop could answer true for a generation that then returns images.+ (tmp_path / "model.gguf").write_bytes(b"x")+ backend = DiffusionBackend()+ backend.load_pipeline(+ str(tmp_path), gguf_filename = "model.gguf", base_repo = "base/repo", family_override = "z-image"+ )++ from core.inference import diffusion as diffusion_module++ seen: list[bool] = []+ real_baked = diffusion_module._baked_lora_names++ def _baked(pipe):+ # Runs after the final check, while the old code still had the event registered.+ seen.append(backend.cancel_generate())+ return real_baked(pipe)++ monkeypatch.setattr(diffusion_module, "_baked_lora_names", _baked)++ out = backend.generate(prompt = "x", steps = 2)+ assert out["images"]+ assert seen == [False]+++def test_cancel_generate_is_a_no_op_without_a_load(fake_runtime):+ # The route calls this unconditionally, so an idle backend must answer False, not raise.+ assert DiffusionBackend().cancel_generate() is Falsediff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.pyindex be69f19eb4c..e25c6137017 100644--- a/studio/backend/tests/test_diffusion_routes.py+++ b/studio/backend/tests/test_diffusion_routes.py@@ -28,6 +28,8 @@ class _FakeBackend:self.loaded = False# Repo ids of in-flight (uncommitted) loads. The unload route reads this to keep DIFFUSION ownership during a concurrent load.self.loading: tuple = ()+ # Stands in for the real engines' _active_generate_cancel: None while idle.+ self.active_generate_cancel = None@propertydef is_loaded(self) -> bool:@@ -148,6 +150,14 @@ class _FakeBackend:# Idle by default; the persist-window override lives in the route, not here.return {"active": False, "step": 0, "total_steps": 0, "fraction": 0.0, "eta_seconds": None}+ def cancel_generate(self):+ # Both real engines return False when nothing is in flight; the fake tracks the same event.+ cancel = self.active_generate_cancel+ if cancel is None:+ return False+ cancel.set()+ return True+def unload(self):self.loaded = Falsereturn _unloaded_status()@@ -1836,6 +1846,61 @@ def test_gallery_image_accepts_a_record_written_before_the_build_fields():assert record.baked_loras == []+def test_cancel_generation_route_reports_false_when_idle(client):+ # Nothing in flight: the route answers 200/False so the page settles its button back to Generate+ # instead of waiting on a generation that already finished.+ resp = client.post("/api/inference/images/generate/cancel")+ assert resp.status_code == 200+ assert resp.json()["cancelled"] is False+++def test_cancel_generation_route_stops_an_in_flight_generation(client):+ # The route must reach the SAME event the denoise loop watches, and the cancelled generation+ # must unwind as a 409 with nothing persisted.+ import threading++ backend = diffusion_module.get_diffusion_backend()+ backend.loaded = True+ started = threading.Event()++ def _wait_for_cancel(**kwargs):+ cancel = threading.Event()+ backend.active_generate_cancel = cancel+ started.set()+ try:+ assert cancel.wait(5), "cancel event was never set"+ raise RuntimeError("Diffusion generation was cancelled.")+ finally:+ backend.active_generate_cancel = None++ backend.generate = _wait_for_cancel+ result: dict = {}++ def _run():+ result["resp"] = client.post("/api/inference/images/generate", json = {"prompt": "p"})++ worker = threading.Thread(target = _run, daemon = True)+ worker.start()+ assert started.wait(5)++ cancelled = client.post("/api/inference/images/generate/cancel")+ assert cancelled.status_code == 200 and cancelled.json()["cancelled"] is True++ worker.join(10)+ assert result["resp"].status_code == 409+ assert result["resp"].json()["detail"] == "Diffusion generation was cancelled."+ # A cancelled run leaves no gallery entry.+ assert client.get("/api/inference/images/gallery").json()["images"] == []+++def test_cancel_generation_route_requires_auth():+ # The cancel route stops a multi-GB job, so it must sit behind the same auth as every other route.+ app = FastAPI()+ app.include_router(studio_router, prefix = "/api/inference")+ unauth = TestClient(app)+ assert unauth.post("/api/inference/images/generate/cancel").status_code in (401, 403)++@pytest.mark.parametrize("memory",[diff --git a/studio/backend/tests/test_diffusion_training.py b/studio/backend/tests/test_diffusion_training.pyindex d84f5fdedb2..24c9cee9fc5 100644--- a/studio/backend/tests/test_diffusion_training.py+++ b/studio/backend/tests/test_diffusion_training.py@@ -1335,6 +1335,9 @@ def test_keepwarm_tracks_image_video_generation_paths():assert not _is_inference_path("/api/inference/images/generate-progress")assert not _is_inference_path("/api/inference/video/generate-progress")assert not _is_inference_path("/api/inference/video/generate/cancel")+ # The images cancel route STOPS a generation, so tracking it as an inference request would+ # keep the model pinned past the run it just cancelled. endswith matching already excludes it.+ assert not _is_inference_path("/api/inference/images/generate/cancel")def test_import_example_partial_failure_leaves_no_partial_dataset(diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex 9227e2f0db6..d0e627dbf72 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -525,6 +525,55 @@ def test_generate_cancellation_raises_cancelled_not_failure():b.generate(prompt = "x", steps = 8, seed = 5)+def test_cancel_generate_stops_a_running_native_run():+ # The native engine serves the same Images page, so the cancel route must reach it too. Here+ # the cancel arrives from ANOTHER thread mid-run, which is what the route does: the engine+ # polls the event, kills the sd-cli process tree, and the backend reports a cancellation.+ started = threading.Event()+ b = None++ class _BlockingEngine(_FakeEngine):+ def generate(+ self,+ files,+ params,+ *,+ output_path,+ cancel_event = None,+ **kw,+ ):+ started.set()+ assert cancel_event is not None and cancel_event.wait(5)+ raise SdCppCancelled("cancelled")++ b = _loaded_backend(engine = _BlockingEngine())+ # Nothing running yet.+ assert b.cancel_generate() is False++ outcome: dict = {}++ def _run():+ try:+ b.generate(prompt = "x", steps = 8, seed = 5)+ except BaseException as exc: # noqa: BLE001 -- the assertion below pins the type+ outcome["error"] = exc++ worker = threading.Thread(target = _run, daemon = True)+ worker.start()+ assert started.wait(5)++ assert b.cancel_generate() is True+ worker.join(10)+ assert isinstance(outcome["error"], RuntimeError)+ # Deregistered on exit, so a later cancel cannot poke a finished run.+ assert b.cancel_generate() is False+++def test_cancel_generate_is_a_no_op_when_idle():+ # The route calls this unconditionally; an idle native backend answers False rather than raising.+ assert SdCppDiffusionBackend(engine = _FakeEngine()).cancel_generate() is False++def test_generate_progress_tracks_parsed_steps():b = _loaded_backend()b._gen = bk._SdGen(total_steps = 8)@@ -1398,3 +1447,30 @@ def test_generate_reports_the_build_the_recipe_persists():assert out["offload_policy"] == b.status()["offload_policy"]assert out["transformer_quant"] is None and out["text_encoder_quant"] is Noneassert out["memory_mode"] is None+++def test_a_completed_native_generation_stops_advertising_itself_as_cancellable(monkeypatch):+ # /images/generate/cancel resolves through the engine router, so the native backend owes the+ # same answer as the diffusers one: the final check and the deregistration are one critical+ # section under the lock cancel_generate takes, and no Stop can be answered true for a run that+ # then returns its images.+ b = _loaded_backend()+ seen: list[bool] = []+ real_oneshot = b._generate_oneshot++ def _oneshot(*args, **kwargs):+ out = real_oneshot(*args, **kwargs)+ # Still mid-generate, so a Stop here is genuine and must be honoured.+ assert b.cancel_generate() is True+ return out++ monkeypatch.setattr(b, "_generate_oneshot", _oneshot)+ with pytest.raises(RuntimeError, match = "cancelled"):+ b.generate(prompt = "a fox", width = 64, height = 64, steps = 4, seed = 1)++ # And once a run completes, the event is gone before the result is handed back.+ b2 = _loaded_backend()+ out = b2.generate(prompt = "a fox", width = 64, height = 64, steps = 4, seed = 1)+ assert out["images"]+ seen.append(b2.cancel_generate())+ assert seen == [False]diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex d8c998b3bcd..1450cd08af9 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -344,6 +344,23 @@ export async function generateDiffusionImage(return parseJson(response);}+/** Request a cancel. Best-effort: the diffusers sampler stops at the next step boundary (the native engine kills its sd-cli run outright) and the in-flight generate POST unwinds as a 409 with nothing persisted. `cancelled` is false when there was nothing to stop. */+export async function cancelDiffusionGeneration(+ signal?: AbortSignal,+): Promise<{ cancelled: boolean }> {+ return parseJson(+ // No network retry, and abortable. The endpoint always targets whichever generation is active+ // NOW, so a retry or a 401 refresh-and-replay firing after the stopped run settled can land on+ // a run the user started meanwhile and stop that one instead. Not retryable, unlike the+ // idempotent GETs; the signal lets the caller drop a pending one when its run is over.+ await authFetch(+ "/api/inference/images/generate/cancel",+ { method: "POST", signal },+ { retryNetworkErrors: false },+ ),+ );+}+export async function unloadDiffusionModel(): Promise<DiffusionStatus> {return parseJson(await authFetch("/api/inference/images/unload", { method: "POST" }));}diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 5563d03800a..6021210cf2b 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -109,6 +109,7 @@ import {type GalleryImage,type LoraSpecInput,GenerateResponseLostError,+ cancelDiffusionGeneration,deleteGalleryImage,fetchGalleryObjectUrl,generateDiffusionImage,@@ -122,6 +123,10 @@ import {loadDiffusionModel,unloadDiffusionModel,} from "./api";+import {+ shouldContinueGenerating,+ shouldReportGenerateError,+} from "./lib/generation-stop";import { useNavigate, useSearch } from "@tanstack/react-router";import { useStagedDownload } from "@/features/hub/download-manager";import { DiffusionTrainPanel } from "./train/diffusion-train-panel";@@ -1307,6 +1312,27 @@ export function ImagesPage({ active = true }: { active?: boolean }) {const visibleIds = useRef<Set<string>>(new Set());// False once the page truly unmounts. Tab switches keep it mounted, so a batch keeps generating off-tab.const isMounted = useRef(true);+ // Set by Stop for the duration of one handleGenerate call. The backend cancel only reaches the+ // denoise that is running RIGHT NOW, so a multi-run request (count > 1) would start its next run+ // straight after; this breaks the loop as well. Cleared when the run settles.+ const cancelRequested = useRef(false);+ // True only once the backend has answered {cancelled: true}, i.e. it really stopped a running+ // denoise. Anything else -- a POST that never landed, or a {cancelled: false} because the run+ // was already past its last cancellation check -- means the run was NOT stopped, so an error it+ // raises afterwards is a real failure and not the user's own Stop coming back.+ const cancelAcked = useRef(false);+ // Bumped once per handleGenerate call, so a cancel can tell its own run from a later one.+ const runToken = useRef(0);+ // The run token owning the Stop currently on the wire, or null. Without it each extra click+ // posts again, and a late duplicate can land after the run settled and stop whichever+ // generation is running by then. Held as a token rather than a flag because the clear is+ // asynchronous: a slow cancel from the PREVIOUS run must neither swallow this run's Stop nor,+ // when it finally settles, release this run's guard.+ const cancelInFlight = useRef<number | null>(null);+ // Aborts the Stop still on the wire, if any. A pending cancel outlives its run when it is+ // waiting on a 401 refresh-and-replay, and the replay would then target whatever is generating+ // by the time it lands. Dropping it as the next run starts is what keeps that from happening.+ const cancelAbort = useRef<AbortController | null>(null);const pollTimer = useRef<ReturnType<typeof setTimeout> | null>(null);// The persistent load toast's id, so each poll updates it in place (chat-style).const loadToastId = useRef<string | number | null>(null);@@ -2558,6 +2584,18 @@ export function ImagesPage({ active = true }: { active?: boolean }) {setBusy("generating");setGenDone(0);setGenStep(null);+ // Fresh run: a Stop from the PREVIOUS run must not cancel this one.+ cancelRequested.current = false;+ cancelAcked.current = false;+ // Per-run, like the two above. A cancel POST still outstanding from the PREVIOUS run (a 401+ // refresh-and-replay is the slow case) would otherwise leave the guard set and swallow this+ // run's own Stop entirely.+ cancelInFlight.current = null;+ // Any Stop still pending belongs to the run that just ended, so it must not reach the server+ // now that a new one is starting.+ cancelAbort.current?.abort();+ cancelAbort.current = null;+ runToken.current += 1;// Poll the backend's per-step progress across the whole run so the bar tracks live denoising steps. A named poll body// (guarded against overlap) also serves the visibilitychange listener, so a throttled tab catches up when visible.let pollInFlight = false;@@ -2590,8 +2628,16 @@ export function ImagesPage({ active = true }: { active?: boolean }) {const knownIds = new Set(galleryCache.images.map((image) => image.id));try {for (let i = 0; i < runs; i++) {- // The page truly unmounted mid-run: stop issuing more GPU generations. A plain tab switch keeps it mounted.- if (!isMounted.current) break;+ // Stop issuing more GPU generations once the page truly unmounted (a plain tab switch+ // keeps it mounted), or once Stop was pressed: the backend cancel only reaches the denoise+ // in flight, so the remaining runs of a count > 1 request would otherwise start anyway.+ if (+ !shouldContinueGenerating({+ mounted: isMounted.current,+ stopRequested: cancelRequested.current,+ })+ )+ break;let res: DiffusionGenerateResponse;try {res = await generateDiffusionImage({@@ -2652,11 +2698,21 @@ export function ImagesPage({ active = true }: { active?: boolean }) {res.images.forEach((image) => void ensureSrc(image));setGenDone(i + 1);}- // A generation can change server-side status: Speed=Auto compiles on the 3rd LoRA-free run (supports_lora flips false),- // so without a refresh the LoRA picker stays enabled and the next LoRA run fails. Cheap status GET.- if (isMounted.current) void refreshStatus();} catch (err) {- toast.error(err instanceof Error ? err.message : "Image generation failed");+ const msg = err instanceof Error ? err.message : "Image generation failed";+ // The user's own Stop comes back as the backend's cancelled sentinel (409). Not an error,+ // so do not toast it. Same treatment the video page gives its Cancel.+ // Only a Stop the backend confirmed it acted on explains an error away. If the POST never+ // landed, or the backend answered {cancelled: false} because the run was already past its+ // last cancellation check while the route was still persisting, the generation was not+ // stopped, so whatever it raised is a real failure rather than "the user stopped it".+ if (+ shouldReportGenerateError({+ message: msg,+ stopRequested: cancelRequested.current && cancelAcked.current,+ })+ )+ toast.error(msg);} finally {if (genPollTimer.current) clearInterval(genPollTimer.current);genPollTimer.current = null;@@ -2664,12 +2720,52 @@ export function ImagesPage({ active = true }: { active?: boolean }) {document.removeEventListener("visibilitychange", genVisibilityListener.current);genVisibilityListener.current = null;}+ cancelRequested.current = false;+ // Refresh on EVERY exit, not just the successful one, and AWAIT it before Generate comes+ // back. A generation can change server-side status (Speed=Auto compiles on the 3rd LoRA-free+ // run and supports_lora flips false), and a cancelled native run can leave no model at all:+ // when the native cancel is not reflected within its grace window, sd-server is stopped+ // outright. Re-enabling Generate first would offer a button that 409s against a backend with+ // nothing loaded. Cheap status GET, so the wait is not felt.+ if (isMounted.current) await refreshStatus();setBusy(null);setGenDone(null);setGenStep(null);}}, [prompt, negativePrompt, width, height, steps, guidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus]);+ // Stop the in-flight generation. Latch FIRST, so a multi-run request stops even if the POST+ // races the run that is already finishing, then ask the backend to break out of the sampler.+ const handleCancelGenerate = useCallback(async () => {+ cancelRequested.current = true;+ // One Stop on the wire at a time. The button stays enabled so the click still latches, but a+ // second POST would target whatever is active when IT arrives, which after the stopped run+ // settles can be a generation the user started since.+ const token = runToken.current;+ if (cancelInFlight.current === token) return;+ cancelInFlight.current = token;+ const abort = new AbortController();+ cancelAbort.current = abort;+ try {+ const { cancelled } = await cancelDiffusionGeneration(abort.signal);+ cancelAcked.current = Boolean(cancelled);+ } catch {+ // An abort means the next run dropped this one on purpose; it belongs to a generation that+ // is already over, so there is nothing to report. Otherwise the request never landed, the+ // denoise in flight keeps running, and the click cannot be treated as handled: say so, and+ // stop it explaining away an error the run raises later.+ if (!abort.signal.aborted) {+ cancelAcked.current = false;+ toast.error("Could not reach the server to stop this generation; it is still running");+ }+ } finally {+ // Only if they are still ours: a slow cancel from an earlier run must not release the guard+ // a later run set, or a duplicate click gets through and can land on a generation after it.+ if (cancelInFlight.current === token) cancelInFlight.current = null;+ if (cancelAbort.current === abort) cancelAbort.current = null;+ }+ }, []);+// Publish what the loaded model can do, so the sidebar submenu dims the rest. null while// nothing is loaded, which leaves every workflow open to set up first.useEffect(() => {@@ -3466,16 +3562,28 @@ export function ImagesPage({ active = true }: { active?: boolean }) {</div>{/* Floats over the settings so it needs no bar of its own. */}<div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center pb-7 pl-8 pr-8">- <Button- className="btn-float-action pointer-events-auto h-11 px-8 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100"- onClick={handleGenerate}- disabled={busy !== null || !status?.loaded}- >- {busy === "generating" ? <Spinner className="mr-2 size-4" /> : null}- {busy === "generating" && genDone != null && count > 1- ? `Generating ${genDone}/${count}…`- : "Generate"}- </Button>+ {busy === "generating" ? (+ /* Replaces Generate while a run is in flight, mirroring the video page. Every workflow+ (Create, Transform, Inpaint, Extend, Upscale, Reference, Edit) funnels through the+ same handler, so one control stops all of them. */+ <Button+ // Opaque hover: this one floats over the settings too.+ className="pointer-events-auto h-11 px-8 hover:bg-muted dark:hover:bg-muted"+ variant="outline"+ onClick={handleCancelGenerate}+ >+ <Spinner className="mr-2 size-4" />+ {genDone != null && count > 1 ? `Stop (${genDone}/${count})` : "Stop"}+ </Button>+ ) : (+ <Button+ className="btn-float-action pointer-events-auto h-11 px-8 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100"+ onClick={handleGenerate}+ disabled={busy !== null || !status?.loaded}+ >+ Generate+ </Button>+ )}</div></div>diff --git a/studio/frontend/src/features/images/lib/generation-stop.ts b/studio/frontend/src/features/images/lib/generation-stop.tsnew file mode 100644index 00000000000..f88cccee7af--- /dev/null+++ b/studio/frontend/src/features/images/lib/generation-stop.ts@@ -0,0 +1,35 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Stop semantics for an in-flight image generation, kept out of the page so they are testable.+ *+ * A generate request is a LOOP of `count` backend calls, but the backend cancel only reaches the+ * denoise running right now. Stopping therefore has two halves: ask the backend to break out of+ * the sampler, and stop the page issuing the runs that have not started yet. */++/** Whether the run loop should issue another backend generation. */+export function shouldContinueGenerating(input: {+ mounted: boolean;+ stopRequested: boolean;+}): boolean {+ return input.mounted && !input.stopRequested;+}++/** The exact sentinel both image engines raise for a user cancellation. */+export const GENERATION_CANCELLED_SENTINEL =+ "Diffusion generation was cancelled.";++/** Whether a failed generation should be toasted as an error.+ *+ * A user's own Stop comes back as the cancelled sentinel on a 409, which is the requested+ * outcome, not a failure. The `stopRequested` latch covers the case where the message never+ * reaches the page verbatim (a proxy rewrites it, or the run unwinds some other way). */+export function shouldReportGenerateError(input: {+ message: string;+ stopRequested: boolean;+}): boolean {+ if (input.stopRequested) {+ return false;+ }+ return !input.message.toLowerCase().includes("cancelled");+}diff --git a/studio/frontend/tests/image-generation-stop.test.ts b/studio/frontend/tests/image-generation-stop.test.tsnew file mode 100644index 00000000000..f032c0dcc7e--- /dev/null+++ b/studio/frontend/tests/image-generation-stop.test.ts@@ -0,0 +1,94 @@+// 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 {+ GENERATION_CANCELLED_SENTINEL,+ shouldContinueGenerating,+ shouldReportGenerateError,+} from "../src/features/images/lib/generation-stop.ts";++test("a mounted page with no stop keeps generating", () => {+ assert.equal(+ shouldContinueGenerating({ mounted: true, stopRequested: false }),+ true,+ );+});++test("Stop breaks the run loop, so a count > 1 request does not start its next run", () => {+ // The backend cancel only reaches the denoise in flight; without this the page would+ // immediately POST run 2 of 4 and the machine would keep generating after Stop.+ assert.equal(+ shouldContinueGenerating({ mounted: true, stopRequested: true }),+ false,+ );+});++test("an unmounted page stops generating regardless of the stop latch", () => {+ assert.equal(+ shouldContinueGenerating({ mounted: false, stopRequested: false }),+ false,+ );+ assert.equal(+ shouldContinueGenerating({ mounted: false, stopRequested: true }),+ false,+ );+});++test("the cancelled sentinel is not reported as an error", () => {+ assert.equal(+ shouldReportGenerateError({+ message: GENERATION_CANCELLED_SENTINEL,+ stopRequested: false,+ }),+ false,+ );+});++test("a stopped run reports nothing even when the message is not the sentinel", () => {+ // A proxy can rewrite the 409 body, and the run can unwind some other way; the latch is what+ // makes the user's own Stop silent rather than a spurious red toast.+ assert.equal(+ shouldReportGenerateError({ message: "Bad Gateway", stopRequested: true }),+ false,+ );+});++test("a real failure is still reported", () => {+ assert.equal(+ shouldReportGenerateError({+ message:+ "The device ran out of memory. Try a smaller size, fewer steps, or a smaller batch.",+ stopRequested: false,+ }),+ true,+ );+});++test("a Stop the backend did not act on does not explain away a real failure", () => {+ // handleCancelGenerate passes stopRequested only once the backend answered {cancelled: true}.+ // A POST that threw, or a {cancelled: false} because the run was already past its last+ // cancellation check while the route was still persisting, means nothing was stopped, so an+ // error raised afterwards is real and the user has to see it.+ const stopRequested = true;+ for (const cancelAcked of [false]) {+ assert.equal(+ shouldReportGenerateError({+ message: "Failed to save the generated image",+ stopRequested: stopRequested && cancelAcked,+ }),+ true,+ );+ }+});++test("a Stop the backend confirmed still silences the run it stopped", () => {+ // The other side: an acknowledged cancel is the user's own Stop coming back, whatever shape the+ // run unwinds in, so it must not raise a red toast.+ assert.equal(+ shouldReportGenerateError({ message: "Bad Gateway", stopRequested: true && true }),+ false,+ );+});