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
Revert "Studio: keep a Downloads entry when the list is empty" (#10298)
Etherlecb20837374c
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 42aafd833a9..10662948821 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,14 +20,11 @@ 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",@@ -38,15 +35,3 @@ 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 1cb3fcb8b5e..172aee678ac 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@@ -8,17 +8,14 @@ import {AUTH_TOKEN_KEY,} from "@/features/auth";import { isTauri } from "@/lib/api-base";+import { resetDownloadApiAdapterState } from "./download-api-adapter";import {createDownloadManagerInitialState,removeJob,setState,useDownloadManagerStore,} from "./download-manager-state";-import { resetDownloadApiAdapterState } from "./download-api-adapter";-import {- hydrateDownloadManager,- resetHydrationState,-} from "./hydration";+import { hydrateDownloadManager, resetHydrationState } from "./hydration";import { cancelJob, probeAndAdopt, setExpected } from "./poll-loop";import { runtimeRegistry } from "./runtime-registry";import {@@ -38,12 +35,10 @@ export {useDownloadManagerStore,} from "./download-manager-state";export type {- ConflictOwner,DownloadRequest,JobListeners,ManagedDownload,} from "./download-manager-types";-export { conflictInfoForOwner } from "./download-manager-types";export { hydrateDownloadManager };function resetDownloadManagerState(): void {@@ -58,7 +53,9 @@ export function __resetDownloadManagerForTests(): void {}function clearWebSessionDownloads(): void {- if (isTauri) return;+ if (isTauri) {+ return;+ }resetDownloadManagerState();// Clearing after the state reset also cancels the throttled empty-state write.void useDownloadManagerStore.persist.clearStorage();@@ -101,7 +98,6 @@ export const downloadManager: DownloadManagerController = {dismiss: removeJob,};-if (import.meta.hot) {import.meta.hot.dispose(() => {window.removeEventListener(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 f15422828f3..2a3bb0e6885 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,23 +9,17 @@ 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 { 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 { useRouterState } from "@tanstack/react-router";+import { useEffect, useMemo, useState } from "react";import {- conflictInfoForOwner,- type DownloadRequest,type ManagedDownload,downloadManager,hydrateDownloadManager,@@ -66,22 +60,6 @@ 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 (@@ -108,26 +86,6 @@ 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>;@@ -151,43 +109,12 @@ 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">@@ -209,53 +136,12 @@ 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" || resumePending}+ disabled={job.state === "cancelling"}onClick={() =>active? void downloadManager.cancel(job.key)@@ -278,7 +164,7 @@ function DownloadRow({ jobKey }: { jobKey: string }) {</TooltipContent></Tooltip></div>- {showProgress ? (+ {active ? (<DownloadProgressBarprogress={{expectedBytes: job.expectedBytes,@@ -295,12 +181,6 @@ 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>);}@@ -310,8 +190,7 @@ export function DownloadManagerPanel({}: { positioned?: boolean } = {}) {const pathname = useRouterState({ select: (s) => s.location.pathname });const enabled = canUseDownloadManager(pathname);- const [collapsed, setCollapsed] = useState(true);- const previousActiveCount = useRef(0);+ const [collapsed, setCollapsed] = useState(false);useEffect(() => {if (!enabled) return;@@ -321,24 +200,13 @@ 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) return null;+ if (!enabled || jobKeys.length === 0) return null;- const attentionCount = activeCount + resumableCount;const headerLabel =activeCount > 0? `Downloading ${activeCount} ${activeCount === 1 ? "item" : "items"}`- : resumableCount > 0- ? `${resumableCount} ${resumableCount === 1 ? "download" : "downloads"} to resume`- : "Downloads";+ : "Downloads";return (<div@@ -365,8 +233,8 @@ export function DownloadManagerPanel({strokeWidth={1.75}className="size-[18px]"/>- {attentionCount > 0 && (- <span className="hub-download-fab-badge">{attentionCount}</span>+ {activeCount > 0 && (+ <span className="hub-download-fab-badge">{activeCount}</span>)}</button></TooltipTrigger>@@ -393,27 +261,11 @@ export function DownloadManagerPanel({/></button></div>- {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>- )}+ <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 f011c36b929..30d6dc6b57d 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,7 +23,6 @@ import {import {ACTIVE_STATES,MAX_PROGRESS_FRACTION,- isPersistedJobState,} from "./download-manager-config";import {type DownloadManagerState,@@ -92,7 +91,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 || !isPersistedJobState(state)) return null;+ if (!kind || !repoId || !ACTIVE_STATES.has(state)) return null;const variant = typeof value.variant === "string" ? value.variant : null;const key = jobKeyOf(kind, repoId, variant);@@ -300,10 +299,7 @@ export const useDownloadManagerStore = create<DownloadManagerState>()(partialize: (state) => ({jobs: Object.fromEntries(Object.entries(state.jobs)- // 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))+ .filter(([, job]) => !job.external && ACTIVE_STATES.has(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 9683db57785..51de5eaa535 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,21 +108,11 @@ 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 35ecd92fa9b..e1c363088ce 100644--- a/studio/frontend/src/features/hub/download-manager/hydration.ts+++ b/studio/frontend/src/features/hub/download-manager/hydration.ts@@ -9,11 +9,7 @@ import {type DownloadJobState,} from "./api";import { DOWNLOAD_KIND, isResolvedTransport } from "./constants";-import {- ACTIVE_STATES,- POLL_REQUEST_TIMEOUT_MS,- RESUMABLE_STATES,-} from "./download-manager-config";+import { ACTIVE_STATES, POLL_REQUEST_TIMEOUT_MS } from "./download-manager-config";import {apiGetProgress,apiGetStatus,@@ -206,40 +202,6 @@ 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,@@ -325,13 +287,6 @@ 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 72cb58e00f9..331b3f302ac 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -19,11 +19,12 @@ 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,@@ -269,8 +270,7 @@ export function finalize(error: null,});notify(job, "onCancelled", 0);- // Stay in Downloads until dismissed so the user can resume the partial- // without searching the model again.+ scheduleRemoval(key, CANCELLED_LINGER_MS);} else {const rawError =typeof opts.error === "string" && opts.error@@ -284,6 +284,7 @@ export function finalize(etaSeconds: 0,});notify(job, "onError", 0);+ scheduleRemoval(key, ERROR_LINGER_MS);}scheduleInventoryBump();}@@ -430,9 +431,7 @@ function handleIdleAfterProgress(} else {rt.idleSinceMs ??= Date.now();if (Date.now() - rt.idleSinceMs >= IDLE_EVICT_GRACE_MS) {- // 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 });+ finalize(key, "gone");}}}diff --git a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts b/studio/frontend/src/features/hub/download-manager/transport-conflict.tsindex 8049d74a02d..1ece48bb3be 100644--- a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts+++ b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts@@ -15,7 +15,6 @@ import {effectiveTransportMode,} from "./download-api-adapter";import type {- ConflictOwner,DownloadRequest,ManagedDownload,} from "./download-manager-types";@@ -160,7 +159,6 @@ 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.@@ -213,7 +211,6 @@ export async function requestStart();if (action === "conflict") {setConflict(jobKeyOf(req.kind, req.repoId, req.variant), {- owner: conflictOwner,info: {previous: last,next: resolved,@@ -283,41 +280,30 @@ export async function requestStart(});}-export async function resumeConflict(- conflictKey: string,- owner: ConflictOwner = "caller",-): Promise<DownloadStartOutcome | undefined> {+export function resumeConflict(conflictKey: string): void {const entry = getState().conflicts[conflictKey];- if (!entry || entry.owner !== owner) return;+ if (!entry) return;setConflict(conflictKey, null);- return runWithPendingStartGuard(entry.pending, async () => {+ void runWithPendingStartGuard(entry.pending, async () => {await startJob(entry.pending, {useXet: entry.info.previous === TRANSPORT.XET,});- return isJobActiveFor(entry.pending) ? "started" : "error";+ return "started";});}-export async function restartConflict(- conflictKey: string,- owner: ConflictOwner = "caller",-): Promise<DownloadStartOutcome | undefined> {+export function restartConflict(conflictKey: string): void {const entry = getState().conflicts[conflictKey];- if (!entry || entry.owner !== owner) return;+ if (!entry) return;setConflict(conflictKey, null);- return runWithPendingStartGuard(entry.pending, async () => {+ void runWithPendingStartGuard(entry.pending, async () => {await startJob(entry.pending, {useXet: entry.info.next === TRANSPORT.XET,});- return isJobActiveFor(entry.pending) ? "started" : "error";+ return "started";});}-export function cancelConflict(- conflictKey: string,- owner: ConflictOwner = "caller",-): void {- const entry = getState().conflicts[conflictKey];- if (!entry || entry.owner !== owner) return;+export function cancelConflict(conflictKey: string): void {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 a3397998d39..94badc84134 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,7 +7,6 @@ import { useLatestRef } from "../hooks/use-latest-ref";import type { ResolvedTransport } from "./constants";import type { TransportConflictInfo } from "./types";import {- conflictInfoForOwner,type DownloadKind,type JobListeners,downloadManager,@@ -124,11 +123,9 @@ export function useRepoDownload(config: RepoDownloadConfig): DownloadJob {const visibleConflict = useDownloadManagerStore(useShallow((state) => {const exact = state.conflicts[conflictKey];- 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",+ if (exact) return { key: conflictKey, info: exact.info };+ const scoped = Object.entries(state.conflicts).find(([key]) =>+ key.startsWith(`${repoConflictKey}#`),);return scoped? { key: scoped[0], info: scoped[1].info }diff --git a/studio/frontend/tests/download-adopt-and-hydrate.test.ts b/studio/frontend/tests/download-adopt-and-hydrate.test.tsindex f246c1ae938..e739ba1955c 100644--- a/studio/frontend/tests/download-adopt-and-hydrate.test.ts+++ b/studio/frontend/tests/download-adopt-and-hydrate.test.ts@@ -98,6 +98,30 @@ test("a scan that never happened does not retire a job", () => {assert.equal(idleProbeVerdict(0, null, null, undefined), "gone");});+test("live idle polls retire an explicitly missing target before the grace period", () => {+ const src = readFileSync(+ new URL(+ "../src/features/hub/download-manager/poll-loop.ts",+ import.meta.url,+ ),+ "utf8",+ );+ const start = src.indexOf("function handleIdleAfterProgress");+ const end = src.indexOf("\nfunction handleTickError", start);+ const handler = src.slice(start, end);++ assert.match(+ handler,+ /idleProbeVerdict\([\s\S]*progressResp\.target_present[\s\S]*\) === "gone"/,+ "an authoritative missing-target response must bypass the idle grace period",+ );+ assert.match(+ src,+ /handleIdleAfterProgress\(rt, key, madeProgress, progressResp\)/,+ "the live poll must pass its progress response to the idle verdict",+ );+});+test("the held-transfer marker travels with the counters it describes", () => {// Keeping the bytes while dropping it restores undefined, which reads as// measured, and the row goes back to "0 B left".diff --git a/studio/frontend/tests/download-center-overlay.test.ts b/studio/frontend/tests/download-center-overlay.test.tsdeleted file mode 100644index 49b0d65577b..00000000000--- a/studio/frontend/tests/download-center-overlay.test.ts+++ /dev/null@@ -1,39 +0,0 @@-// 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.tsdeleted file mode 100644index b1da74e48c7..00000000000--- a/studio/frontend/tests/download-center-resume.test.ts+++ /dev/null@@ -1,226 +0,0 @@-// 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 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\)/);-});diff --git a/studio/frontend/tests/download-session-boundary.test.ts b/studio/frontend/tests/download-session-boundary.test.tsnew file mode 100644index 00000000000..9cd582cb344--- /dev/null+++ b/studio/frontend/tests/download-session-boundary.test.ts@@ -0,0 +1,82 @@+// 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 { register } from "node:module";+import test from "node:test";++import { installLocalStorageFake } from "./helpers/kit.ts";++register("./helpers/download-lifecycle-resolver.mjs", import.meta.url);++const PERSIST_KEY = "unsloth.studio.downloads";+const SESSION_CLEARED = "unsloth:auth-session-cleared";+const SESSION_MARK_KEY = "unsloth_auth_session_mark";+const SESSION_STORED = "unsloth:auth-session-stored";+const TOKEN_KEY = "unsloth_auth_token";++const { fireWindowEvent, store } = installLocalStorageFake();+Object.assign(globalThis.window, {+ setTimeout: globalThis.setTimeout.bind(globalThis),+ clearTimeout: globalThis.clearTimeout.bind(globalThis),+});++const controller = await import(+ "../src/features/hub/download-manager/download-manager-controller.ts"+);+const { getState, jobKeyOf, putJob, useDownloadManagerStore } = await import(+ "../src/features/hub/download-manager/download-manager-state.ts"+);+const { runtimeRegistry } = await import(+ "../src/features/hub/download-manager/runtime-registry.ts"+);++const boundaries: [+ string,+ string,+ Event | { key: string; newValue: string | null },+][] = [+ ["same-tab sign-out", SESSION_CLEARED, new Event(SESSION_CLEARED)],+ ["same-tab sign-in", SESSION_STORED, new Event(SESSION_STORED)],+ [+ "cross-tab session change",+ "storage",+ { key: SESSION_MARK_KEY, newValue: "next" },+ ],+ ["cross-tab sign-out", "storage", { key: TOKEN_KEY, newValue: null }],+];++for (const [name, eventType, event] of boundaries) {+ test(`${name} clears download state and pending persistence`, async () => {+ const key = jobKeyOf("model", "private-org/private-model", "Q4_K_M");+ putJob({+ key,+ kind: "model",+ repoId: "private-org/private-model",+ variant: "Q4_K_M",+ state: "running",+ downloadedBytes: 1_024,+ completedBytes: 0,+ completeOnDisk: false,+ expectedBytes: 4_096,+ fraction: 0.25,+ bytesPerSec: 0,+ etaSeconds: 0,+ error: null,+ startedAt: 1,+ transport: "http",+ });+ runtimeRegistry.pendingStartRepoKeys.add("model:private-org/private-model");+ store.set(PERSIST_KEY, "prior-session-downloads");++ try {+ fireWindowEvent(eventType, event);+ assert.deepEqual(getState().jobs, {});+ assert.equal(runtimeRegistry.pendingStartRepoKeys.size, 0);+ assert.equal(store.has(PERSIST_KEY), false);+ } finally {+ controller.__resetDownloadManagerForTests();+ await useDownloadManagerStore.persist.clearStorage();+ }+ });+}diff --git a/studio/frontend/tests/helpers/download-lifecycle-auth-stub.mjs b/studio/frontend/tests/helpers/download-lifecycle-auth-stub.mjsindex 2cac98bbb43..42b26c3a0d1 100644--- a/studio/frontend/tests/helpers/download-lifecycle-auth-stub.mjs+++ b/studio/frontend/tests/helpers/download-lifecycle-auth-stub.mjs@@ -1,6 +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+export const AUTH_SESSION_CLEARED_EVENT = "unsloth:auth-session-cleared";+export const AUTH_SESSION_MARK_KEY = "unsloth_auth_session_mark";+export const AUTH_SESSION_STORED_EVENT = "unsloth:auth-session-stored";+export const AUTH_TOKEN_KEY = "unsloth_auth_token";+export function authFetch(input, init) {return globalThis.fetch(input, init);}