Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Images/Video: hide the pill's loaded state during eject and fix unload races (#17551)

Lee Jacksonb807d41c81d5
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.yml
index d640e232085..7a9d7e9bdd8 100644
--- a/.github/workflows/studio-ui-smoke.yml
+++ b/.github/workflows/studio-ui-smoke.yml
@@ -514,12 +514,15 @@ jobs:
mkdir -p logs/playwright_image_footprint
python tests/studio/playwright_image_model_footprint.py
- - name: Image generation time regression (Playwright)
+ - name: Image generation time and Images/Video model unload regressions (Playwright)
if: matrix.shard == 'extra'
env:
BASE_URL: http://127.0.0.1:18894
STUDIO_PW: ${{ env.STUDIO_EXTRA_NEW_PW }}
- run: python tests/studio/playwright_images_generation_time.py
+ run: |
+ python tests/studio/playwright_images_generation_time.py
+ python tests/studio/playwright_image_unload.py
+ python tests/studio/playwright_video_unload.py
- name: Image staged-download cancel/retry regression (Playwright)
if: matrix.shard == 'extra'
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 743a7f9ed79..8c142775335 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -78,6 +78,7 @@ import {
import { Slider } from "@/components/ui/slider";
import { useSidebar } from "@/components/ui/sidebar";
import { Spinner } from "@/components/ui/spinner";
+import { readAfterUnload } from "@/lib/read-after-unload";
import { Switch } from "@/components/ui/switch";
import { DeferredTextarea } from "@/components/deferred-textarea";
import { Textarea } from "@/components/ui/textarea";
@@ -2309,6 +2310,7 @@ export function ImagesPage({
const loadSeq = useRef(0);
// Settles only after handleLoad finishes, since begin_load refuses a second load while one is live.
const pendingStart = useRef<Promise<unknown> | null>(null);
+ const pendingUnload = useRef<Promise<boolean> | null>(null);
// Set when the compensating unload failed, so the cancelled load is STILL running.
const loadTrackingRestored = useRef(false);
@@ -3388,6 +3390,8 @@ export function ImagesPage({
);
const refreshStatus = useCallback(async () => {
+ // A read during teardown can still see the resident and supersede the unload response.
+ if (pendingUnload.current) await pendingUnload.current;
const ticket = ++statusTicket.current;
try {
setStatusIfNewest(ticket, ownDiffusionStatus(await getDiffusionStatus()));
@@ -3634,7 +3638,7 @@ export function ImagesPage({
genVisibilityListener.current = null;
}
if (!isMounted.current) return;
- setBusy(null);
+ setBusy((prev) => (prev === "generating" ? null : prev));
setGenStep(null);
void loadGallery();
void refreshStatus();
@@ -3722,7 +3726,7 @@ export function ImagesPage({
// A load runs on the backend as a daemon thread that survives navigation, so resume tracking one still in flight.
let inFlight = false;
try {
- const p = await getDiffusionLoadProgress();
+ const p = await readAfterUnload(pendingUnload, () => getDiffusionLoadProgress());
inFlight = isLoadInFlightPhase(p.phase);
if (inFlight) {
setBusy("loading");
@@ -3747,7 +3751,7 @@ export function ImagesPage({
setInitialLoadProbe(inFlight ? "loading" : "idle");
// Resume tracking a generation started elsewhere so the page shows the in-flight run. Mirrors the video page.
try {
- const g = await getGenerateProgress();
+ const g = await readAfterUnload(pendingUnload, getGenerateProgress);
if (g.active) {
runTarget.current = g.target ?? undefined;
setBusy("generating");
@@ -4989,35 +4993,44 @@ export function ImagesPage({
if (trainingCompletions > 0) setLoraRefreshKey((k) => k + 1);
}, [trainingCompletions]);
- const handleUnload = useCallback(async (): Promise<boolean> => {
+ const handleUnload = useCallback((): Promise<boolean> => {
+ if (pendingUnload.current) return pendingUnload.current;
+
pendingRecalledGeneration.current = null;
dropResidentState();
loadTrackingRestored.current = false;
setBusy("unloading");
- try {
- setStatusIfNewest(++statusTicket.current, await unloadDiffusionModel());
- setQuant(null);
- // Wait for any in-flight load start to finish, compensating unload included, or the older load
- // keeps running with no toast or cancel control.
- const pending = pendingStart.current;
- if (pending) {
- try {
- await pending;
- } catch {
- // Its own handler reports the failure; this only waits for the window to close.
+
+ async function unload(): Promise<boolean> {
+ try {
+ setStatusIfNewest(++statusTicket.current, await unloadDiffusionModel());
+ setQuant(null);
+ // Wait for any in-flight load start to finish, compensating unload included, or the older load
+ // keeps running with no toast or cancel control.
+ const pending = pendingStart.current;
+ if (pending) {
+ try {
+ await pending;
+ } catch {
+ // Its own handler reports the failure; this only waits for the window to close.
+ }
}
+ // Tracking RESTORED means the compensating unload failed and the load is still running.
+ return !loadTrackingRestored.current;
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to unload model");
+ void refreshStatus();
+ return false;
}
- // Tracking RESTORED means the compensating unload failed and the load is still running.
- return !loadTrackingRestored.current;
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to unload model");
- void refreshStatus();
- return false;
- } finally {
+ }
+
+ pendingUnload.current = unload().finally(() => {
+ pendingUnload.current = null;
// Not an unconditional clear: a restore may have set "loading" deliberately.
setBusy((prev) => (prev === "unloading" ? null : prev));
- }
- }, [refreshStatus, dropResidentState]);
+ });
+ return pendingUnload.current;
+ }, [refreshStatus, dropResidentState, setStatusIfNewest]);
const ejecting = useRef(false);
const handleEject = useCallback(() => ejectWithToast(ejecting, handleUnload), [handleUnload]);
@@ -5661,7 +5674,7 @@ export function ImagesPage({
cancelRequested.current = false;
// Await on EVERY exit: a run can change status (compile, cancelled native run), so Generate could 409.
if (isMounted.current) await refreshStatus();
- setBusy(null);
+ setBusy((prev) => (prev === "generating" ? null : prev));
setGenDone(null);
setGenStep(null);
setStopping(false);
@@ -6260,7 +6273,8 @@ export function ImagesPage({
activeGgufVariant={quant}
onValueChange={handleModelSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
- onEject={status?.loaded ? handleEject : undefined}
+ loaded={busy === "unloading" ? false : undefined}
+ onEject={status?.loaded && busy !== "unloading" ? handleEject : undefined}
variant="ghost"
className="ml-1.5 max-w-full overflow-hidden !pl-2.5 !pr-1.5 !h-[var(--studio-chat-control-height,34px)]"
task={IMAGE_GEN_TASKS}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 8f8104589d8..38ea1116f8a 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -121,6 +121,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
+import { readAfterUnload } from "@/lib/read-after-unload";
import { DeferredTextarea } from "@/components/deferred-textarea";
import { Textarea } from "@/components/ui/textarea";
import {
@@ -1438,6 +1439,7 @@ function VideoGenerator({
const loadSeq = useRef(0);
// begin_load refuses a second live load, so a new pick must wait for this to settle.
const pendingStart = useRef<Promise<unknown> | null>(null);
+ const pendingUnload = useRef<Promise<boolean> | null>(null);
// The compensating unload failed, so the load is STILL running; handleUnload reports that.
const loadTrackingRestored = useRef(false);
@@ -2515,6 +2517,8 @@ function VideoGenerator({
// null when the read failed or was superseded.
const refreshStatus = useCallback(async (): Promise<VideoStatus | null> => {
+ // A read during teardown can still see the resident and supersede the unload response.
+ if (pendingUnload.current) await pendingUnload.current;
const ticket = ++statusTicket.current;
try {
const next = await getVideoStatus();
@@ -2742,7 +2746,7 @@ function VideoGenerator({
if (p.phase === "completed" || p.phase === "failed") {
stopGenPoll();
if (!isMounted.current) return;
- setBusy(null);
+ setBusy((prev) => (prev === "generating" ? null : prev));
setGenStep(null);
if (p.phase === "completed" && p.video) {
// Sorted, not prepended: a new clip is unpinned and goes after the pinned group.
@@ -2786,7 +2790,7 @@ function VideoGenerator({
await refreshStatus();
// Loads run on a backend daemon thread that survives navigation, so resume tracking.
try {
- const p = await getVideoLoadProgress();
+ const p = await readAfterUnload(pendingUnload, () => getVideoLoadProgress());
if (p.phase === "downloading" || p.phase === "finalizing") {
setBusy("loading");
dismissLoadToast();
@@ -2800,7 +2804,7 @@ function VideoGenerator({
setLoadProbed(true);
// Generation also runs on a daemon thread, so a reload re-enters the poll loop.
try {
- const g = await getVideoGenerateProgress();
+ const g = await readAfterUnload(pendingUnload, getVideoGenerateProgress);
if (g.active) {
setBusy("generating");
setGenStep(g.phase === "queued" ? null : g);
@@ -3596,34 +3600,40 @@ function VideoGenerator({
);
// True only when the backend accepted the unload.
- const handleUnload = useCallback(async (): Promise<boolean> => {
+ const handleUnload = useCallback((): Promise<boolean> => {
+ if (pendingUnload.current) return pendingUnload.current;
dropResidentState();
loadTrackingRestored.current = false;
setBusy("unloading");
- try {
- setStatusIfNewest(++statusTicket.current, await unloadVideoModel());
- setQuant(null);
- // Wait for any in-flight load start to finish, or the older handler skips its compensating unload
- // and leaves a large load running with no cancel.
- const pending = pendingStart.current;
- if (pending) {
- try {
- await pending;
- } catch {
- // Its own handler reports the failure; this only waits for the window to close.
+ const unload = async (): Promise<boolean> => {
+ try {
+ setStatusIfNewest(++statusTicket.current, await unloadVideoModel());
+ setQuant(null);
+ // Wait for any in-flight load start to finish, or the older handler skips its compensating unload
+ // and leaves a large load running with no cancel.
+ const pending = pendingStart.current;
+ if (pending) {
+ try {
+ await pending;
+ } catch {
+ // Its own handler reports the failure; this only waits for the window to close.
+ }
}
+ // Restored tracking means the compensating unload failed and the load still runs.
+ return !loadTrackingRestored.current;
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to unload model");
+ void refreshStatus();
+ return false;
}
- // Restored tracking means the compensating unload failed and the load still runs.
- return !loadTrackingRestored.current;
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to unload model");
- void refreshStatus();
- return false;
- } finally {
+ };
+ pendingUnload.current = unload().finally(() => {
+ pendingUnload.current = null;
// A restore during the wait set "loading" deliberately; keep its Cancel controls.
setBusy((prev) => (prev === "unloading" ? null : prev));
- }
- }, [refreshStatus, dropResidentState]);
+ });
+ return pendingUnload.current;
+ }, [refreshStatus, dropResidentState, setStatusIfNewest]);
const ejecting = useRef(false);
const handleEject = useCallback(() => ejectWithToast(ejecting, handleUnload), [handleUnload]);
@@ -4094,7 +4104,8 @@ function VideoGenerator({
activeGgufVariant={quant}
onValueChange={handleModelSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
- onEject={status?.loaded ? handleEject : undefined}
+ loaded={busy === "unloading" ? false : undefined}
+ onEject={status?.loaded && busy !== "unloading" ? handleEject : undefined}
variant="ghost"
className="ml-1.5 max-w-full overflow-hidden !pl-2.5 !pr-1.5 !h-[var(--studio-chat-control-height,34px)]"
task={VIDEO_GEN_TASKS}
diff --git a/studio/frontend/src/lib/read-after-unload.ts b/studio/frontend/src/lib/read-after-unload.ts
new file mode 100644
index 00000000000..1ee66278950
--- /dev/null
+++ b/studio/frontend/src/lib/read-after-unload.ts
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Re-reads until no unload is pending: an answer taken mid-teardown may be stale, and a failed unload leaves it live. */
+export async function readAfterUnload<T>(
+ pending: { current: Promise<unknown> | null },
+ read: () => Promise<T>,
+): Promise<T> {
+ for (;;) {
+ const value = await read();
+ const unload = pending.current;
+ if (!unload) return value;
+ await unload.catch(() => undefined);
+ }
+}
diff --git a/studio/frontend/tests/media-eject-toast.test.ts b/studio/frontend/tests/media-eject-toast.test.ts
index 3131b38304e..32240d1354c 100644
--- a/studio/frontend/tests/media-eject-toast.test.ts
+++ b/studio/frontend/tests/media-eject-toast.test.ts
@@ -81,7 +81,7 @@ test("a failed or still-loading unload drops the loading toast", async () => {
for (const path of ["features/images/images-page.tsx", "features/video/video-page.tsx"]) {
test(`${path} routes the pill eject through ejectWithToast`, () => {
const page = readSrc(path);
- assert.match(page, /onEject=\{status\?\.loaded \? handleEject : undefined\}/);
+ assert.match(page, /onEject=\{status\?\.loaded && busy !== "unloading" \? handleEject : undefined\}/);
assert.match(page, /const handleEject = useCallback\(\(\) => ejectWithToast\(ejecting, handleUnload\), \[handleUnload\]\);/);
});
}
diff --git a/studio/frontend/tests/media-load-cancel.test.ts b/studio/frontend/tests/media-load-cancel.test.ts
index 3317bd4a8dc..79c51c27f71 100644
--- a/studio/frontend/tests/media-load-cancel.test.ts
+++ b/studio/frontend/tests/media-load-cancel.test.ts
@@ -137,7 +137,7 @@ for (const [page, path] of PAGES) {
test(`the ${page} eject is still offered only for a resident model`, () => {
assert.match(
SOURCE,
- /onEject=\{status\?\.loaded \? handleEject : undefined\}/,
+ /onEject=\{status\?\.loaded && busy !== "unloading" \? handleEject : undefined\}/,
);
});
diff --git a/studio/frontend/tests/read-after-unload.test.ts b/studio/frontend/tests/read-after-unload.test.ts
new file mode 100644
index 00000000000..7a1ec79a38a
--- /dev/null
+++ b/studio/frontend/tests/read-after-unload.test.ts
@@ -0,0 +1,49 @@
+// 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 { readAfterUnload } from "../src/lib/read-after-unload.ts";
+
+test("a probe answered mid-unload is read again once the unload settles", async () => {
+ const pending: { current: Promise<unknown> | null } = { current: null };
+ let finish!: () => void;
+ const answers = [{ active: true }, { active: true }];
+ let reads = 0;
+ const read = async () => {
+ reads += 1;
+ if (reads === 1) {
+ pending.current = new Promise<void>((resolve) => {
+ finish = () => {
+ pending.current = null;
+ resolve();
+ };
+ });
+ }
+ return answers[reads - 1];
+ };
+ const result = readAfterUnload(pending, read);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(reads, 1);
+ finish();
+ assert.deepEqual(await result, { active: true });
+ assert.equal(reads, 2);
+});
+
+test("a rejected unload still leads to a fresh read", async () => {
+ const pending: { current: Promise<unknown> | null } = { current: null };
+ let reads = 0;
+ const value = await readAfterUnload(pending, async () => {
+ reads += 1;
+ if (reads === 1) {
+ pending.current = new Promise((_, reject) => {
+ setImmediate(() => {
+ pending.current = null;
+ reject(new Error("unload failed"));
+ });
+ });
+ }
+ return reads;
+ });
+ assert.equal(value, 2);
+});
diff --git a/tests/studio/playwright_image_unload.py b/tests/studio/playwright_image_unload.py
new file mode 100644
index 00000000000..235e1b2ecf1
--- /dev/null
+++ b/tests/studio/playwright_image_unload.py
@@ -0,0 +1,103 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A slow Images eject shows progress, sends one request, and allows retry on failure."""
+
+import os
+from urllib.parse import parse_qs, urlparse
+
+from playwright.sync_api import expect, sync_playwright
+
+from playwright_image_model_footprint import BASE_URL, REPO_ID, _api_payload, _json
+
+
+def main():
+ status_path = "/api/inference/images/status"
+ idle = _api_payload(status_path, {}, full_footprint = False)
+ status = {
+ **idle,
+ "loaded": True,
+ "repo_id": REPO_ID,
+ "base_repo": "black-forest-labs/FLUX.2-klein-4B",
+ "family": "flux.2-klein",
+ "model_kind": "gguf",
+ }
+ generating = True
+ unloads = []
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(headless = True, executable_path = os.getenv("PW_CHROME"))
+ context = browser.new_context(viewport = {"width": 1440, "height": 900})
+ context.add_init_script("localStorage.setItem('unsloth_auth_token', 'rendered-ui-test')")
+
+ def route_request(route):
+ url = urlparse(route.request.url)
+ if url.netloc != urlparse(BASE_URL).netloc:
+ _json(route, [])
+ elif url.path == status_path:
+ _json(route, status)
+ elif url.path == "/api/inference/images/generate-progress":
+ _json(
+ route,
+ {
+ "active": generating,
+ "step": 1,
+ "fraction": 0.25,
+ "total_steps": 4,
+ "eta_seconds": 1,
+ },
+ )
+ elif url.path == "/api/inference/images/unload":
+ assert route.request.method == "POST"
+ unloads.append(route)
+ elif url.path.startswith("/api/"):
+ _json(route, _api_payload(url.path, parse_qs(url.query), full_footprint = False))
+ else:
+ route.continue_()
+
+ context.route("**/*", route_request)
+ page = context.new_page()
+ page.goto(f"{BASE_URL}/images", wait_until = "domcontentloaded")
+ picker = page.locator('[data-tour="images-model"]')
+ shortcut = picker.locator("[data-eject-hit]")
+ menu_eject = page.get_by_role("button", name = "Eject model", exact = True)
+ unloading = page.get_by_text("Unloading model", exact = True)
+ expect(shortcut).to_be_visible(timeout = 30_000)
+ expect(page.get_by_role("button").filter(has_text = "Stop")).to_be_visible()
+
+ # Two clicks in one event turn also exercise the guard before React updates the DOM.
+ with page.expect_request("**/api/inference/images/unload"):
+ shortcut.evaluate("(el) => { el.click(); el.click(); }")
+ expect(unloading).to_be_visible()
+ # The generation poll refreshes the gallery when a run ends during teardown.
+ with page.expect_request(
+ lambda req: urlparse(req.url).path == "/api/inference/images/gallery"
+ ):
+ generating = False
+ expect(unloading).to_be_visible()
+ expect(shortcut).to_have_count(0)
+ picker.click()
+ expect(page.locator(".unsloth-model-selector-menu")).to_be_visible()
+ expect(menu_eject).to_have_count(0)
+ page.keyboard.press("Escape")
+ assert len(unloads) == 1
+
+ unloads[0].fulfill(status = 503, json = {"detail": "Test unload failure"})
+ expect(page.get_by_text("Test unload failure", exact = True)).to_be_visible()
+ expect(unloading).to_have_count(0)
+ expect(shortcut).to_be_visible()
+
+ picker.click()
+ with page.expect_request("**/api/inference/images/unload"):
+ menu_eject.click()
+ expect(unloading).to_be_visible()
+ assert len(unloads) == 2
+ status = idle
+ _json(unloads[1], status)
+ expect(picker).to_contain_text("Select image model")
+ expect(shortcut).to_have_count(0)
+ expect(unloading).to_have_count(0)
+ browser.close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/studio/playwright_video_unload.py b/tests/studio/playwright_video_unload.py
new file mode 100644
index 00000000000..75500bc334f
--- /dev/null
+++ b/tests/studio/playwright_video_unload.py
@@ -0,0 +1,104 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A slow Video eject shows progress, sends one request, and allows retry on failure."""
+
+import os
+from urllib.parse import parse_qs, urlparse
+
+from playwright.sync_api import expect, sync_playwright
+
+from playwright_image_model_footprint import BASE_URL, _api_payload, _json
+
+REPO_ID = "Wan-AI/Wan2.2-TI2V-5B-Diffusers"
+IDLE = {
+ "loaded": False,
+ "repo_id": None,
+ "family": None,
+ "base_repo": None,
+ "device": None,
+ "dtype": None,
+ "vae_tiling": False,
+ "speed_optims": [],
+ "has_audio": False,
+ "supports_cfg": True,
+}
+
+
+def main():
+ status = {**IDLE, "loaded": True, "repo_id": REPO_ID, "base_repo": REPO_ID, "family": "wan2.2"}
+ generate = {"active": True, "phase": "denoising", "step": 1, "total": 4}
+ unloads = []
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(headless = True, executable_path = os.getenv("PW_CHROME"))
+ context = browser.new_context(viewport = {"width": 1440, "height": 900})
+ context.add_init_script("localStorage.setItem('unsloth_auth_token', 'rendered-ui-test')")
+
+ def route_request(route):
+ url = urlparse(route.request.url)
+ if url.netloc != urlparse(BASE_URL).netloc:
+ _json(route, [])
+ elif url.path == "/api/inference/video/status":
+ _json(route, status)
+ elif url.path == "/api/inference/video/load-progress":
+ _json(route, {"phase": None, "downloaded_bytes": 0, "total_bytes": 0})
+ elif url.path == "/api/inference/video/generate-progress":
+ _json(route, generate)
+ elif url.path == "/api/inference/video/gallery":
+ _json(route, {"videos": [], "has_more": False})
+ elif url.path == "/api/inference/video/unload":
+ assert route.request.method == "POST"
+ unloads.append(route)
+ elif url.path.startswith("/api/"):
+ _json(route, _api_payload(url.path, parse_qs(url.query), full_footprint = False))
+ else:
+ route.continue_()
+
+ context.route("**/*", route_request)
+ page = context.new_page()
+ page.goto(f"{BASE_URL}/video", wait_until = "domcontentloaded")
+ picker = page.locator('[data-tour="video-model"]')
+ shortcut = picker.locator("[data-eject-hit]")
+ menu_eject = page.get_by_role("button", name = "Eject model", exact = True)
+ unloading = page.get_by_text("Unloading model", exact = True)
+ expect(shortcut).to_be_visible(timeout = 30_000)
+ # The mount probe must have resumed the generation, or the eject parks it behind the held unload.
+ expect(page.get_by_role("button").filter(has_text = "Cancel").first).to_be_visible()
+
+ # Two clicks in one event turn also exercise the guard before React updates the DOM.
+ with page.expect_request("**/api/inference/video/unload"):
+ shortcut.evaluate("(el) => { el.click(); el.click(); }")
+ expect(unloading).to_be_visible()
+ # A generation finishing during teardown must not clear the indicator.
+ generate = {"active": False, "phase": "completed", "step": 4, "total": 4, "video": None}
+ with page.expect_response("**/api/inference/video/generate-progress"):
+ pass
+ page.wait_for_timeout(1_000)
+ expect(unloading).to_be_visible()
+ expect(shortcut).to_have_count(0)
+ picker.click()
+ expect(page.locator(".unsloth-model-selector-menu")).to_be_visible()
+ expect(menu_eject).to_have_count(0)
+ page.keyboard.press("Escape")
+ assert len(unloads) == 1, len(unloads)
+
+ unloads[0].fulfill(status = 503, json = {"detail": "Test unload failure"})
+ expect(page.get_by_text("Test unload failure", exact = True)).to_be_visible()
+ expect(unloading).to_have_count(0)
+ expect(shortcut).to_be_visible()
+
+ picker.click()
+ with page.expect_request("**/api/inference/video/unload"):
+ menu_eject.click()
+ expect(unloading).to_be_visible()
+ assert len(unloads) == 2, len(unloads)
+ status = IDLE
+ _json(unloads[1], status)
+ expect(picker).to_contain_text("Select video model")
+ expect(shortcut).to_have_count(0)
+ expect(unloading).to_have_count(0)
+ browser.close()
+
+
+if __name__ == "__main__":
+ main()