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: keep a Downloads entry when the list is empty (#9849)
Souravrajvi01b596b1dc216
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-config.ts b/studio/frontend/src/features/hub/download-manager/download-manager-config.tsindex 10662948821..42aafd833a9 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-config.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-config.ts@@ -20,11 +20,14 @@ export const CANCEL_WATCHDOG_MS = 20_000;export const IDLE_EVICT_GRACE_MS = 60_000;// A small Xet download can finish before its card ever shows a byte.export const COMPLETE_LINGER_MS = 30_000;-export const CANCELLED_LINGER_MS = 6_000;-export const ERROR_LINGER_MS = 12_000;export const INVENTORY_BUMP_DEBOUNCE_MS = 250;export const TRANSPORT_STATUS_RETRY_DELAY_MS = 300;+/** Shown when a transfer dies with partial files still on disk, so the+ * Downloads list can offer Resume instead of vanishing. */+export const INTERRUPTED_DOWNLOAD_MESSAGE =+ "Download interrupted. Resume from Downloads to continue.";+export const ACTIVE_STATES: ReadonlySet<DownloadJobState> = new Set(["running","cancelling",@@ -35,3 +38,15 @@ export const TERMINAL_DISPLAY_STATES: ReadonlySet<DownloadJobState> = new Set(["error","cancelled",]);++/** Failed or stopped jobs the Downloads list keeps until the user dismisses+ * them, so a mid-transfer failure can be resumed without searching the model+ * again. Complete jobs still linger briefly and are not persisted. */+export const RESUMABLE_STATES: ReadonlySet<DownloadJobState> = new Set([+ "error",+ "cancelled",+]);++export function isPersistedJobState(state: DownloadJobState): boolean {+ return ACTIVE_STATES.has(state) || RESUMABLE_STATES.has(state);+}diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts b/studio/frontend/src/features/hub/download-manager/download-manager-controller.tsindex 2cea1d83048..1cb3fcb8b5e 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts@@ -1,10 +1,18 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import {+ AUTH_SESSION_CLEARED_EVENT,+ AUTH_SESSION_MARK_KEY,+ AUTH_SESSION_STORED_EVENT,+ AUTH_TOKEN_KEY,+} from "@/features/auth";+import { isTauri } from "@/lib/api-base";import {createDownloadManagerInitialState,removeJob,setState,+ useDownloadManagerStore,} from "./download-manager-state";import { resetDownloadApiAdapterState } from "./download-api-adapter";import {@@ -30,19 +38,47 @@ export {useDownloadManagerStore,} from "./download-manager-state";export type {+ ConflictOwner,DownloadRequest,JobListeners,ManagedDownload,} from "./download-manager-types";+export { conflictInfoForOwner } from "./download-manager-types";export { hydrateDownloadManager };-export function __resetDownloadManagerForTests(): void {+function resetDownloadManagerState(): void {runtimeRegistry.reset();resetDownloadApiAdapterState();resetHydrationState();setState(createDownloadManagerInitialState());}+export function __resetDownloadManagerForTests(): void {+ resetDownloadManagerState();+}++function clearWebSessionDownloads(): void {+ if (isTauri) return;+ resetDownloadManagerState();+ // Clearing after the state reset also cancels the throttled empty-state write.+ void useDownloadManagerStore.persist.clearStorage();+}++function handleAuthStorageChange(event: StorageEvent): void {+ if (+ event.key === AUTH_SESSION_MARK_KEY ||+ (event.key === AUTH_TOKEN_KEY && event.newValue === null)+ ) {+ clearWebSessionDownloads();+ }+}++if (typeof window !== "undefined") {+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, clearWebSessionDownloads);+ window.addEventListener(AUTH_SESSION_STORED_EVENT, clearWebSessionDownloads);+ window.addEventListener("storage", handleAuthStorageChange);+}+export interface DownloadManagerController {requestStart: typeof requestStart;cancel: typeof cancelJob;@@ -68,6 +104,15 @@ export const downloadManager: DownloadManagerController = {if (import.meta.hot) {import.meta.hot.dispose(() => {+ window.removeEventListener(+ AUTH_SESSION_CLEARED_EVENT,+ clearWebSessionDownloads,+ );+ window.removeEventListener(+ AUTH_SESSION_STORED_EVENT,+ clearWebSessionDownloads,+ );+ window.removeEventListener("storage", handleAuthStorageChange);__resetDownloadManagerForTests();});}diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsxindex 2a3bb0e6885..f15422828f3 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx+++ b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx@@ -9,17 +9,23 @@ import {import { hasAuthToken, mustChangePassword } from "@/features/auth/session";import { isTauri } from "@/lib/api-base";import { ChevronDownStandardIcon } from "@/lib/chevron-icons";+import { toast } from "@/lib/toast";import { cn } from "@/lib/utils";import {Alert02Icon,Cancel01Icon,CheckmarkCircle02Icon,Download01Icon,+ PlayIcon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import { useRouterState } from "@tanstack/react-router";-import { useEffect, useMemo, useState } from "react";+import { Link, useRouterState } from "@tanstack/react-router";+import { useEffect, useMemo, useRef, useState } from "react";+import { TransportConflictDialog } from "../catalog/transport-conflict-dialog";+import { RESUMABLE_STATES } from "./download-manager-config";import {+ conflictInfoForOwner,+ type DownloadRequest,type ManagedDownload,downloadManager,hydrateDownloadManager,@@ -60,6 +66,22 @@ function selectActiveJobCount(state: {return count;}+function selectResumableJobCount(state: {+ jobs: Record<string, ManagedDownload>;+}): number {+ let count = 0;+ for (const job of Object.values(state.jobs)) {+ if (!job.external && RESUMABLE_STATES.has(job.state)) count += 1;+ }+ return count;+}++function showResumeBusyToast(): void {+ toast.info("This repository is already downloading", {+ description: "Wait for the active download to finish, then try Resume again.",+ });+}+function canUseDownloadManager(pathname: string): boolean {if (isTauri) return true;if (@@ -86,6 +108,26 @@ function variantSuffix(job: ManagedDownload): string {return job.variant ? ` · ${job.variant}` : "";}+function resumeRequestFromJob(job: ManagedDownload): DownloadRequest {+ const scopeId = job.variant?.startsWith("@")+ ? job.variant.slice(1)+ : undefined;+ return {+ kind: job.kind,+ repoId: job.repoId,+ variant: job.variant,+ expectedBytes: job.expectedBytes,+ ...(job.inventoryKind !== undefined+ ? { inventoryKind: job.inventoryKind }+ : {}),+ ...(scopeId ? { scopeId } : {}),+ ...(job.scopedFiles && job.scopedFiles.length > 0+ ? { files: job.scopedFiles }+ : {}),+ ...(job.checkpoint !== undefined ? { checkpoint: job.checkpoint } : {}),+ };+}+function StatusLine({ job }: { job: ManagedDownload }) {if (job.state === "complete") {return <span className="text-status-success">Downloaded</span>;@@ -109,12 +151,43 @@ function StatusLine({ job }: { job: ManagedDownload }) {function DownloadRow({ jobKey }: { jobKey: string }) {const job = useDownloadManagerStore((state) => state.jobs[jobKey]);+ const transportConflict = useDownloadManagerStore(+ (state) => conflictInfoForOwner(state.conflicts[jobKey], "downloads"),+ );+ const mounted = useRef(true);+ const [resumePending, setResumePending] = useState(false);+ useEffect(+ () => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ downloadManager.cancelConflict(jobKey, "downloads");+ };+ },+ [jobKey],+ );if (!job) return null;const active = job.state === "running" || job.state === "cancelling";+ const resumable = !job.external && RESUMABLE_STATES.has(job.state);const terminal =job.state === "complete" ||job.state === "cancelled" ||job.state === "error";+ const showProgress = active || resumable;+ const resolveTransportConflict = (action: "resume" | "restart") => {+ setResumePending(true);+ const resolution =+ action === "resume"+ ? downloadManager.resumeConflict(jobKey, "downloads")+ : downloadManager.restartConflict(jobKey, "downloads");+ void resolution+ .then((outcome) => {+ if (outcome === "busy" && mounted.current) showResumeBusyToast();+ })+ .finally(() => {+ if (mounted.current) setResumePending(false);+ });+ };return (<li className="flex flex-col gap-1.5 py-2.5 pl-4 pr-3"><div className="flex items-center gap-2">@@ -136,12 +209,53 @@ function DownloadRow({ jobKey }: { jobKey: string }) {className="size-4 shrink-0 text-destructive"/>)}+ {resumable && (+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ aria-label="Resume download"+ disabled={resumePending}+ onClick={() => {+ if (resumePending) return;+ setResumePending(true);+ void downloadManager+ .requestStart(resumeRequestFromJob(job), "downloads")+ .then((outcome) => {+ if (outcome === "busy" && mounted.current) {+ showResumeBusyToast();+ }+ if (outcome === "conflict" && !mounted.current) {+ downloadManager.cancelConflict(jobKey, "downloads");+ }+ })+ .finally(() => {+ if (mounted.current) setResumePending(false);+ });+ }}+ className={cn(+ "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors",+ "hover:bg-foreground/[0.06] hover:text-foreground disabled:cursor-default disabled:opacity-50 dark:hover:bg-white/[0.06]",+ )}+ >+ <HugeiconsIcon+ icon={PlayIcon}+ strokeWidth={1.75}+ className="size-3.5"+ />+ </button>+ </TooltipTrigger>+ <TooltipContent side="top" sideOffset={4}>+ Resume download+ </TooltipContent>+ </Tooltip>+ )}<Tooltip><TooltipTrigger asChild={true}><buttontype="button"aria-label={active ? "Cancel download" : "Dismiss"}- disabled={job.state === "cancelling"}+ disabled={job.state === "cancelling" || resumePending}onClick={() =>active? void downloadManager.cancel(job.key)@@ -164,7 +278,7 @@ function DownloadRow({ jobKey }: { jobKey: string }) {</TooltipContent></Tooltip></div>- {active ? (+ {showProgress ? (<DownloadProgressBarprogress={{expectedBytes: job.expectedBytes,@@ -181,6 +295,12 @@ function DownloadRow({ jobKey }: { jobKey: string }) {<StatusLine job={job} /></div>) : null}+ <TransportConflictDialog+ conflict={transportConflict}+ onCancel={() => downloadManager.cancelConflict(jobKey, "downloads")}+ onKeepTransport={() => resolveTransportConflict("resume")}+ onSwitchTransport={() => resolveTransportConflict("restart")}+ /></li>);}@@ -190,7 +310,8 @@ export function DownloadManagerPanel({}: { positioned?: boolean } = {}) {const pathname = useRouterState({ select: (s) => s.location.pathname });const enabled = canUseDownloadManager(pathname);- const [collapsed, setCollapsed] = useState(false);+ const [collapsed, setCollapsed] = useState(true);+ const previousActiveCount = useRef(0);useEffect(() => {if (!enabled) return;@@ -200,13 +321,24 @@ export function DownloadManagerPanel({const selectOrderedJobKeys = useMemo(createOrderedJobKeysSelector, []);const jobKeys = useDownloadManagerStore(selectOrderedJobKeys);const activeCount = useDownloadManagerStore(selectActiveJobCount);+ const resumableCount = useDownloadManagerStore(selectResumableJobCount);++ useEffect(() => {+ if (activeCount > 0 && previousActiveCount.current === 0) {+ setCollapsed(false);+ }+ previousActiveCount.current = activeCount;+ }, [activeCount]);- if (!enabled || jobKeys.length === 0) return null;+ if (!enabled) return null;+ const attentionCount = activeCount + resumableCount;const headerLabel =activeCount > 0? `Downloading ${activeCount} ${activeCount === 1 ? "item" : "items"}`- : "Downloads";+ : resumableCount > 0+ ? `${resumableCount} ${resumableCount === 1 ? "download" : "downloads"} to resume`+ : "Downloads";return (<div@@ -233,8 +365,8 @@ export function DownloadManagerPanel({strokeWidth={1.75}className="size-[18px]"/>- {activeCount > 0 && (- <span className="hub-download-fab-badge">{activeCount}</span>+ {attentionCount > 0 && (+ <span className="hub-download-fab-badge">{attentionCount}</span>)}</button></TooltipTrigger>@@ -261,11 +393,27 @@ export function DownloadManagerPanel({/></button></div>- <ul className="max-h-[60dvh] divide-y divide-foreground/[0.06] overflow-y-auto [scrollbar-width:thin]">- {jobKeys.map((jobKey) => (- <DownloadRow key={jobKey} jobKey={jobKey} />- ))}- </ul>+ {jobKeys.length === 0 ? (+ <div className="flex flex-col gap-2 px-4 py-3 text-ui-12 text-muted-foreground">+ <p>+ No downloads yet. Interrupted transfers stay here so you can+ resume them.+ </p>+ <Link+ to="/hub"+ search={{ tab: "downloaded" }}+ className="text-ui-12p5 font-medium text-foreground underline-offset-2 hover:underline"+ >+ Open Model hub+ </Link>+ </div>+ ) : (+ <ul className="max-h-[60dvh] divide-y divide-foreground/[0.06] overflow-y-auto [scrollbar-width:thin]">+ {jobKeys.map((jobKey) => (+ <DownloadRow key={jobKey} jobKey={jobKey} />+ ))}+ </ul>+ )}</div>)}</div>diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts b/studio/frontend/src/features/hub/download-manager/download-manager-state.tsindex 30d6dc6b57d..f011c36b929 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts@@ -23,6 +23,7 @@ import {import {ACTIVE_STATES,MAX_PROGRESS_FRACTION,+ isPersistedJobState,} from "./download-manager-config";import {type DownloadManagerState,@@ -91,7 +92,7 @@ function sanitizePersistedJob(const kind = isDownloadKind(value.kind) ? value.kind : null;const repoId = typeof value.repoId === "string" ? value.repoId : null;const state = value.state as DownloadJobState;- if (!kind || !repoId || !ACTIVE_STATES.has(state)) return null;+ if (!kind || !repoId || !isPersistedJobState(state)) return null;const variant = typeof value.variant === "string" ? value.variant : null;const key = jobKeyOf(kind, repoId, variant);@@ -299,7 +300,10 @@ export const useDownloadManagerStore = create<DownloadManagerState>()(partialize: (state) => ({jobs: Object.fromEntries(Object.entries(state.jobs)- .filter(([, job]) => !job.external && ACTIVE_STATES.has(job.state))+ // External jobs have no hub job to resume into, so they are not saved.+ // Failed and cancelled jobs stay: the Downloads list is the resume+ // entry after a mid-transfer failure or a restart (#9780).+ .filter(([, job]) => !job.external && isPersistedJobState(job.state)).map(([key, job]) => [key, toPersistedJob(job)] as const),),conflicts: {},diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.tsindex 51de5eaa535..9683db57785 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts@@ -108,11 +108,21 @@ export interface JobListeners {onError?: (variant: string | null) => unknown;}+export type ConflictOwner = "caller" | "downloads";+export interface ConflictEntry {+ owner: ConflictOwner;info: TransportConflictInfo;pending: DownloadRequest;}+export function conflictInfoForOwner(+ entry: ConflictEntry | undefined,+ owner: ConflictOwner,+): TransportConflictInfo | null {+ return entry?.owner === owner ? entry.info : null;+}+export interface DownloadManagerState {jobs: Record<string, ManagedDownload>;conflicts: Record<string, ConflictEntry>;diff --git a/studio/frontend/src/features/hub/download-manager/hydration.ts b/studio/frontend/src/features/hub/download-manager/hydration.tsindex e1c363088ce..35ecd92fa9b 100644--- a/studio/frontend/src/features/hub/download-manager/hydration.ts+++ b/studio/frontend/src/features/hub/download-manager/hydration.ts@@ -9,7 +9,11 @@ import {type DownloadJobState,} from "./api";import { DOWNLOAD_KIND, isResolvedTransport } from "./constants";-import { ACTIVE_STATES, POLL_REQUEST_TIMEOUT_MS } from "./download-manager-config";+import {+ ACTIVE_STATES,+ POLL_REQUEST_TIMEOUT_MS,+ RESUMABLE_STATES,+} from "./download-manager-config";import {apiGetProgress,apiGetStatus,@@ -202,6 +206,40 @@ async function probeHydratedIdleProgress(}}+async function revalidateHydratedResumableJob(+ key: string,+ job: ManagedDownload,+): Promise<void> {+ try {+ const progressResp = await withHydrationTimeout((signal) =>+ apiGetProgress(job, signal),+ );+ const current = getState().jobs[key];+ if (!current || !RESUMABLE_STATES.has(current.state)) return;+ applyProgressUpdate(key, current, progressResp);+ const updated = getState().jobs[key];+ if (!updated || !RESUMABLE_STATES.has(updated.state)) return;+ if (hasObservedExpectedBytes(updated)) {+ // Completed jobs are not restored after a restart; removing the stale+ // terminal row lets the verified inventory state show through.+ removeJob(key);+ return;+ }+ if (+ idleProbeVerdict(+ progressResp.downloaded_bytes,+ progressResp.cache_path,+ progressResp.target_present,+ progressResp.cache_measured,+ ) === "gone"+ ) {+ removeJob(key);+ }+ } catch {+ // An unavailable or unreadable cache is not evidence that the partial is gone.+ }+}+async function settleHydratedJob(key: string,req: DownloadRequest,@@ -287,6 +325,13 @@ export function hydrateDownloadManager(): void {for (const job of jobs) {// External jobs are live in memory and have no hub job to probe.if (job.external) continue;+ // Failed and cancelled rows stay in Downloads so they can be resumed+ // after a restart. Complete jobs are not persisted, and anything else+ // is not a card the list should keep.+ if (RESUMABLE_STATES.has(job.state)) {+ void revalidateHydratedResumableJob(job.key, job);+ continue;+ }if (!ACTIVE_STATES.has(job.state)) {removeJob(job.key);continue;diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex 32937b88c35..edd51de8a47 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -1,7 +1,11 @@// 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 { carriesOverSeed, seededMeasuredTransfer } from "./adopt-rules";+import {+ carriesOverSeed,+ idleProbeVerdict,+ seededMeasuredTransfer,+} from "./adopt-rules";import { invalidateGgufVariantsCache } from "../inventory/api";import { getHfToken } from "../stores/hf-token-store";import { bumpInventoryVersion } from "../stores/inventory-events";@@ -15,12 +19,11 @@ import {} from "./api";import { cancelExternalJob, isExternalJob } from "./external-jobs";import {- CANCELLED_LINGER_MS,CANCEL_WATCHDOG_MS,COMPLETE_LINGER_MS,- ERROR_LINGER_MS,HIDDEN_POLL_INTERVAL_MS,IDLE_EVICT_GRACE_MS,+ INTERRUPTED_DOWNLOAD_MESSAGE,INVENTORY_BUMP_DEBOUNCE_MS,POLL_BACKOFF_AFTER_MS,POLL_BACKOFF_INTERVAL_MS,@@ -243,7 +246,8 @@ export function finalize(error: null,});notify(job, "onCancelled", 0);- scheduleRemoval(key, CANCELLED_LINGER_MS);+ // Stay in Downloads until dismissed so the user can resume the partial+ // without searching the model again.} else {const rawError =typeof opts.error === "string" && opts.error@@ -257,7 +261,6 @@ export function finalize(etaSeconds: 0,});notify(job, "onError", 0);- scheduleRemoval(key, ERROR_LINGER_MS);}scheduleInventoryBump();}@@ -383,18 +386,30 @@ function handleIdleAfterProgress(rt: JobRuntime,key: string,madeProgress: boolean,+ progressResp: ProgressLike,): void {const updatedJob = getState().jobs[key];if (updatedJob && hasObservedExpectedBytes(updatedJob)) {finalize(key, "complete", { bytes: updatedJob.downloadedBytes });} else if (rt.cancelRequested) {finalize(key, "cancelled");+ } else if (+ idleProbeVerdict(+ progressResp.downloaded_bytes,+ progressResp.cache_path,+ progressResp.target_present,+ progressResp.cache_measured,+ ) === "gone"+ ) {+ finalize(key, "gone");} else if (madeProgress) {rt.idleSinceMs = null;} else {rt.idleSinceMs ??= Date.now();if (Date.now() - rt.idleSinceMs >= IDLE_EVICT_GRACE_MS) {- finalize(key, "gone");+ // The backend went idle with the card still up: keep a resumable row+ // instead of dropping it. "gone" is only when the cache itself vanished.+ finalize(key, "error", { error: INTERRUPTED_DOWNLOAD_MESSAGE });}}}@@ -483,7 +498,7 @@ async function tick(key: string): Promise<void> {);if (status.state === "idle") {- handleIdleAfterProgress(rt, key, madeProgress);+ handleIdleAfterProgress(rt, key, madeProgress, progressResp);} else {rt.idleSinceMs = null;}diff --git a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts b/studio/frontend/src/features/hub/download-manager/transport-conflict.tsindex 742315a10c4..c1ce051d889 100644--- a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts+++ b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts@@ -15,6 +15,7 @@ import {effectiveTransportMode,} from "./download-api-adapter";import type {+ ConflictOwner,DownloadRequest,ManagedDownload,} from "./download-manager-types";@@ -155,6 +156,7 @@ async function runWithPendingStartGuard(export async function requestStart(req: DownloadRequest,+ conflictOwner: ConflictOwner = "caller",): Promise<DownloadStartOutcome> {// Before the preflight below, which is two round trips the user can navigate// during; read after them it would name the page they moved to.@@ -204,6 +206,7 @@ export async function requestStart();if (action === "conflict") {setConflict(jobKeyOf(req.kind, req.repoId, req.variant), {+ owner: conflictOwner,info: {previous: last,next: resolved,@@ -217,7 +220,10 @@ export async function requestStart(}mode = action;}- if (status.has_partial && !status.last_transport) {+ if (+ status.has_partial &&+ (status.resumable === false || !status.last_transport)+ ) {toast.info("Restarting this download", {description:"An earlier partial download can't be resumed, so it will start again from the beginning.",@@ -261,30 +267,41 @@ export async function requestStart(});}-export function resumeConflict(conflictKey: string): void {+export async function resumeConflict(+ conflictKey: string,+ owner: ConflictOwner = "caller",+): Promise<DownloadStartOutcome | undefined> {const entry = getState().conflicts[conflictKey];- if (!entry) return;+ if (!entry || entry.owner !== owner) return;setConflict(conflictKey, null);- void runWithPendingStartGuard(entry.pending, async () => {+ return runWithPendingStartGuard(entry.pending, async () => {await startJob(entry.pending, {useXet: entry.info.previous === TRANSPORT.XET,});- return "started";+ return isJobActiveFor(entry.pending) ? "started" : "error";});}-export function restartConflict(conflictKey: string): void {+export async function restartConflict(+ conflictKey: string,+ owner: ConflictOwner = "caller",+): Promise<DownloadStartOutcome | undefined> {const entry = getState().conflicts[conflictKey];- if (!entry) return;+ if (!entry || entry.owner !== owner) return;setConflict(conflictKey, null);- void runWithPendingStartGuard(entry.pending, async () => {+ return runWithPendingStartGuard(entry.pending, async () => {await startJob(entry.pending, {useXet: entry.info.next === TRANSPORT.XET,});- return "started";+ return isJobActiveFor(entry.pending) ? "started" : "error";});}-export function cancelConflict(conflictKey: string): void {+export function cancelConflict(+ conflictKey: string,+ owner: ConflictOwner = "caller",+): void {+ const entry = getState().conflicts[conflictKey];+ if (!entry || entry.owner !== owner) return;setConflict(conflictKey, null);}diff --git a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts b/studio/frontend/src/features/hub/download-manager/use-repo-download.tsindex 94badc84134..a3397998d39 100644--- a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts+++ b/studio/frontend/src/features/hub/download-manager/use-repo-download.ts@@ -7,6 +7,7 @@ import { useLatestRef } from "../hooks/use-latest-ref";import type { ResolvedTransport } from "./constants";import type { TransportConflictInfo } from "./types";import {+ conflictInfoForOwner,type DownloadKind,type JobListeners,downloadManager,@@ -123,9 +124,11 @@ export function useRepoDownload(config: RepoDownloadConfig): DownloadJob {const visibleConflict = useDownloadManagerStore(useShallow((state) => {const exact = state.conflicts[conflictKey];- if (exact) return { key: conflictKey, info: exact.info };- const scoped = Object.entries(state.conflicts).find(([key]) =>- key.startsWith(`${repoConflictKey}#`),+ const exactInfo = conflictInfoForOwner(exact, "caller");+ if (exactInfo) return { key: conflictKey, info: exactInfo };+ const scoped = Object.entries(state.conflicts).find(+ ([key, entry]) =>+ key.startsWith(`${repoConflictKey}#`) && entry.owner === "caller",);return scoped? { key: scoped[0], info: scoped[1].info }diff --git a/studio/frontend/tests/download-center-overlay.test.ts b/studio/frontend/tests/download-center-overlay.test.tsnew file mode 100644index 00000000000..49b0d65577b--- /dev/null+++ b/studio/frontend/tests/download-center-overlay.test.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Overlay UX on top of the resumable Downloads list: keep a Downloads entry+// when the list is empty, start collapsed, and expand when a transfer starts.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++function read(relative: string): string {+ return readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");+}++const PANEL = read(+ "../src/features/hub/download-manager/download-manager-panel.tsx",+);++test("Downloads stays mounted even when the list is empty", () => {+ // The overlay used to return null with no jobs, so after a failure lingered+ // away there was no entry left to open. The empty state is the entry.+ assert.doesNotMatch(+ PANEL,+ /if \(!enabled \|\| jobKeys.length === 0\) return null/,+ );+ assert.match(PANEL, /if \(!enabled\) return null/);+ assert.match(PANEL, /No downloads yet/);+ assert.match(PANEL, /Open Model hub/);+});++test("Downloads starts collapsed and expands when a transfer starts", () => {+ assert.match(PANEL, /useState\(true\)/);+ assert.match(PANEL, /previousActiveCount/);+ assert.match(+ PANEL,+ /if \(activeCount > 0 && previousActiveCount\.current === 0\)/,+ );+});diff --git a/studio/frontend/tests/download-center-resume.test.ts b/studio/frontend/tests/download-center-resume.test.tsnew file mode 100644index 00000000000..7a02a46268e--- /dev/null+++ b/studio/frontend/tests/download-center-resume.test.ts@@ -0,0 +1,233 @@+// 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 mid-transfer failure used to vanish from the Downloads overlay after a few+// seconds, and was never written to storage, so the only way back was to search+// the model again. Failed and cancelled jobs now stay in the list with Resume+// and survive a restart.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import {+ conflictInfoForOwner,+ type ConflictEntry,+ type ManagedDownload,+} from "../src/features/hub/download-manager/download-manager-types.ts";+import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++registerBundlerResolver();+const { store } = installLocalStorageFake();++const PERSIST_KEY = "unsloth.studio.downloads";+let flushPersistedState: (() => void) | undefined;+Object.assign(globalThis.window, {+ addEventListener: (type: string, listener: () => void) => {+ if (type === "pagehide") flushPersistedState = listener;+ },+});++const { getState, jobKeyOf, putJob } = await import(+ "../src/features/hub/download-manager/download-manager-state.ts"+);++function read(relative: string): string {+ return readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");+}++const PANEL = read(+ "../src/features/hub/download-manager/download-manager-panel.tsx",+);+const REPO_DOWNLOAD = read(+ "../src/features/hub/download-manager/use-repo-download.ts",+);+const POLL = read("../src/features/hub/download-manager/poll-loop.ts");+const HYDRATE = read("../src/features/hub/download-manager/hydration.ts");+const CONFLICT = read(+ "../src/features/hub/download-manager/transport-conflict.ts",+);+const CONTROLLER = read(+ "../src/features/hub/download-manager/download-manager-controller.ts",+);+const STATE = read(+ "../src/features/hub/download-manager/download-manager-state.ts",+);++test("a failed or cancelled row offers Resume in Downloads", () => {+ assert.match(PANEL, /aria-label="Resume download"/);+ assert.match(PANEL, /resumeRequestFromJob/);+ assert.match(PANEL, /inventoryKind: job\.inventoryKind/);+ assert.match(+ PANEL,+ /const resumable = !job\.external && RESUMABLE_STATES\.has\(job\.state\)/,+ );+ assert.match(PANEL, /downloadManager\s*\.requestStart/);+ assert.match(PANEL, /outcome === "busy" && mounted\.current/);+ assert.match(PANEL, /This repository is already downloading/);+ assert.match(PANEL, /disabled=\{resumePending\}/);+ assert.match(+ PANEL,+ /disabled=\{job\.state === "cancelling" \|\| resumePending\}/,+ );+ assert.match(PANEL, /if \(mounted\.current\) setResumePending\(false\)/);+ assert.match(PANEL, /resolveTransportConflict\("resume"\)/);+ assert.match(PANEL, /resolveTransportConflict\("restart"\)/);+ assert.match(PANEL, /void resolution[\s\S]*?outcome === "busy"/);+ assert.match(CONFLICT, /export async function resumeConflict/);+ assert.match(CONFLICT, /export async function restartConflict/);+ assert.match(CONFLICT, /return runWithPendingStartGuard/);+ // Playwright and AppImage cancel/retry smokes wait on this exact copy.+ assert.match(PANEL, /Cancelled\. Partial files kept\./);+});++test("the global Resume path exposes transport conflict resolution", () => {+ assert.match(+ PANEL,+ /conflictInfoForOwner\(state\.conflicts\[jobKey\], "downloads"\)/,+ );+ assert.match(PANEL, /<TransportConflictDialog/);+ assert.match(PANEL, /requestStart\(resumeRequestFromJob\(job\), "downloads"\)/);+ assert.match(PANEL, /resumeConflict\(jobKey, "downloads"\)/);+ assert.match(PANEL, /restartConflict\(jobKey, "downloads"\)/);+ assert.match(PANEL, /cancelConflict\(jobKey, "downloads"\)/);+ assert.match(PANEL, /mounted\.current = false/);+ assert.match(PANEL, /outcome === "conflict" && !mounted\.current/);+});++test("the global resumable count excludes external jobs", () => {+ assert.match(+ PANEL,+ /!job\.external && RESUMABLE_STATES\.has\(job\.state\)/,+ );+});++test("web auth session boundaries clear persisted download rows", () => {+ assert.match(+ CONTROLLER,+ /AUTH_SESSION_CLEARED_EVENT[\s\S]*AUTH_SESSION_STORED_EVENT/,+ );+ assert.match(CONTROLLER, /if \(isTauri\) return/);+ assert.match(CONTROLLER, /resetDownloadManagerState\(\)/);+ assert.match(CONTROLLER, /useDownloadManagerStore\.persist\.clearStorage\(\)/);+ assert.match(CONTROLLER, /event\.key === AUTH_SESSION_MARK_KEY/);+});++test("a restart-only partial is disclosed before Resume starts it over", () => {+ assert.match(+ CONFLICT,+ /status\.has_partial &&[\s\S]*?status\.resumable === false[\s\S]*?Restarting this download/,+ );+});++test("a transport conflict belongs to exactly one dialog surface", () => {+ const info = { previous: "http", next: "xet", resumable: true } as const;+ const entry: ConflictEntry = {+ owner: "downloads",+ info,+ pending: {+ kind: "model",+ repoId: "org/conflicted-model",+ variant: "Q4_K_M",+ expectedBytes: 4_096,+ },+ };++ assert.equal(conflictInfoForOwner(entry, "downloads"), info);+ assert.equal(conflictInfoForOwner(entry, "caller"), null);+ assert.match(REPO_DOWNLOAD, /conflictInfoForOwner\(exact, "caller"\)/);+ assert.match(REPO_DOWNLOAD, /entry\.owner === "caller"/);+});++test("failed and cancelled jobs are persisted so a restart can resume them", () => {+ const key = jobKeyOf("model", "org/failed-model", "Q4_K_M");+ const job: ManagedDownload = {+ key,+ kind: "model",+ repoId: "org/failed-model",+ variant: "Q4_K_M",+ state: "error",+ downloadedBytes: 1_024,+ completedBytes: 512,+ completeOnDisk: false,+ expectedBytes: 4_096,+ fraction: 0.25,+ bytesPerSec: 0,+ etaSeconds: 0,+ error: "Download interrupted. Resume from Downloads to continue.",+ startedAt: 9,+ transport: "http",+ };+ putJob(job);+ assert.ok(flushPersistedState);+ flushPersistedState();++ const persisted = JSON.parse(store.get(PERSIST_KEY) ?? "null");+ assert.equal(persisted.state.jobs[key].state, "error");+ assert.equal(persisted.state.jobs[key].repoId, "org/failed-model");+ assert.equal(getState().jobs[key]?.state, "error");+});++test("a completed job is still not persisted", () => {+ const key = jobKeyOf("model", "org/done-model", null);+ putJob({+ key,+ kind: "model",+ repoId: "org/done-model",+ variant: null,+ state: "complete",+ downloadedBytes: 100,+ completedBytes: 100,+ completeOnDisk: true,+ expectedBytes: 100,+ fraction: 1,+ bytesPerSec: 0,+ etaSeconds: 0,+ error: null,+ startedAt: 10,+ });+ assert.ok(flushPersistedState);+ flushPersistedState();++ const persisted = JSON.parse(store.get(PERSIST_KEY) ?? "null");+ assert.equal(persisted.state.jobs[key], undefined);+});++test("hydration revalidates failed and cancelled jobs before keeping them", () => {+ assert.match(HYDRATE, /revalidateHydratedResumableJob\(job\.key, job\)/);+ assert.match(+ HYDRATE,+ /RESUMABLE_STATES\.has\(current\.state\)[\s\S]*idleProbeVerdict\([\s\S]*?progressResp\.target_present[\s\S]*?=== "gone"[\s\S]*?removeJob\(key\)/,+ );+ assert.match(+ HYDRATE,+ /applyProgressUpdate\(key, current, progressResp\)[\s\S]*?hasObservedExpectedBytes\(updated\)[\s\S]*?removeJob\(key\)/,+ );+});++test("an idle transfer with files on disk becomes a resumable error, not gone", () => {+ assert.match(POLL, /INTERRUPTED_DOWNLOAD_MESSAGE/);+ assert.match(+ POLL,+ /finalize\(key, "error", \{ error: INTERRUPTED_DOWNLOAD_MESSAGE \}\)/,+ );+ assert.doesNotMatch(POLL, /scheduleRemoval\(key, ERROR_LINGER_MS\)/);+ assert.doesNotMatch(POLL, /scheduleRemoval\(key, CANCELLED_LINGER_MS\)/);+});++test("a measured missing idle target is removed instead of offered for resume", () => {+ assert.match(+ POLL,+ /idleProbeVerdict\(\s*progressResp\.downloaded_bytes,\s*progressResp\.cache_path,\s*progressResp\.target_present,\s*progressResp\.cache_measured,\s*\) === "gone"/,+ );+ assert.match(POLL, /finalize\(key, "gone"\)/);+});++test("storage writes failed jobs through the shared persistence predicate", () => {+ assert.match(STATE, /isPersistedJobState\(job.state\)/);+ assert.match(STATE, /isPersistedJobState\(state\)/);+});