Skip to content

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

Studio: let a model load be cancelled while it is still loading (#8243)

Daniel Hand38ef17c2051
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 94c53a9121b..d038658b255 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -501,12 +501,20 @@ function loadToastDescription(p: DiffusionLoadProgress) {
}
// Toast args mirroring chat: persistent, closeable, content in `description`. Pass `id` to update in place.
-function loadToastArgs(p: DiffusionLoadProgress, id?: string | number) {
+// `onCancel` adds chat's Cancel action, the one control that reaches a load already in flight: the model
+// selector's eject is hidden for exactly the span a first load runs (nothing is resident, so it has no
+// selection to eject), which left a multi-gigabyte pull with no way out.
+function loadToastArgs(
+ p: DiffusionLoadProgress,
+ id?: string | number,
+ onCancel?: () => void,
+) {
return {
...(id != null ? { id } : {}),
description: loadToastDescription(p),
duration: Infinity,
closeButton: true,
+ ...(onCancel ? { cancel: { label: "Cancel", onClick: onCancel } } : {}),
classNames: LOAD_TOAST_CLASSNAMES,
};
}
@@ -1271,6 +1279,30 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
loadToastId.current = null;
}, []);
+ // The load toast is built by handleLoad and the progress poll, both of which are defined above
+ // handleCancelLoad (it needs handleUnload, which needs them). Route the action through a ref so
+ // the toast keeps a stable onClick instead of dragging the whole load graph into its deps.
+ const cancelLoadRef = useRef<() => void>(() => {});
+ const cancelLoadFromToast = useCallback(() => cancelLoadRef.current(), []);
+ // Bumped by every cancel / eject (see dropResidentState). Requests that were already awaiting a
+ // response when the cancel landed compare against it and discard their own result.
+ const cancelSeq = useRef(0);
+ // Bumped by every load start. The compensating unload below carries no identity, so it must not
+ // fire once a newer load owns the page -- it would tear that one down instead.
+ const loadSeq = useRef(0);
+ // The load currently in flight, if any, as a promise that settles only once handleLoad has run
+ // to the end -- including the compensating unload it may issue. A cancel that lands before the
+ // backend has registered the load has to wait for all of it: begin_load REFUSES a second load
+ // while one is live ("a load is already in progress"), so a model picked in that window would be
+ // rejected while the cancelled one kept going, and the compensating unload names no load, so one
+ // still in flight would tear down whatever the user picked next. Holding busy shuts both.
+ const pendingStart = useRef<Promise<unknown> | null>(null);
+
+ // Set by restoreLoadTracking: handleLoad's compensating unload failed, so the load it was
+ // cancelling is STILL running and its toast and poll are back up. handleUnload reads it to
+ // report that the eject stopped nothing, rather than claiming success over a live load.
+ const loadTrackingRestored = useRef(false);
+
// Client-side state that only means anything while a model is resident: the
// in-flight replacement load's tracking, and the Reapply target. Shared with
// the indicator eject, which frees the runtime without going through the
@@ -1280,6 +1312,14 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// back what was just ejected. In here rather than only in handleUnload, so
// an eject driven from the loaded models card is covered by it too.
pickGuard.cancel();
+ // Everything already in flight is now stale. Clearing the timer below stops the NEXT poll
+ // tick, but not a poll or a start request currently awaiting its response, and those still
+ // apply terminal state when they land. The counter is what they compare against.
+ cancelSeq.current += 1;
+ // A deploy that was cancelled must not resurface: this ref outlives the load and is applied
+ // to whatever LoRA-capable model becomes resident next, which would silently mix a discarded
+ // adapter into an unrelated model's output.
+ pendingDeploy.current = null;
if (pollTimer.current) clearTimeout(pollTimer.current);
pollTimer.current = null;
dismissLoadToast();
@@ -1666,7 +1706,19 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// comes back empty, so only an app reload recovered. Narrowed to
// "loading" so a generation in flight is left alone, as handleUnload's
// own finally does.
- setBusy((prev) => (prev === "loading" ? null : prev));
+ // ...but not while a load start is still in flight. begin_load refuses a second load
+ // while one is registered, so a model picked in that window is rejected while the load
+ // this eject was meant to cancel carries on, and handleLoad's compensating unload names
+ // no load. Hold busy until the whole path settles, exactly as handleCancelLoad does.
+ const pending = pendingStart.current;
+ if (pending) {
+ setBusy((prev) => (prev === "loading" ? "unloading" : prev));
+ void pending
+ .catch(() => {})
+ .finally(() => setBusy((prev) => (prev === "unloading" ? null : prev)));
+ } else {
+ setBusy((prev) => (prev === "loading" ? null : prev));
+ }
setQuant(null);
void refreshStatus();
}),
@@ -1682,11 +1734,23 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// Poll load-progress until the background load reaches "ready" or "error", updating the persistent toast in place each tick.
const pollLoadProgress = useCallback(async () => {
+ // This tick's cancellation fence: clearing pollTimer stops the next tick, not the awaits below.
+ const seq = cancelSeq.current;
try {
const p = await getDiffusionLoadProgress();
+ if (seq !== cancelSeq.current) return;
if (p.phase === "ready") {
dismissLoadToast();
- setStatusIfNewest(++statusTicket.current, await getDiffusionStatus());
+ const ticket = ++statusTicket.current;
+ const loaded = await getDiffusionStatus();
+ if (seq !== cancelSeq.current) {
+ // Cancelled while this read was in flight, so it describes a pipeline being torn down.
+ // Drop it and refresh NOTHING: the unload's own response is authoritative and already
+ // holds the newest ticket, and a status read issued from here would take a newer one
+ // still and could re-report the model mid-teardown.
+ return;
+ }
+ setStatusIfNewest(ticket, loaded);
toast.success("Model loaded");
setBusy(null);
// Load succeeded: the optimistic quant is now the real one, so drop the pending revert.
@@ -1736,13 +1800,26 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
const sig = `${p.phase}:${p.bytes_downloaded}:${p.bytes_total}`;
if (loadToastId.current != null && sig !== lastLoadSig.current) {
lastLoadSig.current = sig;
- toast(null, loadToastArgs(p, loadToastId.current));
+ toast(null, loadToastArgs(p, loadToastId.current, cancelLoadFromToast));
}
} catch {
// Transient poll failure: keep trying.
}
+ if (seq !== cancelSeq.current) return;
pollTimer.current = setTimeout(() => void pollLoadProgress(), 1000);
- }, [dismissLoadToast, refreshStatus]);
+ }, [dismissLoadToast, refreshStatus, cancelLoadFromToast]);
+
+ // Put back what a teardown removed when the load it was tearing down is still running: the
+ // unload failed, so the poll and the toast were stopped for nothing. refreshStatus cannot do
+ // this -- a first load is not resident yet, so status has nothing to report -- and without it a
+ // multi-gigabyte load continues with no progress and no way to cancel it a second time.
+ const restoreLoadTracking = useCallback(() => {
+ loadTrackingRestored.current = true;
+ setBusy("loading");
+ lastLoadSig.current = null;
+ loadToastId.current = toast(null, loadToastArgs(IDLE_PROGRESS, undefined, cancelLoadFromToast));
+ void pollLoadProgress();
+ }, [pollLoadProgress, cancelLoadFromToast]);
// Re-enter the per-step poll for a generation already in flight that this page did not start, instead of a stale idle view.
// generate-progress carries no terminal record, so refresh the gallery on completion to merge any image saved after mount.
@@ -1798,7 +1875,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
setBusy("loading");
dismissLoadToast();
lastLoadSig.current = null;
- loadToastId.current = toast(null, loadToastArgs(p));
+ loadToastId.current = toast(null, loadToastArgs(p, undefined, cancelLoadFromToast));
void pollLoadProgress();
}
} catch {
@@ -1826,7 +1903,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
}
dismissLoadToast();
};
- }, [refreshStatus, dismissLoadToast, pollLoadProgress, resumeGeneratePoll]);
+ }, [refreshStatus, dismissLoadToast, pollLoadProgress, resumeGeneratePoll, cancelLoadFromToast]);
// Seed the generation sliders from a resident model's recipe when the page finds one it did not load itself, else they keep the
// unrecognised-model fallback and a resident flux.1-dev generates garbage at 9 steps. Guarded by lastLoad.current === null and a per-repo ref.
@@ -1932,11 +2009,29 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
): Promise<boolean> => {
// Cancel any prior poll loop so two can't run at once.
if (pollTimer.current) clearTimeout(pollTimer.current);
+ // Read BEFORE the start request goes out: a Cancel pressed while it is in flight sends an
+ // unload that can reach the backend first, find no load registered, and succeed without
+ // stopping anything.
+ const startSeq = cancelSeq.current;
+ const startLoad = ++loadSeq.current;
+ // Published now and settled in the finally below, so a cancel waits for the WHOLE path.
+ let settleLoad: () => void = () => {};
+ const inFlight = new Promise<void>((resolve) => {
+ settleLoad = resolve;
+ });
+ pendingStart.current = inFlight;
+ // Every exit below goes through this: it settles the promise a cancel is waiting on and
+ // releases the ref, so the page cannot stay busy on a load that has already finished.
+ const settle = (started: boolean): boolean => {
+ settleLoad();
+ if (pendingStart.current === inFlight) pendingStart.current = null;
+ return started;
+ };
setBusy("loading");
// Show the chat-style toast immediately; the poll updates it by id.
dismissLoadToast();
lastLoadSig.current = null;
- loadToastId.current = toast(null, loadToastArgs(IDLE_PROGRESS));
+ loadToastId.current = toast(null, loadToastArgs(IDLE_PROGRESS, undefined, cancelLoadFromToast));
// Remember what was loaded so "Reapply" can reload it with new advanced options. Snapshot the prior target first: a load
// that fails to START leaves the previous model resident, so Reapply must keep pointing at it.
const prevLastLoad = lastLoad.current;
@@ -1953,7 +2048,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
try {
// Returns immediately -- the load runs in the background and we poll. The backend infers the family + base repo from the id;
// forward the saved HF token for gated bases. A pipeline load carries no filename; the "auto" sentinels map to omitted.
- await loadDiffusionModel({
+ const startRequest = loadDiffusionModel({
model_path: repoId,
model_kind: opts.kind,
gguf_filename: opts.filename,
@@ -1970,6 +2065,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
transformer_cache: advanced.transformer_cache,
loras: bakeLoras.length > 0 ? bakeLoras : undefined,
});
+ await startRequest;
} catch (err) {
lastLoad.current = prevLastLoad;
setCanReapply(prevLastLoad != null);
@@ -1978,12 +2074,33 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
reportLoadFailure(err instanceof Error ? err.message : "", "Failed to start load");
setBusy(null);
void refreshStatus();
- return false;
+ return settle(false);
+ }
+ if (startSeq !== cancelSeq.current) {
+ // Cancelled during the start request. The unload it sent may have landed before this load
+ // registered, in which case it stopped nothing and the model is loading right now with no
+ // toast and no Cancel button. The load exists on the backend as of this line, so unload
+ // once more -- that one cannot miss it. Unless a NEWER load has since taken the page:
+ // this unload names nothing, so firing it then would cancel that load instead of this
+ // one, and the newer start has already superseded this load's token on the backend.
+ if (startLoad === loadSeq.current) {
+ try {
+ await unloadDiffusionModel();
+ } catch {
+ // This request is the ONLY one that can still stop the load the first unload missed,
+ // so a failure here is not best-effort: the load is running, untracked. Put the
+ // tracking back exactly as a failed cancel does, so it stays visible and cancellable.
+ restoreLoadTracking();
+ return settle(false);
+ }
+ }
+ void refreshStatus();
+ return settle(false);
}
void pollLoadProgress();
- return true;
+ return settle(true);
},
- [pollLoadProgress, refreshStatus, dismissLoadToast, currentLoadAdvanced],
+ [pollLoadProgress, refreshStatus, dismissLoadToast, currentLoadAdvanced, cancelLoadFromToast],
);
// Set (or clear) the Transform/Inpaint source image; always drop any painted mask, which is sized to the previous source.
@@ -2381,21 +2498,72 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
[busy, handleLoad, pickGuard, setPageMode],
);
- const handleUnload = useCallback(async () => {
+ // Resolves true when the backend accepted the unload; handleCancelLoad reports the cancel only then.
+ const handleUnload = useCallback(async (): Promise<boolean> => {
// Ejecting cancels any in-flight replacement load, so tear down its client-side tracking too, or the toast leaks forever.
dropResidentState();
+ loadTrackingRestored.current = false;
setBusy("unloading");
try {
setStatusIfNewest(++statusTicket.current, await unloadDiffusionModel());
setQuant(null);
+ // Hold the page until any load start still in flight has run to its END, compensating
+ // unload and all. The selector's eject routes straight here, so without the fence an eject
+ // landing before the start registered returned success and cleared busy: the user picks
+ // another model, the backend refuses it ("a load is already in progress") because the older
+ // start won the race, and that older handler -- seeing the newer loadSeq -- skips its
+ // compensating unload and returns without restarting its poll, leaving a multi-gigabyte
+ // load running with no toast and no cancel control. Same fence handleCancelLoad and the
+ // external-eject listener take.
+ const pending = pendingStart.current;
+ if (pending) {
+ try {
+ await pending;
+ } catch {
+ // Its own handler reports the failure; this only waits for the window to close.
+ }
+ }
+ // The wait above can end with the tracking RESTORED: handleLoad's compensating unload
+ // failed, so the load is still running. This eject stopped nothing, so do not report
+ // success -- the caller would toast "stopped loading" over a live load.
+ return !loadTrackingRestored.current;
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to unload model");
void refreshStatus();
+ return false;
} finally {
- setBusy(null);
+ // Not an unconditional clear. A restore during the wait above put the page back to
+ // "loading" deliberately; wiping it hides the toast's Cancel and the "Cancel load"
+ // button and re-enables the picker over a load that is still running.
+ setBusy((prev) => (prev === "unloading" ? null : prev));
}
}, [refreshStatus, dropResidentState]);
+ // Cancelling a load IS the unload: it sets the running load's cancel event, bumps the load token so the
+ // worker can never commit, and drops the load marker. What it leaves behind is only cache: bytes already
+ // fetched stay in the HF cache, so loading the same model again resumes instead of restarting, and no
+ // half-built pipeline survives (the worker's commit is token-gated and unload clears the GPU state).
+ const handleCancelLoad = useCallback(async () => {
+ const wasLoading = busy === "loading";
+ if (await handleUnload()) {
+ // handleUnload holds the page for the whole pending-start path before it returns, so by
+ // here the window the backend's "a load is already in progress" refusal lives in is shut.
+ toast.info("Stopped loading the model", {
+ description: "Anything already downloaded stays cached, so loading it again resumes.",
+ });
+ return;
+ }
+ // Already restored inside handleUnload (its own compensating-unload failure), so the toast
+ // and the poll are up: a second restore would raise a duplicate toast and a second poll loop.
+ if (!wasLoading || loadTrackingRestored.current) return;
+ // The unload failed, so the load is still running and its tracking was torn down for nothing.
+ restoreLoadTracking();
+ }, [busy, handleUnload, restoreLoadTracking]);
+
+ useEffect(() => {
+ cancelLoadRef.current = () => void handleCancelLoad();
+ }, [handleCancelLoad]);
+
const handleGenerate = useCallback(async () => {
if (!prompt.trim()) {
toast.error("Prompt is empty");
@@ -2865,6 +3033,27 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
onOpenChange={(o) => setSelectorOpen(active && o)}
/>
)}
+ {/* The load's own cancel, beside the selector rather than inside it: the selector's eject needs a
+ resident model, so it is hidden for exactly the span a first load runs. A real button, not the
+ trigger's aria-hidden eject hit area, so it is reachable by keyboard and a screen reader. Says
+ "load", never "download": the download manager's own Cancel stops a staged pull, a different job. */}
+ {pageMode !== "train" && busy === "loading" && (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label="Cancel load"
+ className="!h-[34px] rounded-full text-xs"
+ onClick={() => void handleCancelLoad()}
+ >
+ Cancel load
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Stop loading this model</TooltipContent>
+ </Tooltip>
+ )}
</div>
</div>
{/* Create | Train page-mode switch, centred on the page rather than tied to the selector width. PillTabs is the app segmented control. */}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 542ea8bef86..15fe4f1021a 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -295,12 +295,20 @@ function loadToastDescription(p: VideoLoadProgress) {
}
// Toast args mirroring chat: persistent, closeable, content in `description`. Pass `id` to update in place.
-function loadToastArgs(p: VideoLoadProgress, id?: string | number) {
+// `onCancel` adds chat's Cancel action, the one control that reaches a load already in flight: the model
+// selector's eject is hidden for exactly the span a first load runs (nothing is resident, so it has no
+// selection to eject), which left a multi-gigabyte pull with no way out.
+function loadToastArgs(
+ p: VideoLoadProgress,
+ id?: string | number,
+ onCancel?: () => void,
+) {
return {
...(id != null ? { id } : {}),
description: loadToastDescription(p),
duration: Infinity,
closeButton: true,
+ ...(onCancel ? { cancel: { label: "Cancel", onClick: onCancel } } : {}),
classNames: LOAD_TOAST_CLASSNAMES,
};
}
@@ -817,6 +825,30 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
loadToastId.current = null;
}, []);
+ // The load toast is built by handleLoad and the progress poll, both of which are defined above
+ // handleCancelLoad (it needs handleUnload, which needs them). Route the action through a ref so
+ // the toast keeps a stable onClick instead of dragging the whole load graph into its deps.
+ const cancelLoadRef = useRef<() => void>(() => {});
+ const cancelLoadFromToast = useCallback(() => cancelLoadRef.current(), []);
+ // Bumped by every cancel / eject (see dropResidentState). Requests that were already awaiting a
+ // response when the cancel landed compare against it and discard their own result.
+ const cancelSeq = useRef(0);
+ // Bumped by every load start. The compensating unload below carries no identity, so it must not
+ // fire once a newer load owns the page -- it would tear that one down instead.
+ const loadSeq = useRef(0);
+ // The load currently in flight, if any, as a promise that settles only once handleLoad has run
+ // to the end -- including the compensating unload it may issue. A cancel that lands before the
+ // backend has registered the load has to wait for all of it: begin_load REFUSES a second load
+ // while one is live ("a load is already in progress"), so a model picked in that window would be
+ // rejected while the cancelled one kept going, and the compensating unload names no load, so one
+ // still in flight would tear down whatever the user picked next. Holding busy shuts both.
+ const pendingStart = useRef<Promise<unknown> | null>(null);
+
+ // Set by restoreLoadTracking: handleLoad's compensating unload failed, so the load it was
+ // cancelling is STILL running and its toast and poll are back up. handleUnload reads it to
+ // report that the eject stopped nothing, rather than claiming success over a live load.
+ const loadTrackingRestored = useRef(false);
+
// Client-side state that only means anything while a model is resident: the
// in-flight replacement load's tracking, and the Reapply target. Shared with
// the indicator eject, which frees the runtime without going through the
@@ -826,6 +858,10 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// back what was just ejected. In here rather than only in handleUnload, so
// an eject driven from the loaded models card is covered by it too.
pickGuard.cancel();
+ // Everything already in flight is now stale. Clearing the timer below stops the NEXT poll
+ // tick, but not a poll or a start request currently awaiting its response, and those still
+ // apply terminal state when they land. The counter is what they compare against.
+ cancelSeq.current += 1;
if (pollTimer.current) clearTimeout(pollTimer.current);
pollTimer.current = null;
dismissLoadToast();
@@ -1291,7 +1327,19 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// comes back empty, so only an app reload recovered. Narrowed to
// "loading" so a generation in flight is left alone, as handleUnload's
// own finally does.
- setBusy((prev) => (prev === "loading" ? null : prev));
+ // ...but not while a load start is still in flight. begin_load refuses a second load
+ // while one is registered, so a model picked in that window is rejected while the load
+ // this eject was meant to cancel carries on, and handleLoad's compensating unload names
+ // no load. Hold busy until the whole path settles, exactly as handleCancelLoad does.
+ const pending = pendingStart.current;
+ if (pending) {
+ setBusy((prev) => (prev === "loading" ? "unloading" : prev));
+ void pending
+ .catch(() => {})
+ .finally(() => setBusy((prev) => (prev === "unloading" ? null : prev)));
+ } else {
+ setBusy((prev) => (prev === "loading" ? null : prev));
+ }
setQuant(null);
void refreshStatus();
}),
@@ -1306,11 +1354,23 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// Poll load-progress until the background load reaches "ready" or "error", updating the persistent toast in place each tick.
const pollLoadProgress = useCallback(async () => {
+ // This tick's cancellation fence: clearing pollTimer stops the next tick, not the awaits below.
+ const seq = cancelSeq.current;
try {
const p = await getVideoLoadProgress();
+ if (seq !== cancelSeq.current) return;
if (p.phase === "ready") {
dismissLoadToast();
- setStatusIfNewest(++statusTicket.current, await getVideoStatus());
+ const ticket = ++statusTicket.current;
+ const loaded = await getVideoStatus();
+ if (seq !== cancelSeq.current) {
+ // Cancelled while this read was in flight, so it describes a pipeline being torn down.
+ // Drop it and refresh NOTHING: the unload's own response is authoritative and already
+ // holds the newest ticket, and a status read issued from here would take a newer one
+ // still and could re-report the model mid-teardown.
+ return;
+ }
+ setStatusIfNewest(ticket, loaded);
toast.success("Model loaded");
setBusy(null);
quantRevert.current = null;
@@ -1355,13 +1415,26 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const sig = `${p.phase}:${p.downloaded_bytes}:${p.expected_bytes ?? 0}`;
if (loadToastId.current != null && sig !== lastLoadSig.current) {
lastLoadSig.current = sig;
- toast(null, loadToastArgs(p, loadToastId.current));
+ toast(null, loadToastArgs(p, loadToastId.current, cancelLoadFromToast));
}
} catch {
// Transient poll failure: keep trying.
}
+ if (seq !== cancelSeq.current) return;
pollTimer.current = setTimeout(() => void pollLoadProgress(), 1000);
- }, [dismissLoadToast, refreshStatus]);
+ }, [dismissLoadToast, refreshStatus, cancelLoadFromToast]);
+
+ // Put back what a teardown removed when the load it was tearing down is still running: the
+ // unload failed, so the poll and the toast were stopped for nothing. refreshStatus cannot do
+ // this -- a first load is not resident yet, so status has nothing to report -- and without it a
+ // multi-gigabyte load continues with no progress and no way to cancel it a second time.
+ const restoreLoadTracking = useCallback(() => {
+ loadTrackingRestored.current = true;
+ setBusy("loading");
+ lastLoadSig.current = null;
+ loadToastId.current = toast(null, loadToastArgs(IDLE_PROGRESS, undefined, cancelLoadFromToast));
+ void pollLoadProgress();
+ }, [pollLoadProgress, cancelLoadFromToast]);
// Stops the generation poll and its visibilitychange catch-up listener.
const stopGenPoll = useCallback(() => {
@@ -1435,7 +1508,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
setBusy("loading");
dismissLoadToast();
lastLoadSig.current = null;
- loadToastId.current = toast(null, loadToastArgs(p));
+ loadToastId.current = toast(null, loadToastArgs(p, undefined, cancelLoadFromToast));
void pollLoadProgress();
}
} catch {
@@ -1470,7 +1543,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
stopGenPoll();
dismissLoadToast();
};
- }, [refreshStatus, dismissLoadToast, pollLoadProgress, startGenPoll, stopGenPoll, ensureSrc]);
+ }, [refreshStatus, dismissLoadToast, pollLoadProgress, startGenPoll, stopGenPoll, ensureSrc, cancelLoadFromToast]);
const handleLoad = useCallback(
// Resolves true when the background load STARTED (callers may revert optimistic picker state on false).
@@ -1482,10 +1555,28 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
},
): Promise<boolean> => {
if (pollTimer.current) clearTimeout(pollTimer.current);
+ // Read BEFORE the start request goes out: a Cancel pressed while it is in flight sends an
+ // unload that can reach the backend first, find no load registered, and succeed without
+ // stopping anything.
+ const startSeq = cancelSeq.current;
+ const startLoad = ++loadSeq.current;
+ // Published now and settled in the finally below, so a cancel waits for the WHOLE path.
+ let settleLoad: () => void = () => {};
+ const inFlight = new Promise<void>((resolve) => {
+ settleLoad = resolve;
+ });
+ pendingStart.current = inFlight;
+ // Every exit below goes through this: it settles the promise a cancel is waiting on and
+ // releases the ref, so the page cannot stay busy on a load that has already finished.
+ const settle = (started: boolean): boolean => {
+ settleLoad();
+ if (pendingStart.current === inFlight) pendingStart.current = null;
+ return started;
+ };
setBusy("loading");
dismissLoadToast();
lastLoadSig.current = null;
- loadToastId.current = toast(null, loadToastArgs(IDLE_PROGRESS));
+ loadToastId.current = toast(null, loadToastArgs(IDLE_PROGRESS, undefined, cancelLoadFromToast));
// Snapshot the prior Reapply target first: a load that fails to START leaves the previous model resident, so Reapply must keep pointing at it.
const prevLastLoad = lastLoad.current;
const prevCanReapply = canReapply;
@@ -1495,7 +1586,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
lastLoadRevert.current = { prev: prevLastLoad, canReapply: prevCanReapply };
try {
// Returns immediately -- the load runs in the background and we poll. The backend infers the family + base repo from the id; the "auto"/"off" sentinels map to omitted.
- await loadVideoModel({
+ const startRequest = loadVideoModel({
model_path: repoId,
model_kind: opts.kind,
gguf_filename: opts.filename,
@@ -1510,6 +1601,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
transformer_quant:
opts.kind === "pipeline" && transformerQuant !== "auto" ? transformerQuant : undefined,
});
+ await startRequest;
} catch (err) {
lastLoad.current = prevLastLoad;
setCanReapply(prevCanReapply);
@@ -1518,15 +1610,37 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
reportLoadFailure(err instanceof Error ? err.message : "", "Failed to start load");
setBusy(null);
void refreshStatus();
- return false;
+ return settle(false);
+ }
+ if (startSeq !== cancelSeq.current) {
+ // Cancelled during the start request. The unload it sent may have landed before this load
+ // registered, in which case it stopped nothing and the model is loading right now with no
+ // toast and no Cancel button. The load exists on the backend as of this line, so unload
+ // once more -- that one cannot miss it. Unless a NEWER load has since taken the page:
+ // this unload names nothing, so firing it then would cancel that load instead of this
+ // one, and the newer start has already superseded this load's token on the backend.
+ if (startLoad === loadSeq.current) {
+ try {
+ await unloadVideoModel();
+ } catch {
+ // This request is the ONLY one that can still stop the load the first unload missed,
+ // so a failure here is not best-effort: the load is running, untracked. Put the
+ // tracking back exactly as a failed cancel does, so it stays visible and cancellable.
+ restoreLoadTracking();
+ return settle(false);
+ }
+ }
+ void refreshStatus();
+ return settle(false);
}
void pollLoadProgress();
- return true;
+ return settle(true);
},
[
pollLoadProgress,
refreshStatus,
dismissLoadToast,
+ cancelLoadFromToast,
canReapply,
memoryMode,
speedMode,
@@ -1890,20 +2004,71 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
[busy, handleLoad, loadGgufRepoPick, loadOrStage, pickGuard, quant],
);
- const handleUnload = useCallback(async () => {
+ // Resolves true when the backend accepted the unload; handleCancelLoad reports the cancel only then.
+ const handleUnload = useCallback(async (): Promise<boolean> => {
dropResidentState();
+ loadTrackingRestored.current = false;
setBusy("unloading");
try {
setStatusIfNewest(++statusTicket.current, await unloadVideoModel());
setQuant(null);
+ // Hold the page until any load start still in flight has run to its END, compensating
+ // unload and all. The selector's eject routes straight here, so without the fence an eject
+ // landing before the start registered returned success and cleared busy: the user picks
+ // another model, the backend refuses it ("a load is already in progress") because the older
+ // start won the race, and that older handler -- seeing the newer loadSeq -- skips its
+ // compensating unload and returns without restarting its poll, leaving a multi-gigabyte
+ // load running with no toast and no cancel control. Same fence handleCancelLoad and the
+ // external-eject listener take.
+ const pending = pendingStart.current;
+ if (pending) {
+ try {
+ await pending;
+ } catch {
+ // Its own handler reports the failure; this only waits for the window to close.
+ }
+ }
+ // The wait above can end with the tracking RESTORED: handleLoad's compensating unload
+ // failed, so the load is still running. This eject stopped nothing, so do not report
+ // success -- the caller would toast "stopped loading" over a live load.
+ return !loadTrackingRestored.current;
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to unload model");
void refreshStatus();
+ return false;
} finally {
- setBusy(null);
+ // Not an unconditional clear. A restore during the wait above put the page back to
+ // "loading" deliberately; wiping it hides the toast's Cancel and the "Cancel load"
+ // button and re-enables the picker over a load that is still running.
+ setBusy((prev) => (prev === "unloading" ? null : prev));
}
}, [refreshStatus, dropResidentState]);
+ // Cancelling a load IS the unload: it sets the running load's cancel event, bumps the load token so the
+ // worker can never commit, and drops the load marker. What it leaves behind is only cache: bytes already
+ // fetched stay in the HF cache, so loading the same model again resumes instead of restarting, and no
+ // half-built pipeline survives (the worker's commit is token-gated and unload clears the GPU state).
+ const handleCancelLoad = useCallback(async () => {
+ const wasLoading = busy === "loading";
+ if (await handleUnload()) {
+ // handleUnload holds the page for the whole pending-start path before it returns, so by
+ // here the window the backend's "a load is already in progress" refusal lives in is shut.
+ toast.info("Stopped loading the model", {
+ description: "Anything already downloaded stays cached, so loading it again resumes.",
+ });
+ return;
+ }
+ // Already restored inside handleUnload (its own compensating-unload failure), so the toast
+ // and the poll are up: a second restore would raise a duplicate toast and a second poll loop.
+ if (!wasLoading || loadTrackingRestored.current) return;
+ // The unload failed, so the load is still running and its tracking was torn down for nothing.
+ restoreLoadTracking();
+ }, [busy, handleUnload, restoreLoadTracking]);
+
+ useEffect(() => {
+ cancelLoadRef.current = () => void handleCancelLoad();
+ }, [handleCancelLoad]);
+
const handleCancelGenerate = useCallback(async () => {
try {
await cancelVideoGeneration();
@@ -2142,6 +2307,27 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
open={active && selectorOpen}
onOpenChange={(o) => setSelectorOpen(active && o)}
/>
+ {/* The load's own cancel, beside the selector rather than inside it: the selector's eject needs a
+ resident model, so it is hidden for exactly the span a first load runs. A real button, not the
+ trigger's aria-hidden eject hit area, so it is reachable by keyboard and a screen reader. Says
+ "load", never "download": the download manager's own Cancel stops a staged pull, a different job. */}
+ {busy === "loading" && (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label="Cancel load"
+ className="!h-[34px] rounded-full text-xs"
+ onClick={() => void handleCancelLoad()}
+ >
+ Cancel load
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Stop loading this model</TooltipContent>
+ </Tooltip>
+ )}
{/* Loaded-model status line: family / kind / offload / speed, as the images page surfaces on load. Hidden until a model is resident. */}
{status?.loaded && (
<div className="hidden min-w-0 items-center gap-3 text-ui-11 @min-[720px]:flex">
diff --git a/studio/frontend/tests/media-eject-busy-state.test.ts b/studio/frontend/tests/media-eject-busy-state.test.ts
index 2bf3a35b99d..b32a8d6c624 100644
--- a/studio/frontend/tests/media-eject-busy-state.test.ts
+++ b/studio/frontend/tests/media-eject-busy-state.test.ts
@@ -32,7 +32,8 @@ for (const [page, runtime, path] of PAGES) {
const SOURCE = read(path);
const listener = SOURCE.slice(
SOURCE.indexOf(`subscribeModelEjected("${runtime}"`),
- SOURCE.indexOf(`subscribeModelEjected("${runtime}"`) + 900,
+ // Wide enough for the pending-start fence the listener grew around that clear.
+ SOURCE.indexOf(`subscribeModelEjected("${runtime}"`) + 1800,
);
test(`the ${page} page settles its busy state on an external eject`, () => {
@@ -50,7 +51,8 @@ for (const [page, runtime, path] of PAGES) {
assert.match(listener, /dropResidentState\(\)/);
const drop = SOURCE.slice(
SOURCE.indexOf("const dropResidentState = useCallback("),
- SOURCE.indexOf("const dropResidentState = useCallback(") + 500,
+ // To the end of the callback, not a fixed window: the body grew a cancel fence.
+ SOURCE.indexOf("}, [dismissLoadToast, pickGuard]);"),
);
assert.match(drop, /clearTimeout\(pollTimer\.current\)/);
assert.doesNotMatch(
diff --git a/studio/frontend/tests/media-load-cancel.test.ts b/studio/frontend/tests/media-load-cancel.test.ts
new file mode 100644
index 00000000000..43b648cf752
--- /dev/null
+++ b/studio/frontend/tests/media-load-cancel.test.ts
@@ -0,0 +1,352 @@
+// 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 first load on the Images or Video page had no stop button. The selector's
+// eject is the control that cancels an in-flight load -- the backend's unload
+// sets the running load's cancel event and bumps its token -- but the pages
+// only pass `onEject` when `status.loaded` is true, and nothing is resident
+// until the load commits. So the one control that would have stopped a
+// multi-gigabyte pull was hidden for exactly its duration.
+//
+// Two exposures fix it, and both are asserted here because either alone can be
+// missed: a Cancel action on the persistent load toast (chat's pattern), and a
+// real "Cancel load" button beside the selector, which survives the toast being
+// dismissed and is reachable by keyboard (the trigger's eject hit area is an
+// aria-hidden span, mouse-only by design).
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const PAGES = [
+ ["Images", "../src/features/images/images-page.tsx"],
+ ["Video", "../src/features/video/video-page.tsx"],
+] as const;
+
+function read(path: string): string {
+ return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");
+}
+
+const DOWNLOAD_PANEL = read(
+ "../src/features/hub/download-manager/download-manager-panel.tsx",
+);
+
+for (const [page, path] of PAGES) {
+ const SOURCE = read(path);
+
+ test(`the ${page} load toast offers a Cancel action`, () => {
+ assert.match(
+ SOURCE,
+ /cancel: \{ label: "Cancel", onClick: onCancel \}/,
+ "the load toast must carry a cancel action, not just a close button",
+ );
+ // Every toast site has to pass it: the toast is created by handleLoad, by
+ // the mount-time resume of a load started elsewhere, re-created in place by
+ // each progress tick, and rebuilt by handleCancelLoad when the unload fails
+ // and the load it could not stop has to stay visible. A tick that dropped
+ // the action would make the button vanish one second into the load.
+ // Call sites only: the declaration's own argument list opens with a newline.
+ const sites = SOURCE.match(/loadToastArgs\((?!\n)[^)\n]*\)/g) ?? [];
+ assert.equal(sites.length, 4, "expected the four load-toast call sites");
+ for (const site of sites) {
+ assert.match(
+ site,
+ /cancelLoadFromToast/,
+ `a load toast built without the cancel action: ${site}`,
+ );
+ }
+ });
+
+ test(`the ${page} page shows a cancel control while a load is in flight`, () => {
+ assert.match(
+ SOURCE,
+ /busy === "loading" && \(\s*<Tooltip>/,
+ "the cancel control must be gated on the load being in flight",
+ );
+ assert.match(SOURCE, /aria-label="Cancel load"/);
+ assert.match(SOURCE, /onClick=\{\(\) => void handleCancelLoad\(\)\}/);
+ });
+
+ test(`the ${page} cancel control does not wait for a resident model`, () => {
+ // The whole bug: `status?.loaded` is false for the span of a first load, so
+ // anything gated on it is invisible exactly when the user wants it.
+ const control = SOURCE.slice(
+ SOURCE.indexOf('aria-label="Cancel load"') - 600,
+ SOURCE.indexOf('aria-label="Cancel load"') + 200,
+ );
+ assert.ok(control.length > 0, "expected the cancel control");
+ assert.doesNotMatch(
+ control,
+ /status\?\.loaded/,
+ "gating the cancel on a resident model reintroduces the bug",
+ );
+ });
+
+ test(`the ${page} cancel routes through the backend unload`, () => {
+ const handler = SOURCE.slice(
+ SOURCE.indexOf("const handleCancelLoad = useCallback("),
+ SOURCE.indexOf("useEffect(() => {\n cancelLoadRef.current"),
+ );
+ assert.ok(handler.length > 0, "expected handleCancelLoad");
+ assert.match(
+ handler,
+ /await handleUnload\(\)/,
+ "unload is what aborts the load: it sets the cancel event and bumps the load token",
+ );
+ // Only report a stop the backend actually accepted, or a failed unload
+ // would claim the load had stopped while it kept downloading.
+ assert.match(handler, /if \(await handleUnload\(\)\)/);
+ assert.match(handler, /Stopped loading the model/);
+ });
+
+ test(`the ${page} unload reports whether it succeeded`, () => {
+ const unload = SOURCE.slice(
+ SOURCE.indexOf("const handleUnload = useCallback("),
+ SOURCE.indexOf("const handleCancelLoad = useCallback("),
+ );
+ assert.match(unload, /Promise<boolean>/);
+ // Success is "the load this eject was cancelling is actually gone", not "the request
+ // returned 200": handleLoad can put the tracking back while this waits (see below).
+ assert.match(unload, /return !loadTrackingRestored[.]current;/);
+ assert.match(unload, /return false;/);
+ });
+
+ test(`the ${page} selector eject is fenced on the pending start too`, () => {
+ // onEject routes STRAIGHT to handleUnload, and it is offered throughout a replacement load
+ // (the outgoing model is still resident). Fencing only handleCancelLoad left that path
+ // clearing busy before the start had registered: the user picks another model, the backend
+ // refuses it because the older start won the race, and the older handler skips its
+ // compensating unload on the newer loadSeq and returns without restarting its poll --
+ // a multi-gigabyte load running with no toast and no cancel control. The fence lives in
+ // handleUnload so every caller of it, the selector included, gets it.
+ const unload = SOURCE.slice(
+ SOURCE.indexOf("const handleUnload = useCallback("),
+ SOURCE.indexOf("const handleCancelLoad = useCallback("),
+ );
+ assert.match(unload, /const pending = pendingStart[.]current;/);
+ // Still busy while it waits: the finally is what clears it, after the await.
+ assert.match(unload, /setBusy[(]"unloading"[)];[\s\S]*await pending;/);
+ assert.match(
+ unload,
+ /await pending;[\s\S]*setBusy[(][(]prev[)] => [(]prev === "unloading" [?] null : prev[)][)];/,
+ );
+ });
+
+ test(`the ${page} unload keeps a restored load visible instead of clearing it`, () => {
+ // The wait the eject now takes can end with handleLoad having PUT THE TRACKING BACK: its
+ // compensating unload failed, so the load is still running. An unconditional setBusy(null)
+ // in the finally wiped that restored "loading" state, hiding the toast's Cancel and the
+ // Cancel load button and re-enabling the picker over a live load -- and the unload reported
+ // success, so the page also claimed the model had stopped.
+ const unload = SOURCE.slice(
+ SOURCE.indexOf("const handleUnload = useCallback("),
+ SOURCE.indexOf("const handleCancelLoad = useCallback("),
+ );
+ assert.match(unload, /loadTrackingRestored[.]current = false;/);
+ assert.match(unload, /return !loadTrackingRestored[.]current;/);
+ assert.match(
+ unload,
+ /setBusy[(][(]prev[)] => [(]prev === "unloading" [?] null : prev[)][)];/,
+ );
+ assert.doesNotMatch(unload, /setBusy[(]null[)];/);
+ // restoreLoadTracking is what raises the flag, and the cancel must not restore twice: a
+ // second call raises a duplicate toast and starts a second poll loop.
+ const restore = SOURCE.slice(
+ SOURCE.indexOf("const restoreLoadTracking = useCallback("),
+ SOURCE.indexOf("}, [pollLoadProgress, cancelLoadFromToast]);"),
+ );
+ assert.match(restore, /loadTrackingRestored[.]current = true;/);
+ const handler = SOURCE.slice(
+ SOURCE.indexOf("const handleCancelLoad = useCallback("),
+ SOURCE.indexOf("useEffect(() => {\n cancelLoadRef.current"),
+ );
+ assert.match(handler, /if [(]!wasLoading [|][|] loadTrackingRestored[.]current[)] return;/);
+ });
+
+ test(`the ${page} eject is still offered only for a resident model`, () => {
+ // Unchanged wiring: eject remains the resident-model control. The fix adds
+ // a second control rather than widening this one, because "Eject" is the
+ // wrong word for stopping a load that never produced anything.
+ assert.match(
+ SOURCE,
+ /onEject=\{status\?\.loaded \? handleUnload : undefined\}/,
+ );
+ });
+
+
+ test(`the ${page} cancel fences the pending start request`, () => {
+ // Cancel is reachable the instant `busy` turns "loading", which is before the start request
+ // has even been sent. Its unload can therefore reach the backend BEFORE begin_load registers
+ // the load, find nothing to stop, and return success -- after which the load runs on with no
+ // toast and no Cancel button. handleLoad has to notice that and unload again.
+ const load = SOURCE.slice(
+ SOURCE.indexOf("const handleLoad = useCallback("),
+ SOURCE.indexOf("// Set (or clear) the Transform"),
+ );
+ const body = load.length > 0 ? load : SOURCE.slice(SOURCE.indexOf("const handleLoad = useCallback("));
+ assert.match(
+ body,
+ /const startSeq = cancelSeq\.current;/,
+ "the cancel counter must be sampled BEFORE the start request goes out",
+ );
+ assert.match(body, /if \(startSeq !== cancelSeq\.current\) \{/);
+ assert.match(
+ body,
+ /await unload(Diffusion|Video)Model\(\)/,
+ "a cancel that raced the start must unload again once the load exists",
+ );
+ // ...and must NOT then start polling a load it just cancelled.
+ const raced = body.slice(body.indexOf("if (startSeq !== cancelSeq.current)"));
+ assert.doesNotMatch(
+ raced.slice(0, raced.indexOf("return settle(false);")),
+ /void pollLoadProgress\(\)/,
+ );
+ // That compensating unload names no load, so it must not fire once a newer one owns the
+ // page -- picking another model straight after cancelling is the natural next action, and
+ // an unscoped unload landing then would tear the replacement down instead.
+ assert.match(body, /const startLoad = \+\+loadSeq\.current;/);
+ assert.match(raced, /if \(startLoad === loadSeq\.current\) \{/);
+ });
+
+ test(`the ${page} cancelled poll leaves the status read to the unload`, () => {
+ // The unload's own response is authoritative and already carries the newest ticket. A status
+ // read issued from the cancelled branch would take a newer one still, and /status can report
+ // the model as resident while teardown is in progress -- which is the same stale-answer-wins
+ // bug the fence exists to close.
+ const poll = SOURCE.slice(
+ SOURCE.indexOf("const pollLoadProgress = useCallback("),
+ SOURCE.indexOf("}, [dismissLoadToast, refreshStatus, cancelLoadFromToast]);"),
+ );
+ const cancelled = poll.slice(poll.lastIndexOf("if (seq !== cancelSeq.current) {"));
+ assert.ok(cancelled.length > 0, "expected the cancelled-status branch");
+ assert.doesNotMatch(
+ cancelled.slice(0, cancelled.indexOf("return;")),
+ /refreshStatus\(\)/,
+ "the cancelled branch must not allocate a ticket newer than the unload's",
+ );
+ });
+
+ test(`the ${page} progress poll is invalidated by a cancel`, () => {
+ // clearTimeout stops the NEXT tick. A tick already awaiting its response still lands, and its
+ // ready branch would announce "Model loaded" and issue a status ticket newer than the
+ // unload's, so the unloaded answer is dropped as stale and the controls keep advertising a
+ // model that is gone.
+ const poll = SOURCE.slice(
+ SOURCE.indexOf("const pollLoadProgress = useCallback("),
+ SOURCE.indexOf("}, [dismissLoadToast, refreshStatus, cancelLoadFromToast]);"),
+ );
+ assert.match(poll, /const seq = cancelSeq\.current;/);
+ assert.match(poll, /if \(seq !== cancelSeq\.current\) return;/);
+ // The status read is the one that has to be checked on BOTH sides of its await.
+ assert.match(poll, /const loaded = await get(Diffusion|Video)Status\(\);\s*\n\s*if \(seq !== cancelSeq\.current\) \{/);
+ });
+
+ test(`the ${page} cancel counter is bumped by every teardown`, () => {
+ const drop = SOURCE.slice(
+ SOURCE.indexOf("const dropResidentState = useCallback("),
+ SOURCE.indexOf("}, [dismissLoadToast, pickGuard]);"),
+ );
+ assert.match(
+ drop,
+ /cancelSeq\.current \+= 1;/,
+ "an eject from the loaded-models card cancels a load too, so it must fence as well",
+ );
+ });
+
+ test(`the ${page} restores load tracking when the unload fails`, () => {
+ // dropResidentState has already killed the poll and the toast by the time the unload's
+ // failure is known, and refreshStatus cannot bring them back: a first load has nothing
+ // resident to report. Without a restore the load keeps running, invisibly and uncancellable.
+ const handler = SOURCE.slice(
+ SOURCE.indexOf("const handleCancelLoad = useCallback("),
+ SOURCE.indexOf("useEffect(() => {\n cancelLoadRef.current"),
+ );
+ assert.match(handler, /const wasLoading = busy === "loading";/);
+ assert.match(handler, /restoreLoadTracking\(\);/);
+ const restore = SOURCE.slice(
+ SOURCE.indexOf("const restoreLoadTracking = useCallback("),
+ SOURCE.indexOf("}, [pollLoadProgress, cancelLoadFromToast]);"),
+ );
+ assert.match(restore, /setBusy\("loading"\);/);
+ assert.match(restore, /loadToastId\.current = toast\(/);
+ assert.match(restore, /void pollLoadProgress\(\);/);
+ });
+
+ test(`the ${page} cancel holds the page until a pending start settles`, () => {
+ // begin_load refuses a second load while one is registered, so a model picked between the
+ // cancel returning and the start request settling is rejected while the cancelled load keeps
+ // running. Staying busy for that window is what makes the compensating unload reachable.
+ // The fence itself lives in handleUnload (see above), which handleCancelLoad awaits before
+ // it reports the cancel, so the window is shut for the selector's eject as well.
+ const handler = SOURCE.slice(
+ SOURCE.indexOf("const handleUnload = useCallback("),
+ SOURCE.indexOf("useEffect(() => {\n cancelLoadRef.current"),
+ );
+ assert.match(handler, /const pending = pendingStart\.current;/);
+ assert.match(handler, /setBusy\("unloading"\);/);
+ assert.match(handler, /await pending;/);
+ assert.match(handler, /if \(await handleUnload\(\)\) \{/);
+ // And it must cover the WHOLE load path, not just the start POST: the compensating unload
+ // runs after that POST resolves and names no load, so a model picked while it is in flight
+ // would be torn down by it. handleLoad publishes one promise up front and settles it at
+ // every exit, so waiting on it waits for the teardown too.
+ const load = SOURCE.slice(
+ SOURCE.indexOf("const handleLoad = useCallback("),
+ SOURCE.indexOf("const handleLoad = useCallback(") + 3000,
+ );
+ assert.match(load, /pendingStart\.current = inFlight;/);
+ assert.match(load, /const settle = \(started: boolean\): boolean => \{/);
+ assert.doesNotMatch(load, /pendingStart\.current = startRequest;/);
+ });
+
+ test(`the ${page} recovers when the compensating unload fails`, () => {
+ // That request is the only one that can still stop the load the first unload missed, so
+ // swallowing its failure leaves the load running with nothing tracking it.
+ const at = SOURCE.indexOf("if (startSeq !== cancelSeq.current)");
+ const raced = SOURCE.slice(at, at + 1400);
+ assert.match(raced, /restoreLoadTracking\(\);/);
+ });
+
+ test(`the ${page} external eject is fenced by the pending start too`, () => {
+ // The loaded-models card ejects without going through handleCancelLoad, so it needs the same
+ // fence: clearing busy while a start request is in flight lets the user pick a model that
+ // begin_load then refuses, while the load the eject meant to cancel keeps running untracked.
+ const listener = SOURCE.slice(
+ SOURCE.indexOf("subscribeModelEjected("),
+ SOURCE.indexOf("subscribeModelEjected(") + 1600,
+ );
+ assert.match(listener, /const pending = pendingStart\.current;/);
+ assert.match(listener, /setBusy\(\(prev\) => \(prev === "loading" \? "unloading" : prev\)\);/);
+ });
+
+ test(`the ${page} cancel names the load, not the download`, () => {
+ // A user mid-load can have a staged download in the manager panel too, and
+ // the two stop different things: this one abandons the load, that one stops
+ // a queued pull. Same word in both corners would be its own bug.
+ const control = SOURCE.slice(
+ SOURCE.indexOf('aria-label="Cancel load"'),
+ SOURCE.indexOf('aria-label="Cancel load"') + 400,
+ );
+ assert.doesNotMatch(control, /Cancel download/);
+ assert.match(control, /Stop loading this model/);
+ });
+}
+
+test("the download manager keeps its own, differently named cancel", () => {
+ assert.match(DOWNLOAD_PANEL, /"Cancel download"/);
+});
+
+
+test("cancelling a deploy does not leave the adapter queued", () => {
+ // handleDeployAdapter parks the trained adapter in pendingDeploy and loads its base. That ref
+ // is applied to whatever LoRA-capable model becomes resident NEXT, so a cancelled deploy would
+ // silently mix a discarded adapter into an unrelated model's generations. Clearing it belongs
+ // in dropResidentState, which every cancel and every eject already runs.
+ const SOURCE = read("../src/features/images/images-page.tsx");
+ const drop = SOURCE.slice(
+ SOURCE.indexOf("const dropResidentState = useCallback("),
+ SOURCE.indexOf("}, [dismissLoadToast, pickGuard]);"),
+ );
+ assert.match(drop, /pendingDeploy\.current = null;/);
+});